diff --git a/src/action-affordance.js b/src/action-affordance.js index 7cb3225..5402cb1 100644 --- a/src/action-affordance.js +++ b/src/action-affordance.js @@ -211,14 +211,14 @@ class ActionAffordance extends InteractionAffordance { /** * Set invoke handler function. * - * @param {(value: any, signal?: AbortSignal) => Promise} handler An asynchronous function to handle action invocations. + * @param {(input: any, signal?: AbortSignal) => Promise} 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. @@ -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. @@ -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} 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. * diff --git a/src/thing-server.js b/src/thing-server.js index 70f8a8b..f621e99 100644 --- a/src/thing-server.js +++ b/src/thing-server.js @@ -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', /** @@ -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); }, ); diff --git a/src/thing.js b/src/thing.js index 59028b1..08c5943 100644 --- a/src/thing.js +++ b/src/thing.js @@ -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; } @@ -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>} The current statuses. + */ + queryAllActions() { + /** @type {Record>} */ + const statuses = {}; + for (const [name, action] of this.actions) { + statuses[name] = action.queryAllActions(); + } + return statuses; } /** diff --git a/src/types.js b/src/types.js index 15f3dfa..6457562 100644 --- a/src/types.js +++ b/src/types.js @@ -164,6 +164,7 @@ * properties?: Record, * actions?: Record, * events?: Record, + * forms?: Array
, * security: string|Array, * securityDefinitions: string|Record * }} ThingDescription @@ -185,6 +186,7 @@ * properties?: Record, * actions?: Record, * events?: Record, + * forms?: Array, * security?: string|Array, * securityDefinitions?: string|Record * }} PartialThingDescription diff --git a/test/thing-server.test.js b/test/thing-server.test.js index 1f51b6c..b480a02 100644 --- a/test/thing-server.test.js +++ b/test/thing-server.test.js @@ -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', { diff --git a/test/thing.test.js b/test/thing.test.js index 454292d..0161edd 100644 --- a/test/thing.test.js +++ b/test/thing.test.js @@ -70,6 +70,7 @@ describe('Thing', () => { }, }, }, + forms: [{ href: 'actions', op: 'queryallactions' }], }); }); }); @@ -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/, + ); + }); + }); });