signalk-multihelm 0.4.0 → 0.5.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/plugin/index.js CHANGED
@@ -1,125 +1,17 @@
1
+ import fs from "node:fs";
1
2
  import os from "node:os";
2
- import { Type } from "typebox";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
3
5
  import makeMdns from "multicast-dns";
4
- import { isDeepStrictEqual } from "node:util";
5
- import fs from "node:fs";
6
6
  import http from "node:http";
7
7
  import https from "node:https";
8
8
  import { pipeline } from "node:stream/promises";
9
+ import { Type } from "typebox";
10
+ import { isDeepStrictEqual } from "node:util";
9
11
  import crypto from "node:crypto";
10
- import path from "node:path";
11
12
  import { Value } from "typebox/value";
12
13
  // src/api.ts
13
14
  var PROPERTY_NAME = "multihelm";
14
- // src/discovery.ts
15
- /**
16
- * Finds the other Signal K servers on the network, to offer them for pairing.
17
- *
18
- * Every Signal K server announces its REST API as `_signalk-http._tcp` (or
19
- * `_signalk-https._tcp`) over mDNS. The server's own discovery turns these
20
- * into data-connection suggestions only, so Multihelm asks for them itself
21
- * while it runs. Found servers are only shown; the user pairs with one.
22
- */
23
- var SERVICES = ["_signalk-http._tcp.local", "_signalk-https._tcp.local"];
24
- var QUERY_INTERVAL_MS = 3e4;
25
- /** A server not heard of for this long is dropped from the list. */
26
- var FORGET_AFTER_MS = 18e4;
27
- function txtRecord(answer) {
28
- const result = {};
29
- const data = Array.isArray(answer.data) ? answer.data : [answer.data];
30
- for (const entry of data) {
31
- const text = typeof entry === "string" ? entry : Buffer.from(entry).toString("utf-8");
32
- const eq = text.indexOf("=");
33
- if (eq > 0) result[text.slice(0, eq)] = text.slice(eq + 1);
34
- }
35
- return result;
36
- }
37
- function ownAddresses() {
38
- const result = /* @__PURE__ */ new Set();
39
- for (const list of Object.values(os.networkInterfaces())) for (const info of list ?? []) result.add(info.address);
40
- return result;
41
- }
42
- var ServerDiscovery = class {
43
- ownPort;
44
- mdns = null;
45
- timer = null;
46
- instances = /* @__PURE__ */ new Map();
47
- addresses = /* @__PURE__ */ new Map();
48
- found = /* @__PURE__ */ new Map();
49
- constructor(ownPort) {
50
- this.ownPort = ownPort;
51
- }
52
- start() {
53
- if (this.mdns) return;
54
- try {
55
- this.mdns = makeMdns();
56
- } catch {
57
- this.mdns = null;
58
- return;
59
- }
60
- this.mdns.on("response", (response) => {
61
- this.takeRecords([...response.answers, ...response.additionals]);
62
- });
63
- this.mdns.on("error", () => {});
64
- const query = () => {
65
- this.mdns?.query(SERVICES.map((name) => ({
66
- name,
67
- type: "PTR"
68
- })));
69
- };
70
- query();
71
- this.timer = setInterval(query, QUERY_INTERVAL_MS);
72
- }
73
- stop() {
74
- if (this.timer) {
75
- clearInterval(this.timer);
76
- this.timer = null;
77
- }
78
- this.mdns?.destroy();
79
- this.mdns = null;
80
- }
81
- list() {
82
- const now = Date.now();
83
- for (const [key, server] of this.found) if (now - server.lastSeen > FORGET_AFTER_MS) this.found.delete(key);
84
- return [...this.found.values()].sort((a, b) => a.name.localeCompare(b.name));
85
- }
86
- /** Fold in the records of one mDNS response. */
87
- takeRecords(records) {
88
- for (const record of records) if (record.type === "PTR" && SERVICES.includes(record.name)) {
89
- const instance = record.data;
90
- if (!this.instances.has(instance)) this.instances.set(instance, {
91
- service: record.name,
92
- txt: {}
93
- });
94
- }
95
- for (const record of records) if (record.type === "SRV") {
96
- const instance = this.instances.get(record.name);
97
- if (instance) {
98
- const srv = record.data;
99
- instance.target = srv.target;
100
- instance.port = srv.port;
101
- }
102
- } else if (record.type === "TXT") {
103
- const instance = this.instances.get(record.name);
104
- if (instance) instance.txt = txtRecord(record);
105
- } else if (record.type === "A") this.addresses.set(record.name, record.data);
106
- const own = ownAddresses();
107
- for (const [instance, info] of this.instances) {
108
- if (!info.target || info.port === void 0) continue;
109
- const address = this.addresses.get(info.target);
110
- if (!address) continue;
111
- if (own.has(address) && info.port === this.ownPort()) continue;
112
- const url = `${info.service.startsWith("_signalk-https") ? "https" : "http"}://${address}:${String(info.port)}`;
113
- const server = {
114
- name: instance.replace(`.${info.service}`, ""),
115
- url,
116
- lastSeen: Date.now()
117
- };
118
- if (info.txt.vname) server.vessel = info.txt.vname;
119
- this.found.set(url, server);
120
- }
121
- }
122
- };
123
15
  // src/peer-client.ts
124
16
  /**
125
17
  * HTTP client for a Multihelm peer: its routes, and the Signal K
@@ -131,6 +23,19 @@ var ServerDiscovery = class {
131
23
  */
132
24
  var ROUTE_PREFIX = "/plugins/signalk-multihelm";
133
25
  var REQUEST_TIMEOUT_MS$1 = 3e4;
26
+ function helloQuery(from) {
27
+ if (!from) return "";
28
+ const query = new URLSearchParams({
29
+ from: from.serverId,
30
+ name: from.name
31
+ });
32
+ if (from.signalk) query.set("signalk", from.signalk);
33
+ if (from.multihelm) query.set("multihelm", from.multihelm);
34
+ return `?${query.toString()}`;
35
+ }
36
+ function optionalText(value) {
37
+ return typeof value === "string" && value !== "" ? value : void 0;
38
+ }
134
39
  var PeerHttpError = class extends Error {
135
40
  status;
136
41
  constructor(status, message) {
@@ -189,16 +94,23 @@ function normalizePeerUrl(input) {
189
94
  if (url.protocol !== "http:" && url.protocol !== "https:" || url.username || url.password) return null;
190
95
  return `${url.protocol}//${url.host}`;
191
96
  }
192
- async function fetchHello(base, token) {
193
- const body = await getJson(`${base}${ROUTE_PREFIX}/hello`, token);
97
+ async function fetchHello(base, token, from) {
98
+ const body = await getJson(`${base}${ROUTE_PREFIX}/hello${helloQuery(from)}`, token);
194
99
  if (typeof body.serverId !== "string" || typeof body.protocol !== "number") throw new Error(`${base} did not answer as a Multihelm peer`);
195
- return {
100
+ const hello = {
196
101
  serverId: body.serverId,
197
102
  name: typeof body.name === "string" ? body.name : base,
198
103
  protocol: body.protocol,
199
104
  datasets: Array.isArray(body.datasets) ? body.datasets.filter((d) => typeof d === "string") : [],
200
105
  master: body.master === true
201
106
  };
107
+ const signalk = optionalText(body.signalk);
108
+ const multihelm = optionalText(body.multihelm);
109
+ return {
110
+ ...hello,
111
+ ...signalk ? { signalk } : {},
112
+ ...multihelm ? { multihelm } : {}
113
+ };
202
114
  }
203
115
  async function fetchVesselSettings(base, token) {
204
116
  return getJson(`${base}${ROUTE_PREFIX}/vessel-settings`, token);
@@ -301,6 +213,144 @@ function interpretReply(raw) {
301
213
  message: "unexpected access request reply"
302
214
  };
303
215
  }
216
+ // src/discovery.ts
217
+ /**
218
+ * Finds the other Signal K servers on the network, to offer them for pairing.
219
+ *
220
+ * Every Signal K server announces its REST API as `_signalk-http._tcp` (or
221
+ * `_signalk-https._tcp`) over mDNS. The server's own discovery turns these
222
+ * into data-connection suggestions only, so Multihelm asks for them itself
223
+ * while it runs. Found servers are only shown; the user pairs with one.
224
+ */
225
+ var SERVICES = ["_signalk-http._tcp.local", "_signalk-https._tcp.local"];
226
+ var QUERY_INTERVAL_MS = 3e4;
227
+ /** A server not heard of for this long is dropped from the list. */
228
+ var FORGET_AFTER_MS = 18e4;
229
+ function txtRecord(answer) {
230
+ const result = {};
231
+ const data = Array.isArray(answer.data) ? answer.data : [answer.data];
232
+ for (const entry of data) {
233
+ const text = typeof entry === "string" ? entry : Buffer.from(entry).toString("utf-8");
234
+ const eq = text.indexOf("=");
235
+ if (eq > 0) result[text.slice(0, eq)] = text.slice(eq + 1);
236
+ }
237
+ return result;
238
+ }
239
+ function ownAddresses() {
240
+ const result = /* @__PURE__ */ new Set();
241
+ for (const list of Object.values(os.networkInterfaces())) for (const info of list ?? []) result.add(info.address);
242
+ return result;
243
+ }
244
+ var ServerDiscovery = class {
245
+ ownPort;
246
+ mdns = null;
247
+ timer = null;
248
+ instances = /* @__PURE__ */ new Map();
249
+ addresses = /* @__PURE__ */ new Map();
250
+ found = /* @__PURE__ */ new Map();
251
+ constructor(ownPort) {
252
+ this.ownPort = ownPort;
253
+ }
254
+ start() {
255
+ if (this.mdns) return;
256
+ try {
257
+ this.mdns = makeMdns();
258
+ } catch {
259
+ this.mdns = null;
260
+ return;
261
+ }
262
+ this.mdns.on("response", (response) => {
263
+ this.takeRecords([...response.answers, ...response.additionals]);
264
+ });
265
+ this.mdns.on("error", () => {});
266
+ const query = () => {
267
+ this.mdns?.query(SERVICES.map((name) => ({
268
+ name,
269
+ type: "PTR"
270
+ })));
271
+ };
272
+ query();
273
+ this.timer = setInterval(query, QUERY_INTERVAL_MS);
274
+ }
275
+ stop() {
276
+ if (this.timer) {
277
+ clearInterval(this.timer);
278
+ this.timer = null;
279
+ }
280
+ this.mdns?.destroy();
281
+ this.mdns = null;
282
+ }
283
+ list() {
284
+ const now = Date.now();
285
+ for (const [key, server] of this.found) if (now - server.lastSeen > FORGET_AFTER_MS) this.found.delete(key);
286
+ return [...this.found.values()].sort((a, b) => a.name.localeCompare(b.name));
287
+ }
288
+ /** Fold in the records of one mDNS response. */
289
+ takeRecords(records) {
290
+ for (const record of records) if (record.type === "PTR" && SERVICES.includes(record.name)) {
291
+ const instance = record.data;
292
+ if (!this.instances.has(instance)) this.instances.set(instance, {
293
+ service: record.name,
294
+ txt: {}
295
+ });
296
+ }
297
+ for (const record of records) if (record.type === "SRV") {
298
+ const instance = this.instances.get(record.name);
299
+ if (instance) {
300
+ const srv = record.data;
301
+ instance.target = srv.target;
302
+ instance.port = srv.port;
303
+ }
304
+ } else if (record.type === "TXT") {
305
+ const instance = this.instances.get(record.name);
306
+ if (instance) instance.txt = txtRecord(record);
307
+ } else if (record.type === "A") this.addresses.set(record.name, record.data);
308
+ const own = ownAddresses();
309
+ for (const [instance, info] of this.instances) {
310
+ if (!info.target || info.port === void 0) continue;
311
+ const address = this.addresses.get(info.target);
312
+ if (!address) continue;
313
+ if (own.has(address) && info.port === this.ownPort()) continue;
314
+ const url = normalizePeerUrl(`${info.service.startsWith("_signalk-https") ? "https" : "http"}://${address}:${String(info.port)}`);
315
+ if (!url) continue;
316
+ const server = {
317
+ name: instance.replace(`.${info.service}`, ""),
318
+ url,
319
+ lastSeen: Date.now()
320
+ };
321
+ if (info.txt.vname) server.vessel = info.txt.vname;
322
+ this.found.set(url, server);
323
+ }
324
+ }
325
+ };
326
+ // src/config.ts
327
+ var ConfigSchema = Type.Object({
328
+ master: Type.Boolean({
329
+ title: "This server is the boat's master",
330
+ description: "Set this on one server only. Plugins that run on the master alone run here, and the other servers use them through this one.",
331
+ default: false
332
+ }),
333
+ followVessel: Type.Boolean({
334
+ title: "Take the vessel data over from the master",
335
+ description: "Name, MMSI, call sign, dimensions and ship type from Server -> Settings. Changes made here are replaced by the master's.",
336
+ default: true
337
+ }),
338
+ followMetadata: Type.Boolean({
339
+ title: "Take the path metadata over from the master",
340
+ description: "Display names, units, zones and alarm limits set for paths. Changes made here are replaced by the master's.",
341
+ default: true
342
+ }),
343
+ followSourcePriorities: Type.Boolean({
344
+ title: "Take the source priorities over from the master",
345
+ description: "Which source wins for a path, from Data -> Source Priorities. They name sources by connection, so give the NMEA 2000 bus the same connection name on every server. Changes made here are replaced by the master's.",
346
+ default: true
347
+ }),
348
+ historyFromMaster: Type.Boolean({
349
+ title: "Answer this server's History API from the master",
350
+ description: "While the master has a history provider (signalk-questdb, for example), history graphs on this server show the master's history, so it is kept once on the boat. Does nothing on the master, while the master has no history, or before Signal K 2.32.0.",
351
+ default: true
352
+ })
353
+ });
304
354
  // src/source-priorities.ts
305
355
  function isRecord$1(value) {
306
356
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -485,7 +535,8 @@ function parseVesselSettings(raw) {
485
535
  * master with the pairing token and written here through this server's own
486
536
  * REST API, the way its settings pages write them, so they survive a
487
537
  * restart. Writing needs an admin device token on this server, asked for
488
- * once; until it is approved nothing is written.
538
+ * once; until it is approved nothing is written. Metadata of a path the
539
+ * master has none for stays as it is, unless it was the master's before.
489
540
  */
490
541
  function errorText$2(error) {
491
542
  return error instanceof Error ? error.message : String(error);
@@ -494,26 +545,68 @@ function errorText$2(error) {
494
545
  function hasPriorities(priorities) {
495
546
  return priorities.groups.length > 0 || Object.keys(priorities.overrides).length > 0;
496
547
  }
548
+ /**
549
+ * What was last written here and what this server kept of it, seen a round
550
+ * later. A server may keep a value differently from how it was written (a
551
+ * base delta file with the same path twice keeps the older one in force), so
552
+ * a value is not written again until the master's or this server's changes.
553
+ */
554
+ var WrittenValues = class {
555
+ written = /* @__PURE__ */ new Map();
556
+ /** Whether `target` is to be written over `local`. */
557
+ due(key, target, local) {
558
+ if (isDeepStrictEqual(target, local)) {
559
+ this.written.delete(key);
560
+ return false;
561
+ }
562
+ const last = this.written.get(key);
563
+ if (last && isDeepStrictEqual(last.target, target)) {
564
+ if (!last.kept) {
565
+ last.kept = { value: local };
566
+ return false;
567
+ }
568
+ if (isDeepStrictEqual(last.kept.value, local)) return false;
569
+ }
570
+ return true;
571
+ }
572
+ wrote(key, target) {
573
+ this.written.set(key, { target });
574
+ }
575
+ /** What is not looked at in a round may have changed meanwhile, so it is forgotten. */
576
+ keepOnly(keys) {
577
+ for (const key of this.written.keys()) if (!keys.has(key)) this.written.delete(key);
578
+ }
579
+ };
497
580
  function metaUrl(base, path) {
498
581
  return `${base}/signalk/v1/api/vessels/self/${path.split(".").map((s) => encodeURIComponent(s)).join("/")}/meta`;
499
582
  }
500
583
  var MasterFollower = class {
501
584
  host;
502
585
  access;
586
+ prioritiesWritten = new WrittenValues();
587
+ metaWritten = new WrittenValues();
503
588
  /**
504
- * The master's priorities last written here and what this server kept of
505
- * them, seen a round later: should it keep them differently, they are not
506
- * written again until the master's or this server's change.
589
+ * The paths whose metadata is the master's: all it has, and the ones it
590
+ * had until they are gone here too.
507
591
  */
508
- prioritiesWritten = null;
592
+ followedMeta;
593
+ /** The list as last saved; a failed save is tried again the next round. */
594
+ followedMetaSaved;
509
595
  constructor(host) {
510
596
  this.host = host;
511
597
  this.access = host.store.loadOwnAccess();
598
+ const followed = host.store.loadFollowedMeta();
599
+ this.followedMeta = new Set(followed);
600
+ this.followedMetaSaved = JSON.stringify(followed.sort());
512
601
  }
513
602
  /** Whether the user has to approve this server's own access request. */
514
603
  waitingForApproval() {
515
604
  return this.access.state === "waiting-approval";
516
605
  }
606
+ /** The identifier of the access request on this server, as Security -> Access Requests lists it. */
607
+ accessRequestId() {
608
+ return `signalk-multihelm-self-${this.host.serverId}`;
609
+ }
517
610
  /** Whether the user denied it; it is asked for again only after a restart. */
518
611
  denied() {
519
612
  return this.access.state === "denied";
@@ -532,7 +625,12 @@ var MasterFollower = class {
532
625
  }
533
626
  if (!remote) return;
534
627
  const vesselChanged = followVessel && VESSEL_FIELDS.some((k) => remote.vessel[k] !== local.vessel[k]);
535
- const metaChanged = followMeta ? [.../* @__PURE__ */ new Set([...Object.keys(remote.meta), ...Object.keys(local.meta)])].filter((p) => !isDeepStrictEqual(remote.meta[p], local.meta[p])) : [];
628
+ if (followMeta) {
629
+ this.followedMeta = /* @__PURE__ */ new Set([...Object.keys(remote.meta), ...[...this.followedMeta].filter((p) => local.meta[p] !== void 0)]);
630
+ this.metaWritten.keepOnly(this.followedMeta);
631
+ this.saveFollowedMeta();
632
+ }
633
+ const metaChanged = followMeta ? [...this.followedMeta].filter((p) => this.metaWritten.due(p, remote.meta[p], local.meta[p])) : [];
536
634
  const priorities = followPriorities ? this.prioritiesToWrite(remote.priorities, local.priorities) : null;
537
635
  if (!vesselChanged && metaChanged.length === 0 && !priorities) return;
538
636
  const token = await this.ownToken();
@@ -543,13 +641,11 @@ var MasterFollower = class {
543
641
  for (const path of metaChanged) {
544
642
  const value = remote.meta[path];
545
643
  await (value === void 0 ? callServer("DELETE", metaUrl(base, path), token) : callServer("PUT", metaUrl(base, path), token, { value }));
644
+ this.metaWritten.wrote(path, value);
546
645
  }
547
646
  if (priorities) {
548
647
  await callServer("PUT", `${base}/skServer/priorities`, token, priorities);
549
- this.prioritiesWritten = {
550
- target: priorities,
551
- kept: null
552
- };
648
+ this.prioritiesWritten.wrote("", priorities);
553
649
  }
554
650
  } catch (error) {
555
651
  if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) this.setAccess({
@@ -558,22 +654,22 @@ var MasterFollower = class {
558
654
  });
559
655
  this.host.error(`Multihelm: taking over the master's vessel settings: ${errorText$2(error)}`);
560
656
  }
657
+ if (followMeta) this.saveFollowedMeta();
658
+ }
659
+ saveFollowedMeta() {
660
+ const paths = [...this.followedMeta].sort();
661
+ const text = JSON.stringify(paths);
662
+ if (text === this.followedMetaSaved) return;
663
+ try {
664
+ this.host.store.saveFollowedMeta(paths);
665
+ this.followedMetaSaved = text;
666
+ } catch (error) {
667
+ this.host.error(`Multihelm: saving the paths that follow the master: ${errorText$2(error)}`);
668
+ }
561
669
  }
562
670
  prioritiesToWrite(remote, local) {
563
671
  if (!remote || !hasPriorities(remote) || !local) return null;
564
- if (isDeepStrictEqual(remote, local)) {
565
- this.prioritiesWritten = null;
566
- return null;
567
- }
568
- const written = this.prioritiesWritten;
569
- if (written && isDeepStrictEqual(written.target, remote)) {
570
- if (written.kept === null) {
571
- written.kept = local;
572
- return null;
573
- }
574
- if (isDeepStrictEqual(written.kept, local)) return null;
575
- }
576
- return remote;
672
+ return this.prioritiesWritten.due("", remote, local) ? remote : null;
577
673
  }
578
674
  /** The vessel route writes every field, so the ones that stay here are sent back as they are. */
579
675
  async writeVessel(base, token, vessel) {
@@ -592,7 +688,7 @@ var MasterFollower = class {
592
688
  if (this.access.state === "denied") return null;
593
689
  let result;
594
690
  try {
595
- result = this.access.state === "waiting-approval" && this.access.requestHref ? await pollAccess(base, this.access.requestHref) : await requestAccess(base, `signalk-multihelm-self-${this.host.serverId}`, "Multihelm: take the vessel settings over from the master", "admin");
691
+ result = this.access.state === "waiting-approval" && this.access.requestHref ? await pollAccess(base, this.access.requestHref) : await requestAccess(base, this.accessRequestId(), "Multihelm: take the vessel settings over from the master", "admin");
596
692
  } catch (error) {
597
693
  this.host.debug(`Multihelm: access request on this server: ${errorText$2(error)}`);
598
694
  return null;
@@ -1070,7 +1166,19 @@ var ROUND_INTERVAL_MS = 6e4;
1070
1166
  * on a timer of its own, so a long round of transfers does not hold it up.
1071
1167
  */
1072
1168
  var MASTER_CHECK_INTERVAL_MS = 3e4;
1073
- 5 * MASTER_CHECK_INTERVAL_MS;
1169
+ /**
1170
+ * A peer set to be the master counts as the master while it answered this
1171
+ * recently, so a few missed answers do not move the role.
1172
+ */
1173
+ var MASTER_STALE_MS = 5 * MASTER_CHECK_INTERVAL_MS;
1174
+ /** Every peer asks every 30 s, so a sighting is saved only now and then. */
1175
+ var PAIRED_BY_SAVE_MS = 6e5;
1176
+ /** Without security anyone may ask, so writes of that list are gathered, never one per request. */
1177
+ var PAIRED_BY_FLUSH_MS = 1e4;
1178
+ /** Without security anyone may ask for `hello`; the list stays small. */
1179
+ var MAX_PAIRED_BY = 32;
1180
+ /** A pairing request waiting for approval is followed this often, so an approval shows at once. */
1181
+ var PAIRING_POLL_MS = 5e3;
1074
1182
  async function hashFile(file) {
1075
1183
  const hash = crypto.createHash("sha256");
1076
1184
  await pipeline(fs.createReadStream(file), hash);
@@ -1079,6 +1187,16 @@ async function hashFile(file) {
1079
1187
  function errorText$1(error) {
1080
1188
  return error instanceof Error ? error.message : String(error);
1081
1189
  }
1190
+ /** Said without the address, which the panel shows anyway. */
1191
+ function helloErrorText(error) {
1192
+ if (!(error instanceof PeerHttpError)) return errorText$1(error);
1193
+ switch (error.status) {
1194
+ case 404: return "Multihelm is not running there";
1195
+ case 401:
1196
+ case 403: return "access was revoked on the peer";
1197
+ default: return `HTTP ${String(error.status)}`;
1198
+ }
1199
+ }
1082
1200
  function toListed(entry) {
1083
1201
  return {
1084
1202
  key: entry.key,
@@ -1104,6 +1222,14 @@ var Multihelm = class {
1104
1222
  stopped = false;
1105
1223
  /** Peer URL → when it last answered as set to be the master. */
1106
1224
  masterSeen = /* @__PURE__ */ new Map();
1225
+ /** Peer URL → its last `hello`, and when. */
1226
+ answers = /* @__PURE__ */ new Map();
1227
+ /** Peer URL → why its last `hello` failed. */
1228
+ helloErrors = /* @__PURE__ */ new Map();
1229
+ /** Server id → a server that asks this one for its `hello`. */
1230
+ pairedBy;
1231
+ pairedBySavedAt = 0;
1232
+ pairedByTimer = null;
1107
1233
  roleListeners = /* @__PURE__ */ new Set();
1108
1234
  statusListeners = /* @__PURE__ */ new Set();
1109
1235
  /** What the role listeners were last told: role and master id. */
@@ -1112,12 +1238,15 @@ var Multihelm = class {
1112
1238
  announcedStatus = "";
1113
1239
  masterTimer = null;
1114
1240
  checkingMasters = false;
1241
+ pairingTimer = null;
1242
+ pollingPairings = false;
1115
1243
  serverId;
1116
1244
  constructor(store, host) {
1117
1245
  this.store = store;
1118
1246
  this.host = host;
1119
1247
  this.peers = store.loadPeers();
1120
1248
  this.serverId = store.serverId();
1249
+ this.pairedBy = new Map(store.loadPairedBy().map((s) => [s.id, s]));
1121
1250
  }
1122
1251
  start() {
1123
1252
  this.started = true;
@@ -1131,6 +1260,11 @@ var Multihelm = class {
1131
1260
  this.masterTimer = setInterval(() => {
1132
1261
  this.checkMasters();
1133
1262
  }, MASTER_CHECK_INTERVAL_MS);
1263
+ this.pairingTimer = setInterval(() => {
1264
+ this.pollPairings().catch((error) => {
1265
+ this.host.error(`Multihelm: following a pairing request: ${errorText$1(error)}`);
1266
+ });
1267
+ }, PAIRING_POLL_MS);
1134
1268
  }
1135
1269
  stop() {
1136
1270
  this.started = false;
@@ -1138,14 +1272,18 @@ var Multihelm = class {
1138
1272
  for (const timer of [this.timer, this.soon]) if (timer) clearTimeout(timer);
1139
1273
  this.timer = null;
1140
1274
  this.soon = null;
1141
- if (this.masterTimer) {
1142
- clearInterval(this.masterTimer);
1143
- this.masterTimer = null;
1275
+ for (const timer of [this.masterTimer, this.pairingTimer]) if (timer) clearInterval(timer);
1276
+ this.masterTimer = null;
1277
+ this.pairingTimer = null;
1278
+ if (this.pairedByTimer) {
1279
+ clearTimeout(this.pairedByTimer);
1280
+ this.pairedByTimer = null;
1281
+ this.savePairedBy();
1144
1282
  }
1145
1283
  }
1146
1284
  /**
1147
1285
  * Asks every paired peer whether it is set to be the master. Runs outside
1148
- * the work queue and touches nothing but `masterSeen`, so it neither waits
1286
+ * the work queue and touches nothing but what it keeps of the answers, so it neither waits
1149
1287
  * for a round nor races one.
1150
1288
  */
1151
1289
  async checkMasters() {
@@ -1155,11 +1293,13 @@ var Multihelm = class {
1155
1293
  await Promise.all(this.peers.filter((p) => p.state === "paired" && p.id !== "").map(async (peer) => {
1156
1294
  let hello;
1157
1295
  try {
1158
- hello = await fetchHello(peer.url, peer.token);
1159
- } catch {
1296
+ hello = await fetchHello(peer.url, peer.token, this.helloFrom());
1297
+ } catch (error) {
1298
+ if (!this.stopped && this.peers.includes(peer)) this.helloErrors.set(peer.url, helloErrorText(error));
1160
1299
  return;
1161
1300
  }
1162
1301
  if (this.stopped || !this.peers.includes(peer) || hello.serverId !== peer.id) return;
1302
+ this.answered(peer.url, hello);
1163
1303
  if (hello.master) this.masterSeen.set(peer.url, Date.now());
1164
1304
  else this.masterSeen.delete(peer.url);
1165
1305
  }));
@@ -1168,6 +1308,30 @@ var Multihelm = class {
1168
1308
  }
1169
1309
  if (!this.stopped) this.announceRole();
1170
1310
  }
1311
+ /**
1312
+ * Follows up the pairing requests waiting for approval, between rounds. At
1313
+ * most one waits in the queue, so a long round does not pile them up.
1314
+ */
1315
+ async pollPairings() {
1316
+ const waiting = () => this.peers.filter((p) => p.state === "waiting-approval");
1317
+ if (this.pollingPairings || this.stopped || waiting().length === 0) return;
1318
+ this.pollingPairings = true;
1319
+ try {
1320
+ await this.serialize(async () => {
1321
+ let paired = false;
1322
+ for (const peer of waiting()) {
1323
+ if (this.stopped) break;
1324
+ await this.pollPairingLocked(peer);
1325
+ paired ||= peer.state === "paired";
1326
+ }
1327
+ this.store.savePeers(this.peers);
1328
+ this.announceRole();
1329
+ if (paired) this.changedSoon();
1330
+ });
1331
+ } finally {
1332
+ this.pollingPairings = false;
1333
+ }
1334
+ }
1171
1335
  /** Run `task` after every task queued before it. */
1172
1336
  serialize(task) {
1173
1337
  const run = this.queue.then(task, task);
@@ -1321,8 +1485,82 @@ var Multihelm = class {
1321
1485
  name: this.host.serverName(),
1322
1486
  protocol: 1,
1323
1487
  datasets: this.datasetIds(),
1324
- master: this.host.isMaster()
1488
+ master: this.host.isMaster(),
1489
+ ...this.versions()
1490
+ };
1491
+ }
1492
+ versions() {
1493
+ const { signalk, multihelm } = this.host.versions?.() ?? {};
1494
+ return {
1495
+ ...signalk ? { signalk } : {},
1496
+ ...multihelm ? { multihelm } : {}
1497
+ };
1498
+ }
1499
+ helloFrom() {
1500
+ return {
1501
+ serverId: this.serverId,
1502
+ name: this.host.serverName(),
1503
+ ...this.versions()
1504
+ };
1505
+ }
1506
+ answered(url, hello) {
1507
+ this.answers.set(url, {
1508
+ at: Date.now(),
1509
+ hello
1510
+ });
1511
+ this.helloErrors.delete(url);
1512
+ }
1513
+ /**
1514
+ * Notes a server that asked for this one's `hello`. Its last sighting is
1515
+ * saved with any change to what it is, and otherwise once in a while.
1516
+ */
1517
+ sawPairedServer(from) {
1518
+ if (from.serverId === this.serverId) return;
1519
+ const now = Date.now();
1520
+ const known = this.pairedBy.get(from.serverId);
1521
+ const server = {
1522
+ id: from.serverId,
1523
+ name: from.name,
1524
+ ...from.signalk ? { signalk: from.signalk } : {},
1525
+ ...from.multihelm ? { multihelm: from.multihelm } : {},
1526
+ lastSeen: now
1325
1527
  };
1528
+ this.pairedBy.set(server.id, server);
1529
+ if (this.pairedBy.size > MAX_PAIRED_BY) {
1530
+ const oldest = [...this.pairedBy.values()].sort((x, y) => x.lastSeen - y.lastSeen)[0];
1531
+ if (oldest) this.pairedBy.delete(oldest.id);
1532
+ }
1533
+ if (!known || known.name !== server.name || known.signalk !== server.signalk || known.multihelm !== server.multihelm || now - this.pairedBySavedAt >= PAIRED_BY_SAVE_MS) this.savePairedBySoon();
1534
+ }
1535
+ /** The servers paired with this one, by name. */
1536
+ pairedByInfo() {
1537
+ const now = Date.now();
1538
+ return [...this.pairedBy.values()].sort((x, y) => x.name.localeCompare(y.name)).map((s) => ({
1539
+ ...s,
1540
+ online: now - s.lastSeen <= MASTER_STALE_MS
1541
+ }));
1542
+ }
1543
+ /** Drops a server from that list; it comes back when it asks again. */
1544
+ forgetPairedBy(id) {
1545
+ const removed = this.pairedBy.delete(id);
1546
+ if (removed) this.savePairedBy();
1547
+ return removed;
1548
+ }
1549
+ savePairedBySoon() {
1550
+ if (this.pairedByTimer) return;
1551
+ this.pairedByTimer = setTimeout(() => {
1552
+ this.pairedByTimer = null;
1553
+ this.savePairedBy();
1554
+ }, PAIRED_BY_FLUSH_MS);
1555
+ this.pairedByTimer.unref();
1556
+ }
1557
+ savePairedBy() {
1558
+ this.pairedBySavedAt = Date.now();
1559
+ try {
1560
+ this.store.savePairedBy([...this.pairedBy.values()]);
1561
+ } catch (error) {
1562
+ this.host.error(`Multihelm: saving the servers paired with this one: ${errorText$1(error)}`);
1563
+ }
1326
1564
  }
1327
1565
  manifest(datasetId, since) {
1328
1566
  const dataset = this.datasets.get(datasetId);
@@ -1338,14 +1576,18 @@ var Multihelm = class {
1338
1576
  if (!file?.sha256 || !local || local.size !== file.size || local.mtimeMs !== file.mtimeMs) return null;
1339
1577
  return local.path;
1340
1578
  }
1579
+ /** Errors with one dataset are cleared by that dataset's next sync. */
1580
+ isDatasetError(text) {
1581
+ return [...this.datasets.keys()].some((id) => text.startsWith(`${id}:`));
1582
+ }
1341
1583
  async syncPeerLocked(peer) {
1342
1584
  try {
1343
1585
  for (const dataset of this.datasets.values()) {
1344
1586
  if (this.stopped) return;
1345
1587
  await this.syncDatasetLocked(peer, dataset);
1346
1588
  }
1347
- peer.lastSeen = Date.now();
1348
1589
  peer.lastSync = Date.now();
1590
+ if (peer.lastError !== void 0 && !this.isDatasetError(peer.lastError)) delete peer.lastError;
1349
1591
  } catch (error) {
1350
1592
  if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {
1351
1593
  peer.state = "needs-pairing";
@@ -1360,7 +1602,10 @@ var Multihelm = class {
1360
1602
  try {
1361
1603
  manifest = await fetchManifest(peer.url, peer.token, id, peer.cursors[id] ?? 0);
1362
1604
  } catch (error) {
1363
- if (error instanceof PeerHttpError && error.status === 404) return;
1605
+ if (error instanceof PeerHttpError && error.status === 404) {
1606
+ if (peer.lastError?.startsWith(`${id}:`)) delete peer.lastError;
1607
+ return;
1608
+ }
1364
1609
  throw error;
1365
1610
  }
1366
1611
  try {
@@ -1498,8 +1743,18 @@ var Multihelm = class {
1498
1743
  if (p.lastSeen !== void 0) info.lastSeen = p.lastSeen;
1499
1744
  if (p.lastSync !== void 0) info.lastSync = p.lastSync;
1500
1745
  if (p.lastError !== void 0) info.lastError = p.lastError;
1746
+ const now = Date.now();
1747
+ const answer = this.answers.get(p.url);
1748
+ if (answer) {
1749
+ info.lastSeen = Math.max(info.lastSeen ?? 0, answer.at);
1750
+ if (answer.hello.signalk) info.signalk = answer.hello.signalk;
1751
+ if (answer.hello.multihelm) info.multihelm = answer.hello.multihelm;
1752
+ }
1753
+ const helloError = this.helloErrors.get(p.url);
1754
+ if (helloError !== void 0 && p.state === "paired") info.lastError = helloError;
1755
+ if (p.state === "paired") info.online = info.lastSeen !== void 0 && now - info.lastSeen <= 15e4;
1501
1756
  const seen = this.masterSeen.get(p.url);
1502
- if (seen !== void 0 && Date.now() - seen <= 15e4) info.master = true;
1757
+ if (seen !== void 0 && now - seen <= 15e4) info.master = true;
1503
1758
  return info;
1504
1759
  }
1505
1760
  /**
@@ -1537,6 +1792,8 @@ var Multihelm = class {
1537
1792
  const before = this.peers.length;
1538
1793
  this.peers = this.peers.filter((p) => p.url !== url);
1539
1794
  this.masterSeen.delete(url);
1795
+ this.answers.delete(url);
1796
+ this.helloErrors.delete(url);
1540
1797
  this.store.savePeers(this.peers);
1541
1798
  this.announceRole();
1542
1799
  return Promise.resolve(this.peers.length !== before);
@@ -1580,7 +1837,7 @@ var Multihelm = class {
1580
1837
  }
1581
1838
  async helloLocked(peer) {
1582
1839
  try {
1583
- const hello = await fetchHello(peer.url, peer.token);
1840
+ const hello = await fetchHello(peer.url, peer.token, this.helloFrom());
1584
1841
  if (hello.serverId === this.serverId) {
1585
1842
  peer.state = "needs-pairing";
1586
1843
  peer.lastError = "this is this server itself";
@@ -1589,10 +1846,11 @@ var Multihelm = class {
1589
1846
  peer.id = hello.serverId;
1590
1847
  peer.name = hello.name;
1591
1848
  peer.lastSeen = Date.now();
1849
+ this.answered(peer.url, hello);
1592
1850
  if (hello.master) this.masterSeen.set(peer.url, peer.lastSeen);
1593
1851
  else this.masterSeen.delete(peer.url);
1594
1852
  } catch (error) {
1595
- peer.lastError = error instanceof PeerHttpError && error.status === 404 ? "Multihelm is not running there" : errorText$1(error);
1853
+ this.helloErrors.set(peer.url, helloErrorText(error));
1596
1854
  }
1597
1855
  }
1598
1856
  };
@@ -1602,10 +1860,26 @@ function queryString(req, name) {
1602
1860
  const value = req.query[name];
1603
1861
  return typeof value === "string" ? value : "";
1604
1862
  }
1863
+ var SERVER_ID = /^[\w-]{1,64}$/;
1864
+ var VERSION = /^[\w.+-]{1,32}$/;
1865
+ /** The server asking, when it said; what does not fit is left out. */
1866
+ function helloFrom(req) {
1867
+ const serverId = queryString(req, "from");
1868
+ const name = queryString(req, "name").trim().slice(0, 100);
1869
+ if (!SERVER_ID.test(serverId) || name === "") return null;
1870
+ const signalk = queryString(req, "signalk");
1871
+ const multihelm = queryString(req, "multihelm");
1872
+ return {
1873
+ serverId,
1874
+ name,
1875
+ ...VERSION.test(signalk) ? { signalk } : {},
1876
+ ...VERSION.test(multihelm) ? { multihelm } : {}
1877
+ };
1878
+ }
1605
1879
  function errorText(error) {
1606
1880
  return error instanceof Error ? error.message : String(error);
1607
1881
  }
1608
- function registerRoutes(router, multihelm, discovered, vesselSettings = () => null, masterProxy = () => null) {
1882
+ function registerRoutes(router, multihelm, discovered, vesselSettings = () => null, masterProxy = () => null, ownAccess = () => null) {
1609
1883
  const scoped = router.access;
1610
1884
  const available = typeof scoped === "function";
1611
1885
  const readonly = available ? scoped.call(router, "readonly") : { get(path, handler) {
@@ -1624,7 +1898,9 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
1624
1898
  res.status(500).json({ error: errorText(error) });
1625
1899
  }
1626
1900
  };
1627
- readonly.get("/hello", running((mh, _req, res) => {
1901
+ readonly.get("/hello", running((mh, req, res) => {
1902
+ const from = helloFrom(req);
1903
+ if (from) mh.sawPairedServer(from);
1628
1904
  res.json(mh.hello());
1629
1905
  }));
1630
1906
  readonly.get("/vessel-settings", running((_mh, _req, res) => {
@@ -1674,17 +1950,21 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
1674
1950
  }
1675
1951
  router.get("/status", (_req, res) => {
1676
1952
  const mh = multihelm();
1677
- res.json({
1953
+ const status = {
1678
1954
  available,
1679
1955
  running: mh !== null,
1680
1956
  serverId: mh?.serverId ?? null,
1957
+ name: mh?.hello().name ?? "",
1681
1958
  role: mh?.role() ?? null,
1682
1959
  master: mh?.master() ?? null,
1683
1960
  masterConflict: mh?.masterConflict() ?? false,
1684
1961
  datasets: mh?.datasetIds() ?? [],
1685
1962
  peers: mh?.peerInfo() ?? [],
1686
- discovered: mh ? discovered() : []
1687
- });
1963
+ pairedBy: mh?.pairedByInfo() ?? [],
1964
+ discovered: mh ? discovered() : [],
1965
+ ownAccess: mh ? ownAccess() : null
1966
+ };
1967
+ res.json(status);
1688
1968
  });
1689
1969
  router.post("/peers", running(async (mh, req, res) => {
1690
1970
  const url = req.body?.url;
@@ -1702,6 +1982,10 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
1702
1982
  const url = queryString(req, "url");
1703
1983
  res.status(await mh.unpair(url) ? 200 : 404).json({ removed: url });
1704
1984
  }));
1985
+ router.delete("/paired-by", running((mh, req, res) => {
1986
+ const id = queryString(req, "id");
1987
+ res.status(mh.forgetPairedBy(id) ? 200 : 404).json({ removed: id });
1988
+ }));
1705
1989
  router.post("/run", running((mh, _req, res) => {
1706
1990
  mh.runRound();
1707
1991
  res.status(202).json({ started: true });
@@ -1746,6 +2030,16 @@ var OwnAccessSchema = Type.Object({
1746
2030
  Type.Literal("denied")
1747
2031
  ])
1748
2032
  });
2033
+ var PathsFileSchema = Type.Array(Type.String());
2034
+ /** A server that asked this one for its `hello`, which a server does while paired with it. */
2035
+ var PairedServerSchema = Type.Object({
2036
+ id: Type.String(),
2037
+ name: Type.String(),
2038
+ signalk: Type.Optional(Type.String()),
2039
+ multihelm: Type.Optional(Type.String()),
2040
+ lastSeen: Type.Number()
2041
+ });
2042
+ var PairedServersFileSchema = Type.Array(PairedServerSchema);
1749
2043
  var LibraryFileSchema = Type.Object({
1750
2044
  seq: Type.Integer({ minimum: 0 }),
1751
2045
  entries: Type.Record(Type.String(), Type.Any())
@@ -1799,6 +2093,21 @@ var MultihelmStore = class {
1799
2093
  saveOwnAccess(access) {
1800
2094
  writeAtomic(path.join(this.dir, "own-access.json"), JSON.stringify(access), 384);
1801
2095
  }
2096
+ /** The paths whose metadata this server takes over from the master. */
2097
+ loadFollowedMeta() {
2098
+ const raw = readJson(path.join(this.dir, "followed-meta.json"));
2099
+ return Value.Check(PathsFileSchema, raw) ? raw : [];
2100
+ }
2101
+ saveFollowedMeta(paths) {
2102
+ writeAtomic(path.join(this.dir, "followed-meta.json"), JSON.stringify(paths));
2103
+ }
2104
+ loadPairedBy() {
2105
+ const raw = readJson(path.join(this.dir, "paired-by.json"));
2106
+ return Value.Check(PairedServersFileSchema, raw) ? raw : [];
2107
+ }
2108
+ savePairedBy(servers) {
2109
+ writeAtomic(path.join(this.dir, "paired-by.json"), JSON.stringify(servers));
2110
+ }
1802
2111
  /** A random id made once per installation: every server of a boat shares its vessel id. */
1803
2112
  serverId() {
1804
2113
  const file = path.join(this.dir, "server-id");
@@ -1813,33 +2122,16 @@ var MultihelmStore = class {
1813
2122
  };
1814
2123
  // src/index.ts
1815
2124
  var PLUGIN_ID = "signalk-multihelm";
1816
- var ConfigSchema = Type.Object({
1817
- master: Type.Boolean({
1818
- title: "This server is the boat's master",
1819
- description: "Set this on one server only. Plugins that run on the master alone run here, and the other servers use them through this one.",
1820
- default: false
1821
- }),
1822
- followVessel: Type.Boolean({
1823
- title: "Take the vessel data over from the master",
1824
- description: "Name, MMSI, call sign, dimensions and ship type from Server -> Settings. Changes made here are replaced by the master's.",
1825
- default: true
1826
- }),
1827
- followMetadata: Type.Boolean({
1828
- title: "Take the path metadata over from the master",
1829
- description: "Display names, units, zones and alarm limits set for paths. Changes made here are replaced by the master's.",
1830
- default: true
1831
- }),
1832
- followSourcePriorities: Type.Boolean({
1833
- title: "Take the source priorities over from the master",
1834
- description: "Which source wins for a path, from Data -> Source Priorities. They name sources by connection, so give the NMEA 2000 bus the same connection name on every server. Changes made here are replaced by the master's.",
1835
- default: true
1836
- }),
1837
- historyFromMaster: Type.Boolean({
1838
- title: "Answer this server's History API from the master",
1839
- description: "While the master has a history provider (signalk-questdb, for example), history graphs on this server show the master's history, so it is kept once on the boat. Does nothing on the master, while the master has no history, or before Signal K 2.32.0.",
1840
- default: true
1841
- })
1842
- });
2125
+ /** The bundle and the sources both sit one folder below `package.json`. */
2126
+ function multihelmVersion() {
2127
+ try {
2128
+ const file = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json");
2129
+ const { version } = JSON.parse(fs.readFileSync(file, "utf-8"));
2130
+ return typeof version === "string" ? version : void 0;
2131
+ } catch {
2132
+ return;
2133
+ }
2134
+ }
1843
2135
  var APPROVE_HINT = "approve Multihelm's request under Security -> Access Requests on this server to take the vessel settings over";
1844
2136
  var DENIED_HINT = "the access request on this server was denied, so the vessel settings are not taken over; restart the plugin to ask again";
1845
2137
  function statusText(role, master, conflict) {
@@ -1854,6 +2146,7 @@ function src_default(app) {
1854
2146
  let masterProxy = null;
1855
2147
  let stopRoleStatus = null;
1856
2148
  let stopFollowing = null;
2149
+ let masterFollower = null;
1857
2150
  function localVesselSettings() {
1858
2151
  const deltas = host.config?.baseDeltaEditor?.deltas;
1859
2152
  if (deltas === void 0) return null;
@@ -1870,6 +2163,13 @@ function src_default(app) {
1870
2163
  if (settings?.ssl) return `https://127.0.0.1:${String(Number(process.env.SSLPORT) || settings.sslport || 3443)}`;
1871
2164
  return `http://127.0.0.1:${String(Number(process.env.PORT) || settings?.port || 3e3)}`;
1872
2165
  }
2166
+ function ownAccessState() {
2167
+ if (masterFollower?.waitingForApproval()) return {
2168
+ state: "waiting-approval",
2169
+ request: masterFollower.accessRequestId()
2170
+ };
2171
+ return masterFollower?.denied() ? { state: "denied" } : null;
2172
+ }
1873
2173
  function publish(value) {
1874
2174
  app.emitPropertyValue(PROPERTY_NAME, value);
1875
2175
  }
@@ -1885,6 +2185,10 @@ function src_default(app) {
1885
2185
  const mh = new Multihelm(store, {
1886
2186
  serverName: () => os.hostname(),
1887
2187
  isMaster: () => isMaster,
2188
+ versions: () => ({
2189
+ signalk: host.config?.version,
2190
+ multihelm: multihelmVersion()
2191
+ }),
1888
2192
  debug: (msg) => {
1889
2193
  app.debug(msg);
1890
2194
  },
@@ -1926,6 +2230,7 @@ function src_default(app) {
1926
2230
  app.error(msg);
1927
2231
  }
1928
2232
  });
2233
+ masterFollower = follower;
1929
2234
  const showRole = () => {
1930
2235
  const text = statusText(mh.role(), mh.master(), mh.masterConflict());
1931
2236
  if (follower.waitingForApproval()) app.setPluginStatus(`${text}; ${APPROVE_HINT}`);
@@ -1980,6 +2285,7 @@ function src_default(app) {
1980
2285
  stop() {
1981
2286
  stopFollowing?.();
1982
2287
  stopFollowing = null;
2288
+ masterFollower = null;
1983
2289
  stopRoleStatus?.();
1984
2290
  stopRoleStatus = null;
1985
2291
  if (multihelm) publish({ apiVersion: 1 });
@@ -1991,7 +2297,7 @@ function src_default(app) {
1991
2297
  discovery = null;
1992
2298
  },
1993
2299
  registerWithRouter(router) {
1994
- registerRoutes(router, () => multihelm, () => discovery?.list() ?? [], localVesselSettings, () => masterProxy);
2300
+ registerRoutes(router, () => multihelm, () => discovery?.list() ?? [], localVesselSettings, () => masterProxy, ownAccessState);
1995
2301
  }
1996
2302
  };
1997
2303
  }