Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions src/action-affordance.js
Original file line number Diff line number Diff line change
Expand Up @@ -211,14 +211,14 @@ class ActionAffordance extends InteractionAffordance {
/**
* Set invoke handler function.
*
* @param {(value: any, signal?: AbortSignal) => Promise<any>} handler An asynchronous function to handle action invocations.
* @param {(input: any, signal?: AbortSignal) => Promise<any>} handler An asynchronous function to handle action invocations.
*/
setInvokeHandler(handler) {
this.invokeHandler = handler;
}

/**
* Invoke the action.
* Invoke a synchronous action.
*
* @param {any} input The input to the action, conforming to the input data
* schema.
Expand All @@ -236,7 +236,7 @@ class ActionAffordance extends InteractionAffordance {
}

/**
* Start an asynchronous invocation and return its initial status.
* Invoke an asynchronous action.
*
* @param {any} input The action input.
* @returns {ActionStatus & {href: string}} The initial status of the action request.
Expand Down Expand Up @@ -303,6 +303,21 @@ class ActionAffordance extends InteractionAffordance {
return request ? { ...request.status } : undefined;
}

/**
* Get the statuses of all action requests, most recent first.
*
* @returns {Array<ActionStatus>} The current statuses of the action requests.
*/
queryAllActions() {
return [...this.#actionRequests.values()]
.reverse()
.map(({ status }) => ({ ...status }))
.sort(
(a, b) =>
Date.parse(b.timeRequested ?? '') - Date.parse(a.timeRequested ?? ''),
);
}

/**
* Cancel an ongoing action request.
*
Expand Down
32 changes: 28 additions & 4 deletions src/thing-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,23 @@ class ThingServer {
},
);

this.app.get(
'/actions',
/**
* Query All Actions
*
* @param {Request} _request
* @param {Response} response
*/
(_request, response) => {
if (this.thing.actions.size === 0) {
response.status(404).send();
return;
}
response.status(200).json(this.thing.queryAllActions());
},
);

this.app.get(
'/actions/:name/:actionID',
/**
Expand All @@ -192,12 +209,19 @@ class ThingServer {
const actionID = Array.isArray(request.params.actionID)
? request.params.actionID[0]
: request.params.actionID;
const actionStatus = this.thing.queryAction(name, actionID);
if (!actionStatus) {
response.status(404).send();
try {
const actionStatus = this.thing.queryAction(name, actionID);
response.status(200).json(actionStatus);
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : 'InternalError';
if (errorMessage === 'NotFoundError') {
response.status(404).send();
} else {
response.status(500).send();
}
return;
}
response.status(200).json(actionStatus);
},
);

Expand Down
24 changes: 22 additions & 2 deletions src/thing.js
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ class Thing {
// If actions are defined then add an actions member
if (Object.keys(actions).length > 0) {
thingDescription.actions = actions;
thingDescription.forms = [{ href: 'actions', op: 'queryallactions' }];
}
return thingDescription;
}
Expand Down Expand Up @@ -472,11 +473,30 @@ class Thing {
*
* @param {string} name The name of the action.
* @param {string} actionID The ID of the action request.
* @returns {ActionStatus|undefined} The current status, if it exists.
* @returns {ActionStatus} The current status.
* @throws {Error} Throws NotFoundError if the action or request does not exist.
*/
queryAction(name, actionID) {
const action = this.actions.get(name);
return action?.queryAction(actionID);
const status = action?.queryAction(actionID);
if (!status) {
throw new Error('NotFoundError');
}
return status;
}

/**
* Get the statuses of all action requests, grouped by action name.
*
* @returns {Record<string, Array<ActionStatus>>} The current statuses.
*/
queryAllActions() {
/** @type {Record<string, Array<ActionStatus>>} */
const statuses = {};
for (const [name, action] of this.actions) {
statuses[name] = action.queryAllActions();
}
return statuses;
}

/**
Expand Down
2 changes: 2 additions & 0 deletions src/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@
* properties?: Record<string, PropertyDescription>,
* actions?: Record<string, ActionDescription>,
* events?: Record<string, EventDescription>,
* forms?: Array<Form>,
* security: string|Array<string>,
* securityDefinitions: string|Record<string, object>
* }} ThingDescription
Expand All @@ -185,6 +186,7 @@
* properties?: Record<string, PartialPropertyDescription>,
* actions?: Record<string, PartialActionDescription>,
* events?: Record<string, PartialEventDescription>,
* forms?: Array<Form>,
* security?: string|Array<string>,
* securityDefinitions?: string|Record<string, object>
* }} PartialThingDescription
Expand Down
62 changes: 62 additions & 0 deletions test/thing-server.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,68 @@ describe('ThingServer', () => {
});
});

describe('GET /actions', () => {
it('should return action request statuses grouped newest first', async () => {
const firstInvocation = await fetch(baseUrl + '/actions/fade', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ level: 25 }),
});
const firstStatus = await firstInvocation.json();

const secondInvocation = await fetch(baseUrl + '/actions/fade', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ level: 50 }),
});
const secondStatus = await secondInvocation.json();

const response = await fetch(baseUrl + '/actions');
assert.equal(response.status, 200);
const statuses = await response.json();
assert.deepEqual(Object.keys(statuses).sort(), [
'blink',
'cancel',
'fade',
'fail',
]);
assert.deepEqual(statuses.blink, []);
assert.deepEqual(statuses.cancel, []);
assert.deepEqual(statuses.fail, []);
assert.deepEqual(
statuses.fade.map(({ href }) => href),
[secondStatus.href, firstStatus.href],
);
assert.ok(
Date.parse(statuses.fade[0].timeRequested) >=
Date.parse(statuses.fade[1].timeRequested),
);
});

it('should return 404 when the Thing has no actions', async () => {
const emptyThingServer = new ThingServer(
new Thing({ title: 'No Actions' }),
);
await new Promise((resolve) => {
emptyThingServer.server = emptyThingServer.app.listen(0, resolve);
});

try {
const port = emptyThingServer.server.address().port;
const emptyBaseUrl = `http://localhost:${port}`;
const tdResponse = await fetch(emptyBaseUrl + '/');
const td = await tdResponse.json();
assert.equal(td.actions, undefined);
assert.equal(td.forms, undefined);

const response = await fetch(emptyBaseUrl + '/actions');
assert.equal(response.status, 404);
} finally {
emptyThingServer.stop();
}
});
});

describe('PUT /properties/:name', () => {
it('should update the property value when the property exists', async () => {
const response = await fetch(baseUrl + '/properties/on', {
Expand Down
126 changes: 126 additions & 0 deletions test/thing.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ describe('Thing', () => {
},
},
},
forms: [{ href: 'actions', op: 'queryallactions' }],
});
});
});
Expand Down Expand Up @@ -153,4 +154,129 @@ describe('Thing', () => {
);
});
});

describe('invokeActionAsync', () => {
it('should return the initial action status', () => {
const thing = new Thing(partialTD);
thing.setActionInvokeHandler('blink', async (input) => input.count);

const input = { count: 3 };
const status = thing.invokeActionAsync('blink', input);

assert.equal(status.status, 'pending');
assert.match(status.href, /^\/actions\/blink\/[0-9a-f-]+$/);
assert.equal(typeof status.timeRequested, 'string');
});

it('should throw when the action does not exist', () => {
const thing = new Thing(partialTD);

assert.throws(
() => thing.invokeActionAsync('missing', {}),
/NotFoundError/,
);
});
});

describe('queryAction', () => {
it('should throw when the action does not exist', () => {
const thing = new Thing(partialTD);

assert.throws(
() => thing.queryAction('missing', 'request-id'),
/NotFoundError/,
);
});

it('should throw when the action request does not exist', () => {
const thing = new Thing(partialTD);

assert.throws(
() => thing.queryAction('blink', 'missing-request'),
/NotFoundError/,
);
});
});

describe('queryAllActions', () => {
it('should return request statuses grouped by action, newest first', () => {
const thing = new Thing({
...partialTD,
actions: {
...partialTD.actions,
fade: {},
unused: {},
},
});
thing.setActionInvokeHandler('blink', async (input) => input);
thing.setActionInvokeHandler('fade', async (input) => input);

const blinkStatus = thing.invokeActionAsync('blink', { count: 1 });
const firstFadeStatus = thing.invokeActionAsync('fade', { count: 2 });
const secondFadeStatus = thing.invokeActionAsync('fade', { count: 3 });

const statuses = thing.queryAllActions();
assert.deepEqual(
statuses.blink.map(({ href }) => href),
[blinkStatus.href],
);
assert.deepEqual(
statuses.fade.map(({ href }) => href),
[secondFadeStatus.href, firstFadeStatus.href],
);
assert.deepEqual(statuses.unused, []);
assert.ok(
Date.parse(statuses.fade[0].timeRequested) >=
Date.parse(statuses.fade[1].timeRequested),
);
});
});

describe('cancelAction', () => {
it('should abort and remove the action request', async () => {
const thing = new Thing(partialTD);
let actionSignal;
let resolveStarted;
const started = new Promise((resolve) => {
resolveStarted = resolve;
});
thing.setActionInvokeHandler(
'blink',
async (_input, signal) =>
new Promise((resolve) => {
actionSignal = signal;
resolveStarted();
signal.addEventListener('abort', resolve, { once: true });
}),
);

const status = thing.invokeActionAsync('blink', {});
await started;
thing.cancelAction('blink', status.href.split('/').at(-1));

assert.equal(actionSignal.aborted, true);
assert.throws(
() => thing.queryAction('blink', status.href.split('/').at(-1)),
/NotFoundError/,
);
});

it('should throw when the action does not exist', () => {
const thing = new Thing(partialTD);

assert.throws(
() => thing.cancelAction('missing', 'request-id'),
/NotFoundError/,
);
});

it('should throw when the action request does not exist', () => {
const thing = new Thing(partialTD);

assert.throws(
() => thing.cancelAction('blink', 'missing-request'),
/NotFoundError/,
);
});
});
});
Loading