Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(server) Add new /invoke/:template endpoint implementation #746

Merged
merged 18 commits into from
Sep 19, 2022
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10,817 changes: 4,070 additions & 6,747 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions packages/cicero-server/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ jspm_packages/
# Typescript v1 declaration files
typings/

# Optional VS Code debug folder
.vscode

# Optional npm cache directory
.npm

Expand Down
118 changes: 114 additions & 4 deletions packages/cicero-server/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

'use strict';

const fs = require('fs');

const app = require('express')();
const bodyParser = require('body-parser');
const Template = require('@accordproject/cicero-core').Template;
Expand Down Expand Up @@ -162,14 +164,122 @@ app.post('/draft/:template', async function (req, httpResponse, next) {
}
});

/**
* Handle POST requests to /invoke/:template
* The body of the POST should contain the params, data and state.
* The clause is created using the template and the data.
* The call returns the output of requested clause.
*
* Template
* ----------
* The template parameter is the name of a directory under CICERO_DIR that contains
* the template to use.
*
* Request
* ----------
* The POST body contains six properties:
* - sample or data
* - parameters
* - clause name
* - state
* - currentTime
* - utcOffset
*
* Response
* ----------
* Output of the given clause from contract
*
*/
app.post('/invoke/:template', async function(req, httpResponse, next) {

try {
const options = req.body.options ? req.body.options : {};
const currentTime = req.body.currentTime ? req.body.currentTime : new Date().toISOString();
const utcOffset = req.body.utcOffset ? req.body.utcOffset : new Date().getTimezoneOffset();
mttrbrts marked this conversation as resolved.
Show resolved Hide resolved

const engine = new Engine();
const clause = await initTemplateInstance(req, options);
let clauseName;
let params;
let state;

if (req.body.clauseName) {
clauseName = req.body.clauseName.toString();
} else {
throw new Error('Missing clause name in /invoke body');
mttrbrts marked this conversation as resolved.
Show resolved Hide resolved
}

if (req.body.params) {
params = req.body.params;
} else {
throw new Error('Missing params in /invoke body');
mttrbrts marked this conversation as resolved.
Show resolved Hide resolved
}

if (req.body.sample) {
clause.parse(req.body.sample.toString(), currentTime, utcOffset);
} else if (req.body.data) {
clause.setData(req.body.data);
} else {
throw new Error('Missing sample or data in /invoke body');
mttrbrts marked this conversation as resolved.
Show resolved Hide resolved
}

if(req.body.state) {
state = req.body.state;
} else {
const initResult = await engine.init(clause, currentTime, utcOffset);
state = initResult.state;
}

const result = await engine.invoke(clause, clauseName, params, state, currentTime, utcOffset);
httpResponse.status(200).send(result);
} catch(err) {
httpResponse.status(400).send({error: err.message});
mttrbrts marked this conversation as resolved.
Show resolved Hide resolved
}
});

/**
* Helper function to determine whether the template is archived or not
* @param {string} templateName Name of the template
* @returns {boolean} True if the given template is a .cta file
*/
function isTemplateArchive(templateName) {
try {
fs.lstatSync(`${process.env.CICERO_DIR}/${templateName}.cta`).isFile();
return true;
} catch(err) {
return false;
}
}

/**
* Helper function to load a template from disk
* @param {string} templateName Name of the template
* @param {object} options an optional set of options
* @returns {object} The template instance object.
*/
async function loadTemplate(templateName, options) {
mttrbrts marked this conversation as resolved.
Show resolved Hide resolved
if (isTemplateArchive(templateName)) {
const buffer = fs.readFileSync(`${process.env.CICERO_DIR}/${templateName}.cta`);
return await Template.fromArchive(buffer, options);
} else {
return await Template.fromDirectory(`${process.env.CICERO_DIR}/${templateName}`, options);
}
}

/**
* Helper function to initialise the template.
* @param {req} req The request passed in from endpoint.
* @returns {object} The template instance object.
* @param {object} options an optional set of options
* @returns {object} The clause instance object.
*/
async function initTemplateInstance(req) {
const template = await Template.fromDirectory(`${process.env.CICERO_DIR}/${req.params.template}`);
return new Clause(template);
async function initTemplateInstance(req, options) {
if (process.env.CICERO_URL) {
const template = await Template.fromUrl(`${process.env.CICERO_URL}/${req.params.template}.cta`);
return new Clause(template);
} else {
const template = await loadTemplate(req.params.template, options);
return new Clause(template);
}
}

const server = app.listen(app.get('port'), function () {
Expand Down
2 changes: 1 addition & 1 deletion packages/cicero-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
"eslint": "8.2.0",
"jsdoc": "^3.6.10",
"license-check": "1.1.5",
"mocha": "8.3.2",
"mocha": "^8.4.0",
"mockery": "2.0.0",
"nyc": "15.1.0",
"supertest": "3.0.0"
Expand Down
55 changes: 55 additions & 0 deletions packages/cicero-server/test/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ let server;
chai.should();

const body = require('./data/latedeliveryandpenalty/request.json');
const params = require('./data/latedeliveryandpenalty/params.json');
const state = require('./data/latedeliveryandpenalty/state.json');
const triggerData = require('./data/latedeliveryandpenalty/data.json');
const responseBody = {
Expand Down Expand Up @@ -255,6 +256,60 @@ describe('cicero-server', () => {
});
});

it('/should invoke a clause from contract', async () => {
return request.post('/invoke/latedeliveryandpenalty')
.send({
data: parseBody,
state: state,
params: params,
clauseName: 'latedeliveryandpenalty'
})
.expect(200);
});

it('/should fail to invoke without clause name', async () => {
return request.post('/invoke/latedeliveryandpenalty')
.send({
data: parseBody,
state: state,
params: params,
})
.expect(400)
.expect('Content-Type',/json/)
.then(response => {
response.body.error.should.equal('Missing clause name in /invoke body');
});
});

it('/should fail to invoke without sample or data', async () => {
return request.post('/invoke/latedeliveryandpenalty')
.send({
state: state,
params: params,
clauseName: 'latedeliveryandpenalty'
})
.expect(400)
.expect('Content-Type',/json/)
.then(response => {
response.body.error.should.equal('Missing sample or data in /invoke body');
});
});

it('/should fail to invoke without params', async () => {
return request.post('/invoke/latedeliveryandpenalty')
.send({
data: parseBody,
state: state,
clauseName: 'latedeliveryandpenalty'
})
.expect(400)
.expect('Content-Type',/json/)
.then(response => {
response.body.error.should.equal('Missing params in /invoke body');
});
});


after(() => {
server.close();
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"request" : {
"$class": "org.accordproject.latedeliveryandpenalty.LateDeliveryAndPenaltyRequest",
"forceMajeure": false,
"agreedDelivery": "2017-12-17T03:24:00Z",
"deliveredAt": null,
"goodsValue": 200.00
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{ "request" :
{
"forceMajeure": false,
"agreedDelivery": "December 17, 2017 03:24:00",
"deliveredAt": null,
"goodsValue": 200.00
}
}