Source
...
Target
Commits (43)
......@@ -3,24 +3,19 @@ module.exports = {
env: {
browser: true,
node: true,
'jest/globals': true,
es6: true,
},
parserOptions: {
parser: '@babel/eslint-parser',
// Fix "No Babel config file detected for [file]" error
// https://github.com/babel/babel/issues/11975#issuecomment-786803214
sourceType: 'module',
requireConfigFile: false,
ecmaVersion: 'latest',
},
extends: [
'eslint:recommended',
'prettier',
],
// required to lint *.vue files
plugins: ['vue', 'jest', 'prettier'],
extends: ['eslint:recommended', 'plugin:prettier/recommended'],
ignorePatterns: ['**/dist/'],
// add your custom rules here
rules: {
'no-console': ['warn', { allow: ['warn', 'error'] }],
'no-debugger': 'warn',
'no-console': ['error', { allow: ['warn', 'error'] }],
'no-unused-vars': ['error', { args: 'none' }],
},
};
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
###
# 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
# Ignore artifacts:
**/dist/
**/*.esm.js
**/*.ssr.js
**/*.min.js
**/.nyc-output/
**/.nuxt/
**/.turbo/
\ No newline at end of file
{
"trailingComma": "es5",
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"bracketSameLine": false,
"arrowParens": "always",
"endOfLine": "lf"
}
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.0]: 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 [NOC](https://noc.ac.uk)
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.
\ No newline at end of file
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.
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
- 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
## Setup
```
yarn install
......@@ -18,65 +18,51 @@ yarn install
yarn copytests
```
## Test
## 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.
tests across adapter ports written in multiple languages.
```
yarn test
```
## Installing in your project
## Installing in your project
We may publish this to a public registry but for now you need to install the package
from git.
We may publish this to a public registry but for now you need to install the package
from git.
### Requirements
### 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.
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
#### Once public
```yarn
yarn add git+https://git.noc.ac.uk/communications-backbone-system/backbone-adapter-javascript.git
```
#### For now
```yarn
# You may need to tell it how to use your ssh key
eval `ssh-agent -s`
ssh-add ~/.ssh/id_rsa
export GIT_SSH_COMMAND="/usr/bin/ssh -i /home/danjon/.ssh/id_rsa -o IdentitiesOnly=yes"
# Then you can install the private repo via ssh
yarn add ssh://git@git.noc.ac.uk:communications-backbone-system/backbone-adapter-javascript.git#1-import-prototype-adapter-code-from-example-web-client
```
### NPM
```npm
npm install git+https://git.noc.ac.uk/communications-backbone-system/backbone-adapter-javascript.git
```
## Schema
## 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.
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
## 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.
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
{
......@@ -88,54 +74,44 @@ This will be provided by the backbone operator or requested via the API.
}
```
### Topics and Subscriptions
The topics have the following structure:
```
project.operator.vehicleType.vehicleID.[send|receive].messageType
# eg
soar.noc.autosub.ah1.send.platform-mission
# or
soar.po.ecosub.eco1.receive.platform-status
```
### Topics
Subscriptions may contain single-word wildcards (*) or multi-word wildcards (#).
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
## Encoding and decoding
### Decoding
### Decoding
Decoding refers to translation from the backbone message protocol into a
native format for the client app to process.
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.
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.
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
Encoding refers to translation from the client app's native format into a
message conforming to the backbone message protocol.
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.
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
Messages passed to the publish and broadcast methods should have been
encoded and validated against the protocol schema.
## Publish vs Broadcast
## 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.
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.
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
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 = {
default: {
formatOptions: {
snippetInterface: "synchronous"
snippetInterface: 'synchronous',
},
paths: [ 'test/features/**/*.feature' ],
require: [ 'test/cucumber/**/*.steps.js' ],
paths: ['test/features/**/*.feature'],
require: ['test/cucumber/**/*.steps.js'],
},
};
......@@ -12,14 +12,14 @@ class Adapter {
/**
* Test parsing the message based on the provided protocol schema
*
* The message must be successfully json decoded into an object
*
* 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
*
* 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) {
......@@ -81,11 +81,12 @@ class Adapter {
/**
* Call the GET /receive endpoint and process the messages with decode
*
* Returns the response
*
* Returns the response
* @param {boolean} is_retry
* @returns {object}
*/
poll() {
poll(is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -100,24 +101,40 @@ class Adapter {
if (validation.valid) {
const type = this.protocol.getType(parsed);
this.protocol.decode(type, parsed);
}
} else {
this.protocol.receivedInvalid(parsed, validation);
}
});
return response;
})
.catch((error) => {
return Promise.reject(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
*
* 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
* @param {string} topic
* @param {string} body
* @param {boolean} is_retry
* @returns
*/
publish(topic, body) {
publish(topic, body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -136,22 +153,36 @@ class Adapter {
return response;
})
.catch((error) => {
return Promise.reject(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
*
* 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
* @param {string} body
* @param {boolean} is_retry
* @returns
*/
broadcast(body) {
broadcast(body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -169,7 +200,20 @@ class Adapter {
return response;
})
.catch((error) => {
return Promise.reject(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);
});
}
}
......
......@@ -14,14 +14,14 @@ class Adapter {
/**
* Test parsing the message based on the provided protocol schema
*
* The message must be successfully json decoded into an object
*
* 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
*
* 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) {
......@@ -83,11 +83,12 @@ class Adapter {
/**
* Call the GET /receive endpoint and process the messages with decode
*
* Returns the response
*
* Returns the response
* @param {boolean} is_retry
* @returns {object}
*/
poll() {
poll(is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -102,24 +103,40 @@ class Adapter {
if (validation.valid) {
const type = this.protocol.getType(parsed);
this.protocol.decode(type, parsed);
}
} else {
this.protocol.receivedInvalid(parsed, validation);
}
});
return response;
})
.catch((error) => {
return Promise.reject(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
*
* 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
* @param {string} topic
* @param {string} body
* @param {boolean} is_retry
* @returns
*/
publish(topic, body) {
publish(topic, body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -138,22 +155,36 @@ class Adapter {
return response;
})
.catch((error) => {
return Promise.reject(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
*
* 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
* @param {string} body
* @param {boolean} is_retry
* @returns
*/
broadcast(body) {
broadcast(body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -171,7 +202,20 @@ class Adapter {
return response;
})
.catch((error) => {
return Promise.reject(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 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
*
* 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
*
* 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
* and call invoke internal functions and services as required
*/
class GenericProtocol {
constructor(schema, services) {
this.schema = schema;
this.validator = new Validator(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
* Validate that a message meets the reqiured schema
* @param {object} message
* @returns {object}
*/
validate(message) {
......@@ -40,43 +50,54 @@ class GenericProtocol {
this.schema.components.schemas.Message,
this.schema.components.schemas,
false,
true
false
);
}
/**
* Identify the payload type from the message content
* @param {object} message
* @param {object} message
* @returns {string}
*/
getType(message) {
try {
return message.payload.message_type;
} catch(error) {
} catch (error) {
return null;
}
}
/**
* Invoked on receiving a message from the backbone
*
* Whilst type isn't used in the generic stub it will
* 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
* @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
*
* 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
* @param {string} type
* @param {*} message
* @returns {object}
*/
encode(type, message) {
......@@ -84,4 +105,65 @@ class GenericProtocol {
}
}
export { GenericProtocol };
/**
* 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
*
* 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
*
* 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
* and call invoke internal functions and services as required
*/
class GenericProtocol {
constructor(schema, services) {
this.schema = schema;
this.validator = new Validator(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
* Validate that a message meets the reqiured schema
* @param {object} message
* @returns {object}
*/
validate(message) {
......@@ -42,43 +52,54 @@ class GenericProtocol {
this.schema.components.schemas.Message,
this.schema.components.schemas,
false,
true
false
);
}
/**
* Identify the payload type from the message content
* @param {object} message
* @param {object} message
* @returns {string}
*/
getType(message) {
try {
return message.payload.message_type;
} catch(error) {
} catch (error) {
return null;
}
}
/**
* Invoked on receiving a message from the backbone
*
* Whilst type isn't used in the generic stub it will
* 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
* @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
*
* 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
* @param {string} type
* @param {*} message
* @returns {object}
*/
encode(type, message) {
......@@ -86,4 +107,66 @@ class GenericProtocol {
}
}
/**
* 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;
......@@ -8,7 +8,6 @@ module.exports = {
'^.+\\.js$': 'babel-jest',
},
collectCoverage: true,
collectCoverageFrom: [
],
collectCoverageFrom: [],
testEnvironment: 'jsdom',
};
{
"name": "@noc-comms-backbone/backbone-adapter-javascript",
"version": "1.0.0",
"version": "0.1.0",
"private": true,
"contributors": [
{
......@@ -21,7 +21,7 @@
"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 --ext \".js\" --ignore-path .gitignore .",
"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",
......@@ -49,16 +49,16 @@
"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#packages",
"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.4.1",
"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.5.1",
"prettier": "^2.8.4",
"recursive-copy-cli": "^1.0.20",
"rollup": "^3.9.1"
}
......
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
......@@ -12,14 +12,14 @@ export class Adapter {
/**
* Test parsing the message based on the provided protocol schema
*
* The message must be successfully json decoded into an object
*
* 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
*
* 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) {
......@@ -81,11 +81,12 @@ export class Adapter {
/**
* Call the GET /receive endpoint and process the messages with decode
*
* Returns the response
*
* Returns the response
* @param {boolean} is_retry
* @returns {object}
*/
poll() {
poll(is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -100,24 +101,40 @@ export class Adapter {
if (validation.valid) {
const type = this.protocol.getType(parsed);
this.protocol.decode(type, parsed);
}
} else {
this.protocol.receivedInvalid(parsed, validation);
}
});
return response;
})
.catch((error) => {
return Promise.reject(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
*
* 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
* @param {string} topic
* @param {string} body
* @param {boolean} is_retry
* @returns
*/
publish(topic, body) {
publish(topic, body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -136,22 +153,36 @@ export class Adapter {
return response;
})
.catch((error) => {
return Promise.reject(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
*
* 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
* @param {string} body
* @param {boolean} is_retry
* @returns
*/
broadcast(body) {
broadcast(body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -169,7 +200,20 @@ export class Adapter {
return response;
})
.catch((error) => {
return Promise.reject(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
// 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
* 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
* @param {string} type
* @param {object} message
* @returns
*/
decode(type, message) {
switch (type) {
......@@ -39,13 +38,13 @@ export class ExampleClientProtocol extends GenericProtocol {
/**
* 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
*
* 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;
......@@ -53,8 +52,8 @@ export class ExampleClientProtocol extends GenericProtocol {
/**
* Act upon a received VehicleStatus message
* @param {object} message
* @returns {object}
* @param {object} message
* @returns {object}
*/
decodeVehicleStatus(message) {
const battery = message.battery_percentage;
......@@ -66,7 +65,7 @@ export class ExampleClientProtocol extends GenericProtocol {
/**
* Act upon a received VehicleMission message
* @param {object} message
* @param {object} message
* @returns {object}
*/
decodeVehicleMission(message) {
......@@ -76,7 +75,7 @@ export class ExampleClientProtocol extends GenericProtocol {
/**
* Transform local data into a VehicleStatus message
* @param {object} message
* @param {object} message
* @returns {object}
*/
encodeVehicleStatus(message) {
......
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
*
* 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
*
* 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
* 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;
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
* Validate that a message meets the reqiured schema
* @param {object} message
* @returns {object}
*/
validate(message) {
......@@ -40,46 +50,118 @@ export class GenericProtocol {
this.schema.components.schemas.Message,
this.schema.components.schemas,
false,
true
false
);
}
/**
* Identify the payload type from the message content
* @param {object} message
* @param {object} message
* @returns {string}
*/
getType(message) {
try {
return message.payload.message_type;
} catch(error) {
} catch (error) {
return null;
}
}
/**
* Invoked on receiving a message from the backbone
*
* Whilst type isn't used in the generic stub it will
* 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
* @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
*
* 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
* @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
*/
export 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
);
}
}
......@@ -3,17 +3,19 @@ const { When, Then } = require('@cucumber/cucumber');
const { fixtures } = require('../../fixtures/server');
When('the auth method is called', async function() {
When('the auth method is called', async function () {
await this.adapter.auth();
});
Then('the adapter credentials are populated', function() {
assert.equal(this.adapter.credentials.token, fixtures.get('response-valid-token').token);
Then('the adapter credentials are populated', function () {
assert.equal(
this.adapter.credentials.token,
fixtures.get('response-valid-token').token
);
});
Then('the adapter auth fails', function() {
this.adapter.auth()
.catch((error) => {
Then('the adapter auth fails', function () {
this.adapter.auth().catch((error) => {
assert.equal(error.response.status, 403);
});
});
\ No newline at end of file
});