Commit d295a6a0 authored by Dan Jones's avatar Dan Jones
Browse files

Merge branch '15-release-v0-1' into 'master'

Resolve "Release v0.1"

See merge request !15
parents a8eef21a bcc74f0d
1 merge request!15Resolve "Release v0.1"
Pipeline #113980 passed with stages
in 57 seconds
module.exports = {
root: true,
env: {
browser: true,
node: true,
es6: true,
},
parserOptions: {
parser: '@babel/eslint-parser',
sourceType: 'module',
requireConfigFile: false,
ecmaVersion: 'latest',
},
extends: ['eslint:recommended', 'plugin:prettier/recommended'],
ignorePatterns: ['**/dist/'],
// add your custom rules here
rules: {
'no-console': ['error', { allow: ['warn', 'error'] }],
'no-unused-vars': ['error', { args: 'none' }],
},
};
# 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
# backbone-adapter-testsuite
test/features/*.feature
test/fixtures/*.json
\ No newline at end of file
include:
- project: communications-backbone-system/backbone-infrastructure-config
ref: master
file: gitlab/all.yml
variables:
CI_SKIP_DOCKER_TAG: 1
CI_SKIP_BUILD: 1
LINTER_IMAGE: node:18
# Ignore artifacts:
**/dist/
**/*.esm.js
**/*.ssr.js
**/*.min.js
**/.nyc-output/
**/.nuxt/
**/.turbo/
\ No newline at end of file
module.exports = {
trailingComma: 'es5',
tabWidth: 2,
useTabs: false,
semi: true,
singleQuote: true,
bracketSameLine: false,
arrowParens: 'always',
endOfLine: 'lf',
};
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [v0.1.0] - 2023-03-24
### Added
Create an adapter class which handles authentication with the communications-backbone (Nucleus)
- implement client credentials token grant
- implement poll/publish/broadcast
Create a protocol instance class
- implement scchema validation
- implement stubs for encode/decode/receivedInvalid
Create a soar protocol instance
- implement retreive schema version by tag/branch/commitref
- override methods to handle soar message structure
[v0.1]: https://git.noc.ac.uk/communications-backbone-system/backbone-adapter-javascript/compare/a8eef21a...v0.1.0
[unreleased]: https://git.noc.ac.uk/communications-backbone-system/backbone-adapter-javascript/compare/v0.1.0...dev
Copyright 2023 [National Oceanography Centre](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.
# backbone-adapter-javascript
Generic adapter for the communications-backbone.
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
Generic adapter for the communications-backbone.
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
## Setup
```
yarn install
# move testsuite files into view
yarn copytests
```
## Test
The tests are written in [cucumber](https://cucumber.io/docs/installation/javascript/)
This means we can have a common suite of [gherkin](https://github.com/cucumber/gherkin)
tests across adapter ports written in multiple languages.
```
yarn test
```
## Installing in your project
We may publish this to a public registry but for now you need to install the package
from git.
### Requirements
An `axios` library. Axios is included as a dev dependency to run the tests.
I've not installed it as a runtime dependency because in nuxt you need to
use `@nuxtjs/axios` instead.
**TODO fix this in rollup config**
### 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
```
## Schema
The example code uses a mock schema with some example messages. The intention is the message
protocol schema is retreived from an external source.
## 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
{
"api": "[backbone api root url]",
"client_id": "unique-client-id",
"client_name": "UniqueClientName",
"subscription": "dot.delimited.topic.subscription.#",
"secret": "[a generated secret]"
}
```
### Topics
When sending messages you should publish them using a topic matching [this definition](https://git.noc.ac.uk/communications-backbone-system/backbone-message-format#topics).
## 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.
module.exports = {
extends: ['@commitlint/config-conventional'],
};
module.exports = {
default: {
formatOptions: {
snippetInterface: 'synchronous',
},
paths: ['test/features/**/*.feature'],
require: ['test/cucumber/**/*.steps.js'],
},
};
import axios from 'axios';
/**
* Handle authentication and send/receive with the backbone
*/
class Adapter {
constructor(protocol, config) {
this.protocol = protocol;
this.config = config;
this.axios = axios;
}
/**
* 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.protocol.validate(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 ${response.data.token}`,
};
});
else {
return Promise.resolve({
Authorization: `Bearer ${this.credentials.token}`,
});
}
}
/**
* Do a client credentials grant and store in this.credentials
* @returns {object}
*/
auth() {
let adapterConfig = this.config;
return this.axios
.get(`${adapterConfig.api}/token`, {
params: {
client_id: adapterConfig.client_id,
secret: adapterConfig.secret,
},
})
.then((response) => {
this.credentials = response.data;
return response;
})
.catch((error) => {
return Promise.reject(error);
});
}
/**
* Call the GET /receive endpoint and process the messages with decode
*
* Returns the response
* @param {boolean} is_retry
* @returns {object}
*/
poll(is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
return this.axios.get(`${adapterConfig.api}/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);
} else {
this.protocol.receivedInvalid(parsed, validation);
}
});
return response;
})
.catch((error) => {
let retry = false;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
}
if (retry && !is_retry) return this.poll(true);
else return Promise.reject(error);
});
}
/**
* Publish a message to the backbone with the specified topic
*
* Messages should be passed through encode before sending
* @param {string} topic
* @param {string} body
* @param {boolean} is_retry
* @returns
*/
publish(topic, body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
return this.axios.post(
`${adapterConfig.api}/send`,
{
topic,
body,
},
{
headers,
}
);
})
.then((response) => {
return response;
})
.catch((error) => {
let retry = false;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
}
if (retry && !is_retry) return this.publish(topic, body, true);
else return Promise.reject(error);
});
}
/**
* 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 {string} body
* @param {boolean} is_retry
* @returns
*/
broadcast(body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
return this.axios.post(
`${adapterConfig.api}/notify`,
{
body,
},
{
headers,
}
);
})
.then((response) => {
return response;
})
.catch((error) => {
let retry = false;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
}
if (retry && !is_retry) return this.broadcast(body, true);
else return Promise.reject(error);
});
}
}
export { Adapter };
'use strict';
var axios = require('axios');
/**
* Handle authentication and send/receive with the backbone
*/
class Adapter {
constructor(protocol, config) {
this.protocol = protocol;
this.config = config;
this.axios = axios;
}
/**
* 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.protocol.validate(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 ${response.data.token}`,
};
});
else {
return Promise.resolve({
Authorization: `Bearer ${this.credentials.token}`,
});
}
}
/**
* Do a client credentials grant and store in this.credentials
* @returns {object}
*/
auth() {
let adapterConfig = this.config;
return this.axios
.get(`${adapterConfig.api}/token`, {
params: {
client_id: adapterConfig.client_id,
secret: adapterConfig.secret,
},
})
.then((response) => {
this.credentials = response.data;
return response;
})
.catch((error) => {
return Promise.reject(error);
});
}
/**
* Call the GET /receive endpoint and process the messages with decode
*
* Returns the response
* @param {boolean} is_retry
* @returns {object}
*/
poll(is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
return this.axios.get(`${adapterConfig.api}/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);
} else {
this.protocol.receivedInvalid(parsed, validation);
}
});
return response;
})
.catch((error) => {
let retry = false;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
}
if (retry && !is_retry) return this.poll(true);
else return Promise.reject(error);
});
}
/**
* Publish a message to the backbone with the specified topic
*
* Messages should be passed through encode before sending
* @param {string} topic
* @param {string} body
* @param {boolean} is_retry
* @returns
*/
publish(topic, body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
return this.axios.post(
`${adapterConfig.api}/send`,
{
topic,
body,
},
{
headers,
}
);
})
.then((response) => {
return response;
})
.catch((error) => {
let retry = false;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
}
if (retry && !is_retry) return this.publish(topic, body, true);
else return Promise.reject(error);
});
}
/**
* 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 {string} body
* @param {boolean} is_retry
* @returns
*/
broadcast(body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
return this.axios.post(
`${adapterConfig.api}/notify`,
{
body,
},
{
headers,
}
);
})
.then((response) => {
return response;
})
.catch((error) => {
let retry = false;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
}
if (retry && !is_retry) return this.broadcast(body, true);
else return Promise.reject(error);
});
}
}
exports.Adapter = Adapter;
import axios from 'axios';
import Validator from 'swagger-model-validator';
/**
* GenericProtocol defines a simple passthru handler for messages
* This can be extended to handle different schemas
*
* The assumption 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
*/
class GenericProtocol {
constructor(schema, services) {
this.schema = schema;
this.services = services;
this.createValidator(schema);
}
/**
* Create a Validator from the provided JSONSchema
* @param {object} schema
* @returns {Validator}
*/
createValidator(schema) {
this.validator = new Validator(schema);
}
/**
* Validate that a message meets the reqiured schema
* @param {object} message
* @returns {object}
*/
validate(message) {
return this.validator.validate(
message,
this.schema.components.schemas.Message,
this.schema.components.schemas,
false,
false
);
}
/**
* Identify the payload type from the message content
* @param {object} message
* @returns {string}
*/
getType(message) {
try {
return message.payload.message_type;
} catch (error) {
return null;
}
}
/**
* Invoked on receiving a message from the backbone
*
* Whilst type isn't used in the generic stub it will
* be needed by sub-classes overriding the decode method
* @param {string} type
* @param {object} message
* @returns {*}
*/
decode(type, message) {
return message;
}
/**
* Invoked on receiving an invalid message from the backbone
*
* @param {object} message
* @param {object} validation
* @returns {*}
*/
receivedInvalid(message, validation) {
return message;
}
/**
* Optionally invoked before delivering a message to the backbone
*
* Whilst type isn't used in the generic stub it will
* be needed by sub-classes overriding the encode method
* @param {string} type
* @param {*} message
* @returns {object}
*/
encode(type, message) {
return message;
}
}
/**
* GenericSoarProtocol defines a simple passthru handler for messages
*
* This provides the same as above but loads a version of the
* SoAR message protocol
*/
class GenericSoarProtocol extends GenericProtocol {
constructor(schema, services) {
super(schema, services);
}
/**
* Create a Validator from the provided JSONSchema
*
* If schema is a string build a URL and retrieve the
* schema from gitlab
* @param {string|object} schema
* @returns {object}
*/
createValidator(schema) {
if (typeof schema === 'string' && schema.match(/^[\w.]+$/)) {
this.loadSchema(schema).then((schema) => {
this.validator = new Validator(schema);
});
} else {
this.validator = new Validator(schema);
}
}
/**
* Load schema from gitlab by tag/branch/commitref
* @param {string} version
* @returns {object}
*/
loadSchema(version) {
this.axios = axios;
let repository =
'https://git.noc.ac.uk/communications-backbone-system/backbone-message-format';
let url = `${repository}/-/raw/${version}/project/soar/swagger.json`;
return this.axios.get(url).then((response) => {
this.schema = response.data;
return response.data;
});
}
/**
* Validate that a message meets the reqiured schema
* @param {object} message
* @returns {object}
*/
validate(message) {
return this.validator.validate(
message,
this.schema.components.schemas.MESSAGE,
this.schema.components.schemas,
false,
false
);
}
}
export { GenericProtocol, GenericSoarProtocol };
'use strict';
var axios = require('axios');
var Validator = require('swagger-model-validator');
/**
* GenericProtocol defines a simple passthru handler for messages
* This can be extended to handle different schemas
*
* The assumption 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
*/
class GenericProtocol {
constructor(schema, services) {
this.schema = schema;
this.services = services;
this.createValidator(schema);
}
/**
* Create a Validator from the provided JSONSchema
* @param {object} schema
* @returns {Validator}
*/
createValidator(schema) {
this.validator = new Validator(schema);
}
/**
* Validate that a message meets the reqiured schema
* @param {object} message
* @returns {object}
*/
validate(message) {
return this.validator.validate(
message,
this.schema.components.schemas.Message,
this.schema.components.schemas,
false,
false
);
}
/**
* Identify the payload type from the message content
* @param {object} message
* @returns {string}
*/
getType(message) {
try {
return message.payload.message_type;
} catch (error) {
return null;
}
}
/**
* Invoked on receiving a message from the backbone
*
* Whilst type isn't used in the generic stub it will
* be needed by sub-classes overriding the decode method
* @param {string} type
* @param {object} message
* @returns {*}
*/
decode(type, message) {
return message;
}
/**
* Invoked on receiving an invalid message from the backbone
*
* @param {object} message
* @param {object} validation
* @returns {*}
*/
receivedInvalid(message, validation) {
return message;
}
/**
* Optionally invoked before delivering a message to the backbone
*
* Whilst type isn't used in the generic stub it will
* be needed by sub-classes overriding the encode method
* @param {string} type
* @param {*} message
* @returns {object}
*/
encode(type, message) {
return message;
}
}
/**
* GenericSoarProtocol defines a simple passthru handler for messages
*
* This provides the same as above but loads a version of the
* SoAR message protocol
*/
class GenericSoarProtocol extends GenericProtocol {
constructor(schema, services) {
super(schema, services);
}
/**
* Create a Validator from the provided JSONSchema
*
* If schema is a string build a URL and retrieve the
* schema from gitlab
* @param {string|object} schema
* @returns {object}
*/
createValidator(schema) {
if (typeof schema === 'string' && schema.match(/^[\w.]+$/)) {
this.loadSchema(schema).then((schema) => {
this.validator = new Validator(schema);
});
} else {
this.validator = new Validator(schema);
}
}
/**
* Load schema from gitlab by tag/branch/commitref
* @param {string} version
* @returns {object}
*/
loadSchema(version) {
this.axios = axios;
let repository =
'https://git.noc.ac.uk/communications-backbone-system/backbone-message-format';
let url = `${repository}/-/raw/${version}/project/soar/swagger.json`;
return this.axios.get(url).then((response) => {
this.schema = response.data;
return response.data;
});
}
/**
* Validate that a message meets the reqiured schema
* @param {object} message
* @returns {object}
*/
validate(message) {
return this.validator.validate(
message,
this.schema.components.schemas.MESSAGE,
this.schema.components.schemas,
false,
false
);
}
}
exports.GenericProtocol = GenericProtocol;
exports.GenericSoarProtocol = GenericSoarProtocol;
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": "0.1.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": {
"copytest:features": "npx recursive-copy -w node_modules/backbone-adapter-testsuite/features test/features",
"copytest:fixtures": "npx recursive-copy -w node_modules/backbone-adapter-testsuite/fixtures test/fixtures",
"copytests": "npm run copytest:features && npm run copytest:fixtures",
"lint:js": "eslint -c .eslintrc.js --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": "yarn build && yarn cucumber",
"cucumber": "cucumber-js",
"build": "cross-env NODE_ENV=production rollup -c"
},
"lint-staged": {
"*.{js,vue}": "eslint --cache",
"*.**": "prettier --check --ignore-unknown"
},
"dependencies": {
"faye-websocket": "^0.11.4",
"json-schema-remote": "^1.6.2",
"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",
"@cucumber/cucumber": "^8.10.0",
"@rollup/plugin-babel": "^6.0.3",
"axios": "^1.2.3",
"axios-mock-adapter": "^1.21.2",
"babel-jest": "^27.4.4",
"backbone-adapter-testsuite": "git+https://git.noc.ac.uk/communications-backbone-system/backbone-adapter-testsuite.git#v0.1.0",
"cross-env": "^7.0.3",
"eslint": "^8.36.0",
"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",
"openapi-schema-validator": "^12.1.0",
"prettier": "^2.8.4",
"recursive-copy-cli": "^1.0.20",
"rollup": "^3.9.1"
}
}
exports.default = [
{
input: 'src/adapter/index.js',
output: [
{
file: 'dist/adapter.esm.js',
format: 'es',
},
{
file: 'dist/adapter.js',
format: 'cjs',
},
],
},
{
input: 'src/protocol/index.js',
output: [
{
file: 'dist/protocol.esm.js',
format: 'es',
},
{
file: 'dist/protocol.js',
format: 'cjs',
},
],
},
];
yarn install
yarn copytests
yarn test
# Need to tidy up things with 'root' permissions in the docker container
# As can't do it on the gitlab runner
rm -rf node_modules test/features
find test/fixtures -name "*.json" -type f -delete
\ No newline at end of file
import axios from 'axios';
/**
* Handle authentication and send/receive with the backbone
*/
export class Adapter {
constructor(protocol, config) {
this.protocol = protocol;
this.config = config;
this.axios = axios;
}
/**
* 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.protocol.validate(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 ${response.data.token}`,
};
});
else {
return Promise.resolve({
Authorization: `Bearer ${this.credentials.token}`,
});
}
}
/**
* Do a client credentials grant and store in this.credentials
* @returns {object}
*/
auth() {
let adapterConfig = this.config;
return this.axios
.get(`${adapterConfig.api}/token`, {
params: {
client_id: adapterConfig.client_id,
secret: adapterConfig.secret,
},
})
.then((response) => {
this.credentials = response.data;
return response;
})
.catch((error) => {
return Promise.reject(error);
});
}
/**
* Call the GET /receive endpoint and process the messages with decode
*
* Returns the response
* @param {boolean} is_retry
* @returns {object}
*/
poll(is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
return this.axios.get(`${adapterConfig.api}/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);
} else {
this.protocol.receivedInvalid(parsed, validation);
}
});
return response;
})
.catch((error) => {
let retry = false;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
}
if (retry && !is_retry) return this.poll(true);
else return Promise.reject(error);
});
}
/**
* Publish a message to the backbone with the specified topic
*
* Messages should be passed through encode before sending
* @param {string} topic
* @param {string} body
* @param {boolean} is_retry
* @returns
*/
publish(topic, body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
return this.axios.post(
`${adapterConfig.api}/send`,
{
topic,
body,
},
{
headers,
}
);
})
.then((response) => {
return response;
})
.catch((error) => {
let retry = false;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
}
if (retry && !is_retry) return this.publish(topic, body, true);
else return Promise.reject(error);
});
}
/**
* 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 {string} body
* @param {boolean} is_retry
* @returns
*/
broadcast(body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
return this.axios.post(
`${adapterConfig.api}/notify`,
{
body,
},
{
headers,
}
);
})
.then((response) => {
return response;
})
.catch((error) => {
let retry = false;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
}
if (retry && !is_retry) return this.broadcast(body, true);
else return Promise.reject(error);
});
}
}
import { GenericProtocol } from '~/modules/comms-adapter/protocol';
/**
*
*/
export class ExampleClientProtocol 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;
}
}
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