node-red-contrib-ccu 4.9.0 → 4.10.1

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
  */
@@ -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,