node-red-contrib-ccu 4.9.0 → 4.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,29 @@ Notable changes to node-red-contrib-ccu. Format follows
5
5
  user-visible symptom and the cause, not the commit list (the release notes
6
6
  append commits automatically).
7
7
 
8
+ ## 4.10.0 (2026-11-09)
9
+
10
+ ### Changed
11
+
12
+ - **openccu-lite: the names come from occulite-client's live copy.** The
13
+ connection's own HTTP client for the metadata API (snapshot, change
14
+ stream, re-reads) is gone; names, rooms and functions now come from
15
+ occulite-client, in the ReGa shape as before. Where the connection node
16
+ has its own token (as pairing makes it), one client serves the names and
17
+ the interfaces - one connection to the system instead of two. Where the
18
+ names and the interfaces have different credentials (RedMatic on the
19
+ system: the system's read-only token for the names, RedMatic's own token
20
+ for lite-rpc) or the interfaces go the CCU way, a names-only client follows
21
+ the names and opens no lite-rpc stream of its own.
22
+
23
+ ### Fixed
24
+
25
+ - **openccu-lite: a system that did not answer the first connect of the
26
+ lite-rpc client is connected later.** The client was given up after a
27
+ failed first connect while the log said it kept trying; now a new client
28
+ is opened after 5 s, growing to a minute. A refused credential, or a system
29
+ that is not openccu-lite, still ends it with a message.
30
+
8
31
  ## 4.9.0 (2026-11-09)
9
32
 
10
33
  ### Added
@@ -732,6 +732,8 @@ module.exports = function (RED) {
732
732
  ? config.connectionType
733
733
  : 'auto';
734
734
  this.liteToken = config.metaToken || lite.readAddonToken();
735
+ // the enabled interfaces, for startMeta()'s choice of one client for names and interfaces
736
+ this.liteConfig = config;
735
737
  this.lite = null;
736
738
  this.liteIfaces = [];
737
739
  this.metaMode = false;
@@ -1797,8 +1799,16 @@ module.exports = function (RED) {
1797
1799
  );
1798
1800
  }
1799
1801
 
1802
+ // one client for names and interfaces where the lite-rpc credential reads the names too
1803
+ // (the connection node's own token, as pairing makes it); a names-only client of its own
1804
+ // where they differ (RedMatic: the system's local token for the names, the addon token
1805
+ // for lite-rpc) or where the interfaces go another way
1806
+ const shared =
1807
+ Boolean(this.metaToken) &&
1808
+ this.metaToken === this.liteToken &&
1809
+ this.liteInterfaces(this.liteConfig, true).length > 0;
1800
1810
  return new Promise((resolve) => {
1801
- const done = setTimeout(resolve, 5000);
1811
+ const done = setTimeout(resolve, shared ? 0 : 5000);
1802
1812
  this.meta = new metaProvider.MetaProvider({
1803
1813
  host: this.host,
1804
1814
  port: this.metaPort,
@@ -1806,6 +1816,7 @@ module.exports = function (RED) {
1806
1816
  insecure: Boolean(this.inSecure),
1807
1817
  fingerprint256: this.fingerprint256,
1808
1818
  token: this.metaToken,
1819
+ shared,
1809
1820
  logger: this.logger,
1810
1821
  onNames: (names) => {
1811
1822
  this.applyMetaNames(names);
@@ -2570,12 +2581,14 @@ module.exports = function (RED) {
2570
2581
  * lite-rpc carries (not CUxD, not CCU-Jack), on an openccu-lite system, with a credential,
2571
2582
  * unless the connection type says `ccu`.
2572
2583
  * @param {object} config the node's config
2584
+ * @param {boolean} [quiet] no log line for a CCU by choice (startMeta's look ahead, which runs
2585
+ * with the system detected and a credential at hand)
2573
2586
  * @returns {string[]}
2574
2587
  */
2575
- liteInterfaces(config) {
2588
+ liteInterfaces(config, quiet = false) {
2576
2589
  const enabled = lite.LITE_INTERFACES.filter((iface) => config[this.ifaceTypes[iface].conf + 'Enabled']);
2577
2590
  if (this.connectionType === 'ccu') {
2578
- if (this.metaMode) {
2591
+ if (this.metaMode && !quiet) {
2579
2592
  this.logger.info(
2580
2593
  'openccu-lite: the direct connection with callbacks by choice (connection type CCU) - the interfaces are reached on their own ports',
2581
2594
  );
@@ -2662,6 +2675,13 @@ module.exports = function (RED) {
2662
2675
  insecure: Boolean(this.inSecure),
2663
2676
  fingerprint256: this.fingerprint256,
2664
2677
  interfaces: ifaces,
2678
+ // the names from the same client (startMeta decided it): its live copy to the provider
2679
+ meta: Boolean(this.meta && this.meta.shared),
2680
+ onBox: (box) => {
2681
+ if (this.meta && this.meta.shared) {
2682
+ this.meta.attach(box);
2683
+ }
2684
+ },
2665
2685
  initId: (iface) => this.liteInitId(iface),
2666
2686
  logger: this.logger,
2667
2687
  createClient: this.liteCreateClient,
package/nodes/lib/lite.js CHANGED
@@ -167,42 +167,6 @@ function liteValue(value, jsonDouble) {
167
167
  return value;
168
168
  }
169
169
 
170
- const RPC_TIERS = ['rpc:operate', 'rpc:configure', 'rpc:admin'];
171
-
172
- /**
173
- * occulite-client B-3: the client decides "names only" from the literal `rpc:read` in
174
- * GET /api/auth/v1/state, but a token made with a higher tier (rpc:admin, say) carries that tier
175
- * alone - the system includes the lower ones. The transport spells `rpc:read` out for the client
176
- * where a tier implies it. Goes once the package fixes it.
177
- * @param {object} transport occulite-client's Transport
178
- * @returns {object} the same transport
179
- */
180
- function tierAwareTransport(transport) {
181
- return {
182
- request: (method, url, headers, body, signal) =>
183
- transport.request(method, url, headers, body, signal).then((response) => {
184
- if (response.status !== 200 || !/\/api\/auth\/v1\/state(\?|$)/.test(String(url))) {
185
- return response;
186
- }
187
-
188
- let parsed;
189
- try {
190
- parsed = JSON.parse(response.body);
191
- } catch {
192
- return response;
193
- }
194
-
195
- const scopes = Array.isArray(parsed && parsed.scopes) ? parsed.scopes : [];
196
- if (scopes.includes('rpc:read') || !scopes.some((scope) => RPC_TIERS.includes(scope))) {
197
- return response;
198
- }
199
-
200
- return {...response, body: JSON.stringify({...parsed, scopes: [...scopes, 'rpc:read']})};
201
- }),
202
- stream: (url, headers, signal) => transport.stream(url, headers, signal),
203
- };
204
- }
205
-
206
170
  /**
207
171
  * The certificate trust for occulite-client's transport: the fingerprint pinned at pairing, else
208
172
  * any certificate where the node says so, else Node's own store.
@@ -233,6 +197,10 @@ class LiteConnection {
233
197
  * @param {object} options.logger {debug, info, warn, error}
234
198
  * @param {number} [options.timeout] per request, ms
235
199
  * @param {Function} [options.createClient] for tests, in place of new OccuLite()
200
+ * @param {boolean} [options.meta] the client keeps the live copy of the names too (one client for both)
201
+ * @param {function(object)} [options.onBox] every client this connection opens, before it connects
202
+ * @param {number} [options.retryMin] the first wait before a failed connect is tried again, ms
203
+ * @param {number} [options.retryMax] the longest wait, ms
236
204
  */
237
205
  constructor(options) {
238
206
  this.options = options;
@@ -242,6 +210,9 @@ class LiteConnection {
242
210
  this.server = null;
243
211
  this.closed = false;
244
212
  this.ready = false;
213
+ this.retryTimeout = null;
214
+ this.retryMin = options.retryMin === undefined ? 5000 : options.retryMin;
215
+ this.retryMax = options.retryMax === undefined ? 60000 : options.retryMax;
245
216
  }
246
217
 
247
218
  /**
@@ -253,27 +224,70 @@ class LiteConnection {
253
224
  }
254
225
 
255
226
  /**
256
- * Opens the client. Resolves once the first picture is loaded, rejects with the client's
257
- * reason (unauthenticated, forbidden, unreachable, timeout ...); the stream keeps trying by
258
- * itself afterwards.
227
+ * Opens the client. Resolves once the first picture is loaded. occulite-client (0.4) does not
228
+ * try a failed connect again (its streams only reconnect once connected), so a system that
229
+ * did not answer (unreachable, timeout, still starting) gets a new client after a wait,
230
+ * growing to a minute; a refused credential, or a system that is not openccu-lite, rejects.
259
231
  * @returns {Promise<void>}
260
232
  */
261
233
  start() {
234
+ return new Promise((resolve, reject) => {
235
+ let attempt = 0;
236
+ const connect = () => {
237
+ this.retryTimeout = null;
238
+ this.open().then(resolve, (error) => {
239
+ if (this.closed) {
240
+ reject(error);
241
+ return;
242
+ }
243
+
244
+ const kind = kindOf(error);
245
+ if (kind === 'unauthenticated' || kind === 'forbidden' || kind === 'unsupported') {
246
+ reject(error);
247
+ return;
248
+ }
249
+
250
+ const delay = Math.min(this.retryMin * 2 ** attempt, this.retryMax);
251
+ attempt += 1;
252
+ this.logger[attempt === 1 ? 'warn' : 'debug'](
253
+ 'lite-rpc: ' + (error.message || error) + ' - connecting again in ' + delay / 1000 + ' s',
254
+ );
255
+ this.retryTimeout = setTimeout(connect, delay);
256
+ });
257
+ };
258
+
259
+ connect();
260
+ });
261
+ }
262
+
263
+ /**
264
+ * One client: the stream's events into the callback table, the first picture.
265
+ * @returns {Promise<void>}
266
+ */
267
+ open() {
268
+ if (this.box) {
269
+ this.box.close();
270
+ }
271
+
262
272
  const {OccuLite, callbackEvents, nodeTransport} = load();
263
273
  const debug = (message) => this.logger.debug('occulite-client: ' + message);
264
274
  const clientOptions = {
265
275
  url: this.options.url,
266
276
  auth: {token: this.options.token},
267
- transport: tierAwareTransport(nodeTransport(trustOf(this.options))),
277
+ transport: nodeTransport(trustOf(this.options)),
268
278
  interfaces: this.interfaces,
269
279
  values: true,
270
- meta: false,
280
+ meta: Boolean(this.options.meta),
271
281
  devices: true,
272
282
  timeout: this.options.timeout || 30000,
273
283
  log: {debug, info: debug, warn: debug, error: debug},
274
284
  };
275
285
  const box = this.options.createClient ? this.options.createClient(clientOptions) : new OccuLite(clientOptions);
276
286
  this.box = box;
287
+ if (this.options.onBox) {
288
+ this.options.onBox(box);
289
+ }
290
+
277
291
  box.on('status', (event) => {
278
292
  if (this.closed || this.box !== box) {
279
293
  return;
@@ -357,6 +371,8 @@ class LiteConnection {
357
371
  close() {
358
372
  this.closed = true;
359
373
  this.ready = false;
374
+ clearTimeout(this.retryTimeout);
375
+ this.retryTimeout = null;
360
376
  if (this.box) {
361
377
  this.box.close();
362
378
  this.box = null;
@@ -371,7 +387,6 @@ module.exports = {
371
387
  CALLBACK_METHODS,
372
388
  readAddonToken,
373
389
  liteValue,
374
- tierAwareTransport,
375
390
  trustOf,
376
391
  translateError,
377
392
  isFault,
@@ -13,10 +13,12 @@
13
13
  * endpoints) can tell the two apart. Everything ReGa-only - system variables,
14
14
  * programs, `exec()` - has no replacement and stays empty.
15
15
  *
16
- * Deliberately built on node:http / node:https rather than global fetch: the
17
- * connection node already offers "ignore invalid TLS certificates", which fetch
18
- * cannot express per request without pulling in undici, and a Node stream is
19
- * the natural shape for SSE. No new dependency either way.
16
+ * The snapshot and the change stream are occulite-client's live copy
17
+ * (`box.meta`), shared with the lite-rpc client where the connection has one
18
+ * (MetaProvider). The detection - one unauthenticated GET of the version
19
+ * answer, telling "not openccu-lite" from "not now" (a 502 while the system
20
+ * starts) - stays on node:http / node:https here, with the connection's TLS
21
+ * choice and the certificate pinned at pairing.
20
22
  *
21
23
  * @see https://github.com/hobbyquaker/openccu-lite `docs/meta-api.md`
22
24
  */
@@ -257,41 +259,26 @@ function pinnedConnection(host, port, fingerprint256, timeout) {
257
259
  }
258
260
 
259
261
  /**
260
- * One HTTP request against the metadata API.
261
- * @param {object} options
262
- * @returns {Promise<{status: number, headers: object, res: object, body: Promise<string>}>}
262
+ * One GET against the metadata API without a credential (the version answer of the detection).
263
+ * @param {object} options host, port, tls, insecure, fingerprint256, path, timeout
264
+ * @returns {Promise<{status: number, headers: object, res: object}>}
263
265
  */
264
266
  function request(options) {
265
- const {
266
- host,
267
- port,
268
- tls: useTls,
269
- insecure,
270
- fingerprint256,
271
- path,
272
- token,
273
- timeout = 10000,
274
- idleTimeout,
275
- accept = 'application/json',
276
- } = options;
267
+ const {host, port, tls: useTls, insecure, fingerprint256, path, timeout = 10000} = options;
277
268
  return new Promise((resolve, reject) => {
278
- const headers = {accept, 'user-agent': 'node-red-contrib-ccu'};
279
- if (token) {
280
- headers.authorization = 'Bearer ' + token;
281
- }
282
-
283
269
  const lib = useTls ? https : http;
284
270
  const requestOptions = {
285
271
  host,
286
272
  port,
287
273
  path,
288
274
  method: 'GET',
289
- headers,
275
+ headers: {accept: 'application/json', 'user-agent': 'node-red-contrib-ccu'},
290
276
  ...(useTls ? {rejectUnauthorized: !insecure} : {}),
291
277
  };
292
278
  if (useTls && fingerprint256) {
293
279
  requestOptions.createConnection = pinnedConnection(host, port, fingerprint256, timeout);
294
280
  }
281
+
295
282
  if (timeout > 0) {
296
283
  // as an option, not request.setTimeout(): only this form arms the
297
284
  // timer before the socket is connected, so an unreachable box does
@@ -300,24 +287,12 @@ function request(options) {
300
287
  }
301
288
 
302
289
  const request_ = lib.request(requestOptions, (res) => {
303
- resolve({status: res.statusCode, headers: res.headers, res, request: request_});
290
+ resolve({status: res.statusCode, headers: res.headers, res});
304
291
  });
305
292
 
306
293
  request_.on('timeout', () => {
307
294
  request_.destroy(new Error('timeout'));
308
295
  });
309
-
310
- if (idleTimeout !== undefined) {
311
- // the event stream may legitimately stay silent between heartbeats,
312
- // so the connect timeout above must not keep applying to it
313
- request_.on('socket', (socket) => {
314
- if (socket.connecting) {
315
- socket.once('connect', () => socket.setTimeout(idleTimeout));
316
- } else {
317
- socket.setTimeout(idleTimeout);
318
- }
319
- });
320
- }
321
296
  request_.on('error', reject);
322
297
  request_.end();
323
298
  });
@@ -362,7 +337,6 @@ async function detectOutcome(options) {
362
337
  const answer = await request({
363
338
  ...options,
364
339
  path: API_PATH + '/version',
365
- token: undefined,
366
340
  timeout: options.timeout || 5000,
367
341
  });
368
342
  status = answer.status;
@@ -402,13 +376,105 @@ async function detect(options) {
402
376
  return (await detectOutcome(options)).info;
403
377
  }
404
378
 
379
+ /** an occulite-client error that a new attempt with the same credential does not fix */
380
+ const REFUSED = new Set(['unauthenticated', 'forbidden']);
381
+
382
+ /** the metadata change stream's path */
383
+ const META_STREAM = /\/api\/meta\/v1\/events\/sse(\?|$)/;
384
+
405
385
  /**
406
- * Loads the metadata snapshot and follows the change stream. Public surface
407
- * mirrors what ccu-connection.js needs: start(), stop() and two callbacks.
386
+ * The transport of a names client of its own:
387
+ * - the auth state it reads says no rpc scope, so occulite-client runs it names-only - the
388
+ * snapshot and the change stream, no lite-rpc stream of its own (the system allows a token
389
+ * three streams);
390
+ * - the metadata change stream is watched: occulite-client (0.4) keeps a names-only client's state
391
+ * `ready` while that stream is down, so `onStream(open, status)` says when it opens and ends.
392
+ * @param {object} transport occulite-client's Transport
393
+ * @param {function(boolean, number=)} onStream
394
+ * @returns {object}
395
+ */
396
+ function namesTransport(transport, onStream) {
397
+ return {
398
+ request: (method, url, headers, body, signal) =>
399
+ transport.request(method, url, headers, body, signal).then((response) => {
400
+ if (response.status !== 200 || !/\/api\/auth\/v1\/state(\?|$)/.test(String(url))) {
401
+ return response;
402
+ }
403
+
404
+ let parsed;
405
+ try {
406
+ parsed = JSON.parse(response.body);
407
+ } catch {
408
+ return response;
409
+ }
410
+
411
+ const scopes = Array.isArray(parsed && parsed.scopes) ? parsed.scopes : [];
412
+ const names = scopes.filter((scope) => scope !== '*' && !String(scope).startsWith('rpc:'));
413
+ return {...response, body: JSON.stringify({...parsed, scopes: names})};
414
+ }),
415
+ stream: (url, headers, signal) => {
416
+ const opening = transport.stream(url, headers, signal);
417
+ if (!META_STREAM.test(String(url))) {
418
+ return opening;
419
+ }
420
+
421
+ return opening.then(
422
+ (answer) => {
423
+ if (answer.status !== 200) {
424
+ onStream(false, answer.status);
425
+ return answer;
426
+ }
427
+
428
+ onStream(true);
429
+ const {chunks} = answer;
430
+ return {
431
+ ...answer,
432
+ chunks: (async function* () {
433
+ try {
434
+ yield* chunks;
435
+ } finally {
436
+ onStream(false);
437
+ }
438
+ })(),
439
+ };
440
+ },
441
+ (error) => {
442
+ onStream(false);
443
+ throw error;
444
+ },
445
+ );
446
+ },
447
+ };
448
+ }
449
+
450
+ /**
451
+ * The system's names, rooms and functions from occulite-client's live copy (`box.meta`): the
452
+ * snapshot at connect, the change stream after it, a re-read where an event cannot be applied in
453
+ * place. The copy is either the one of the connection's lite-rpc client (one client for names and
454
+ * interfaces, `shared`: attach() hands it over) or one of its own, names-only, for a connection
455
+ * whose credential reads names only (the system's local token, a token without rpc scopes) or
456
+ * that reaches the interfaces another way.
457
+ *
458
+ * The surface is what ccu-connection.js needs: start(), stop(), onNames with the ReGa shape
459
+ * (buildNames, the conformance corpus' function), onStatus, and onGone when the system stops
460
+ * answering as openccu-lite - the version probe while the copy is not connected, as at startup.
408
461
  */
409
462
  class MetaProvider {
410
463
  /**
411
464
  * @param {object} options
465
+ * @param {string} options.host
466
+ * @param {number} [options.port]
467
+ * @param {boolean} [options.tls]
468
+ * @param {boolean} [options.insecure]
469
+ * @param {string} [options.fingerprint256] the certificate pinned at pairing
470
+ * @param {string} [options.token] the credential of a client of its own
471
+ * @param {boolean} [options.shared] the names come from the lite-rpc client's copy (attach())
472
+ * @param {number} [options.attachTimeout] how long a shared provider waits for attach() before it opens a client of its own
473
+ * @param {object} [options.logger]
474
+ * @param {function(object)} [options.onNames]
475
+ * @param {function(boolean)} [options.onStatus]
476
+ * @param {Function} [options.onGone]
477
+ * @param {Function} [options.createClient] for tests, in place of new OccuLite()
412
478
  */
413
479
  constructor(options = {}) {
414
480
  this.host = options.host;
@@ -417,6 +483,7 @@ class MetaProvider {
417
483
  this.insecure = Boolean(options.insecure);
418
484
  this.fingerprint256 = options.fingerprint256 || '';
419
485
  this.token = options.token || '';
486
+ this.shared = Boolean(options.shared);
420
487
  this.logger = options.logger || SILENT;
421
488
  this.onNames = options.onNames || NOOP;
422
489
  this.onStatus = options.onStatus || NOOP;
@@ -428,368 +495,294 @@ class MetaProvider {
428
495
  this.retryMin = options.retryMin === undefined ? 5000 : options.retryMin;
429
496
  this.retryMax = options.retryMax === undefined ? 60000 : options.retryMax;
430
497
  this.emitDelay = options.emitDelay === undefined ? 100 : options.emitDelay;
431
- this.streamTimeout = options.streamTimeout === undefined ? 95000 : options.streamTimeout;
498
+ this.attachTimeout = options.attachTimeout === undefined ? 15000 : options.attachTimeout;
499
+ this.createClient = options.createClient;
432
500
 
433
- this.document = null;
434
- this.revision = 0;
501
+ this.box = null;
502
+ this.owned = false;
435
503
  this.stopped = true;
436
504
  this.connected = false;
437
- this.retry = 0;
438
- this.unauthorizedLogged = false;
439
- this.stream = null;
440
- this.retryTimeout = null;
441
- this.emitTimeout = null;
442
- this.cycles = 0;
505
+ this.connectFailed = false;
506
+ this.streamRefused = false;
507
+ this.refusedLogged = false;
443
508
  this.missedProbes = 0;
509
+ this.probeRetry = 0;
510
+ this.probeTimeout = null;
511
+ this.emitTimeout = null;
512
+ this.attachTimer = null;
513
+ this.unsubscribe = [];
444
514
  }
445
515
 
446
- /**
447
- * Snapshot, then the event stream. Errors are retried, never thrown.
448
- */
449
- start() {
450
- this.stopped = false;
451
- this.retry = 0;
452
- this._cycle();
516
+ /** @returns {number} the revision of the copy */
517
+ get revision() {
518
+ return this.box ? this.box.meta.revision : 0;
453
519
  }
454
520
 
455
- /**
456
- * Stops the stream and every pending timer.
457
- */
458
- stop() {
459
- this.stopped = true;
460
- clearTimeout(this.retryTimeout);
461
- clearTimeout(this.emitTimeout);
462
- this.retryTimeout = null;
463
- this.emitTimeout = null;
464
- if (this.stream) {
465
- this.stream.destroy();
466
- this.stream = null;
467
- }
468
-
469
- this._setConnected(false);
521
+ /** @returns {string} the system's URL */
522
+ get url() {
523
+ const host =
524
+ String(this.host).includes(':') && !String(this.host).startsWith('[') ? '[' + this.host + ']' : this.host;
525
+ return (this.tls ? 'https' : 'http') + '://' + host + ':' + this.port;
470
526
  }
471
527
 
472
528
  /**
473
- * @param {boolean} connected
529
+ * A client of its own now; a shared provider waits for attach() (and opens its own when the
530
+ * lite-rpc client does not come).
474
531
  */
475
- _setConnected(connected) {
476
- if (this.connected !== connected) {
477
- this.connected = connected;
478
- this.onStatus(connected);
479
- }
480
- }
481
-
482
- /**
483
- * Schedule the next attempt with a bounded exponential backoff.
484
- */
485
- _scheduleRetry() {
486
- if (this.stopped || this.retryTimeout) {
532
+ start() {
533
+ this.stopped = false;
534
+ if (!this.shared) {
535
+ this._own();
487
536
  return;
488
537
  }
489
538
 
490
- const delay = Math.min(this.retryMin * 2 ** this.retry, this.retryMax);
491
- this.retry += 1;
492
- this.logger.debug('meta api retry in ' + delay + ' ms');
493
- this.retryTimeout = setTimeout(() => {
494
- this.retryTimeout = null;
495
- this._cycle();
496
- }, delay);
539
+ this.attachTimer = setTimeout(() => {
540
+ this.attachTimer = null;
541
+ if (!this.box && !this.stopped) {
542
+ this.logger.debug('meta api: no lite-rpc client to share - a names client of its own');
543
+ this.shared = false;
544
+ this._own();
545
+ }
546
+ }, this.attachTimeout);
497
547
  }
498
548
 
499
549
  /**
500
- * One full attempt: snapshot, then follow the stream.
550
+ * The lite-rpc client whose copy the names come from (again, after it was replaced).
551
+ * @param {object} box occulite-client's OccuLite
501
552
  */
502
- async _cycle() {
553
+ attach(box) {
503
554
  if (this.stopped) {
504
555
  return;
505
556
  }
506
557
 
507
- // the version probe again on every reconnect, as at startup: it needs no
508
- // credential, and it is how a box that is no longer an openccu-lite is
509
- // noticed without a Node-RED restart
510
- if (this.cycles > 0) {
511
- const info = await detect({
512
- host: this.host,
513
- port: this.port,
514
- tls: this.tls,
515
- insecure: this.insecure,
516
- fingerprint256: this.fingerprint256,
517
- logger: this.logger,
518
- });
519
- if (info) {
520
- this.missedProbes = 0;
521
- } else {
522
- this.missedProbes += 1;
523
- if (this.missedProbes >= this.goneAfter) {
524
- this.logger.warn(
525
- 'the box stopped answering the openccu-lite metadata api (' +
526
- this.missedProbes +
527
- ' probes) - falling back to detection from scratch',
528
- );
529
- this.stop();
530
- this.onGone();
531
- return;
532
- }
558
+ clearTimeout(this.attachTimer);
559
+ this.attachTimer = null;
560
+ this._follow(box, false);
561
+ }
562
+
563
+ /** Stops following; a client of its own is closed, a shared one is the lite-rpc connection's. */
564
+ stop() {
565
+ this.stopped = true;
566
+ clearTimeout(this.attachTimer);
567
+ clearTimeout(this.probeTimeout);
568
+ clearTimeout(this.emitTimeout);
569
+ this.attachTimer = null;
570
+ this.probeTimeout = null;
571
+ this.emitTimeout = null;
572
+ this._release();
573
+ this._setConnected(false);
574
+ }
575
+
576
+ /** A names-only client of its own. */
577
+ _own() {
578
+ const {OccuLite, nodeTransport} = require('./lite.js').load();
579
+ const debug = (message) => this.logger.debug('occulite-client (names): ' + message);
580
+ let box = null;
581
+ // the change stream's state is the copy's (see namesTransport)
582
+ const onStream = (open, status) => {
583
+ if (this.box !== box || this.stopped) {
584
+ return;
533
585
  }
534
- }
535
586
 
536
- this.cycles += 1;
537
- const ok = await this._loadSnapshot();
538
- if (!ok) {
539
- this._setConnected(false);
540
- this._scheduleRetry();
541
- return;
542
- }
587
+ this.streamRefused = !open && [401, 403, 404].includes(status);
588
+ this._status(open ? 'ready' : 'offline');
589
+ };
543
590
 
544
- this.retry = 0;
545
- this._openStream();
591
+ const clientOptions = {
592
+ url: this.url,
593
+ ...(this.token ? {auth: {token: this.token}} : {}),
594
+ transport: namesTransport(nodeTransport(require('./lite.js').trustOf(this)), onStream),
595
+ values: false,
596
+ devices: false,
597
+ meta: true,
598
+ timeout: this.requestTimeout,
599
+ log: {debug, info: debug, warn: debug, error: debug},
600
+ };
601
+ box = this.createClient ? this.createClient(clientOptions) : new OccuLite(clientOptions);
602
+ this._follow(box, true);
546
603
  }
547
604
 
548
605
  /**
549
- * `GET /snapshot`. A 401/403 degrades to "no names": logged once, retried
550
- * on the next cycle, never fatal.
551
- * @returns {Promise<boolean>}
606
+ * Follows a client's copy: its state, its change events, its first picture.
607
+ * @param {object} box
608
+ * @param {boolean} owned
552
609
  */
553
- async _loadSnapshot() {
554
- try {
555
- const {status, res} = await request({
556
- host: this.host,
557
- port: this.port,
558
- tls: this.tls,
559
- insecure: this.insecure,
560
- fingerprint256: this.fingerprint256,
561
- path: API_PATH + '/snapshot',
562
- token: this.token,
563
- timeout: this.requestTimeout,
564
- });
565
- const body = await readBody(res);
566
- if (status === 401 || status === 403) {
567
- if (!this.unauthorizedLogged) {
568
- this.unauthorizedLogged = true;
569
- this.logger.error(
570
- 'openccu-lite metadata api rejected the credential (' +
571
- status +
572
- '). Running without names - configure a token created on the box (Users page) in the ccu-connection node.',
573
- );
610
+ _follow(box, owned) {
611
+ this._release();
612
+ this.box = box;
613
+ this.owned = owned;
614
+ this.connectFailed = false;
615
+ this.streamRefused = false;
616
+ this.unsubscribe = [
617
+ box.on('status', (event) => {
618
+ // a client of its own: the change stream says it (namesTransport); a shared one: its state
619
+ if (this.box === box && !this.stopped && !owned) {
620
+ this._status(event.state);
621
+ }
622
+ }),
623
+ // the copy is in step again: after a change applied in place, or once the snapshot read
624
+ // again for a change it cannot apply in place is in
625
+ box.on('metaSettled', () => {
626
+ if (this.box === box && !this.stopped) {
627
+ this._scheduleEmit();
628
+ }
629
+ }),
630
+ ];
631
+ box.ready().then(
632
+ () => {
633
+ if (this.box !== box || this.stopped) {
634
+ return;
574
635
  }
575
636
 
576
- return false;
577
- }
578
-
579
- if (status !== 200) {
580
- this.logger.warn('meta api snapshot: status ' + status);
581
- return false;
582
- }
637
+ this.refusedLogged = false;
638
+ if (!owned) {
639
+ this._status('ready');
640
+ }
583
641
 
584
- const document = JSON.parse(body);
585
- this.unauthorizedLogged = false;
586
- this._applyDocument(document);
587
- this._setConnected(true);
588
- return true;
589
- } catch (error) {
590
- this.logger.warn('meta api snapshot: ' + error.message);
591
- return false;
592
- }
593
- }
642
+ this._emit();
643
+ },
644
+ (error) => {
645
+ if (this.box !== box || this.stopped) {
646
+ return;
647
+ }
594
648
 
595
- /**
596
- * @param {object} document
597
- */
598
- _applyDocument(document) {
599
- this.document = document;
600
- this.revision = Number(document.revision) || 0;
601
- this._emit();
602
- }
649
+ this.connectFailed = true;
650
+ const {code} = error;
651
+ if (REFUSED.has(code)) {
652
+ if (!this.refusedLogged) {
653
+ this.refusedLogged = true;
654
+ this.logger.error(
655
+ 'openccu-lite metadata api rejected the credential (' +
656
+ code +
657
+ '). Running without names - pair the connection node with the system, or enter a token made on the system.',
658
+ );
659
+ }
660
+ } else {
661
+ this.logger.warn('meta api: ' + error.message);
662
+ }
603
663
 
604
- /**
605
- * Rebuild the derived maps and hand them to the connection node.
606
- */
607
- _emit() {
608
- clearTimeout(this.emitTimeout);
609
- this.emitTimeout = null;
610
- const names = buildNames(this.document);
611
- names.revision = this.revision;
612
- this.onNames(names);
664
+ this._status('offline');
665
+ },
666
+ );
613
667
  }
614
668
 
615
- /**
616
- * Coalesce a burst of events into one update.
617
- */
618
- _scheduleEmit() {
619
- if (this.emitTimeout) {
620
- return;
669
+ /** Lets go of the current client. */
670
+ _release() {
671
+ this.unsubscribe.forEach((off) => typeof off === 'function' && off());
672
+ this.unsubscribe = [];
673
+ if (this.box && this.owned) {
674
+ this.box.close();
621
675
  }
622
676
 
623
- this.emitTimeout = setTimeout(() => {
624
- this.emitTimeout = null;
625
- if (!this.stopped) {
626
- this._emit();
627
- }
628
- }, this.emitDelay);
677
+ this.box = null;
678
+ this.owned = false;
629
679
  }
630
680
 
631
681
  /**
632
- * Follow `GET /events/sse?since=<revision>`.
682
+ * The client's state: connected when ready; otherwise the version probe runs.
683
+ * @param {string} state
633
684
  */
634
- _openStream() {
635
- if (this.stopped) {
685
+ _status(state) {
686
+ if (state === 'ready') {
687
+ this.missedProbes = 0;
688
+ this.probeRetry = 0;
689
+ clearTimeout(this.probeTimeout);
690
+ this.probeTimeout = null;
691
+ this._setConnected(true);
636
692
  return;
637
693
  }
638
694
 
639
- request({
640
- host: this.host,
641
- port: this.port,
642
- tls: this.tls,
643
- insecure: this.insecure,
644
- fingerprint256: this.fingerprint256,
645
- path: API_PATH + '/events/sse?since=' + this.revision,
646
- token: this.token,
647
- accept: 'text/event-stream',
648
- timeout: this.requestTimeout,
649
- idleTimeout: this.streamTimeout,
650
- })
651
- .then(({status, res}) => {
652
- if (this.stopped) {
653
- res.destroy();
654
- return;
655
- }
656
-
657
- if (status !== 200) {
658
- res.resume();
659
- this.logger.warn('meta api event stream: status ' + status);
660
- this._setConnected(false);
661
- this._scheduleRetry();
662
- return;
663
- }
664
-
665
- this.logger.debug('openccu-lite metadata event stream open (revision ' + this.revision + ')');
666
- this.stream = res;
667
-
668
- let buffer = '';
669
- res.setEncoding('utf8');
670
- res.on('data', (chunk) => {
671
- buffer += chunk;
672
- let index = buffer.indexOf('\n\n');
673
- while (index !== -1) {
674
- const frame = buffer.slice(0, index);
675
- buffer = buffer.slice(index + 2);
676
- this._onFrame(frame);
677
- index = buffer.indexOf('\n\n');
678
- }
679
-
680
- if (buffer.length > 1_000_000) {
681
- buffer = '';
682
- }
683
- });
684
- const done = () => {
685
- if (this.stream === res) {
686
- this.stream = null;
687
- this._scheduleRetry();
688
- }
689
- };
690
-
691
- res.on('end', done);
692
- res.on('close', done);
693
- res.on('error', (error) => {
694
- this.logger.debug('meta api event stream: ' + error.message);
695
- done();
696
- });
697
- })
698
- .catch((error) => {
699
- this.logger.warn('meta api event stream: ' + error.message);
700
- this._setConnected(false);
701
- this._scheduleRetry();
702
- });
695
+ this._setConnected(false);
696
+ if (state !== 'closed') {
697
+ this._probeLater();
698
+ }
703
699
  }
704
700
 
705
701
  /**
706
- * One SSE frame. Comments (the 30 s heartbeat) carry no data line.
707
- * @param {string} frame
702
+ * @param {boolean} connected
708
703
  */
709
- _onFrame(frame) {
710
- const data = frame
711
- .split('\n')
712
- .filter((line) => line.startsWith('data:'))
713
- .map((line) => line.slice(5).trim())
714
- .join('\n');
715
- if (!data) {
716
- return;
704
+ _setConnected(connected) {
705
+ if (this.connected !== connected) {
706
+ this.connected = connected;
707
+ this.onStatus(connected);
717
708
  }
709
+ }
718
710
 
719
- let event;
720
- try {
721
- event = JSON.parse(data);
722
- } catch {
723
- this.logger.debug('meta api event stream: unparsable frame');
711
+ /** The next version probe, with a bounded exponential backoff. */
712
+ _probeLater() {
713
+ if (this.stopped || this.probeTimeout) {
724
714
  return;
725
715
  }
726
716
 
727
- this._onEvent(event);
717
+ const delay = Math.min(this.retryMin * 2 ** this.probeRetry, this.retryMax);
718
+ this.probeRetry += 1;
719
+ this.probeTimeout = setTimeout(() => {
720
+ this.probeTimeout = null;
721
+ this._probe();
722
+ }, delay);
728
723
  }
729
724
 
730
725
  /**
731
- * Apply one change event. Object changes are applied in place; anything
732
- * that can rewrite member paths (enum and node events, an import, a gap in
733
- * the revisions, an explicit resync) re-reads the snapshot.
734
- * @param {object} event
726
+ * The version probe while the copy is not connected: needs no credential, and it is how a box
727
+ * that is no longer an openccu-lite is noticed without a Node-RED restart. A client of its own
728
+ * whose first connect failed is opened again once the system answers.
729
+ * @returns {Promise<void>}
735
730
  */
736
- _onEvent(event) {
737
- if (!event || typeof event !== 'object') {
731
+ async _probe() {
732
+ const info = await detect({
733
+ host: this.host,
734
+ port: this.port,
735
+ tls: this.tls,
736
+ insecure: this.insecure,
737
+ fingerprint256: this.fingerprint256,
738
+ logger: this.logger,
739
+ });
740
+ if (this.stopped || this.connected) {
738
741
  return;
739
742
  }
740
743
 
741
- const revision = Number(event.revision) || 0;
742
- const gap = revision > 0 && this.revision > 0 && revision > this.revision + 1;
743
-
744
- if (event.kind === 'resync' || event.kind === 'import' || gap) {
745
- this.logger.debug('meta api resnapshot (' + (gap ? 'revision gap' : event.kind) + ')');
746
- this._loadSnapshot().catch((error) => this.logger.warn('meta api snapshot: ' + error.message));
747
- return;
744
+ if (!info) {
745
+ this.missedProbes += 1;
746
+ if (this.missedProbes >= this.goneAfter) {
747
+ this.logger.warn(
748
+ 'the box stopped answering the openccu-lite metadata api (' +
749
+ this.missedProbes +
750
+ ' probes) - falling back to detection from scratch',
751
+ );
752
+ this.stop();
753
+ this.onGone();
754
+ return;
755
+ }
756
+ } else {
757
+ this.missedProbes = 0;
758
+ if (this.owned && (this.connectFailed || this.streamRefused)) {
759
+ this.logger.debug('meta api: the system answers - connecting the names client again');
760
+ this._own();
761
+ }
748
762
  }
749
763
 
750
- if (revision > this.revision) {
751
- this.revision = revision;
752
- }
764
+ this._probeLater();
765
+ }
753
766
 
754
- if (!this.document) {
767
+ /** Coalesce a burst of events into one update. */
768
+ _scheduleEmit() {
769
+ if (this.emitTimeout) {
755
770
  return;
756
771
  }
757
772
 
758
- switch (event.kind) {
759
- case 'object.updated': {
760
- if (typeof event.ref === 'string' && event.value) {
761
- this.document.objects = this.document.objects || {};
762
- this.document.objects[event.ref] = event.value;
763
- this._scheduleEmit();
764
- }
765
-
766
- break;
767
- }
768
-
769
- case 'object.deleted': {
770
- if (typeof event.ref === 'string' && this.document.objects) {
771
- delete this.document.objects[event.ref];
772
- this._scheduleEmit();
773
- }
774
-
775
- break;
776
- }
777
-
778
- case 'enum.created':
779
- case 'enum.updated':
780
- case 'enum.deleted':
781
- case 'node.created':
782
- case 'node.updated':
783
- case 'node.deleted':
784
- case 'node.moved': {
785
- // rooms and functions changed shape - member paths may have been
786
- // rewritten in the same revision, so take a fresh snapshot
787
- this._loadSnapshot().catch((error) => this.logger.warn('meta api snapshot: ' + error.message));
788
- break;
773
+ this.emitTimeout = setTimeout(() => {
774
+ this.emitTimeout = null;
775
+ if (!this.stopped) {
776
+ this._emit();
789
777
  }
778
+ }, this.emitDelay);
779
+ }
790
780
 
791
- default:
792
- }
781
+ /** Derive the maps from the copy and hand them to the connection node. */
782
+ _emit() {
783
+ const names = buildNames(this.box.meta.doc);
784
+ names.revision = this.box.meta.revision;
785
+ this.onNames(names);
793
786
  }
794
787
  }
795
788
 
@@ -797,6 +790,7 @@ module.exports = {
797
790
  API_PATH,
798
791
  LOCAL_TOKEN_FILE,
799
792
  MetaProvider,
793
+ namesTransport,
800
794
  buildNames,
801
795
  detect,
802
796
  detectOutcome,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-ccu",
3
- "version": "4.9.0",
3
+ "version": "4.10.0",
4
4
  "license": "MIT",
5
5
  "main": "none",
6
6
  "keywords": [
@@ -54,7 +54,7 @@
54
54
  "homematic-rega": "^2.0.1",
55
55
  "homematic-xmlrpc": "^2.0.0",
56
56
  "mqtt-wildcard": "^3.0.9",
57
- "occulite-client": "^0.3.0"
57
+ "occulite-client": "^0.4.0"
58
58
  },
59
59
  "deprecated": false,
60
60
  "description": "Node-RED Nodes for the Homematic CCU",