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
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ Instantiate a Web Thing from the partial Thing Description:
const thing = new Thing(partialTD);
```

### Properties

Set property handlers:

```javascript
Expand All @@ -95,6 +97,22 @@ thing.setPropertyReadHandler('level', async function () {
});
```

### Actions

Set action handlers:

```javascript
thing.setActionInvokeHandler('fade', async (input, signal) => {
// Check signal.aborted or listen for its "abort" event during long-running work.
});
```

For synchronous actions set `synchronous` to `true` in the Thing Description. The invoke handler should accept the action input as an argument and return a promise which resolves with the action output.

For asynchronous actions set `synchronous` to `false` in the Thing Description. The invoke handler should accept the action input as its first argument, and an optional `AbortSignal` as a second argument so the action can be stopped if the request is cancelled.

### Thing Server

Expose to the Thing to the Web of Things by starting its web server, providing
a port number as an argument:

Expand Down
7 changes: 3 additions & 4 deletions examples/lamp.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { setTimeout as delay } from 'node:timers/promises';
import Thing from '../src/thing.js';
import ThingServer from '../src/thing-server.js';

Expand Down Expand Up @@ -81,7 +82,7 @@ thing.setPropertyWriteHandler('level', async function (value) {
return;
});

thing.setActionHandler('fade', async function (input) {
thing.setActionInvokeHandler('fade', async function (input, signal) {
if (
typeof input.level !== 'number' ||
!Number.isFinite(input.level) ||
Expand All @@ -106,9 +107,7 @@ thing.setActionHandler('fade', async function (input) {

let elapsed = 0;
while (elapsed < duration) {
await new Promise((resolve) =>
setTimeout(resolve, Math.min(100, duration - elapsed)),
);
await delay(Math.min(100, duration - elapsed), undefined, { signal });
elapsed = Math.min(performance.now() - startTime, duration);
currentLevelValue =
startLevel + (targetLevel - startLevel) * (elapsed / duration);
Expand Down
106 changes: 104 additions & 2 deletions src/action-affordance.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import InteractionAffordance from './interaction-affordance.js';
import ValidationError from './validation-error.js';
import { randomUUID } from 'node:crypto';

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

/** @typedef {{status: ActionStatus, controller: AbortController}} ActionRequest */

/**
* Action Affordance
*
Expand Down Expand Up @@ -37,6 +40,16 @@ class ActionAffordance extends InteractionAffordance {
*/
synchronous;

/**
* @type {((value: any, signal?: AbortSignal) => Promise<any>)|undefined}
*/
invokeHandler;

/**
* @type {Map<string, ActionRequest>}
*/
#actionRequests = new Map();

/**
* Create a new Action.
*
Expand Down Expand Up @@ -198,7 +211,7 @@ class ActionAffordance extends InteractionAffordance {
/**
* Set invoke handler function.
*
* @param {(value: any) => Promise<void>} handler An asynchronous function to action invocations.
* @param {(value: any, signal?: AbortSignal) => Promise<any>} handler An asynchronous function to handle action invocations.
*/
setInvokeHandler(handler) {
this.invokeHandler = handler;
Expand All @@ -212,7 +225,6 @@ class ActionAffordance extends InteractionAffordance {
* @returns {Promise<any>} A Promise which resolves with the output of the
* action (if any), conforming to the output data schema.
*
* Note: All actions are currently treated as synchronous.
*/
async invoke(input) {
// TODO: Validate input against data schema
Expand All @@ -223,6 +235,96 @@ class ActionAffordance extends InteractionAffordance {
return this.invokeHandler(input);
}

/**
* Start an asynchronous invocation and return its initial status.
*
* @param {any} input The action input.
* @returns {ActionStatus & {href: string}} The initial status of the action request.
*/
invokeAsync(input) {
if (!this.invokeHandler) {
console.error(`No invoke handler set for action ${this.name}`);
throw new Error('InternalError');
}

const actionID = randomUUID();
const status = /** @type {ActionStatus & {href: string}} */ ({
status: 'pending',
href: `/actions/${encodeURIComponent(this.name)}/${actionID}`,
timeRequested: new Date().toISOString(),
});
const request = {
status,
controller: new AbortController(),
};
this.#actionRequests.set(actionID, request);

void Promise.resolve().then(async () => {
if (this.#actionRequests.get(actionID) !== request) {
return;
}
request.status.status = 'running';
try {
const output = await this.invokeHandler?.(
input,
request.controller.signal,
);
if (this.#actionRequests.get(actionID) !== request) {
return;
}
request.status.status = 'completed';
if (output !== undefined) {
request.status.output = output;
}
} catch (error) {
if (this.#actionRequests.get(actionID) !== request) {
return;
}
request.status.status = 'failed';
request.status.error = {
title: 'Action failed',
...(error instanceof Error ? { detail: error.message } : {}),
};
}
request.status.timeEnded = new Date().toISOString();
});

return { ...status };
}

/**
* Get the current status of an action request.
*
* @param {string} actionID The ID of the action request.
* @returns {ActionStatus|undefined} The status, if the request exists.
*/
queryAction(actionID) {
const request = this.#actionRequests.get(actionID);
return request ? { ...request.status } : undefined;
}

/**
* Cancel an ongoing action request.
*
* @param {string} actionID The ID of the action request.
* @throws {Error} Throws NotFoundError if the request does not exist,
* or ConflictError if it has already completed or failed.
*/
cancelAction(actionID) {
const request = this.#actionRequests.get(actionID);
if (!request) {
throw new Error('NotFoundError');
}
if (
request.status.status === 'completed' ||
request.status.status === 'failed'
) {
throw new Error('ConflictError');
}
request.controller.abort();
this.#actionRequests.delete(actionID);
}

/**
* @returns {ActionDescription}
*/
Expand Down
3 changes: 0 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
export { default as Thing } from './thing.js';
export { default as ThingServer } from './thing-server.js';
export { default as InteractionAffordance } from './interaction-affordance.js';
export { default as PropertyAffordance } from './property-affordance.js';
export { default as ValidationError } from './validation-error.js';
116 changes: 102 additions & 14 deletions src/thing-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,41 +111,129 @@ class ThingServer {
*
* @param {Request} request
* @param {Response} response
*
* Note: All actions are currently treated as synchronous.
*/
async (request, response) => {
// Make sure name is a string since param can also be array
const name = Array.isArray(request.params.name)
? request.params.name[0]
: request.params.name;
const input = request.body;
let output;
const action = this.thing.actions.get(name);

if (action?.synchronous === true) {
// Synchronous action
let output;
try {
output = await this.thing.invokeAction(name, input);
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : 'InternalError';
switch (errorMessage) {
case 'NotFoundError':
response.status(404).send();
break;
case 'BadRequest':
response.status(400).send();
break;
case 'InternalError':
response.status(500).send();
break;
default:
response.status(500).send();
}
return;
}
if (output != undefined) {
response.status(200).send(output);
} else {
response.status(204).send();
}
} else {
// Asynchronous action
let actionStatus;
try {
actionStatus = this.thing.invokeActionAsync(name, input);
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : 'InternalError';
switch (errorMessage) {
case 'NotFoundError':
response.status(404).send();
break;
case 'BadRequest':
response.status(400).send();
break;
case 'InternalError':
response.status(500).send();
break;
default:
response.status(500).send();
}
return;
}
response.location(actionStatus.href).status(201).json(actionStatus);
return;
}
},
);

this.app.get(
'/actions/:name/:actionID',
/**
* Query Action Status
*
* @param {Request} request
* @param {Response} response
*/
(request, response) => {
const name = Array.isArray(request.params.name)
? request.params.name[0]
: request.params.name;
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();
return;
}
response.status(200).json(actionStatus);
},
);

this.app.delete(
'/actions/:name/:actionID',
/**
* Cancel Action
*
* @param {Request} request
* @param {Response} response
*/
(request, response) => {
const name = Array.isArray(request.params.name)
? request.params.name[0]
: request.params.name;
const actionID = Array.isArray(request.params.actionID)
? request.params.actionID[0]
: request.params.actionID;
try {
output = await this.thing.invokeAction(name, input);
this.thing.cancelAction(name, actionID);
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : 'InternalError';
switch (errorMessage) {
case 'NotFoundError':
response.status(404).send();
break;
case 'BadRequest':
response.status(400).send();
break;
case 'InternalError':
response.status(500).send();
case 'ConflictError':
response.status(409).send();
break;
default:
response.status(500).send();
}
return;
}
if (output != undefined) {
response.status(200).send(output);
} else {
response.status(204).send();
}
response.status(204).send();
},
);
}
Expand Down
Loading
Loading