Unverified Commit b9dfcc49 authored by Dan Jones's avatar Dan Jones
Browse files

fix: linting

parent a8e98ce4
......@@ -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' }],
},
};
###
# 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',
};
......@@ -4,4 +4,4 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
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,27 +18,27 @@ 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**
......@@ -54,15 +54,15 @@ yarn add git+https://git.noc.ac.uk/communications-backbone-system/backbone-adapt
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
{
......@@ -74,44 +74,44 @@ This will be provided by the backbone operator or requested via the API.
}
```
### Topics
### 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
## 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.
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,12 +81,12 @@ class Adapter {
/**
* Call the GET /receive endpoint and process the messages with decode
*
*
* Returns the response
* @param {boolean} is_retry
* @param {boolean} is_retry
* @returns {object}
*/
poll(is_retry=false) {
poll(is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -109,11 +109,13 @@ class Adapter {
})
.catch((error) => {
let retry = false;
switch(error.response.status) {
case 403: {
this.credentials = null;
retry = true;
} break;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
......@@ -124,15 +126,15 @@ class Adapter {
}
/**
* 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
* @param {string} topic
* @param {string} body
* @param {boolean} is_retry
* @returns
* @returns
*/
publish(topic, body, is_retry=false) {
publish(topic, body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -152,11 +154,13 @@ class Adapter {
})
.catch((error) => {
let retry = false;
switch(error.response.status) {
case 403: {
this.credentials = null;
retry = true;
} break;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
......@@ -168,17 +172,17 @@ class Adapter {
/**
* 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 {string} body
* @param {string} body
* @param {boolean} is_retry
* @returns
* @returns
*/
broadcast(body, is_retry=false) {
broadcast(body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -197,11 +201,13 @@ class Adapter {
})
.catch((error) => {
let retry = false;
switch(error.response.status) {
case 403: {
this.credentials = null;
retry = true;
} break;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
......
......@@ -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,12 +83,12 @@ class Adapter {
/**
* Call the GET /receive endpoint and process the messages with decode
*
*
* Returns the response
* @param {boolean} is_retry
* @param {boolean} is_retry
* @returns {object}
*/
poll(is_retry=false) {
poll(is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -111,11 +111,13 @@ class Adapter {
})
.catch((error) => {
let retry = false;
switch(error.response.status) {
case 403: {
this.credentials = null;
retry = true;
} break;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
......@@ -126,15 +128,15 @@ class Adapter {
}
/**
* 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
* @param {string} topic
* @param {string} body
* @param {boolean} is_retry
* @returns
* @returns
*/
publish(topic, body, is_retry=false) {
publish(topic, body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -154,11 +156,13 @@ class Adapter {
})
.catch((error) => {
let retry = false;
switch(error.response.status) {
case 403: {
this.credentials = null;
retry = true;
} break;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
......@@ -170,17 +174,17 @@ class Adapter {
/**
* 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 {string} body
* @param {string} body
* @param {boolean} is_retry
* @returns
* @returns
*/
broadcast(body, is_retry=false) {
broadcast(body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -199,11 +203,13 @@ class Adapter {
})
.catch((error) => {
let retry = false;
switch(error.response.status) {
case 403: {
this.credentials = null;
retry = true;
} break;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
......
......@@ -3,25 +3,25 @@ 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) {
......@@ -32,7 +32,7 @@ class GenericProtocol {
/**
* Create a Validator from the provided JSONSchema
* @param {object} schema
* @param {object} schema
* @returns {Validator}
*/
createValidator(schema) {
......@@ -40,8 +40,8 @@ class GenericProtocol {
}
/**
* 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) {
......@@ -56,35 +56,34 @@ class GenericProtocol {
/**
* 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
* Invoked on receiving an invalid message from the backbone
*
* @param {object} message
* @param {object} validation
* @returns {*}
*/
......@@ -94,11 +93,11 @@ class GenericProtocol {
/**
* 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) {
......@@ -106,12 +105,11 @@ 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
*
* This provides the same as above but loads a version of the
* SoAR message protocol
*/
class GenericSoarProtocol extends GenericProtocol {
constructor(schema, services) {
......@@ -120,42 +118,41 @@ class GenericSoarProtocol extends GenericProtocol {
/**
* 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
*
* 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);
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
* Load schema from gitlab by tag/branch/commitref
* @param {string} version
* @returns {object}
* @returns {object}
*/
loadSchema(version) {
this.axios = axios;
let repository = "https://git.noc.ac.uk/communications-backbone-system/backbone-message-format";
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) => {
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
* Validate that a message meets the reqiured schema
* @param {object} message
* @returns {object}
*/
validate(message) {
......
......@@ -5,25 +5,25 @@ 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) {
......@@ -34,7 +34,7 @@ class GenericProtocol {
/**
* Create a Validator from the provided JSONSchema
* @param {object} schema
* @param {object} schema
* @returns {Validator}
*/
createValidator(schema) {
......@@ -42,8 +42,8 @@ class GenericProtocol {
}
/**
* 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) {
......@@ -58,35 +58,34 @@ class GenericProtocol {
/**
* 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
* Invoked on receiving an invalid message from the backbone
*
* @param {object} message
* @param {object} validation
* @returns {*}
*/
......@@ -96,11 +95,11 @@ class GenericProtocol {
/**
* 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) {
......@@ -108,12 +107,11 @@ 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
*
* This provides the same as above but loads a version of the
* SoAR message protocol
*/
class GenericSoarProtocol extends GenericProtocol {
constructor(schema, services) {
......@@ -122,42 +120,41 @@ class GenericSoarProtocol extends GenericProtocol {
/**
* 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
*
* 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);
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
* Load schema from gitlab by tag/branch/commitref
* @param {string} version
* @returns {object}
* @returns {object}
*/
loadSchema(version) {
this.axios = axios;
let repository = "https://git.noc.ac.uk/communications-backbone-system/backbone-message-format";
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) => {
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
* Validate that a message meets the reqiured schema
* @param {object} message
* @returns {object}
*/
validate(message) {
......
......@@ -8,7 +8,6 @@ module.exports = {
'^.+\\.js$': 'babel-jest',
},
collectCoverage: true,
collectCoverageFrom: [
],
collectCoverageFrom: [],
testEnvironment: 'jsdom',
};
......@@ -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",
......@@ -51,14 +51,14 @@
"babel-jest": "^27.4.4",
"backbone-adapter-testsuite": "git+https://git.noc.ac.uk/communications-backbone-system/backbone-adapter-testsuite.git#dev",
"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"
}
......
......@@ -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,12 +81,12 @@ export class Adapter {
/**
* Call the GET /receive endpoint and process the messages with decode
*
*
* Returns the response
* @param {boolean} is_retry
* @param {boolean} is_retry
* @returns {object}
*/
poll(is_retry=false) {
poll(is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -109,11 +109,13 @@ export class Adapter {
})
.catch((error) => {
let retry = false;
switch(error.response.status) {
case 403: {
this.credentials = null;
retry = true;
} break;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
......@@ -124,15 +126,15 @@ export class Adapter {
}
/**
* 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
* @param {string} topic
* @param {string} body
* @param {boolean} is_retry
* @returns
* @returns
*/
publish(topic, body, is_retry=false) {
publish(topic, body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -152,11 +154,13 @@ export class Adapter {
})
.catch((error) => {
let retry = false;
switch(error.response.status) {
case 403: {
this.credentials = null;
retry = true;
} break;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
......@@ -168,17 +172,17 @@ export class Adapter {
/**
* 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 {string} body
* @param {string} body
* @param {boolean} is_retry
* @returns
* @returns
*/
broadcast(body, is_retry=false) {
broadcast(body, is_retry = false) {
let adapterConfig = this.config;
return this.getAuthorizationHeader()
.then((headers) => {
......@@ -197,11 +201,13 @@ export class Adapter {
})
.catch((error) => {
let retry = false;
switch(error.response.status) {
case 403: {
this.credentials = null;
retry = true;
} break;
switch (error.response.status) {
case 403:
{
this.credentials = null;
retry = true;
}
break;
case 503: {
retry = true;
}
......
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) {
......
......@@ -3,25 +3,25 @@ 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) {
......@@ -32,7 +32,7 @@ export class GenericProtocol {
/**
* Create a Validator from the provided JSONSchema
* @param {object} schema
* @param {object} schema
* @returns {Validator}
*/
createValidator(schema) {
......@@ -40,8 +40,8 @@ export class GenericProtocol {
}
/**
* 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) {
......@@ -56,35 +56,34 @@ export class GenericProtocol {
/**
* 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
* Invoked on receiving an invalid message from the backbone
*
* @param {object} message
* @param {object} validation
* @returns {*}
*/
......@@ -94,11 +93,11 @@ export class GenericProtocol {
/**
* 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) {
......@@ -106,12 +105,11 @@ export 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
*
* This provides the same as above but loads a version of the
* SoAR message protocol
*/
export class GenericSoarProtocol extends GenericProtocol {
constructor(schema, services) {
......@@ -120,42 +118,41 @@ export class GenericSoarProtocol extends GenericProtocol {
/**
* 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
*
* 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);
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
* Load schema from gitlab by tag/branch/commitref
* @param {string} version
* @returns {object}
* @returns {object}
*/
loadSchema(version) {
this.axios = axios;
let repository = "https://git.noc.ac.uk/communications-backbone-system/backbone-message-format";
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 this.axios.get(url).then((response) => {
this.schema = response.data;
return response.data;
});
}
/**
* 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) {
......@@ -167,4 +164,4 @@ export class GenericSoarProtocol extends GenericProtocol {
false
);
}
}
\ No newline at end of file
}
......@@ -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
});
const assert = require('assert');
const { Before } = require('@cucumber/cucumber');
const axios = require("axios");
const MockAdapter = require("axios-mock-adapter");
const axios = require('axios');
const MockAdapter = require('axios-mock-adapter');
// This sets the mock adapter on the default instance
const mockAxios = new MockAdapter(axios);
......@@ -17,13 +17,13 @@ const { GenericProtocol } = require('../../../dist/protocol');
const { Adapter } = require('../../../dist/adapter');
/**
* Use assert.CallTracker to track internal method calls
* Instead of adding trackers to each method, create a
* Use assert.CallTracker to track internal method calls
* Instead of adding trackers to each method, create a
* single tracked stub function and then use the parameters
* to record what is being tracked.
* to record what is being tracked.
*/
const tracker = new assert.CallTracker();
const trackedFunction = function(method, params) {
const trackedFunction = function (method, params) {
// do nothing;
};
const recorder = tracker.calls(trackedFunction);
......@@ -51,7 +51,7 @@ class TrackedAdapter extends Adapter {
}
getTrackedCalls(method) {
let calls = this.tracker.getCalls(this.recorder);
let methodCalls = calls.filter(call => call.arguments[0] === method);
let methodCalls = calls.filter((call) => call.arguments[0] === method);
return methodCalls;
}
resetTracker() {
......@@ -65,20 +65,20 @@ class TrackedGenericProtocol extends GenericProtocol {
this.tracker = tracker;
}
encode(type, message) {
this.recorder('encode', {type, message});
return super.encode(type, message)
this.recorder('encode', { type, message });
return super.encode(type, message);
}
decode(type, message) {
this.recorder('decode', {type, message});
return super.decode(type, message)
this.recorder('decode', { type, message });
return super.decode(type, message);
}
validate(message) {
this.recorder('validate', {message});
this.recorder('validate', { message });
return super.validate(message);
}
getTrackedCalls(method) {
let calls = this.tracker.getCalls(this.recorder);
let methodCalls = calls.filter(call => call.arguments[0] === method);
let methodCalls = calls.filter((call) => call.arguments[0] === method);
return methodCalls;
}
resetTracker() {
......@@ -86,35 +86,45 @@ class TrackedGenericProtocol extends GenericProtocol {
}
}
Before(function() {
Before(function () {
this.api = mockValidConfig.api;
this.schema = mockSchema;
this.tracker = tracker;
this.recorder = recorder;
let services = {
recorder,
tracker
tracker,
};
this.classes = {
TrackedAdapter,
TrackedGenericProtocol,
};
this.callCounts = {};
this.protocol = new this.classes.TrackedGenericProtocol(this.schema, services);
this.protocol = new this.classes.TrackedGenericProtocol(
this.schema,
services
);
this.protocol.setupCallTracking(this.recorder, this.tracker);
this.protocol.resetTracker();
this.mockAxios = mockAxios;
this.mockAxios.reset();
this.mockAxios.resetHistory();
this.mockAxios.onGet(
`${mockValidConfig.api}/token`,
{ params: { client_id: mockValidConfig.client_id, secret: mockValidConfig.secret } }
).reply(200, fixtures.get('response-valid-token'));
this.mockAxios
.onGet(`${mockValidConfig.api}/token`, {
params: {
client_id: mockValidConfig.client_id,
secret: mockValidConfig.secret,
},
})
.reply(200, fixtures.get('response-valid-token'));
this.mockAxios.onGet(
`${mockInvalidConfig.api}/token`,
{ params: { client_id: mockInvalidConfig.client_id, secret: mockInvalidConfig.secret } }
).reply(403, fixtures.get('response-denied-token'));
});
\ No newline at end of file
this.mockAxios
.onGet(`${mockInvalidConfig.api}/token`, {
params: {
client_id: mockInvalidConfig.client_id,
secret: mockInvalidConfig.secret,
},
})
.reply(403, fixtures.get('response-denied-token'));
});
......@@ -5,24 +5,25 @@ const { fixtures } = require('../../fixtures/server');
const mockValidConfig = fixtures.get('config-valid');
When('a mock notify API response is configured to return success', function() {
When('a mock notify API response is configured to return success', function () {
const response = {};
this.mockAxios.onPost(
`${mockValidConfig.api}/notify`,
).reply(200, response);
this.mockAxios.onPost(`${mockValidConfig.api}/notify`).reply(200, response);
});
When('a mock notify API response is configured to return a {int} error', function(statusCode) {
const statusMessages = {
403: 'Token expired',
503: 'Service unavailable'
};
this.mockAxios.onPost(
`${mockValidConfig.api}/notify`,
).reply(statusCode, { message: statusMessages[statusCode] })
});
When('the broadcast method is called', function() {
When(
'a mock notify API response is configured to return a {int} error',
function (statusCode) {
const statusMessages = {
403: 'Token expired',
503: 'Service unavailable',
};
this.mockAxios
.onPost(`${mockValidConfig.api}/notify`)
.reply(statusCode, { message: statusMessages[statusCode] });
}
);
When('the broadcast method is called', function () {
const message = fixtures.get('message-vehicle-status');
this.message = message;
const body = JSON.stringify(message);
......@@ -30,7 +31,7 @@ When('the broadcast method is called', function() {
this.callCounts.broadcast = this.adapter.getTrackedCalls('broadcast').length;
});
When('the broadcast method is called with is_retry on', function() {
When('the broadcast method is called with is_retry on', function () {
const message = fixtures.get('message-vehicle-status');
this.message = message;
const body = JSON.stringify(message);
......@@ -38,13 +39,13 @@ When('the broadcast method is called with is_retry on', function() {
this.callCounts.broadcast = this.adapter.getTrackedCalls('broadcast').length;
});
Then('the broadcast method was called with is_retry on', function() {
Then('the broadcast method was called with is_retry on', function () {
let broadcastCalls = this.adapter.getTrackedCalls('broadcast');
let lastCall = broadcastCalls[broadcastCalls.length-1];
let lastCall = broadcastCalls[broadcastCalls.length - 1];
assert.ok(lastCall.arguments[1].is_retry);
});
Then('the broadcast method is not called again', function() {
Then('the broadcast method is not called again', function () {
let newBroadcastCallCount = this.adapter.getTrackedCalls('broadcast').length;
assert.equal(this.callCounts.broadcast, newBroadcastCallCount);
});
\ No newline at end of file
});
......@@ -8,60 +8,71 @@ const mockInvalidConfig = fixtures.get('config-invalid');
const mockSchema = require('../../mock/swagger.json');
// const { Adapter } = require('../../../dist/adapter');
Given('valid config', function() {
this.config = mockValidConfig
Given('valid config', function () {
this.config = mockValidConfig;
});
Given('invalid config', function() {
Given('invalid config', function () {
this.schema = mockSchema;
this.config = mockInvalidConfig;
});
When('the adapter instance is created', function() {
When('the adapter instance is created', function () {
this.adapter = new this.classes.TrackedAdapter(this.protocol, this.config);
this.adapter.setupCallTracking(this.recorder, this.tracker);
});
Then('a successful response is returned with status {int}', function(expectedStatus) {
this.call
.then(response => {
assert.equal(response.status, expectedStatus);
});
});
Then(
'a successful response is returned with status {int}',
function (expectedStatus) {
this.call.then((response) => {
assert.equal(response.status, expectedStatus);
});
}
);
Then('an error response is returned with status {int}', function(expectedStatus) {
this.call
.catch((error) => {
assert.equal(error.response.status, expectedStatus);
});
});
Then(
'an error response is returned with status {int}',
function (expectedStatus) {
this.call.catch((error) => {
assert.equal(error.response.status, expectedStatus);
});
}
);
Then('the credentials are deleted', function() {
Then('the credentials are deleted', function () {
assert.equal(this.adapter.credentials, null);
});
Then('the credentials are not deleted', function() {
Then('the credentials are not deleted', function () {
assert.notEqual(this.adapter.credentials, null);
});
When('the {string} method call counts are checked', function(method) {
When('the {string} method call counts are checked', function (method) {
let newCallCount = this.adapter.getTrackedCalls(method).length;
this.callCounts[method] = newCallCount;
});
Then('the {string} method is not called again', function(method) {
Then('the {string} method is not called again', function (method) {
let newCallCount = this.adapter.getTrackedCalls(method).length;
assert.equal(this.callCounts[method], newCallCount);
});
Then('the total number of calls to {string} was {int}', function(method, expectedCallCount) {
let callCount = this.adapter.getTrackedCalls(method).length;
assert.equal(callCount, expectedCallCount);
});
Then('the total number of {string} requests to {string} was {int}', function(method, endpoint, expectedCallCount) {
let url = `${this.api}${endpoint}`;
let requestHistory = this.mockAxios.history[method.toLowerCase()].filter((request) => request.url === url);
assert.equal(requestHistory.length, expectedCallCount);
});
Then(
'the total number of calls to {string} was {int}',
function (method, expectedCallCount) {
let callCount = this.adapter.getTrackedCalls(method).length;
assert.equal(callCount, expectedCallCount);
}
);
Then(
'the total number of {string} requests to {string} was {int}',
function (method, endpoint, expectedCallCount) {
let url = `${this.api}${endpoint}`;
let requestHistory = this.mockAxios.history[method.toLowerCase()].filter(
(request) => request.url === url
);
assert.equal(requestHistory.length, expectedCallCount);
}
);
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