Skip to content

Commit f31c183

Browse files
committed
HTTP asynchronous action implementation - closes #19 #8 #9
1 parent 83258de commit f31c183

8 files changed

Lines changed: 336 additions & 13 deletions

File tree

‎README.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,18 @@ const server = new ThingServer(thing);
106106
server.start(8080);
107107
```
108108

109+
For an asynchronous action, set `synchronous` to `false` in its Action
110+
Description. Invoking it returns an ActionStatus resource with `201 Created`;
111+
query that URL with `GET` to read its status, or use `DELETE` to cancel it.
112+
Action handlers receive an optional `AbortSignal` as their second argument so
113+
they can stop work when a request is cancelled:
114+
115+
```javascript
116+
thing.setActionHandler('fade', async (input, signal) => {
117+
// Check signal.aborted or listen for its "abort" event during long-running work.
118+
});
119+
```
120+
109121
## Development
110122

111123
### Type Checking

‎examples/lamp.js‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { setTimeout as delay } from 'node:timers/promises';
12
import Thing from '../src/thing.js';
23
import ThingServer from '../src/thing-server.js';
34

@@ -81,7 +82,7 @@ thing.setPropertyWriteHandler('level', async function (value) {
8182
return;
8283
});
8384

84-
thing.setActionHandler('fade', async function (input) {
85+
thing.setActionHandler('fade', async function (input, signal) {
8586
if (
8687
typeof input.level !== 'number' ||
8788
!Number.isFinite(input.level) ||
@@ -106,9 +107,7 @@ thing.setActionHandler('fade', async function (input) {
106107

107108
let elapsed = 0;
108109
while (elapsed < duration) {
109-
await new Promise((resolve) =>
110-
setTimeout(resolve, Math.min(100, duration - elapsed)),
111-
);
110+
await delay(Math.min(100, duration - elapsed), undefined, { signal });
112111
elapsed = Math.min(performance.now() - startTime, duration);
113112
currentLevelValue =
114113
startLevel + (targetLevel - startLevel) * (elapsed / duration);

‎src/action-affordance.js‎

Lines changed: 104 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
import InteractionAffordance from './interaction-affordance.js';
22
import ValidationError from './validation-error.js';
3+
import { randomUUID } from 'node:crypto';
34

45
/** @import {DataSchema, PartialActionDescription, ActionDescription, Form,
56
* ActionStatus} from "./types.js"
67
*/
78

9+
/** @typedef {{status: ActionStatus, controller: AbortController}} ActionRequest */
10+
811
/**
912
* Action Affordance
1013
*
@@ -37,6 +40,16 @@ class ActionAffordance extends InteractionAffordance {
3740
*/
3841
synchronous;
3942

43+
/**
44+
* @type {((value: any, signal?: AbortSignal) => Promise<any>)|undefined}
45+
*/
46+
invokeHandler;
47+
48+
/**
49+
* @type {Map<string, ActionRequest>}
50+
*/
51+
#actionRequests = new Map();
52+
4053
/**
4154
* Create a new Action.
4255
*
@@ -198,7 +211,7 @@ class ActionAffordance extends InteractionAffordance {
198211
/**
199212
* Set invoke handler function.
200213
*
201-
* @param {(value: any) => Promise<void>} handler An asynchronous function to action invocations.
214+
* @param {(value: any, signal?: AbortSignal) => Promise<any>} handler An asynchronous function to handle action invocations.
202215
*/
203216
setInvokeHandler(handler) {
204217
this.invokeHandler = handler;
@@ -212,7 +225,6 @@ class ActionAffordance extends InteractionAffordance {
212225
* @returns {Promise<any>} A Promise which resolves with the output of the
213226
* action (if any), conforming to the output data schema.
214227
*
215-
* Note: All actions are currently treated as synchronous.
216228
*/
217229
async invoke(input) {
218230
// TODO: Validate input against data schema
@@ -223,6 +235,96 @@ class ActionAffordance extends InteractionAffordance {
223235
return this.invokeHandler(input);
224236
}
225237

238+
/**
239+
* Start an asynchronous invocation and return its initial status.
240+
*
241+
* @param {any} input The action input.
242+
* @returns {ActionStatus & {href: string}} The initial status of the action request.
243+
*/
244+
invokeAsync(input) {
245+
if (!this.invokeHandler) {
246+
console.error(`No invoke handler set for action ${this.name}`);
247+
throw new Error('InternalError');
248+
}
249+
250+
const actionID = randomUUID();
251+
const status = /** @type {ActionStatus & {href: string}} */ ({
252+
status: 'pending',
253+
href: `/actions/${encodeURIComponent(this.name)}/${actionID}`,
254+
timeRequested: new Date().toISOString(),
255+
});
256+
const request = {
257+
status,
258+
controller: new AbortController(),
259+
};
260+
this.#actionRequests.set(actionID, request);
261+
262+
void Promise.resolve().then(async () => {
263+
if (this.#actionRequests.get(actionID) !== request) {
264+
return;
265+
}
266+
request.status.status = 'running';
267+
try {
268+
const output = await this.invokeHandler?.(
269+
input,
270+
request.controller.signal,
271+
);
272+
if (this.#actionRequests.get(actionID) !== request) {
273+
return;
274+
}
275+
request.status.status = 'completed';
276+
if (output !== undefined) {
277+
request.status.output = output;
278+
}
279+
} catch (error) {
280+
if (this.#actionRequests.get(actionID) !== request) {
281+
return;
282+
}
283+
request.status.status = 'failed';
284+
request.status.error = {
285+
title: 'Action failed',
286+
...(error instanceof Error ? { detail: error.message } : {}),
287+
};
288+
}
289+
request.status.timeEnded = new Date().toISOString();
290+
});
291+
292+
return { ...status };
293+
}
294+
295+
/**
296+
* Get the current status of an action request.
297+
*
298+
* @param {string} actionID The ID of the action request.
299+
* @returns {ActionStatus|undefined} The status, if the request exists.
300+
*/
301+
getActionStatus(actionID) {
302+
const request = this.#actionRequests.get(actionID);
303+
return request ? { ...request.status } : undefined;
304+
}
305+
306+
/**
307+
* Cancel an ongoing action request.
308+
*
309+
* @param {string} actionID The ID of the action request.
310+
* @returns {'cancelled'|'not-found'|'not-cancellable'} The cancellation result.
311+
*/
312+
cancelAction(actionID) {
313+
const request = this.#actionRequests.get(actionID);
314+
if (!request) {
315+
return 'not-found';
316+
}
317+
if (
318+
request.status.status === 'completed' ||
319+
request.status.status === 'failed'
320+
) {
321+
return 'not-cancellable';
322+
}
323+
request.controller.abort();
324+
this.#actionRequests.delete(actionID);
325+
return 'cancelled';
326+
}
327+
226328
/**
227329
* @returns {ActionDescription}
228330
*/

‎src/index.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@ export { default as Thing } from './thing.js';
22
export { default as ThingServer } from './thing-server.js';
33
export { default as InteractionAffordance } from './interaction-affordance.js';
44
export { default as PropertyAffordance } from './property-affordance.js';
5+
export { default as ActionAffordance } from './action-affordance.js';
56
export { default as ValidationError } from './validation-error.js';

‎src/thing-server.js‎

Lines changed: 78 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,15 +111,39 @@ class ThingServer {
111111
*
112112
* @param {Request} request
113113
* @param {Response} response
114-
*
115-
* Note: All actions are currently treated as synchronous.
116114
*/
117115
async (request, response) => {
118116
// Make sure name is a string since param can also be array
119117
const name = Array.isArray(request.params.name)
120118
? request.params.name[0]
121119
: request.params.name;
122120
const input = request.body;
121+
const action = this.thing.actions.get(name);
122+
if (action?.synchronous === false) {
123+
let actionStatus;
124+
try {
125+
actionStatus = this.thing.invokeActionAsync(name, input);
126+
} catch (error) {
127+
const errorMessage =
128+
error instanceof Error ? error.message : 'InternalError';
129+
switch (errorMessage) {
130+
case 'NotFoundError':
131+
response.status(404).send();
132+
break;
133+
case 'BadRequest':
134+
response.status(400).send();
135+
break;
136+
case 'InternalError':
137+
response.status(500).send();
138+
break;
139+
default:
140+
response.status(500).send();
141+
}
142+
return;
143+
}
144+
response.location(actionStatus.href).status(201).json(actionStatus);
145+
return;
146+
}
123147
let output;
124148
try {
125149
output = await this.thing.invokeAction(name, input);
@@ -148,6 +172,58 @@ class ThingServer {
148172
}
149173
},
150174
);
175+
176+
this.app.get(
177+
'/actions/:name/:actionID',
178+
/**
179+
* Query Action Status
180+
*
181+
* @param {Request} request
182+
* @param {Response} response
183+
*/
184+
(request, response) => {
185+
const name = Array.isArray(request.params.name)
186+
? request.params.name[0]
187+
: request.params.name;
188+
const actionID = Array.isArray(request.params.actionID)
189+
? request.params.actionID[0]
190+
: request.params.actionID;
191+
const actionStatus = this.thing.getActionStatus(name, actionID);
192+
if (!actionStatus) {
193+
response.status(404).send();
194+
return;
195+
}
196+
response.status(200).json(actionStatus);
197+
},
198+
);
199+
200+
this.app.delete(
201+
'/actions/:name/:actionID',
202+
/**
203+
* Cancel Action
204+
*
205+
* @param {Request} request
206+
* @param {Response} response
207+
*/
208+
(request, response) => {
209+
const name = Array.isArray(request.params.name)
210+
? request.params.name[0]
211+
: request.params.name;
212+
const actionID = Array.isArray(request.params.actionID)
213+
? request.params.actionID[0]
214+
: request.params.actionID;
215+
const result = this.thing.cancelAction(name, actionID);
216+
if (result === 'not-found') {
217+
response.status(404).send();
218+
return;
219+
}
220+
if (result === 'not-cancellable') {
221+
response.status(409).send();
222+
return;
223+
}
224+
response.status(204).send();
225+
},
226+
);
151227
}
152228

153229
/**

‎src/thing.js‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -390,7 +390,7 @@ class Thing {
390390
* Set Action Handler.
391391
*
392392
* @param {string} name The name of the action to handle.
393-
* @param {(value: any) => Promise<any>} handler An async function to handle action invocations.
393+
* @param {(value: any, signal?: AbortSignal) => Promise<any>} handler An async function to handle action invocations.
394394
*/
395395
setActionHandler(name, handler) {
396396
let action = this.actions.get(name);
@@ -441,7 +441,6 @@ class Thing {
441441
* @returns {Promise<any>} A Promise resolving to the output of the action,
442442
* conforming to the output data schema.
443443
*
444-
* Note: All actions are currently treated as synchronous.
445444
*/
446445
async invokeAction(name, input) {
447446
let action = this.actions.get(name);
@@ -451,6 +450,46 @@ class Thing {
451450
}
452451
return action.invoke(input);
453452
}
453+
454+
/**
455+
* Invoke an asynchronous action.
456+
*
457+
* @param {string} name The name of the action to invoke.
458+
* @param {any} input The action input.
459+
* @returns {ActionStatus & {href: string}} The initial status of the action request.
460+
*/
461+
invokeActionAsync(name, input) {
462+
let action = this.actions.get(name);
463+
if (!action) {
464+
console.error(`No action called ${name} could be found`);
465+
throw new Error('NotFoundError');
466+
}
467+
return action.invokeAsync(input);
468+
}
469+
470+
/**
471+
* Get the status of an action request.
472+
*
473+
* @param {string} name The name of the action.
474+
* @param {string} actionID The ID of the action request.
475+
* @returns {ActionStatus|undefined} The current status, if it exists.
476+
*/
477+
getActionStatus(name, actionID) {
478+
const action = this.actions.get(name);
479+
return action?.getActionStatus(actionID);
480+
}
481+
482+
/**
483+
* Cancel an action request.
484+
*
485+
* @param {string} name The name of the action.
486+
* @param {string} actionID The ID of the action request.
487+
* @returns {'cancelled'|'not-found'|'not-cancellable'} The cancellation result.
488+
*/
489+
cancelAction(name, actionID) {
490+
const action = this.actions.get(name);
491+
return action ? action.cancelAction(actionID) : 'not-found';
492+
}
454493
}
455494

456495
export default Thing;

‎src/types.js‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -194,10 +194,10 @@
194194
* Action Status
195195
*
196196
* @typedef {{
197-
* actionID: string,
198-
* state: 'pending'|'running'|'completed'|'failed',
197+
* status: 'pending'|'running'|'completed'|'failed',
198+
* href?: string,
199199
* output?: any,
200-
* error: ProblemDetails
200+
* error?: ProblemDetails,
201201
* timeRequested?: string,
202202
* timeEnded?: string
203203
* }} ActionStatus

0 commit comments

Comments
 (0)