Unverified Commit 8f44e4b3 authored by Dan Jones's avatar Dan Jones
Browse files

feat: prototype adapter from example-web-client

This is not yet ready.
I want to test installing it as a dependency of the
example-web-client and running it before going any further.
2 merge requests!15Resolve "Release v0.1",!1Resolve "Import prototype adapter code from example-web-client"
Pipeline #100845 failed with stages
in 0 seconds
module.exports = {
root: true,
env: {
browser: true,
node: true,
'jest/globals': true,
},
parserOptions: {
parser: '@babel/eslint-parser',
// Fix "No Babel config file detected for [file]" error
// https://github.com/babel/babel/issues/11975#issuecomment-786803214
requireConfigFile: false,
},
extends: [
'eslint:recommended',
'prettier',
],
// required to lint *.vue files
plugins: ['vue', 'jest', 'prettier'],
// add your custom rules here
rules: {
'no-console': ['warn', { allow: ['warn', 'error'] }],
'no-debugger': 'warn',
'no-unused-vars': ['error', { args: 'none' }],
},
};
# Created by .ignore support plugin (hsz.mobi)
soar-config.json
### Node template
# Logs
/logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Dependency directories
node_modules/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# parcel-bundler cache (https://parceljs.org/)
.cache
# IDE / Editor
.idea
# macOS
.DS_Store
# Vim swap files
*.swp
###
# Place your Prettier ignore content here
###
# .gitignore content is duplicated here due to https://github.com/prettier/prettier/issues/8506
# Created by .ignore support plugin (hsz.mobi)
### Node template
# Logs
/logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Dependency directories
node_modules/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# parcel-bundler cache (https://parceljs.org/)
.cache
# IDE / Editor
.idea
# macOS
.DS_Store
# Vim swap files
*.swp
{
"trailingComma": "es5",
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"bracketSameLine": false,
"arrowParens": "always",
"endOfLine": "lf"
}
Copyright 2023 [NOC](https://noc.ac.uk)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
......@@ -2,9 +2,88 @@
Generic adapter for the communications-backbone.
Implements:
Implements:
- client credentials grant
- http send/receive/notify to backbone
- websockets send and receive
- validation of messages against a specified OpenAPI schema
- decode/encode stubs
\ No newline at end of file
- decode/encode stubs
## Install
**TODO** These should work once the repository is made public
### Yarn
```yarn
yarn add git+https://git.noc.ac.uk/communications-backbone-system/backbone-adapter-javascript.git
```
### NPM
```npm
npm install git+https://git.noc.ac.uk/communications-backbone-system/backbone-adapter-javascript.git
```
## Config
To run the adapter you need a credentials file called `soar-config.json`.
This will be provided by the backbone operator or requested via the API.
```json
{
"client_id": "unique-client-id",
"client_name": "UniqueClientName",
"subscription": "dot.delimited.topic.subscription.#",
"secret": "[a generated secret]"
}
```
### Topics and Subscriptions
The topics have the following structure:
```
project.operator.vehicleType.vehicleID.[send|receive].messageType
```
Subscriptions may contain single-word wildcards (*) or multi-word wildcards (#).
## Encoding and decoding
### Decoding
Decoding refers to translation from the backbone message protocol into a
native format for the client app to process.
All messages received from the backbone are parsed and validated against the
protocol schema and then passed to the protocol decode function.
By overriding the decode function the client can define local actions to be
executed when a message of a given type is received.
### Encoding
Encoding refers to translation from the client app's native format into a
message conforming to the backbone message protocol.
The equivalent encode method allows the client to define translations per
message type to transform local data into a message conforming to the
protocol schema for transmission.
Messages passed to the publish and broadcast methods should have been
encoded and validated against the protocol schema.
## Publish vs Broadcast
It is intended that all normal-operation messages will be published on
a given topic allowing clients to choose which message topics to
subscribe to.
Broadcast is provided for contingency scenarios. The intention is that
in the case of a failure/abort a message can be sent to all parties
which bypasses any existing messages in the publish queue.
The client implementation can chose to take no-action on decoding one of
these messages but they will be made available to all clients.
\ No newline at end of file
module.exports = {
extends: ['@commitlint/config-conventional'],
};
import Validator from 'swagger-model-validator';
import axios from 'axios';
import * as soarConfig from '~/soar-config.json';
/**
* Handle authentication and send/receive with the backbone
*/
export class Adapter {
constructor(protocol) {
this.apiRoot = soarConfig.api;
this.protocol = protocol;
this.axios = axios;
this.validator = new Validator(protocol.schema);
this.auth();
}
/**
* Test parsing the message based on the provided protocol schema
*
* The message must be successfully json decoded into an object
* prior to validation
*
* At present this returns the validation result which is an
* object containing a boolean valid field as well as details
* of any errors.
* @param {object} message
* @returns {object}
*/
validate(message) {
return this.validator.validate(
message,
this.protocol.schema.definitions.Message
);
}
/**
* Ensure the token in this.credentials is still valid
* @returns {boolean}
*/
tokenValid() {
let valid = false;
if (this.credentials) {
const now = new Date().toISOString();
valid = this.credentials.expiry > now;
}
return valid;
}
/**
* Return an http headers object containing a bearer token authorisation header
* @returns {object}
*/
getAuthorizationHeader() {
if (!this.tokenValid())
return this.auth().then((response) => {
return {
Authorization: `Bearer ${this.credentials.token}`,
};
});
else {
return Promise.resolve({
Authorization: `Bearer ${this.credentials.token}`,
});
}
}
/**
* Do a client credentials grant and store in this.credentials
* @returns {object}
*/
auth() {
return this.axios
.get(`{this.apiRoot}/token`, {
params: {
client_id: soarConfig.client_id,
secret: soarConfig.secret,
},
})
.then((response) => {
this.credentials = response.data;
return response;
});
}
/**
* Call the GET /receive endpoint and process the messages with decode
*
* Returns the response
* @returns {object}
*/
poll() {
return this.getAuthorizationHeader()
.then((headers) => {
return this.axios.get(`{this.apiRoot}/receive`, {
headers,
});
})
.then((response) => {
response.data.forEach((message) => {
const parsed = JSON.parse(message.message);
const validation = this.validate(parsed);
if (validation.valid) {
const type = this.protocol.getType(parsed);
this.protocol.decode(type, parsed);
}
});
return response;
});
}
/**
* Publish a message to the backbone with the specified topic
*
* Messages should be passed through encode before sending
* @param {string} topic
* @param {string} body
* @returns
*/
publish(topic, body) {
return this.getAuthorizationHeader()
.then((headers) => {
return this.axios.post(
`{this.apiRoot}/send`,
{
topic,
body,
},
{
headers,
}
);
})
.then((response) => {
return response;
});
}
/**
* Broadcast the message on the backbone
*
* Broadcast messages bypass the normal publisher queues
* this means they can be used to deliver messages more
* quickly in an emergency scenario.
*
* Messages should be passed through encode before sending
* @param {*} body
* @returns
*/
broadcast(body) {
return this.getAuthorizationHeader()
.then((headers) => {
return this.axios.post(
`{this.apiRoot}/notify`,
{
body,
},
{
headers,
}
);
})
.then((response) => {
return response;
});
}
}
import { GenericProtocol } from '~/modules/comms-adapter/protocol/generic';
/**
*
*/
export class SoarWebClientProtocol extends GenericProtocol {
constructor(schema, services) {
super(schema, services);
// bootstrap any injected services
}
/**
* Process a message received from the backbone
*
* This method is overridden to take appropriate
* action for each message type.
*
* Further methods can then be defined to handle
* each message type.
*
* You can use this to take action directly or
* transform that data to invoke an existing process.
* @param {string} type
* @param {object} message
* @returns
*/
decode(type, message) {
switch (type) {
case 'VehicleStatus':
this.decodeVehicleStatus(message);
break;
case 'VehicleMission':
this.decodeVehicleMission(message);
break;
}
return message;
}
/**
* Transform local data into a message conforming to the protocol schema
*
* When a client event occurs the local data is passed through
* encode to handle the translation from the native client format
* into a message conforming to the protocol schema.
* @param {string} type
* @param {object} message
* @returns
*/
encode(type, message) {
return message;
}
/**
* Act upon a received VehicleStatus message
* @param {object} message
* @returns {object}
*/
decodeVehicleStatus(message) {
const battery = message.battery_percentage;
message.battery_rag_status =
battery > 20 ? 'green' : battery > 10 ? 'amber' : 'red';
this.services.bridge.$emit('soar.vehicle.status', message);
return message;
}
/**
* Act upon a received VehicleMission message
* @param {object} message
* @returns {object}
*/
decodeVehicleMission(message) {
this.services.bridge.$emit('soar.vehicle.mission', message);
return message;
}
/**
* Transform local data into a VehicleStatus message
* @param {object} message
* @returns {object}
*/
encodeVehicleStatus(message) {
return message;
}
}
import Validator from 'swagger-model-validator';
/**
* GenericProtocol defines a simple passthru handler for messages
* This can be extended to handle different schemas
*
* The assunption is that all messages conform to a single
* wrapper schema definition. Different payloads are handled
* by a oneOf definitions within the schema determined by a
* field value.
*
* This class can be extended and overridden to handle
* different schemas and to implement the client specific
* logic related to be executed when invoked for a given
* message type.
*
* By default encode and decode are just passthru stubs
*
* decode is invoked when receiving a message from the backbone
* encode is invoked before delivering a message to the backbone
*
* The intention is that these allow you to transform the message
* and call invoke internal functions and services as required
*/
export class GenericProtocol {
constructor(schema, services) {
this.schema = schema;
this.validator = new Validator(schema);
this.services = services;
}
/**
* Validate that a message meets the reqiured schema
* @param {object} message
* @returns {object}
*/
validate(message) {
return this.validator.validate(message, this.schema.definitions.Message);
}
/**
* Identify the payload type from the message content
* @param {object} message
* @returns {string}
*/
getType(message) {
return message.message_type;
}
/**
* Invoked on receiving a message from the backbone
* @param {string} type
* @param {object} message
* @returns {*}
*/
decode(type, message) {
return message;
}
/**
* Optionally invoked before delivering a message to the backbone
* @param {string} type
* @param {*} message
* @returns {object}
*/
encode(type, message) {
return message;
}
}
module.exports = {
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1',
'^~/(.*)$': '<rootDir>/$1',
},
moduleFileExtensions: ['js', 'json'],
transform: {
'^.+\\.js$': 'babel-jest',
},
collectCoverage: true,
collectCoverageFrom: [
],
testEnvironment: 'jsdom',
};
{
"name": "@noc-comms-backbone/backbone-adapter-javascript",
"version": "1.0.0",
"private": true,
"contributors": [
{
"name": "James Kirk",
"email": "james.kirk@noc.ac.uk"
},
{
"name": "Dan Jones",
"email": "dan.jones@noc.ac.uk"
},
{
"name": "Trishna Saeharaseelan",
"email": "trishna.saeharaseelan@noc.ac.uk"
}
],
"license": "MIT",
"scripts": {
"lint:js": "eslint --ext \".js\" --ignore-path .gitignore .",
"lint:prettier": "prettier --check .",
"lint": "yarn lint:js && yarn lint:prettier",
"lintfix": "prettier --write --list-different . && yarn lint:js --fix",
"prepare": "husky install",
"test": "jest"
},
"lint-staged": {
"*.{js,vue}": "eslint --cache",
"*.**": "prettier --check --ignore-unknown"
},
"dependencies": {
"faye-websocket": "^0.11.4",
"swagger-model-validator": "^3.0.21"
},
"devDependencies": {
"@babel/core": "^7.0.0-0",
"@babel/eslint-parser": "^7.0.0",
"@commitlint/cli": "^15.0.0",
"@commitlint/config-conventional": "^15.0.0",
"babel-jest": "^27.4.4",
"cucumber": "^6.0.7",
"eslint": "^8.4.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.2.1",
"husky": "^7.0.4",
"jest": "^27.4.4",
"lint-staged": "^12.1.2",
"prettier": "^2.5.1"
}
}
{
"message_type": "VehicleMission",
"headers": {
"source": "ae",
"destination": "soar.po.ecosub.eco1",
"delivery_type": "publish",
"message_id": "test"
},
"operator_id": "po",
"vehicle_id": "eco1",
"coordinates": {
"latitude": 59.234,
"longitude": -10.432,
"depth": 50,
"projection": "EPSG:4326"
}
}
{
"message_type": "VehicleMission",
"headers": {
"source": "ae",
"destination": "soar.po.ecosub.eco1",
"delivery_type": "publish",
"message_id": "test"
},
"operator_id": "po",
"vehicle_id": "eco1",
"coordinates": {
"latitude": 59.234,
"longitude": -10.432,
"depth": 50,
"projection": "EPSG:4326"
},
"actions": [
{
"action_type": "GoToWaypoint",
"coordinates": {
"latitude": 59.234,
"longitude": -10.432,
"depth": 50,
"projection": "EPSG:4326"
}
},
{
"action_type": "DescendToAltitude",
"coordinates": {
"latitude": 59.234,
"longitude": -10.432,
"altitude": 50,
"projection": "EPSG:4326"
}
}
]
}
{
"message_type": "VehicleStatus",
"headers": {
"source": "ae",
"destination": "soar.po.ecosub.eco1",
"delivery_type": "publish",
"message_id": "test"
},
"operator_id": "po",
"vehicle_id": "eco1",
"coordinates": {
"latitude": 57.234,
"longitude": -8.432,
"depth": 50,
"projection": "EPSG:4326"
},
"battery_percentage": 64
}
{
"swagger": "2.0",
"basePath": "/soar",
"info": {
"title": "soar",
"version": "1.3.1",
"description": "SoAR message schemas"
},
"produces": ["application/json"],
"consumes": ["application/json"],
"definitions": {
"Message": {
"discriminator": {
"propertyName": "message_type",
"mapping": {
"VehicleStatus": "#/definitions/VehicleStatus",
"VehicleMission": "#/definitions/VehicleMission",
"AreaOfInterest": "#/definitions/AreaOfInterest"
}
},
"oneOf": [
{
"$ref": "#/definitions/VehicleStatus"
},
{
"$ref": "#/definitions/VehicleMission"
},
{
"$ref": "#/definitions/AreaOfInterest"
}
]
},
"Metadata": {
"properties": {
"source": {
"type": "string",
"description": "The sender.",
"example": "autonomy-engine"
},
"destination": {
"type": "string",
"description": "Publisher topic.",
"example": "soar.noc.autosub.ah1.status"
},
"delivery_type": {
"type": "string",
"description": "Published or broadcast",
"enum": ["broadcast", "publish"],
"example": "2.0.0"
},
"message_id": {
"type": "string",
"description": "An identifier for the type of message received.",
"example": "VehicleStatus"
}
},
"type": "object"
},
"Coordinates": {
"properties": {
"latitude": {
"type": "number",
"description": "Latitude in decimal degrees.",
"example": 54.234
},
"longitude": {
"type": "number",
"description": "Longitude in decimal degrees.",
"example": -1.432
},
"depth": {
"type": "number",
"description": "Target depth",
"default": 0,
"example": 50
},
"altitude": {
"type": "number",
"description": "Target altitude above bottom",
"default": 0,
"example": 50
},
"projection": {
"type": "integer",
"description": "EPSG Projection Code",
"example": 4326,
"default": 4326
}
}
},
"VehicleStatus": {
"properties": {
"message_type": {
"type": "string",
"description": "An identifier for the payload type.",
"example": "VehicleStatus",
"enum": ["VehicleStatus"]
},
"metadata": {
"$ref": "#/definitions/Metadata"
},
"operator_id": {
"type": "string",
"description": "An identifier for the operator.",
"example": "noc"
},
"vehicle_id": {
"type": "string",
"description": "An identifier for the vehicle.",
"example": "noc_ah1"
},
"coordinates": {
"$ref": "#/definitions/Coordinates"
},
"battery_percentage": {
"type": "number",
"description": "The remaining battery capacity.",
"example": 64
}
}
},
"VehicleMission": {
"properties": {
"message_type": {
"type": "string",
"description": "An identifier for the payload type.",
"example": "VehicleMission",
"enum": ["VehicleMission"]
},
"metadata": {
"$ref": "#/definitions/Metadata"
},
"operator_id": {
"type": "string",
"description": "An identifier for the operator.",
"example": "noc"
},
"vehicle_id": {
"type": "string",
"description": "An identifier for the vehicle.",
"example": "noc_ah1"
},
"coordinates": {
"$ref": "#/definitions/Coordinates"
},
"actions": {
"type": "array",
"items": {
"discriminator": {
"propertyName": "action_type",
"mapping": {
"GoToWaypoint": "#/definitions/GoToWaypoint",
"DescendToAltitude": "#/definitions/DescendToAltitude",
"AscendToSurface": "#/definitions/AscendToSurface"
}
},
"oneOf": [
{
"$ref": "#/definitions/VehicleStatus"
},
{
"$ref": "#/definitions/VehicleMission"
},
{
"$ref": "#/definitions/AreaOfInterest"
}
]
}
}
}
},
"AreaOfInterest": {
"properties": {
"message_type": {
"type": "string",
"description": "An identifier for the payload type.",
"example": "AreaOfInterest",
"enum": ["AreaOfInterest"]
},
"metadata": {
"$ref": "#/definitions/Metadata"
},
"operator_id": {
"type": "string",
"description": "An identifier for the operator.",
"example": "noc"
},
"vehicle_id": {
"type": "string",
"description": "An identifier for the vehicle.",
"example": "noc_ah1"
},
"coordinates": {
"$ref": "#/definitions/Coordinates"
}
}
},
"GoToWaypoint": {
"properties": {
"action_type": {
"type": "string",
"description": "An identifier for the payload type.",
"example": "GoToWaypoint",
"enum": ["GoToWaypoint"]
},
"coordinates": {
"$ref": "#/definitions/Coordinates"
}
}
},
"DescendToAltitude": {
"properties": {
"action_type": {
"type": "string",
"description": "An identifier for the payload type.",
"example": "DescendToAltitude",
"enum": ["DescendToAltitude"]
},
"coordinates": {
"$ref": "#/definitions/Coordinates"
}
}
},
"AscendToSurface": {
"properties": {
"action_type": {
"type": "string",
"description": "An identifier for the payload type.",
"example": "AscendToSurface",
"enum": ["AscendToSurface"]
},
"coordinates": {
"$ref": "#/definitions/Coordinates"
}
}
}
}
}
This diff is collapsed.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment