node-red-contrib-ccu 4.8.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.
@@ -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
  */
@@ -24,6 +26,8 @@
24
26
  const fs = require('fs');
25
27
  const http = require('http');
26
28
  const https = require('https');
29
+ const net = require('net');
30
+ const tls = require('tls');
27
31
 
28
32
  const API_PATH = '/api/meta/v1';
29
33
 
@@ -210,28 +214,71 @@ function readLocalToken(file = LOCAL_TOKEN_FILE) {
210
214
  }
211
215
  }
212
216
 
217
+ /** a fingerprint as its bare lower-case hex, for comparing */
218
+ const bareFingerprint = (fingerprint) => String(fingerprint).replace(/:/g, '').toLowerCase();
219
+
213
220
  /**
214
- * One HTTP request against the metadata API.
215
- * @param {object} options
216
- * @returns {Promise<{status: number, headers: object, res: object, body: Promise<string>}>}
221
+ * A TLS connection that accepts exactly the certificate pinned at pairing (the system's own,
222
+ * usually self-signed): the socket goes to the request only after the handshake and the check, so
223
+ * nothing - the token least of all - is written to another server.
224
+ * @param {string} host
225
+ * @param {number} port
226
+ * @param {string} fingerprint256 colon-separated SHA-256, as pairing returns it
227
+ * @param {number} [timeout] for the connection and the handshake, ms (0: none)
228
+ * @returns {function(object, Function): undefined} for the request's createConnection
217
229
  */
218
- function request(options) {
219
- const {host, port, tls, insecure, path, token, timeout = 10000, idleTimeout, accept = 'application/json'} = options;
220
- return new Promise((resolve, reject) => {
221
- const headers = {accept, 'user-agent': 'node-red-contrib-ccu'};
222
- if (token) {
223
- headers.authorization = 'Bearer ' + token;
230
+ function pinnedConnection(host, port, fingerprint256, timeout) {
231
+ const pin = bareFingerprint(fingerprint256);
232
+ const name = String(host).replace(/^\[|\]$/g, '');
233
+ return (_options, oncreate) => {
234
+ const socket = tls.connect({
235
+ host: name,
236
+ port,
237
+ servername: net.isIP(name) ? undefined : name,
238
+ rejectUnauthorized: false,
239
+ });
240
+ if (timeout > 0) {
241
+ // the request's own timeout starts only once it has the socket, after the handshake
242
+ socket.setTimeout(timeout, () => socket.destroy(new Error('timeout')));
224
243
  }
225
244
 
226
- const lib = tls ? https : http;
245
+ socket.once('secureConnect', () => {
246
+ socket.setTimeout(0);
247
+ const seen = socket.getPeerCertificate().fingerprint256;
248
+ if (bareFingerprint(seen) !== pin) {
249
+ socket.destroy();
250
+ oncreate(new Error('the system presents another certificate than the one pinned at pairing'));
251
+ return;
252
+ }
253
+
254
+ oncreate(null, socket);
255
+ });
256
+ socket.once('error', (error) => oncreate(error));
257
+ return undefined;
258
+ };
259
+ }
260
+
261
+ /**
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}>}
265
+ */
266
+ function request(options) {
267
+ const {host, port, tls: useTls, insecure, fingerprint256, path, timeout = 10000} = options;
268
+ return new Promise((resolve, reject) => {
269
+ const lib = useTls ? https : http;
227
270
  const requestOptions = {
228
271
  host,
229
272
  port,
230
273
  path,
231
274
  method: 'GET',
232
- headers,
233
- ...(tls ? {rejectUnauthorized: !insecure} : {}),
275
+ headers: {accept: 'application/json', 'user-agent': 'node-red-contrib-ccu'},
276
+ ...(useTls ? {rejectUnauthorized: !insecure} : {}),
234
277
  };
278
+ if (useTls && fingerprint256) {
279
+ requestOptions.createConnection = pinnedConnection(host, port, fingerprint256, timeout);
280
+ }
281
+
235
282
  if (timeout > 0) {
236
283
  // as an option, not request.setTimeout(): only this form arms the
237
284
  // timer before the socket is connected, so an unreachable box does
@@ -240,24 +287,12 @@ function request(options) {
240
287
  }
241
288
 
242
289
  const request_ = lib.request(requestOptions, (res) => {
243
- resolve({status: res.statusCode, headers: res.headers, res, request: request_});
290
+ resolve({status: res.statusCode, headers: res.headers, res});
244
291
  });
245
292
 
246
293
  request_.on('timeout', () => {
247
294
  request_.destroy(new Error('timeout'));
248
295
  });
249
-
250
- if (idleTimeout !== undefined) {
251
- // the event stream may legitimately stay silent between heartbeats,
252
- // so the connect timeout above must not keep applying to it
253
- request_.on('socket', (socket) => {
254
- if (socket.connecting) {
255
- socket.once('connect', () => socket.setTimeout(idleTimeout));
256
- } else {
257
- socket.setTimeout(idleTimeout);
258
- }
259
- });
260
- }
261
296
  request_.on('error', reject);
262
297
  request_.end();
263
298
  });
@@ -302,7 +337,6 @@ async function detectOutcome(options) {
302
337
  const answer = await request({
303
338
  ...options,
304
339
  path: API_PATH + '/version',
305
- token: undefined,
306
340
  timeout: options.timeout || 5000,
307
341
  });
308
342
  status = answer.status;
@@ -342,20 +376,114 @@ async function detect(options) {
342
376
  return (await detectOutcome(options)).info;
343
377
  }
344
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
+
385
+ /**
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
+
345
450
  /**
346
- * Loads the metadata snapshot and follows the change stream. Public surface
347
- * mirrors what ccu-connection.js needs: start(), stop() and two callbacks.
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.
348
461
  */
349
462
  class MetaProvider {
350
463
  /**
351
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()
352
478
  */
353
479
  constructor(options = {}) {
354
480
  this.host = options.host;
355
481
  this.port = options.port || (options.tls ? 443 : 80);
356
482
  this.tls = Boolean(options.tls);
357
483
  this.insecure = Boolean(options.insecure);
484
+ this.fingerprint256 = options.fingerprint256 || '';
358
485
  this.token = options.token || '';
486
+ this.shared = Boolean(options.shared);
359
487
  this.logger = options.logger || SILENT;
360
488
  this.onNames = options.onNames || NOOP;
361
489
  this.onStatus = options.onStatus || NOOP;
@@ -367,365 +495,294 @@ class MetaProvider {
367
495
  this.retryMin = options.retryMin === undefined ? 5000 : options.retryMin;
368
496
  this.retryMax = options.retryMax === undefined ? 60000 : options.retryMax;
369
497
  this.emitDelay = options.emitDelay === undefined ? 100 : options.emitDelay;
370
- this.streamTimeout = options.streamTimeout === undefined ? 95000 : options.streamTimeout;
498
+ this.attachTimeout = options.attachTimeout === undefined ? 15000 : options.attachTimeout;
499
+ this.createClient = options.createClient;
371
500
 
372
- this.document = null;
373
- this.revision = 0;
501
+ this.box = null;
502
+ this.owned = false;
374
503
  this.stopped = true;
375
504
  this.connected = false;
376
- this.retry = 0;
377
- this.unauthorizedLogged = false;
378
- this.stream = null;
379
- this.retryTimeout = null;
380
- this.emitTimeout = null;
381
- this.cycles = 0;
505
+ this.connectFailed = false;
506
+ this.streamRefused = false;
507
+ this.refusedLogged = false;
382
508
  this.missedProbes = 0;
383
- }
384
-
385
- /**
386
- * Snapshot, then the event stream. Errors are retried, never thrown.
387
- */
388
- start() {
389
- this.stopped = false;
390
- this.retry = 0;
391
- this._cycle();
392
- }
393
-
394
- /**
395
- * Stops the stream and every pending timer.
396
- */
397
- stop() {
398
- this.stopped = true;
399
- clearTimeout(this.retryTimeout);
400
- clearTimeout(this.emitTimeout);
401
- this.retryTimeout = null;
509
+ this.probeRetry = 0;
510
+ this.probeTimeout = null;
402
511
  this.emitTimeout = null;
403
- if (this.stream) {
404
- this.stream.destroy();
405
- this.stream = null;
406
- }
512
+ this.attachTimer = null;
513
+ this.unsubscribe = [];
514
+ }
407
515
 
408
- this._setConnected(false);
516
+ /** @returns {number} the revision of the copy */
517
+ get revision() {
518
+ return this.box ? this.box.meta.revision : 0;
409
519
  }
410
520
 
411
- /**
412
- * @param {boolean} connected
413
- */
414
- _setConnected(connected) {
415
- if (this.connected !== connected) {
416
- this.connected = connected;
417
- this.onStatus(connected);
418
- }
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;
419
526
  }
420
527
 
421
528
  /**
422
- * Schedule the next attempt with a bounded exponential backoff.
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).
423
531
  */
424
- _scheduleRetry() {
425
- if (this.stopped || this.retryTimeout) {
532
+ start() {
533
+ this.stopped = false;
534
+ if (!this.shared) {
535
+ this._own();
426
536
  return;
427
537
  }
428
538
 
429
- const delay = Math.min(this.retryMin * 2 ** this.retry, this.retryMax);
430
- this.retry += 1;
431
- this.logger.debug('meta api retry in ' + delay + ' ms');
432
- this.retryTimeout = setTimeout(() => {
433
- this.retryTimeout = null;
434
- this._cycle();
435
- }, 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);
436
547
  }
437
548
 
438
549
  /**
439
- * 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
440
552
  */
441
- async _cycle() {
553
+ attach(box) {
442
554
  if (this.stopped) {
443
555
  return;
444
556
  }
445
557
 
446
- // the version probe again on every reconnect, as at startup: it needs no
447
- // credential, and it is how a box that is no longer an openccu-lite is
448
- // noticed without a Node-RED restart
449
- if (this.cycles > 0) {
450
- const info = await detect({
451
- host: this.host,
452
- port: this.port,
453
- tls: this.tls,
454
- insecure: this.insecure,
455
- logger: this.logger,
456
- });
457
- if (info) {
458
- this.missedProbes = 0;
459
- } else {
460
- this.missedProbes += 1;
461
- if (this.missedProbes >= this.goneAfter) {
462
- this.logger.warn(
463
- 'the box stopped answering the openccu-lite metadata api (' +
464
- this.missedProbes +
465
- ' probes) - falling back to detection from scratch',
466
- );
467
- this.stop();
468
- this.onGone();
469
- return;
470
- }
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;
471
585
  }
472
- }
473
586
 
474
- this.cycles += 1;
475
- const ok = await this._loadSnapshot();
476
- if (!ok) {
477
- this._setConnected(false);
478
- this._scheduleRetry();
479
- return;
480
- }
587
+ this.streamRefused = !open && [401, 403, 404].includes(status);
588
+ this._status(open ? 'ready' : 'offline');
589
+ };
481
590
 
482
- this.retry = 0;
483
- 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);
484
603
  }
485
604
 
486
605
  /**
487
- * `GET /snapshot`. A 401/403 degrades to "no names": logged once, retried
488
- * on the next cycle, never fatal.
489
- * @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
490
609
  */
491
- async _loadSnapshot() {
492
- try {
493
- const {status, res} = await request({
494
- host: this.host,
495
- port: this.port,
496
- tls: this.tls,
497
- insecure: this.insecure,
498
- path: API_PATH + '/snapshot',
499
- token: this.token,
500
- timeout: this.requestTimeout,
501
- });
502
- const body = await readBody(res);
503
- if (status === 401 || status === 403) {
504
- if (!this.unauthorizedLogged) {
505
- this.unauthorizedLogged = true;
506
- this.logger.error(
507
- 'openccu-lite metadata api rejected the credential (' +
508
- status +
509
- '). Running without names - configure a token created on the box (Users page) in the ccu-connection node.',
510
- );
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;
511
635
  }
512
636
 
513
- return false;
514
- }
515
-
516
- if (status !== 200) {
517
- this.logger.warn('meta api snapshot: status ' + status);
518
- return false;
519
- }
637
+ this.refusedLogged = false;
638
+ if (!owned) {
639
+ this._status('ready');
640
+ }
520
641
 
521
- const document = JSON.parse(body);
522
- this.unauthorizedLogged = false;
523
- this._applyDocument(document);
524
- this._setConnected(true);
525
- return true;
526
- } catch (error) {
527
- this.logger.warn('meta api snapshot: ' + error.message);
528
- return false;
529
- }
530
- }
642
+ this._emit();
643
+ },
644
+ (error) => {
645
+ if (this.box !== box || this.stopped) {
646
+ return;
647
+ }
531
648
 
532
- /**
533
- * @param {object} document
534
- */
535
- _applyDocument(document) {
536
- this.document = document;
537
- this.revision = Number(document.revision) || 0;
538
- this._emit();
539
- }
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
+ }
540
663
 
541
- /**
542
- * Rebuild the derived maps and hand them to the connection node.
543
- */
544
- _emit() {
545
- clearTimeout(this.emitTimeout);
546
- this.emitTimeout = null;
547
- const names = buildNames(this.document);
548
- names.revision = this.revision;
549
- this.onNames(names);
664
+ this._status('offline');
665
+ },
666
+ );
550
667
  }
551
668
 
552
- /**
553
- * Coalesce a burst of events into one update.
554
- */
555
- _scheduleEmit() {
556
- if (this.emitTimeout) {
557
- 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();
558
675
  }
559
676
 
560
- this.emitTimeout = setTimeout(() => {
561
- this.emitTimeout = null;
562
- if (!this.stopped) {
563
- this._emit();
564
- }
565
- }, this.emitDelay);
677
+ this.box = null;
678
+ this.owned = false;
566
679
  }
567
680
 
568
681
  /**
569
- * Follow `GET /events/sse?since=<revision>`.
682
+ * The client's state: connected when ready; otherwise the version probe runs.
683
+ * @param {string} state
570
684
  */
571
- _openStream() {
572
- 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);
573
692
  return;
574
693
  }
575
694
 
576
- request({
577
- host: this.host,
578
- port: this.port,
579
- tls: this.tls,
580
- insecure: this.insecure,
581
- path: API_PATH + '/events/sse?since=' + this.revision,
582
- token: this.token,
583
- accept: 'text/event-stream',
584
- timeout: this.requestTimeout,
585
- idleTimeout: this.streamTimeout,
586
- })
587
- .then(({status, res}) => {
588
- if (this.stopped) {
589
- res.destroy();
590
- return;
591
- }
592
-
593
- if (status !== 200) {
594
- res.resume();
595
- this.logger.warn('meta api event stream: status ' + status);
596
- this._setConnected(false);
597
- this._scheduleRetry();
598
- return;
599
- }
600
-
601
- this.logger.debug('openccu-lite metadata event stream open (revision ' + this.revision + ')');
602
- this.stream = res;
603
-
604
- let buffer = '';
605
- res.setEncoding('utf8');
606
- res.on('data', (chunk) => {
607
- buffer += chunk;
608
- let index = buffer.indexOf('\n\n');
609
- while (index !== -1) {
610
- const frame = buffer.slice(0, index);
611
- buffer = buffer.slice(index + 2);
612
- this._onFrame(frame);
613
- index = buffer.indexOf('\n\n');
614
- }
615
-
616
- if (buffer.length > 1_000_000) {
617
- buffer = '';
618
- }
619
- });
620
- const done = () => {
621
- if (this.stream === res) {
622
- this.stream = null;
623
- this._scheduleRetry();
624
- }
625
- };
626
-
627
- res.on('end', done);
628
- res.on('close', done);
629
- res.on('error', (error) => {
630
- this.logger.debug('meta api event stream: ' + error.message);
631
- done();
632
- });
633
- })
634
- .catch((error) => {
635
- this.logger.warn('meta api event stream: ' + error.message);
636
- this._setConnected(false);
637
- this._scheduleRetry();
638
- });
695
+ this._setConnected(false);
696
+ if (state !== 'closed') {
697
+ this._probeLater();
698
+ }
639
699
  }
640
700
 
641
701
  /**
642
- * One SSE frame. Comments (the 30 s heartbeat) carry no data line.
643
- * @param {string} frame
702
+ * @param {boolean} connected
644
703
  */
645
- _onFrame(frame) {
646
- const data = frame
647
- .split('\n')
648
- .filter((line) => line.startsWith('data:'))
649
- .map((line) => line.slice(5).trim())
650
- .join('\n');
651
- if (!data) {
652
- return;
704
+ _setConnected(connected) {
705
+ if (this.connected !== connected) {
706
+ this.connected = connected;
707
+ this.onStatus(connected);
653
708
  }
709
+ }
654
710
 
655
- let event;
656
- try {
657
- event = JSON.parse(data);
658
- } catch {
659
- 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) {
660
714
  return;
661
715
  }
662
716
 
663
- 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);
664
723
  }
665
724
 
666
725
  /**
667
- * Apply one change event. Object changes are applied in place; anything
668
- * that can rewrite member paths (enum and node events, an import, a gap in
669
- * the revisions, an explicit resync) re-reads the snapshot.
670
- * @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>}
671
730
  */
672
- _onEvent(event) {
673
- 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) {
674
741
  return;
675
742
  }
676
743
 
677
- const revision = Number(event.revision) || 0;
678
- const gap = revision > 0 && this.revision > 0 && revision > this.revision + 1;
679
-
680
- if (event.kind === 'resync' || event.kind === 'import' || gap) {
681
- this.logger.debug('meta api resnapshot (' + (gap ? 'revision gap' : event.kind) + ')');
682
- this._loadSnapshot().catch((error) => this.logger.warn('meta api snapshot: ' + error.message));
683
- 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
+ }
684
762
  }
685
763
 
686
- if (revision > this.revision) {
687
- this.revision = revision;
688
- }
764
+ this._probeLater();
765
+ }
689
766
 
690
- if (!this.document) {
767
+ /** Coalesce a burst of events into one update. */
768
+ _scheduleEmit() {
769
+ if (this.emitTimeout) {
691
770
  return;
692
771
  }
693
772
 
694
- switch (event.kind) {
695
- case 'object.updated': {
696
- if (typeof event.ref === 'string' && event.value) {
697
- this.document.objects = this.document.objects || {};
698
- this.document.objects[event.ref] = event.value;
699
- this._scheduleEmit();
700
- }
701
-
702
- break;
703
- }
704
-
705
- case 'object.deleted': {
706
- if (typeof event.ref === 'string' && this.document.objects) {
707
- delete this.document.objects[event.ref];
708
- this._scheduleEmit();
709
- }
710
-
711
- break;
712
- }
713
-
714
- case 'enum.created':
715
- case 'enum.updated':
716
- case 'enum.deleted':
717
- case 'node.created':
718
- case 'node.updated':
719
- case 'node.deleted':
720
- case 'node.moved': {
721
- // rooms and functions changed shape - member paths may have been
722
- // rewritten in the same revision, so take a fresh snapshot
723
- this._loadSnapshot().catch((error) => this.logger.warn('meta api snapshot: ' + error.message));
724
- break;
773
+ this.emitTimeout = setTimeout(() => {
774
+ this.emitTimeout = null;
775
+ if (!this.stopped) {
776
+ this._emit();
725
777
  }
778
+ }, this.emitDelay);
779
+ }
726
780
 
727
- default:
728
- }
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);
729
786
  }
730
787
  }
731
788
 
@@ -733,11 +790,13 @@ module.exports = {
733
790
  API_PATH,
734
791
  LOCAL_TOKEN_FILE,
735
792
  MetaProvider,
793
+ namesTransport,
736
794
  buildNames,
737
795
  detect,
738
796
  detectOutcome,
739
797
  flattenEnum,
740
798
  memberNames,
799
+ pinnedConnection,
741
800
  readLocalToken,
742
801
  refToAddress,
743
802
  refToIface,