From 8395192569c38f2b2be1574952b12f2fb41958cd Mon Sep 17 00:00:00 2001 From: Ben Francis Date: Thu, 3 Dec 2026 22:06:11 +0000 Subject: [PATCH] HTTP subscribeevent operation - closes #10 and #11 --- README.md | 30 ++++++++---- src/action-affordance.js | 4 +- src/event-affordance.js | 81 +++++++++++++++++++++++++++++++ src/property-affordance.js | 4 +- src/thing-server.js | 50 +++++++++++++++++++ src/thing.js | 99 +++++++++++++++++++++++++++++++++++++- test/thing-server.test.js | 58 ++++++++++++++++++++++ test/thing.test.js | 46 ++++++++++++++++++ 8 files changed, 358 insertions(+), 14 deletions(-) create mode 100644 src/event-affordance.js diff --git a/README.md b/README.md index ae15f62..aaccfeb 100644 --- a/README.md +++ b/README.md @@ -85,7 +85,7 @@ const thing = new Thing(partialTD); ### Properties -Set property handlers: +Set property read and write handlers for each property defined in the Thing Description: ```javascript thing.setPropertyReadHandler('on', async function () { @@ -97,21 +97,27 @@ thing.setPropertyReadHandler('level', async function () { }); thing.setPropertyWriteHandler('on', async function (value) { - // Update the lamp state. + // Update the lamp on/off state. +}); + +thing.setPropertyWriteHandler('level', async function (value) { + // Update the lamp level. }); ``` -Property changes are emitted automatically when an observable property is written via its write handler, but for other property changes you should explicitly call `emitPropertyChange()` to notify active SSE observers. You can provide the new value directly, or -omit it to read the current value using the property's read handler: +Property changes are emitted automatically when an observable property is written via its write handler, but for other property changes you should explicitly call `emitPropertyChange()` to notify active SSE observers: ```javascript await thing.emitPropertyChange('on', true); + +If the value argument is omitted then the current value is read using the read handler and that value is emitted. + await thing.emitPropertyChange('on'); ``` ### Actions -Set action handlers: +Set action invoke handlers for each action defined in the Thing Description: ```javascript thing.setActionInvokeHandler('fade', async (input, signal) => { @@ -123,12 +129,18 @@ For synchronous actions set `synchronous` to `true` in the Thing Description. Th 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 +### Events -Expose to the Thing to the Web of Things by starting its web server, providing -a port number as an argument: +Call `emitEvent()` whenever an event occurs for one of the +event affordances defined in the Thing Description: + +```javascript +thing.emitEvent('overheated', 90); +``` + +### Thing Server -Create and start a Thing server using your Thing. +Expose to the Thing to the Web of Things by instantiating a Thing server for the Thing, then calling start() to start its web server (providing a port number as an argument): ```javascript const server = new ThingServer(thing); diff --git a/src/action-affordance.js b/src/action-affordance.js index 4246026..fd7d3df 100644 --- a/src/action-affordance.js +++ b/src/action-affordance.js @@ -62,7 +62,7 @@ class ActionAffordance extends InteractionAffordance { outputSchema; /** - * Create a new Action. + * Create a new Action Affordance. * * @param {string} name The name of the ActionAffordance from its * key in an actions Map. @@ -409,7 +409,7 @@ class ActionAffordance extends InteractionAffordance { /** @type {Array
} */ metadata.forms = []; const invokeActionForm = { - href: `actions/${this.name}`, + href: `actions/${encodeURIComponent(this.name)}`, op: 'invokeaction', }; metadata.forms.push(invokeActionForm); diff --git a/src/event-affordance.js b/src/event-affordance.js new file mode 100644 index 0000000..3329226 --- /dev/null +++ b/src/event-affordance.js @@ -0,0 +1,81 @@ +import InteractionAffordance from './interaction-affordance.js'; +import ValidationError from './validation-error.js'; +import DataSchema from './data-schema.js'; + +/** @import {DataSchemaDescription, EventDescription, PartialEventDescription} from "./types.js" */ + +/** + * Event Affordance + * + * Represents an EventAffordance from the W3C WoT Thing Description 1.1 + * specification https://www.w3.org/TR/wot-thing-description/#eventaffordance + */ +class EventAffordance extends InteractionAffordance { + /** + * Raw data schema description. + * + * @type {DataSchemaDescription|undefined} + */ + data; + + /** + * Parsed data schema used for validation. + * + * @type {DataSchema} + */ + dataSchema; + + /** + * Create a new Event Affordance. + * + * @param {string} name The name of the EventAffordance from its key in an + * events Map. + * @param {PartialEventDescription} metadata Metadata describing an + * EventAffordance from a partial Thing Description. + */ + constructor(name, metadata) { + super(name, metadata); + + // Parse data member + this.#parseDataMember(metadata.data); + this.dataSchema = new DataSchema(this.data, `events.${this.name}.data`); + } + + /** + * Parse data member. + * + * @param {DataSchemaDescription|undefined} data + */ + #parseDataMember(data) { + if (!(data === undefined || typeof data === 'object')) { + throw new ValidationError([ + { + field: `events.${this.name}.data`, + description: 'data member is not valid', + }, + ]); + } + this.data = data; + } + + /** + * @returns {EventDescription} + */ + getMetadata() { + const metadata = /** @type {EventDescription} */ (super.getMetadata()); + if (this.data !== undefined) { + metadata.data = this.data; + } + metadata.forms = [ + { + href: `events/${encodeURIComponent(this.name)}`, + op: ['subscribeevent', 'unsubscribeevent'], + contentType: 'application/json', + subprotocol: 'sse', + }, + ]; + return metadata; + } +} + +export default EventAffordance; diff --git a/src/property-affordance.js b/src/property-affordance.js index 69bdb61..ce57f2a 100644 --- a/src/property-affordance.js +++ b/src/property-affordance.js @@ -71,7 +71,7 @@ class PropertyAffordance extends InteractionAffordance { valueSchema; /** - * Create a new Property. + * Create a new Property Affordance. * * @param {string} name The name of the PropertyAffordance from its * key in a properties Map. @@ -359,7 +359,7 @@ class PropertyAffordance extends InteractionAffordance { if (this.writeOnly !== true && this.observable === true) { metadata.forms.push({ - href: `properties/${this.name}`, + href: `properties/${encodeURIComponent(this.name)}`, op: ['observeproperty', 'unobserveproperty'], contentType: 'application/json', subprotocol: 'sse', diff --git a/src/thing-server.js b/src/thing-server.js index 8198939..86bf5b7 100644 --- a/src/thing-server.js +++ b/src/thing-server.js @@ -225,6 +225,56 @@ class ThingServer { }, ); + this.app.get( + '/events/:name', + /** + * Subscribe to an Event + * + * @param {Request} request + * @param {Response} response + */ + (request, response) => { + const name = Array.isArray(request.params.name) + ? request.params.name[0] + : request.params.name; + if (!this.thing.events.has(name)) { + response.status(404).send(); + return; + } + if (!request.accepts('text/event-stream')) { + response.status(406).send(); + return; + } + + response.status(200); + response.set({ + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive', + }); + + /** + * @param {string} eventName The name of the Event that occurred. + * @param {any} data The event data. + * @param {string} eventId Event ID in date-time format. + */ + const onEventEmitted = (eventName, data, eventId) => { + if (eventName !== name || response.writableEnded) { + return; + } + const dataLine = + data === undefined ? '' : `data: ${JSON.stringify(data)}\n`; + response.write(`event: ${name}\n${dataLine}id: ${eventId}\n\n`); + }; + + this.thing.on('eventEmitted', onEventEmitted); + response.on('close', () => { + this.thing.off('eventEmitted', onEventEmitted); + }); + response.flushHeaders(); + }, + ); + this.app.put( '/properties', /** diff --git a/src/thing.js b/src/thing.js index 18bd17e..f2ed9f6 100644 --- a/src/thing.js +++ b/src/thing.js @@ -1,10 +1,11 @@ import ValidationError from './validation-error.js'; import PropertyAffordance from './property-affordance.js'; import ActionAffordance from './action-affordance.js'; +import EventAffordance from './event-affordance.js'; import { EventEmitter } from 'node:events'; /** @import {SecurityScheme, PartialPropertyDescription, PropertyDescription, * PartialActionDescription, ActionDescription, PartialThingDescription, - * ThingDescription, ActionStatus} from "./types.js" + * PartialEventDescription, EventDescription, ThingDescription, ActionStatus} from "./types.js" */ /** @@ -38,8 +39,15 @@ class Thing extends EventEmitter { */ actions = new Map(); + /** + * @type {Map} + */ + events = new Map(); + #lastPropertyChangeTimestamp = 0; + #lastEventTimestamp = 0; + /** * @type {Record} */ @@ -102,6 +110,13 @@ class Thing extends EventEmitter { validationError.merge(error); } + // Parse events member + try { + this.#parseEventsMember(partialTD.events); + } catch (error) { + validationError.merge(error); + } + // Hard code the nosec security scheme for now this.securityDefinitions = { nosec_sc: { @@ -284,6 +299,31 @@ class Thing extends EventEmitter { } } + /** + * Parse the events member of a Thing Description. + * + * @param {Record|undefined} eventDescriptions Map of event + * descriptions provided in a partial TD, indexed by event name. + */ + #parseEventsMember(eventDescriptions) { + if (!eventDescriptions) { + return; + } + + if (typeof eventDescriptions !== 'object') { + throw new ValidationError([ + { + field: 'events', + description: 'events member is not an object', + }, + ]); + } + + for (const eventName in eventDescriptions) { + this.addEvent(eventName, eventDescriptions[eventName]); + } + } + /** * Add a Property. * @@ -308,6 +348,18 @@ class Thing extends EventEmitter { this.actions.set(actionName, action); } + /** + * Add an Event. + * + * @param {string} eventName The name of the event to add. + * @param {PartialEventDescription} eventDescription A partial EventAffordance + * description from a Thing Description. + */ + addEvent(eventName, eventDescription) { + const event = new EventAffordance(eventName, eventDescription); + this.events.set(eventName, event); + } + /** * Get Thing Description. * @@ -337,6 +389,17 @@ class Thing extends EventEmitter { } } + /** + * @type {Record} + */ + let events = {}; + for (const eventName of this.events.keys()) { + const event = this.events.get(eventName); + if (event) { + events[eventName] = event.getMetadata(); + } + } + /** @type {ThingDescription} */ const thingDescription = { '@context': this.context, @@ -385,6 +448,9 @@ class Thing extends EventEmitter { op: 'queryallactions', }); } + if (Object.keys(events).length > 0) { + thingDescription.events = events; + } return thingDescription; } @@ -503,6 +569,37 @@ class Thing extends EventEmitter { ); } + /** + * Emit an Event to subscribers. + * + * @param {string} name The name of the EventAffordance that occurred. + * @param {any} [data] The event data. + * @throws {Error} Throws NotFoundError for an unknown event or InternalError + * when data does not conform to the event's data schema. + */ + emitEvent(name, data) { + const event = this.events.get(name); + if (!event) { + console.error(`No event called ${name} could be found`); + throw new Error('NotFoundError'); + } + if (!event.dataSchema.validate(data)) { + console.error(`Tried to emit invalid data for event ${name}`); + throw new Error('InternalError'); + } + + this.#lastEventTimestamp = Math.max( + Date.now(), + this.#lastEventTimestamp + 1, + ); + this.emit( + 'eventEmitted', + name, + data, + new Date(this.#lastEventTimestamp).toISOString(), + ); + } + /** * Read All Properties. * diff --git a/test/thing-server.test.js b/test/thing-server.test.js index 05475fa..b0486ba 100644 --- a/test/thing-server.test.js +++ b/test/thing-server.test.js @@ -36,6 +36,13 @@ describe('ThingServer', () => { synchronous: false, }, }, + events: { + overheated: { + title: 'Overheated', + data: { type: 'number' }, + }, + reset: {}, + }, }; let server; @@ -120,6 +127,57 @@ describe('ThingServer', () => { }); }); + describe('GET /events/:name (SSE)', () => { + it('should stream named event data as JSON and stop on disconnect', async () => { + const response = await fetch(baseUrl + '/events/overheated', { + headers: { Accept: 'text/event-stream' }, + }); + + assert.equal(response.status, 200); + assert.match(response.headers.get('content-type'), /^text\/event-stream/); + assert.equal(response.headers.get('cache-control'), 'no-cache'); + + const reader = response.body.getReader(); + const nextEvent = reader.read(); + server.thing.emitEvent('overheated', 90); + const { value, done } = await nextEvent; + assert.equal(done, false); + assert.match( + new TextDecoder().decode(value), + /^event: overheated\ndata: 90\nid: .+\n\n$/, + ); + await reader.cancel(); + }); + + it('should omit data for events without a payload', async () => { + const response = await fetch(baseUrl + '/events/reset', { + headers: { Accept: 'text/event-stream' }, + }); + const reader = response.body.getReader(); + const nextEvent = reader.read(); + server.thing.emitEvent('reset'); + const { value } = await nextEvent; + + assert.match( + new TextDecoder().decode(value), + /^event: reset\nid: .+\n\n$/, + ); + await reader.cancel(); + }); + + it('should reject unknown events and requests without SSE Accept', async () => { + const unknownResponse = await fetch(baseUrl + '/events/missing', { + headers: { Accept: 'text/event-stream' }, + }); + const unsupportedResponse = await fetch(baseUrl + '/events/overheated', { + headers: { Accept: 'application/json' }, + }); + + assert.equal(unknownResponse.status, 404); + assert.equal(unsupportedResponse.status, 406); + }); + }); + describe('GET /properties', () => { it('should return all readable property values', async () => { const response = await fetch(baseUrl + '/properties'); diff --git a/test/thing.test.js b/test/thing.test.js index debcb81..2c72aef 100644 --- a/test/thing.test.js +++ b/test/thing.test.js @@ -24,6 +24,12 @@ describe('Thing', () => { }, }, }, + events: { + overheated: { + title: 'Overheated', + data: { type: 'number' }, + }, + }, }; describe('constructor', () => { @@ -78,6 +84,20 @@ describe('Thing', () => { }, }, }, + events: { + overheated: { + title: 'Overheated', + data: { type: 'number' }, + forms: [ + { + href: 'events/overheated', + op: ['subscribeevent', 'unsubscribeevent'], + contentType: 'application/json', + subprotocol: 'sse', + }, + ], + }, + }, forms: [ { href: 'properties', @@ -298,6 +318,32 @@ describe('Thing', () => { }); }); + describe('emitEvent', () => { + it('should emit event data with a unique timestamp identifier', () => { + const thing = new Thing(partialTD); + const emitted = []; + thing.on('eventEmitted', (...args) => emitted.push(args)); + + thing.emitEvent('overheated', 90); + thing.emitEvent('overheated', 91); + + assert.equal(emitted[0][0], 'overheated'); + assert.equal(emitted[0][1], 90); + assert.match(emitted[0][2], /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/); + assert.notEqual(emitted[0][2], emitted[1][2]); + }); + + it('should reject unknown events and data that does not match the schema', () => { + const thing = new Thing(partialTD); + + assert.throws(() => thing.emitEvent('missing', 90), /NotFoundError/); + assert.throws( + () => thing.emitEvent('overheated', 'hot'), + /InternalError/, + ); + }); + }); + describe('writeMultipleProperties', () => { it('should write all requested writable properties', async () => { const thing = new Thing({