diff --git a/README.md b/README.md index 20e45f9..ae15f62 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,14 @@ thing.setPropertyWriteHandler('on', async function (value) { }); ``` +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: + +```javascript +await thing.emitPropertyChange('on', true); +await thing.emitPropertyChange('on'); +``` + ### Actions Set action handlers: diff --git a/examples/lamp.js b/examples/lamp.js index e93845c..1c8f336 100644 --- a/examples/lamp.js +++ b/examples/lamp.js @@ -13,6 +13,7 @@ const partialTD = { type: 'boolean', title: 'On/Off', description: 'Whether the lamp is turned on', + observable: true, }, level: { type: 'number', @@ -21,13 +22,13 @@ const partialTD = { unit: 'percent', minimum: 0, maximum: 100, + observable: true, }, }, actions: { fade: { title: 'Fade', description: 'Fade the lamp to a given level', - synchronous: false, input: { type: 'object', properties: { diff --git a/src/property-affordance.js b/src/property-affordance.js index c68cb3e..69bdb61 100644 --- a/src/property-affordance.js +++ b/src/property-affordance.js @@ -39,14 +39,14 @@ class PropertyAffordance extends InteractionAffordance { enum; /** - * @type {boolean|undefined} + * @type {boolean} */ - readOnly; + readOnly = false; /** - * @type {boolean|undefined} + * @type {boolean} */ - writeOnly; + writeOnly = false; /** * @type {string|undefined} @@ -61,9 +61,9 @@ class PropertyAffordance extends InteractionAffordance { /* End of property data schema */ /** - * @type {boolean|undefined} + * @type {boolean} */ - observeable; + observable = false; /** * @type {DataSchema} @@ -97,6 +97,13 @@ class PropertyAffordance extends InteractionAffordance { validationError.merge(error); } + // Parse observable member + try { + this.#parseObservableMember(metadata.observable); + } catch (error) { + validationError.merge(error); + } + // Check that readOnly and writeOnly are not both set if (this.readOnly && this.writeOnly) { let readWriteError = new ValidationError([ @@ -176,6 +183,30 @@ class PropertyAffordance extends InteractionAffordance { } } + /** + * Parse observable member. + * + * @param {boolean|undefined} observable + */ + #parseObservableMember(observable) { + if (!(observable === undefined || typeof observable == 'boolean')) { + throw new ValidationError([ + { + field: `properties.${this.name}.observable`, + description: 'observable member is not a boolean', + }, + ]); + } + + // If undefined then default to false + if (observable === undefined) { + this.observable = false; + // Otherwise set the provided value + } else { + this.observable = observable; + } + } + /** * Parse type member. * @@ -308,6 +339,11 @@ class PropertyAffordance extends InteractionAffordance { metadata.writeOnly = true; } + // Only set observable member if explicitly set to true since false is default + if (this.observable === true) { + metadata.observable = true; + } + // Generate Form const propertyForm = { href: `properties/${this.name}`, @@ -321,6 +357,15 @@ class PropertyAffordance extends InteractionAffordance { } metadata.forms.push(propertyForm); + if (this.writeOnly !== true && this.observable === true) { + metadata.forms.push({ + href: `properties/${this.name}`, + op: ['observeproperty', 'unobserveproperty'], + contentType: 'application/json', + subprotocol: 'sse', + }); + } + return metadata; } } diff --git a/src/thing-server.js b/src/thing-server.js index 93f33a0..9075833 100644 --- a/src/thing-server.js +++ b/src/thing-server.js @@ -34,7 +34,7 @@ class ThingServer { this.app.get( '/properties/:name', /** - * Read Property + * Read or Observe Property * * @param {Request} request * @param {Response} response @@ -44,6 +44,53 @@ class ThingServer { const name = Array.isArray(request.params.name) ? request.params.name[0] : request.params.name; + + const requestedEventStream = + request.accepts('text/event-stream') && + !request.accepts('application/json'); + + if (requestedEventStream) { + const property = this.thing.properties.get(name); + if (!property) { + response.status(404).send(); + return; + } else if ( + property.writeOnly === true || + property.observable !== true + ) { + response.status(406).send(); + return; + } + + response.status(200); + response.set({ + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive', + }); + + /** + * @param {string} changedName The name of the Property that changed. + * @param {any} value The new value of the changed Property. + * @param {string} eventId Event ID in date-time format. + */ + const onPropertyChanged = (changedName, value, eventId) => { + if (changedName !== name || response.writableEnded) { + return; + } + response.write( + `event: ${name}\ndata: ${JSON.stringify(value)}\nid: ${eventId}\n\n`, + ); + }; + + this.thing.on('propertyChanged', onPropertyChanged); + response.on('close', () => { + this.thing.off('propertyChanged', onPropertyChanged); + }); + response.flushHeaders(); + return; + } + let value; try { value = await this.thing.readProperty(name); diff --git a/src/thing.js b/src/thing.js index cf3690f..58fc351 100644 --- a/src/thing.js +++ b/src/thing.js @@ -1,6 +1,7 @@ import ValidationError from './validation-error.js'; import PropertyAffordance from './property-affordance.js'; import ActionAffordance from './action-affordance.js'; +import { EventEmitter } from 'node:events'; /** @import {SecurityScheme, PartialPropertyDescription, PropertyDescription, * PartialActionDescription, ActionDescription, PartialThingDescription, * ThingDescription, ActionStatus} from "./types.js" @@ -14,7 +15,7 @@ import ActionAffordance from './action-affordance.js'; * Implements a Thing from the W3C WoT Thing Description 1.1 specification. * https://www.w3.org/TR/wot-thing-description/#thing */ -class Thing { +class Thing extends EventEmitter { DEFAULT_CONTEXT = 'https://www.w3.org/2022/wot/td/v1.1'; /** @@ -37,6 +38,8 @@ class Thing { */ actions = new Map(); + #lastPropertyChangeTimestamp = 0; + /** * @type {Record} */ @@ -59,6 +62,8 @@ class Thing { * to which Forms will be added. */ constructor(partialTD) { + super(); + // Create an empty validation error to collect errors during parsing. let validationError = new ValidationError([]); @@ -442,7 +447,47 @@ class Thing { console.error(`No property called ${name} could be found`); throw new Error('NotFoundError'); } - return property.write(value); + const result = await property.write(value); + if (property.observable === true && property.writeOnly !== true) { + await this.emitPropertyChange(name, value); + } + return result; + } + + /** + * Emit a property change to observers. + * + * @param {string} name The name of the property that changed. + * @param {any} [value] The new property value. If omitted, it is read from the property handler. + * @returns {Promise} A Promise that resolves once the change has been emitted. + */ + async emitPropertyChange(name, value) { + const property = this.properties.get(name); + if (!property) { + console.error(`No property called ${name} could be found`); + throw new Error('NotFoundError'); + } + if (property.writeOnly === true || property.observable !== true) { + console.error( + 'Tried to emit a property change for a non-observable or write-only property', + ); + throw new Error('InternalError'); + } + const data = value === undefined ? await property.read() : value; + if (!property.valueSchema.validate(data)) { + console.error('Tried to emit a property change with an invalid value'); + throw new Error('InternalError'); + } + this.#lastPropertyChangeTimestamp = Math.max( + Date.now(), + this.#lastPropertyChangeTimestamp + 1, + ); + this.emit( + 'propertyChanged', + name, + data, + new Date(this.#lastPropertyChangeTimestamp).toISOString(), + ); } /** diff --git a/src/types.js b/src/types.js index bdde562..3866f8f 100644 --- a/src/types.js +++ b/src/types.js @@ -84,7 +84,7 @@ * * @typedef {InteractionDescription & DataSchemaDescription & { * forms: Array
, - * observeable?: boolean|undefined + * observable?: boolean|undefined * }} PropertyDescription */ @@ -95,7 +95,7 @@ * * @typedef {InteractionDescription & DataSchemaDescription & { * forms?: Array, - * observeable?: boolean|undefined + * observable?: boolean|undefined * }} PartialPropertyDescription */ diff --git a/test/property-affordance.test.js b/test/property-affordance.test.js index 0441c9b..ab28e6f 100644 --- a/test/property-affordance.test.js +++ b/test/property-affordance.test.js @@ -28,6 +28,7 @@ describe('PropertyAffordance', () => { assert.equal(property.readOnly, false); assert.equal(property.writeOnly, false); + assert.equal(property.observable, false); assert.equal(property.type, 'string'); assert.ok(property.valueSchema instanceof DataSchema); }); @@ -64,6 +65,22 @@ describe('PropertyAffordance', () => { return true; }, ); + + assert.throws( + () => new PropertyAffordance('badObservable', { observable: 'yes' }), + (error) => { + assert.ok(error instanceof ValidationError); + assert.equal( + error.validationErrors[0].field, + 'properties.badObservable.observable', + ); + assert.equal( + error.validationErrors[0].description, + 'observable member is not a boolean', + ); + return true; + }, + ); }); it('should reject properties that are both readOnly and writeOnly', () => { @@ -106,6 +123,30 @@ describe('PropertyAffordance', () => { }); }); + it('should generate observe forms only for observable properties', () => { + const property = new PropertyAffordance('brightness', { + type: 'number', + observable: true, + }); + + assert.deepEqual(property.getMetadata(), { + type: 'number', + observable: true, + forms: [ + { + href: 'properties/brightness', + op: ['readproperty', 'writeproperty'], + }, + { + href: 'properties/brightness', + op: ['observeproperty', 'unobserveproperty'], + contentType: 'application/json', + subprotocol: 'sse', + }, + ], + }); + }); + it('should generate read-only form operations for readOnly properties', () => { const property = new PropertyAffordance('temperature', { type: 'number', diff --git a/test/thing-server.test.js b/test/thing-server.test.js index c14eda6..b3517fe 100644 --- a/test/thing-server.test.js +++ b/test/thing-server.test.js @@ -11,6 +11,7 @@ describe('ThingServer', () => { on: { type: 'boolean', title: 'On/Off', + observable: true, }, token: { type: 'string', @@ -88,6 +89,21 @@ describe('ThingServer', () => { 'readallproperties', 'writemultipleproperties', ]); + assert.deepEqual( + td.properties.on.forms.find(({ subprotocol }) => subprotocol === 'sse'), + { + href: 'properties/on', + op: ['observeproperty', 'unobserveproperty'], + contentType: 'application/json', + subprotocol: 'sse', + }, + ); + assert.equal( + td.properties.token.forms.some( + ({ subprotocol }) => subprotocol === 'sse', + ), + false, + ); assert.deepEqual(td.securityDefinitions, { nosec_sc: { scheme: 'nosec' }, }); @@ -155,6 +171,93 @@ describe('ThingServer', () => { }); }); + describe('GET /properties/:name (SSE)', () => { + it('should read the property when both JSON and SSE are acceptable', async () => { + for (const accept of ['text/event-stream, application/json', '*/*']) { + const response = await fetch(baseUrl + '/properties/on', { + headers: { Accept: accept }, + }); + + assert.equal(response.status, 200); + assert.match( + response.headers.get('content-type'), + /^application\/json/, + ); + assert.equal(await response.json(), true); + } + }); + + it('should stream property changes as named JSON events', async () => { + const response = await fetch(baseUrl + '/properties/on', { + 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(); + const writeResponse = await fetch(baseUrl + '/properties/on', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(false), + }); + assert.equal(writeResponse.status, 204); + + const { value, done } = await nextEvent; + assert.equal(done, false); + const event = new TextDecoder().decode(value); + assert.match(event, /^event: on\ndata: false\nid: .+\n\n$/); + assert.match( + event.match(/^id: (.+)$/m)[1], + /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/, + ); + + const nextEventRead = reader.read(); + currentValue = true; + await server.thing.emitPropertyChange('on'); + const { value: nextValue, done: nextDone } = await nextEventRead; + assert.equal(nextDone, false); + const nextEventText = new TextDecoder().decode(nextValue); + assert.match(nextEventText, /^event: on\ndata: true\nid: .+\n\n$/); + assert.notEqual( + nextEventText.match(/^id: (.+)$/m)[1], + event.match(/^id: (.+)$/m)[1], + ); + await reader.cancel(); + }); + + it('should return 406 for properties that cannot be observed', async () => { + const unobservableServer = new ThingServer( + new Thing({ + title: 'Unobservable Thing', + properties: { + status: { type: 'string' }, + token: { type: 'string', writeOnly: true, observable: true }, + }, + }), + ); + await new Promise((resolve) => { + unobservableServer.server = unobservableServer.app.listen(0, resolve); + }); + + try { + const url = `http://localhost:${unobservableServer.server.address().port}/properties`; + const headers = { Accept: 'text/event-stream' }; + const unknownResponse = await fetch(`${url}/missing`, { headers }); + const nonObservableResponse = await fetch(`${url}/status`, { headers }); + const writeOnlyResponse = await fetch(`${url}/token`, { headers }); + + assert.equal(unknownResponse.status, 404); + assert.equal(nonObservableResponse.status, 406); + assert.equal(writeOnlyResponse.status, 406); + } finally { + unobservableServer.stop(); + } + }); + }); + describe('GET /actions', () => { it('should return action request statuses grouped newest first', async () => { const firstInvocation = await fetch(baseUrl + '/actions/fade', { diff --git a/test/thing.test.js b/test/thing.test.js index e8e2fce..2506e07 100644 --- a/test/thing.test.js +++ b/test/thing.test.js @@ -10,6 +10,7 @@ describe('Thing', () => { on: { type: 'boolean', title: 'On/Off', + observable: true, }, }, actions: { @@ -48,11 +49,18 @@ describe('Thing', () => { security: 'nosec_sc', properties: { on: { + observable: true, forms: [ { href: 'properties/on', op: ['readproperty', 'writeproperty'], }, + { + href: 'properties/on', + op: ['observeproperty', 'unobserveproperty'], + contentType: 'application/json', + subprotocol: 'sse', + }, ], title: 'On/Off', type: 'boolean', @@ -157,6 +165,25 @@ describe('Thing', () => { assert.strictEqual(value, true); }); + it('should emit propertyChanged after writing an observable property', async () => { + const thing = new Thing(partialTD); + let writtenValue; + let change; + thing.setPropertyWriteHandler('on', async (value) => { + writtenValue = value; + }); + thing.once('propertyChanged', (...args) => { + change = args; + }); + + await thing.writeProperty('on', true); + + assert.equal(writtenValue, true); + assert.equal(change[0], 'on'); + assert.equal(change[1], true); + assert.equal(typeof change[2], 'string'); + }); + it('should reject when no handler is registered', async () => { const thing = new Thing(partialTD); await assert.rejects( @@ -164,6 +191,86 @@ describe('Thing', () => { /InternalError/, ); }); + + it('should not emit propertyChanged when the write fails', async () => { + const thing = new Thing(partialTD); + thing.setPropertyWriteHandler('on', async () => { + throw new Error('write failed'); + }); + let emitted = false; + thing.once('propertyChanged', () => { + emitted = true; + }); + + await assert.rejects( + () => thing.writeProperty('on', true), + /write failed/, + ); + assert.equal(emitted, false); + }); + }); + + describe('emitPropertyChange', () => { + it('should emit the provided value and resolve after emission', async () => { + const thing = new Thing(partialTD); + let emittedValue; + thing.once('propertyChanged', (_name, value) => { + emittedValue = value; + }); + + await thing.emitPropertyChange('on', true); + + assert.equal(emittedValue, true); + }); + + it('should read and emit the current value when omitted', async () => { + const thing = new Thing(partialTD); + thing.setPropertyReadHandler('on', async () => true); + let emittedValue; + thing.once('propertyChanged', (_name, value) => { + emittedValue = value; + }); + + await thing.emitPropertyChange('on'); + + assert.equal(emittedValue, true); + }); + + it('should reject for an unknown property, invalid value, or missing read handler', async () => { + const thing = new Thing(partialTD); + + await assert.rejects( + () => thing.emitPropertyChange('missing'), + /NotFoundError/, + ); + await assert.rejects( + () => thing.emitPropertyChange('on', 'invalid'), + /InternalError/, + ); + await assert.rejects( + () => thing.emitPropertyChange('on'), + /InternalError/, + ); + }); + + it('should reject changes for non-observable and write-only properties', async () => { + const thing = new Thing({ + title: 'Test Thing', + properties: { + status: { type: 'boolean' }, + secret: { type: 'boolean', writeOnly: true, observable: true }, + }, + }); + + await assert.rejects( + () => thing.emitPropertyChange('status', true), + /InternalError/, + ); + await assert.rejects( + () => thing.emitPropertyChange('secret', true), + /InternalError/, + ); + }); }); describe('writeMultipleProperties', () => {