From 8bca67d7ad9c976680a1e91ac5175fd7af2e502e Mon Sep 17 00:00:00 2001 From: Ben Francis Date: Fri, 4 Dec 2026 17:00:47 +0000 Subject: [PATCH] HTTP subscribeallevents operation - closes #26 and #27 --- src/thing-server.js | 147 ++++++++----- src/thing.js | 7 + test/thing-server.test.js | 437 +++++++++++++++++++++----------------- test/thing.test.js | 58 ++--- 4 files changed, 377 insertions(+), 272 deletions(-) diff --git a/src/thing-server.js b/src/thing-server.js index 86bf5b7..52d6bcb 100644 --- a/src/thing-server.js +++ b/src/thing-server.js @@ -225,56 +225,6 @@ 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', /** @@ -464,6 +414,103 @@ class ThingServer { response.status(200).json(this.thing.queryAllActions()); }, ); + + 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.get( + '/events', + /** + * Subscribe to all Events + * + * @param {Request} request + * @param {Response} response + */ + (request, response) => { + if (this.thing.events.size === 0) { + 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 (response.writableEnded) { + return; + } + const dataLine = + data === undefined ? '' : `data: ${JSON.stringify(data)}\n`; + response.write(`event: ${eventName}\n${dataLine}id: ${eventId}\n\n`); + }; + + this.thing.on('eventEmitted', onEventEmitted); + response.on('close', () => { + this.thing.off('eventEmitted', onEventEmitted); + }); + response.flushHeaders(); + }, + ); } /** diff --git a/src/thing.js b/src/thing.js index f2ed9f6..f79b30f 100644 --- a/src/thing.js +++ b/src/thing.js @@ -450,6 +450,13 @@ class Thing extends EventEmitter { } if (Object.keys(events).length > 0) { thingDescription.events = events; + thingDescription.forms ??= []; + thingDescription.forms.push({ + href: 'events', + op: ['subscribeallevents', 'unsubscribeallevents'], + contentType: 'application/json', + subprotocol: 'sse', + }); } return thingDescription; } diff --git a/test/thing-server.test.js b/test/thing-server.test.js index b0486ba..f0713e8 100644 --- a/test/thing-server.test.js +++ b/test/thing-server.test.js @@ -1,4 +1,4 @@ -import { describe, it, before, after } from 'node:test'; +import { describe, it, before, beforeEach, after } from 'node:test'; import assert from 'node:assert/strict'; import Thing from '../src/thing.js'; import ThingServer from '../src/thing-server.js'; @@ -50,6 +50,10 @@ describe('ThingServer', () => { let currentValue = true; let actionSignal; + beforeEach(() => { + currentValue = true; + }); + before(async () => { const thing = new Thing(partialTD); thing.setPropertyReadHandler('on', async () => currentValue); @@ -127,9 +131,31 @@ 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', { + describe('GET /properties/:invalidname', () => { + it('should return 404 for an invalid property name', async () => { + const response = await fetch(baseUrl + '/properties/foo'); + assert.strictEqual(response.status, 404); + }); + }); + + 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' }, }); @@ -139,42 +165,92 @@ describe('ThingServer', () => { const reader = response.body.getReader(); const nextEvent = reader.read(); - server.thing.emitEvent('overheated', 90); + 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( - new TextDecoder().decode(value), - /^event: overheated\ndata: 90\nid: .+\n\n$/, + 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 omit data for events without a payload', async () => { - const response = await fetch(baseUrl + '/events/reset', { - headers: { Accept: 'text/event-stream' }, + 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); }); - 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(); + 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(); + } }); + }); - it('should reject unknown events and requests without SSE Accept', async () => { - const unknownResponse = await fetch(baseUrl + '/events/missing', { - headers: { Accept: 'text/event-stream' }, + describe('PUT /properties/:name', () => { + it('should update the property value when the property exists', async () => { + const response = await fetch(baseUrl + '/properties/on', { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(false), }); - const unsupportedResponse = await fetch(baseUrl + '/events/overheated', { - headers: { Accept: 'application/json' }, + + assert.strictEqual(response.status, 204); + assert.strictEqual(currentValue, false); + }); + }); + + describe('PUT /properties/:invalidname', () => { + it('should return 404 when the property does not exist', async () => { + const response = await fetch(baseUrl + '/properties/foo', { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(true), }); - assert.equal(unknownResponse.status, 404); - assert.equal(unsupportedResponse.status, 406); + assert.strictEqual(response.status, 404); }); }); @@ -288,96 +364,61 @@ describe('ThingServer', () => { }); }); - describe('GET /properties/:invalidname', () => { - it('should return 404 for an invalid property name', async () => { - const response = await fetch(baseUrl + '/properties/foo'); - assert.strictEqual(response.status, 404); - }); - }); - - 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' }, + describe('PUT /properties', () => { + it('should write multiple writable properties and reject invalid requests', async () => { + const writtenValues = {}; + const multiPropertyThing = new Thing({ + title: 'Multiple Properties', + properties: { + on: { type: 'boolean' }, + level: { type: 'number' }, + locked: { type: 'boolean', readOnly: true }, + }, }); - - 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), + multiPropertyThing.setPropertyWriteHandler('on', async (value) => { + writtenValues.on = value; }); - 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 }, - }, - }), - ); + multiPropertyThing.setPropertyWriteHandler('level', async (value) => { + writtenValues.level = value; + }); + const multiPropertyServer = new ThingServer(multiPropertyThing); await new Promise((resolve) => { - unobservableServer.server = unobservableServer.app.listen(0, resolve); + multiPropertyServer.server = multiPropertyServer.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 }); + const url = `http://localhost:${multiPropertyServer.server.address().port}/properties`; + const options = { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + }; + let response = await fetch(url, { + ...options, + body: JSON.stringify({ on: true, level: 50 }), + }); + assert.equal(response.status, 204); + assert.deepEqual(writtenValues, { on: true, level: 50 }); - assert.equal(unknownResponse.status, 404); - assert.equal(nonObservableResponse.status, 406); - assert.equal(writeOnlyResponse.status, 406); + response = await fetch(url, { + ...options, + body: JSON.stringify({ on: false, missing: 1 }), + }); + assert.equal(response.status, 404); + assert.deepEqual(writtenValues, { on: true, level: 50 }); + + response = await fetch(url, { + ...options, + body: JSON.stringify({ locked: true }), + }); + assert.equal(response.status, 400); + + response = await fetch(url, { + ...options, + body: JSON.stringify([]), + }); + assert.equal(response.status, 400); } finally { - unobservableServer.stop(); + multiPropertyServer.stop(); } }); }); @@ -444,94 +485,6 @@ describe('ThingServer', () => { }); }); - describe('PUT /properties/:name', () => { - it('should update the property value when the property exists', async () => { - const response = await fetch(baseUrl + '/properties/on', { - method: 'PUT', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(false), - }); - - assert.strictEqual(response.status, 204); - assert.strictEqual(currentValue, false); - }); - }); - - describe('PUT /properties/:invalidname', () => { - it('should return 404 when the property does not exist', async () => { - const response = await fetch(baseUrl + '/properties/foo', { - method: 'PUT', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(true), - }); - - assert.strictEqual(response.status, 404); - }); - }); - - describe('PUT /properties', () => { - it('should write multiple writable properties and reject invalid requests', async () => { - const writtenValues = {}; - const multiPropertyThing = new Thing({ - title: 'Multiple Properties', - properties: { - on: { type: 'boolean' }, - level: { type: 'number' }, - locked: { type: 'boolean', readOnly: true }, - }, - }); - multiPropertyThing.setPropertyWriteHandler('on', async (value) => { - writtenValues.on = value; - }); - multiPropertyThing.setPropertyWriteHandler('level', async (value) => { - writtenValues.level = value; - }); - const multiPropertyServer = new ThingServer(multiPropertyThing); - await new Promise((resolve) => { - multiPropertyServer.server = multiPropertyServer.app.listen(0, resolve); - }); - - try { - const url = `http://localhost:${multiPropertyServer.server.address().port}/properties`; - const options = { - method: 'PUT', - headers: { 'Content-Type': 'application/json' }, - }; - let response = await fetch(url, { - ...options, - body: JSON.stringify({ on: true, level: 50 }), - }); - assert.equal(response.status, 204); - assert.deepEqual(writtenValues, { on: true, level: 50 }); - - response = await fetch(url, { - ...options, - body: JSON.stringify({ on: false, missing: 1 }), - }); - assert.equal(response.status, 404); - assert.deepEqual(writtenValues, { on: true, level: 50 }); - - response = await fetch(url, { - ...options, - body: JSON.stringify({ locked: true }), - }); - assert.equal(response.status, 400); - - response = await fetch(url, { - ...options, - body: JSON.stringify([]), - }); - assert.equal(response.status, 400); - } finally { - multiPropertyServer.stop(); - } - }); - }); - describe('POST /actions/:name', () => { it('should invoke the action and return its output', async () => { const input = { duration: 3 }; @@ -643,4 +596,96 @@ describe('ThingServer', () => { assert.equal(cancelResponse.status, 409); }); }); + + 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 /events (SSE)', () => { + it('should stream all named events and stop on disconnect', async () => { + const response = await fetch(baseUrl + '/events', { + 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$/, + ); + + const nextEventWithoutData = reader.read(); + server.thing.emitEvent('reset'); + const { value: resetValue, done: resetDone } = await nextEventWithoutData; + assert.equal(resetDone, false); + assert.match( + new TextDecoder().decode(resetValue), + /^event: reset\nid: .+\n\n$/, + ); + + await reader.cancel(); + }); + + it('should reject requests without SSE Accept', async () => { + const response = await fetch(baseUrl + '/events', { + headers: { Accept: 'application/json' }, + }); + + assert.equal(response.status, 406); + }); + }); }); diff --git a/test/thing.test.js b/test/thing.test.js index 2c72aef..187eb46 100644 --- a/test/thing.test.js +++ b/test/thing.test.js @@ -110,6 +110,12 @@ describe('Thing', () => { subprotocol: 'sse', }, { href: 'actions', op: 'queryallactions' }, + { + href: 'events', + op: ['subscribeallevents', 'unsubscribeallevents'], + contentType: 'application/json', + subprotocol: 'sse', + }, ], }); }); @@ -318,32 +324,6 @@ 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({ @@ -556,4 +536,30 @@ 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/, + ); + }); + }); });