signalk-multihelm 0.6.0 → 0.8.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
@@ -45,6 +45,7 @@ function helloQuery(from) {
45
45
  name: from.name
46
46
  });
47
47
  if (from.master !== void 0) query.set("master", from.master ? "1" : "0");
48
+ if (from.acting !== void 0) query.set("acting", from.acting ? "1" : "0");
48
49
  if (from.signalk) query.set("signalk", from.signalk);
49
50
  if (from.multihelm) query.set("multihelm", from.multihelm);
50
51
  return `?${query.toString()}`;
@@ -217,8 +218,16 @@ async function fetchHello(peer, token, from) {
217
218
  };
218
219
  const signalk = optionalText(body.signalk);
219
220
  const multihelm = optionalText(body.multihelm);
221
+ const standby = body.standby;
222
+ const acting = body.acting;
223
+ const elects = body.elects;
224
+ const seesStandby = body.seesStandby;
220
225
  return {
221
226
  ...hello,
227
+ ...typeof standby === "number" && Number.isInteger(standby) && standby > 0 ? { standby } : {},
228
+ ...typeof acting === "boolean" ? { acting } : {},
229
+ ...typeof elects === "string" && elects !== "" ? { elects } : {},
230
+ ...typeof seesStandby === "number" && Number.isInteger(seesStandby) && seesStandby >= 0 ? { seesStandby } : {},
222
231
  ...signalk ? { signalk } : {},
223
232
  ...multihelm ? { multihelm } : {}
224
233
  };
@@ -344,6 +353,239 @@ function interpretReply(raw) {
344
353
  message: "unexpected access request reply"
345
354
  };
346
355
  }
356
+ // src/alarms-from-master.ts
357
+ /**
358
+ * Alarms are matched by path: each server gives its alarms ids of its own,
359
+ * and stations on one NMEA 2000 bus raise the same alarm themselves.
360
+ */
361
+ var NOTIFICATIONS_PATH = "/signalk/v2/api/notifications";
362
+ var ALARMS_POLL_MS = 1e3;
363
+ /** In the data of an alarm shown for the master: the master's server id, and its id for the alarm. */
364
+ var FROM_MASTER = "multihelmMaster";
365
+ var MASTER_ALARM = "multihelmMasterAlarm";
366
+ /**
367
+ * The server's Notifications API, while the server manages notifications:
368
+ * older servers lack it, and with management off it still raises alarms but
369
+ * can no longer clear, silence or acknowledge them.
370
+ */
371
+ function managedNotifications(api) {
372
+ const notifications = api;
373
+ if (typeof notifications?.list !== "function" || typeof notifications.getId !== "function") return null;
374
+ try {
375
+ notifications.getId("signalk-multihelm-probe");
376
+ } catch {
377
+ return null;
378
+ }
379
+ return notifications;
380
+ }
381
+ var ACTIVE = /* @__PURE__ */ new Set([
382
+ "alert",
383
+ "warn",
384
+ "alarm",
385
+ "emergency"
386
+ ]);
387
+ function isActive(state) {
388
+ return typeof state === "string" && ACTIVE.has(state);
389
+ }
390
+ function isRecord$5(value) {
391
+ return typeof value === "object" && value !== null && !Array.isArray(value);
392
+ }
393
+ function errorText$8(error) {
394
+ return error instanceof Error ? error.message : String(error);
395
+ }
396
+ function activeAlarms(listing) {
397
+ if (!isRecord$5(listing)) return [];
398
+ const alarms = [];
399
+ for (const [id, entry] of Object.entries(listing)) {
400
+ if (!isRecord$5(entry) || typeof entry.path !== "string" || !isRecord$5(entry.value)) continue;
401
+ const value = entry.value;
402
+ const status = isRecord$5(value.status) ? value.status : {};
403
+ if (!isActive(value.state)) continue;
404
+ alarms.push({
405
+ id,
406
+ path: entry.path,
407
+ state: value.state,
408
+ message: typeof value.message === "string" ? value.message : "",
409
+ data: isRecord$5(value.data) ? value.data : {},
410
+ silenced: status.silenced === true,
411
+ acknowledged: status.acknowledged === true
412
+ });
413
+ }
414
+ return alarms;
415
+ }
416
+ function isMirror(alarm) {
417
+ return typeof alarm.data[FROM_MASTER] === "string";
418
+ }
419
+ function byPath(alarms) {
420
+ const paths = /* @__PURE__ */ new Map();
421
+ for (const alarm of alarms) if (!paths.has(alarm.path)) paths.set(alarm.path, alarm);
422
+ return paths;
423
+ }
424
+ var MasterAlarms = class {
425
+ host;
426
+ timer = null;
427
+ running = false;
428
+ stopped = false;
429
+ seen = /* @__PURE__ */ new Map();
430
+ constructor(host) {
431
+ this.host = host;
432
+ }
433
+ start() {
434
+ this.timer = setInterval(() => {
435
+ this.sync();
436
+ }, ALARMS_POLL_MS);
437
+ }
438
+ stop() {
439
+ this.stopped = true;
440
+ if (this.timer) clearInterval(this.timer);
441
+ this.timer = null;
442
+ this.clearMirrors(() => false);
443
+ }
444
+ /** One pass; never rejects. */
445
+ async sync() {
446
+ if (this.running || this.stopped) return;
447
+ this.running = true;
448
+ try {
449
+ await this.syncOnce();
450
+ } catch (error) {
451
+ this.host.debug(`Multihelm: the alarms from the master: ${errorText$8(error)}`);
452
+ } finally {
453
+ this.running = false;
454
+ }
455
+ }
456
+ async syncOnce() {
457
+ const master = this.host.master();
458
+ if (!master) {
459
+ this.clearMirrors(() => false);
460
+ return;
461
+ }
462
+ this.clearMirrors((mirror) => mirror.data[FROM_MASTER] === master.id);
463
+ const listing = await callPeer("GET", master.access, NOTIFICATIONS_PATH, master.access.token);
464
+ if (!this.stillFor(master)) return;
465
+ const theirs = byPath(activeAlarms(listing).filter((alarm) => !isMirror(alarm)));
466
+ this.clearMirrors((mirror) => mirror.data["multihelmMaster"] === master.id && mirror.data["multihelmMasterAlarm"] === theirs.get(mirror.path)?.id);
467
+ const seen = /* @__PURE__ */ new Map();
468
+ for (const [path, alarm] of theirs) {
469
+ if (!this.stillFor(master)) return;
470
+ try {
471
+ const here = this.alarmHere(path, alarm, master.id);
472
+ seen.set(here.id, await this.keepInStep(master, here, alarm));
473
+ } catch (error) {
474
+ this.host.debug(`Multihelm: the master's alarm ${path}: ${errorText$8(error)}`);
475
+ }
476
+ }
477
+ this.seen = seen;
478
+ }
479
+ stillFor(master) {
480
+ return !this.stopped && this.host.master()?.id === master.id;
481
+ }
482
+ /**
483
+ * This server's own alarm on the path, or the one shown for the master's.
484
+ * Read again for each alarm, since the server may have raised one of its own while a send waited.
485
+ */
486
+ alarmHere(path, theirs, masterId) {
487
+ const here = activeAlarms(this.host.notifications.list()).filter((a) => a.path === path);
488
+ const own = here.find((alarm) => !isMirror(alarm));
489
+ const mirror = here.find(isMirror);
490
+ if (!own) return this.mirrored(mirror, theirs, masterId);
491
+ if (mirror) this.host.notifications.clear(mirror.id);
492
+ return own;
493
+ }
494
+ mirrored(mirror, theirs, masterId) {
495
+ const notifications = this.host.notifications;
496
+ const data = {
497
+ ...theirs.data,
498
+ [FROM_MASTER]: masterId,
499
+ [MASTER_ALARM]: theirs.id
500
+ };
501
+ const shown = {
502
+ ...theirs,
503
+ data,
504
+ silenced: false,
505
+ acknowledged: false
506
+ };
507
+ if (!mirror) {
508
+ const id = notifications.raise({
509
+ state: theirs.state,
510
+ message: theirs.message,
511
+ path: theirs.path,
512
+ data
513
+ });
514
+ return {
515
+ ...shown,
516
+ id
517
+ };
518
+ }
519
+ if (mirror.state === theirs.state && mirror.message === theirs.message && isDeepStrictEqual(mirror.data, data)) return mirror;
520
+ notifications.update(mirror.id, {
521
+ state: theirs.state,
522
+ message: theirs.message,
523
+ data
524
+ });
525
+ return mirror.state === theirs.state ? {
526
+ ...mirror,
527
+ message: theirs.message,
528
+ data
529
+ } : {
530
+ ...shown,
531
+ id: mirror.id
532
+ };
533
+ }
534
+ async keepInStep(master, here, theirs) {
535
+ const last = this.seen.get(here.id);
536
+ const before = last?.masterId === master.id && last.theirId === theirs.id ? last : null;
537
+ const now = {
538
+ masterId: master.id,
539
+ theirId: theirs.id,
540
+ silenced: here.silenced,
541
+ acknowledged: here.acknowledged,
542
+ unsent: null
543
+ };
544
+ const id = here.id;
545
+ if (theirs.acknowledged && !here.acknowledged) {
546
+ this.host.notifications.acknowledge(id);
547
+ return {
548
+ ...now,
549
+ acknowledged: true
550
+ };
551
+ }
552
+ if (theirs.silenced && !here.silenced && !here.acknowledged) {
553
+ this.host.notifications.silence(id);
554
+ return {
555
+ ...now,
556
+ silenced: true
557
+ };
558
+ }
559
+ if (!before) return now;
560
+ const unsent = here.acknowledged && !theirs.acknowledged && (!before.acknowledged || before.unsent === "acknowledge") ? "acknowledge" : here.silenced && !theirs.silenced && !theirs.acknowledged && (!before.silenced || before.unsent === "silence") ? "silence" : null;
561
+ if (unsent && !await this.sendToMaster(master, theirs, unsent)) return {
562
+ ...now,
563
+ unsent
564
+ };
565
+ return now;
566
+ }
567
+ async sendToMaster(master, alarm, action) {
568
+ const token = await this.host.control.token(master);
569
+ if (token === null || !this.stillFor(master)) return false;
570
+ try {
571
+ await callPeer("POST", master.access, `${NOTIFICATIONS_PATH}/${encodeURIComponent(alarm.id)}/${action}`, token);
572
+ } catch (error) {
573
+ if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) this.host.control.revoked(master.id, token);
574
+ this.host.debug(`Multihelm: sending the ${action} of ${alarm.path} to the master: ${errorText$8(error)}`);
575
+ return false;
576
+ }
577
+ this.host.debug(`Multihelm: sent the ${action} of ${alarm.path} to the master`);
578
+ return true;
579
+ }
580
+ clearMirrors(keep) {
581
+ const notifications = this.host.notifications;
582
+ for (const alarm of activeAlarms(notifications.list())) if (isMirror(alarm) && !keep(alarm)) try {
583
+ notifications.clear(alarm.id);
584
+ } catch (error) {
585
+ this.host.debug(`Multihelm: clearing ${alarm.path}: ${errorText$8(error)}`);
586
+ }
587
+ }
588
+ };
347
589
  // src/autopilot-from-master.ts
348
590
  /**
349
591
  * On a server that is not the master: the master's autopilot, served by this
@@ -368,7 +610,7 @@ var AutopilotError = class extends Error {
368
610
  this.statusCode = statusCode;
369
611
  }
370
612
  };
371
- function errorText$6(error) {
613
+ function errorText$7(error) {
372
614
  return error instanceof Error ? error.message : String(error);
373
615
  }
374
616
  function isRecord$4(value) {
@@ -432,7 +674,7 @@ var MasterAutopilot = class {
432
674
  try {
433
675
  answer = await callPeer("GET", master.access, AUTOPILOTS_PATH, master.access.token);
434
676
  } catch (error) {
435
- this.host.debug(`Multihelm: the master's autopilots: ${errorText$6(error)}`);
677
+ this.host.debug(`Multihelm: the master's autopilots: ${errorText$7(error)}`);
436
678
  return;
437
679
  }
438
680
  const devices = isRecord$4(answer) ? Object.keys(answer).sort() : [];
@@ -453,7 +695,7 @@ var MasterAutopilot = class {
453
695
  try {
454
696
  info = asInfo(await this.read(master, device, ""));
455
697
  } catch (error) {
456
- this.host.debug(`Multihelm: the state of the master's autopilot ${device}: ${errorText$6(error)}`);
698
+ this.host.debug(`Multihelm: the state of the master's autopilot ${device}: ${errorText$7(error)}`);
457
699
  continue;
458
700
  }
459
701
  if (withdrawals !== this.withdrawals) return;
@@ -511,12 +753,12 @@ var MasterAutopilot = class {
511
753
  }
512
754
  run(work) {
513
755
  work().catch((error) => {
514
- this.host.error(`Multihelm: the master's autopilot: ${errorText$6(error)}`);
756
+ this.host.error(`Multihelm: the master's autopilot: ${errorText$7(error)}`);
515
757
  });
516
758
  }
517
759
  asAutopilotError(error) {
518
760
  if (error instanceof AutopilotError) return error;
519
- return new AutopilotError(error instanceof PeerHttpError ? error.status : 502, `the master's autopilot: ${errorText$6(error)}`);
761
+ return new AutopilotError(error instanceof PeerHttpError ? error.status : 502, `the master's autopilot: ${errorText$7(error)}`);
520
762
  }
521
763
  provider = {
522
764
  getData: async (device) => asInfo(await this.read(this.masterOrFail(), device, "")),
@@ -546,7 +788,7 @@ var MasterAutopilot = class {
546
788
  };
547
789
  };
548
790
  // src/master-control.ts
549
- function errorText$5(error) {
791
+ function errorText$6(error) {
550
792
  return error instanceof Error ? error.message : String(error);
551
793
  }
552
794
  var MasterControlAccess = class {
@@ -596,7 +838,7 @@ var MasterControlAccess = class {
596
838
  try {
597
839
  result = this.control?.state === "waiting-approval" && this.control.requestHref ? await pollAccess(master.access, this.control.requestHref) : await requestAccess(master.access, this.requestId(), "Multihelm: send commands to the master from another station", "readwrite");
598
840
  } catch (error) {
599
- this.host.debug(`Multihelm: access request on the master: ${errorText$5(error)}`);
841
+ this.host.debug(`Multihelm: access request on the master: ${errorText$6(error)}`);
600
842
  return null;
601
843
  }
602
844
  if (this.host.currentMaster() !== master.id) return null;
@@ -661,7 +903,7 @@ var COURSE_POLL_MS = 1e3;
661
903
  function isRecord$3(value) {
662
904
  return typeof value === "object" && value !== null && !Array.isArray(value);
663
905
  }
664
- function errorText$4(error) {
906
+ function errorText$5(error) {
665
907
  return error instanceof Error ? error.message : String(error);
666
908
  }
667
909
  function asPosition(value) {
@@ -754,7 +996,7 @@ var MasterCourse = class {
754
996
  try {
755
997
  await this.syncOnce();
756
998
  } catch (error) {
757
- this.host.debug(`Multihelm: the course from the master: ${errorText$4(error)}`);
999
+ this.host.debug(`Multihelm: the course from the master: ${errorText$5(error)}`);
758
1000
  } finally {
759
1001
  this.running = false;
760
1002
  }
@@ -966,6 +1208,13 @@ var ConfigSchema = Type.Object({
966
1208
  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.",
967
1209
  default: false
968
1210
  }),
1211
+ takeOver: Type.Integer({
1212
+ title: "Take over as master when the master is gone (order, 0 = never)",
1213
+ description: "While no server set to be the master has been reachable for three and a half minutes, the server with the lowest number here takes over, as long as it reaches most of the boat's servers. Give the servers that may take over different numbers.",
1214
+ minimum: 0,
1215
+ maximum: 9,
1216
+ default: 0
1217
+ }),
969
1218
  syncResources: Type.Boolean({
970
1219
  title: "Keep routes and waypoints in step",
971
1220
  description: "Routes, waypoints, regions and notes, kept the same on every server of the boat: a change on one reaches the others, with no master.",
@@ -1000,6 +1249,11 @@ var ConfigSchema = Type.Object({
1000
1249
  title: "Keep the course the same as on the master",
1001
1250
  description: "This server takes the master's active destination or route over, and a destination or route set here is sent to the master, so every station follows the same course. Does nothing on the master.",
1002
1251
  default: true
1252
+ }),
1253
+ alarmsFromMaster: Type.Boolean({
1254
+ title: "Show the master's alarms here",
1255
+ description: "Every active alarm on the master also sounds here, and silencing or acknowledging an alarm here does it on the master and every other station. An alarm this server raises itself on the same path is not shown twice. Does nothing on the master, or on a server without the Notifications API or with notification management off.",
1256
+ default: true
1003
1257
  })
1004
1258
  });
1005
1259
  // src/source-priorities.ts
@@ -1188,7 +1442,7 @@ function parseVesselSettings(raw) {
1188
1442
  * restart, with this server's admin device token on itself. Metadata of a path the
1189
1443
  * master has none for stays as it is, unless it was the master's before.
1190
1444
  */
1191
- function errorText$3(error) {
1445
+ function errorText$4(error) {
1192
1446
  return error instanceof Error ? error.message : String(error);
1193
1447
  }
1194
1448
  /** A master where none are set yet would wipe the ones a server kept from before Multihelm. */
@@ -1256,7 +1510,7 @@ var MasterFollower = class {
1256
1510
  try {
1257
1511
  remote = parseVesselSettings(await fetchVesselSettings(master, master.token));
1258
1512
  } catch (error) {
1259
- this.host.debug(`Multihelm: vessel settings from the master: ${errorText$3(error)}`);
1513
+ this.host.debug(`Multihelm: vessel settings from the master: ${errorText$4(error)}`);
1260
1514
  return;
1261
1515
  }
1262
1516
  if (!remote) return;
@@ -1285,7 +1539,7 @@ var MasterFollower = class {
1285
1539
  }
1286
1540
  } catch (error) {
1287
1541
  if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) this.host.access.revoked();
1288
- this.host.error(`Multihelm: taking over the master's vessel settings: ${errorText$3(error)}`);
1542
+ this.host.error(`Multihelm: taking over the master's vessel settings: ${errorText$4(error)}`);
1289
1543
  }
1290
1544
  if (followMeta) this.saveFollowedMeta();
1291
1545
  }
@@ -1297,7 +1551,7 @@ var MasterFollower = class {
1297
1551
  this.host.store.saveFollowedMeta(paths);
1298
1552
  this.followedMetaSaved = text;
1299
1553
  } catch (error) {
1300
- this.host.error(`Multihelm: saving the paths that follow the master: ${errorText$3(error)}`);
1554
+ this.host.error(`Multihelm: saving the paths that follow the master: ${errorText$4(error)}`);
1301
1555
  }
1302
1556
  }
1303
1557
  prioritiesToWrite(remote, local) {
@@ -1323,9 +1577,12 @@ var MasterFollower = class {
1323
1577
  */
1324
1578
  var SETTINGS_DATASET = "signalk-multihelm/settings";
1325
1579
  var MASTER_PLUGINS_KEY = "master-plugins";
1326
- var FILE$1 = "plugins.json";
1327
- var PLUGIN_ID$1 = /^[\w.@-]{1,100}$/;
1580
+ var FILE$2 = "plugins.json";
1581
+ var PLUGIN_ID$1 = /^[\w@-][\w.@-]{0,99}$/;
1328
1582
  var MAX_PLUGINS = 100;
1583
+ function isPluginId(id) {
1584
+ return PLUGIN_ID$1.test(id);
1585
+ }
1329
1586
  function parsePluginIds(raw) {
1330
1587
  if (!Array.isArray(raw) || raw.length > MAX_PLUGINS) return null;
1331
1588
  const ids = [];
@@ -1335,20 +1592,26 @@ function parsePluginIds(raw) {
1335
1592
  }
1336
1593
  return [...new Set(ids)].sort();
1337
1594
  }
1338
- function errorText$2(error) {
1595
+ function errorText$3(error) {
1339
1596
  return error instanceof Error ? error.message : String(error);
1340
1597
  }
1341
- /** The list, kept in a file of its own under `dir`, since a dataset entry is made of files. */
1342
- var MasterPluginList = class {
1598
+ /** A list of plugins the same on every server, kept in a file of its own under `dir`, since a dataset entry is made of files. */
1599
+ var PluginList = class {
1343
1600
  onChange;
1601
+ datasetId;
1602
+ key;
1344
1603
  file;
1345
1604
  current;
1346
1605
  /** Writes one after the other, so two cannot share the temporary file or publish out of order. */
1347
1606
  writes = Promise.resolve();
1348
- constructor(dir, onChange) {
1607
+ dataset;
1608
+ constructor(dir, onChange, datasetId = SETTINGS_DATASET, key = MASTER_PLUGINS_KEY) {
1349
1609
  this.onChange = onChange;
1350
- this.file = path.join(dir, FILE$1);
1610
+ this.datasetId = datasetId;
1611
+ this.key = key;
1612
+ this.file = path.join(dir, FILE$2);
1351
1613
  this.current = this.read();
1614
+ this.dataset = this.define();
1352
1615
  }
1353
1616
  ids() {
1354
1617
  return this.current;
@@ -1356,42 +1619,44 @@ var MasterPluginList = class {
1356
1619
  set(ids) {
1357
1620
  return this.queued(() => this.write(ids));
1358
1621
  }
1359
- dataset = {
1360
- id: SETTINGS_DATASET,
1361
- isValidKey: (key) => key === MASTER_PLUGINS_KEY,
1362
- list: async () => {
1363
- let stat;
1364
- try {
1365
- stat = await fs.promises.stat(this.file);
1366
- } catch {
1367
- return [];
1622
+ define() {
1623
+ return {
1624
+ id: this.datasetId,
1625
+ isValidKey: (key) => key === this.key,
1626
+ list: async () => {
1627
+ let stat;
1628
+ try {
1629
+ stat = await fs.promises.stat(this.file);
1630
+ } catch {
1631
+ return [];
1632
+ }
1633
+ return [{
1634
+ key: this.key,
1635
+ meta: null,
1636
+ files: [{
1637
+ name: FILE$2,
1638
+ path: this.file,
1639
+ size: stat.size,
1640
+ mtimeMs: stat.mtimeMs
1641
+ }]
1642
+ }];
1643
+ },
1644
+ apply: async (entry) => {
1645
+ const file = entry.files.find((f) => f.name === FILE$2);
1646
+ if (!file || entry.files.length !== 1) throw new Error(`the plugin list has one file, ${String(entry.files.length)} came`);
1647
+ const ids = parsePluginIds(JSON.parse(await fs.promises.readFile(file.path, "utf8")));
1648
+ if (!ids) throw new Error("not a list of plugin ids");
1649
+ await this.queued(() => this.write(ids));
1650
+ },
1651
+ remove: async () => {
1652
+ await this.queued(async () => {
1653
+ await fs.promises.rm(this.file, { force: true });
1654
+ this.changed([]);
1655
+ });
1656
+ return true;
1368
1657
  }
1369
- return [{
1370
- key: MASTER_PLUGINS_KEY,
1371
- meta: null,
1372
- files: [{
1373
- name: FILE$1,
1374
- path: this.file,
1375
- size: stat.size,
1376
- mtimeMs: stat.mtimeMs
1377
- }]
1378
- }];
1379
- },
1380
- apply: async (entry) => {
1381
- const file = entry.files.find((f) => f.name === FILE$1);
1382
- if (!file || entry.files.length !== 1) throw new Error(`the plugin list has one file, ${String(entry.files.length)} came`);
1383
- const ids = parsePluginIds(JSON.parse(await fs.promises.readFile(file.path, "utf8")));
1384
- if (!ids) throw new Error("not a list of plugin ids");
1385
- await this.queued(() => this.write(ids));
1386
- },
1387
- remove: async () => {
1388
- await this.queued(async () => {
1389
- await fs.promises.rm(this.file, { force: true });
1390
- this.changed([]);
1391
- });
1392
- return true;
1393
- }
1394
- };
1658
+ };
1659
+ }
1395
1660
  queued(work) {
1396
1661
  const result = this.writes.then(work);
1397
1662
  this.writes = result.catch(() => void 0);
@@ -1426,27 +1691,115 @@ var MasterPluginList = class {
1426
1691
  if (JSON.stringify(ids) !== before) this.onChange();
1427
1692
  }
1428
1693
  };
1694
+ /**
1695
+ * Nothing is switched before the role is known, nor on a server with no master to defer to,
1696
+ * unless it reaches too few of the boat's servers to know there is none elsewhere, should be
1697
+ * the master but may not be it yet, or sees another server still acting as it.
1698
+ */
1699
+ function masterPluginsWanted(e) {
1700
+ if (!e.roleKnown()) return null;
1701
+ if (e.role() === "master") return true;
1702
+ return e.masterElsewhere() || !e.hasMajority() || e.electedWithout() || e.otherActs() ? false : null;
1703
+ }
1704
+ var configWrites = /* @__PURE__ */ new Map();
1705
+ /** One read-modify-write of a plugin's settings at a time, so no writer restores what another just changed. */
1706
+ function exclusivePluginConfig(id, work) {
1707
+ const result = (configWrites.get(id) ?? Promise.resolve()).then(work);
1708
+ const settled = result.catch(() => void 0);
1709
+ configWrites.set(id, settled);
1710
+ settled.then(() => {
1711
+ if (configWrites.get(id) === settled) configWrites.delete(id);
1712
+ });
1713
+ return result;
1714
+ }
1429
1715
  function pluginUrl(base, id, rest = "") {
1430
1716
  return `${base}/plugins/${encodeURIComponent(id)}${rest}`;
1431
1717
  }
1432
1718
  /** Switches the listed plugins on this server to what its role wants; one run at a time. */
1433
1719
  var MasterOnlyPlugins = class {
1434
1720
  host;
1435
- running = false;
1721
+ busy = false;
1436
1722
  again = false;
1723
+ /** Listed plugins this server found running or started, until it saw them stopped. */
1724
+ running = /* @__PURE__ */ new Set();
1725
+ /** Without a usable record from before, a plugin not looked at since the start may run. */
1726
+ unknown;
1727
+ looked = /* @__PURE__ */ new Set();
1728
+ /** A pass still running after stop() must not write the record the next start reads. */
1729
+ stopped = false;
1437
1730
  constructor(host) {
1438
1731
  this.host = host;
1732
+ const kept = this.loadRunning();
1733
+ this.unknown = kept === null;
1734
+ for (const id of kept ?? []) this.running.add(id);
1735
+ }
1736
+ /** null: no usable record, so what runs here is unknown. */
1737
+ loadRunning() {
1738
+ if (this.host.runningFile === void 0) return [];
1739
+ try {
1740
+ const kept = JSON.parse(fs.readFileSync(this.host.runningFile, "utf-8"));
1741
+ return Array.isArray(kept) && kept.every((id) => typeof id === "string" && PLUGIN_ID$1.test(id)) ? kept : null;
1742
+ } catch {
1743
+ return null;
1744
+ }
1745
+ }
1746
+ /**
1747
+ * Whether the record is safe to rely on after a restart: written, or
1748
+ * removed when it could not be, so the next start treats it as unknown.
1749
+ */
1750
+ saveRunning() {
1751
+ const file = this.host.runningFile;
1752
+ if (file === void 0) return true;
1753
+ try {
1754
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1755
+ fs.writeFileSync(`${file}.tmp`, JSON.stringify([...this.running]));
1756
+ fs.renameSync(`${file}.tmp`, file);
1757
+ return true;
1758
+ } catch (error) {
1759
+ this.host.error(`Multihelm: cannot keep which plugins run here: ${errorText$3(error)}`);
1760
+ }
1761
+ try {
1762
+ fs.rmSync(file, { force: true });
1763
+ return true;
1764
+ } catch (error) {
1765
+ this.host.error(`Multihelm: cannot remove ${file}: ${errorText$3(error)}`);
1766
+ return false;
1767
+ }
1768
+ }
1769
+ /**
1770
+ * Whether a plugin that runs on the master only may still run here. A stop
1771
+ * that failed keeps it so, and is tried again on the next pass; while it
1772
+ * does, the servers that see this one take no other master.
1773
+ */
1774
+ runsHere() {
1775
+ return this.host.ids().some((id) => id !== this.host.selfId && (this.running.has(id) || this.unknown && !this.looked.has(id)));
1776
+ }
1777
+ stop() {
1778
+ this.stopped = true;
1779
+ }
1780
+ /** Returns whether the record could be kept; a plugin is started only then. */
1781
+ mark(id, running) {
1782
+ if (this.stopped) return false;
1783
+ const before = this.runsHere();
1784
+ const changed = this.running.has(id) !== running || !this.looked.has(id);
1785
+ this.looked.add(id);
1786
+ if (running) this.running.add(id);
1787
+ else this.running.delete(id);
1788
+ const kept = changed ? this.saveRunning() : true;
1789
+ if (before !== this.runsHere()) this.host.runningChanged?.();
1790
+ return kept;
1439
1791
  }
1440
1792
  apply() {
1441
- if (this.running) {
1793
+ if (this.stopped) return;
1794
+ if (this.busy) {
1442
1795
  this.again = true;
1443
1796
  return;
1444
1797
  }
1445
- this.running = true;
1798
+ this.busy = true;
1446
1799
  this.applyOnce().catch((error) => {
1447
- this.host.error(`Multihelm: switching the plugins that run on the master: ${errorText$2(error)}`);
1800
+ this.host.error(`Multihelm: switching the plugins that run on the master: ${errorText$3(error)}`);
1448
1801
  }).finally(() => {
1449
- this.running = false;
1802
+ this.busy = false;
1450
1803
  if (this.again) {
1451
1804
  this.again = false;
1452
1805
  this.apply();
@@ -1456,32 +1809,43 @@ var MasterOnlyPlugins = class {
1456
1809
  async applyOnce() {
1457
1810
  const wanted = this.host.wanted();
1458
1811
  const ids = this.host.ids().filter((id) => id !== this.host.selfId);
1459
- if (wanted === null || ids.length === 0) return;
1812
+ if (ids.length === 0) return;
1460
1813
  const token = await this.host.access.token();
1461
1814
  if (token === null) return;
1462
1815
  const base = this.host.ownUrl();
1463
1816
  for (const id of ids) try {
1464
- if ((await callServer("GET", pluginUrl(base, id), token))?.enabled === wanted) continue;
1465
- const options = await callServer("GET", pluginUrl(base, id, "/config"), token);
1466
- if (this.host.wanted() !== wanted) return;
1467
- if (!this.host.ids().includes(id)) continue;
1468
- const body = typeof options === "object" && options !== null && !Array.isArray(options) ? {
1469
- ...options,
1470
- enabled: wanted
1471
- } : { enabled: wanted };
1472
- await callServer("POST", pluginUrl(base, id, "/config"), token, body);
1473
- this.host.debug(`Multihelm: ${wanted ? "started" : "stopped"} ${id}, which runs on the master only`);
1817
+ const enabled = (await callServer("GET", pluginUrl(base, id), token))?.enabled === true;
1818
+ this.mark(id, enabled);
1819
+ if (wanted === null || enabled === wanted) continue;
1820
+ if (await exclusivePluginConfig(id, async () => {
1821
+ const options = await callServer("GET", pluginUrl(base, id, "/config"), token);
1822
+ if (this.host.wanted() !== wanted) return true;
1823
+ if (!this.host.ids().includes(id)) return false;
1824
+ const body = typeof options === "object" && options !== null && !Array.isArray(options) ? {
1825
+ ...options,
1826
+ enabled: wanted
1827
+ } : { enabled: wanted };
1828
+ if (wanted && !this.mark(id, true)) {
1829
+ this.host.error(`Multihelm: not starting ${id}: cannot keep that it runs here`);
1830
+ return false;
1831
+ }
1832
+ await callServer("POST", pluginUrl(base, id, "/config"), token, body);
1833
+ this.mark(id, wanted);
1834
+ this.host.debug(`Multihelm: ${wanted ? "started" : "stopped"} ${id}, which runs on the master only`);
1835
+ return false;
1836
+ })) return;
1474
1837
  } catch (error) {
1475
1838
  if (error instanceof PeerHttpError && error.status === 404) {
1476
1839
  this.host.debug(`Multihelm: ${id}, set to run on the master only, is not installed here`);
1840
+ this.mark(id, false);
1477
1841
  continue;
1478
1842
  }
1479
1843
  if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {
1480
1844
  this.host.access.revoked();
1481
- this.host.error(`Multihelm: this server refused its own admin token: ${errorText$2(error)}`);
1845
+ this.host.error(`Multihelm: this server refused its own admin token: ${errorText$3(error)}`);
1482
1846
  return;
1483
1847
  }
1484
- this.host.error(`Multihelm: cannot ${wanted ? "start" : "stop"} ${id}, which runs on the master only: ${errorText$2(error)}`);
1848
+ this.host.error(`Multihelm: cannot ${wanted ? "start" : "stop"} ${id}, which runs on the master only: ${errorText$3(error)}`);
1485
1849
  }
1486
1850
  }
1487
1851
  };
@@ -1928,6 +2292,7 @@ var MASTER_CHECK_INTERVAL_MS = 3e4;
1928
2292
  * recently, so a few missed answers do not move the role.
1929
2293
  */
1930
2294
  var MASTER_STALE_MS = 5 * MASTER_CHECK_INTERVAL_MS;
2295
+ 2 * MASTER_CHECK_INTERVAL_MS;
1931
2296
  /** Every peer asks every 30 s, so a sighting is saved only now and then. */
1932
2297
  var PAIRED_BY_SAVE_MS = 6e5;
1933
2298
  /** Without security anyone may ask, so writes of that list are gathered, never one per request. */
@@ -1941,7 +2306,7 @@ async function hashFile(file) {
1941
2306
  await pipeline(fs.createReadStream(file), hash);
1942
2307
  return hash.digest("hex");
1943
2308
  }
1944
- function errorText$1(error) {
2309
+ function errorText$2(error) {
1945
2310
  return error instanceof Error ? error.message : String(error);
1946
2311
  }
1947
2312
  /** What Node calls a certificate chain that does not lead to a certificate it trusts. */
@@ -1974,7 +2339,7 @@ function connectionText(error) {
1974
2339
  }
1975
2340
  /** Said without the address, which the panel shows anyway. */
1976
2341
  function helloErrorText(error) {
1977
- if (!(error instanceof PeerHttpError)) return connectionText(error) ?? errorText$1(error);
2342
+ if (!(error instanceof PeerHttpError)) return connectionText(error) ?? errorText$2(error);
1978
2343
  switch (error.status) {
1979
2344
  case 404: return "Multihelm is not running there";
1980
2345
  case 401:
@@ -2008,6 +2373,7 @@ var Multihelm = class {
2008
2373
  /** Peer URL → when it last answered as set to be the master. */
2009
2374
  masterSeen = /* @__PURE__ */ new Map();
2010
2375
  /** Peer URL → its last `hello`, and when. */
2376
+ /** `asked`: when the request for the answer went out. */
2011
2377
  answers = /* @__PURE__ */ new Map();
2012
2378
  /** Peer URL → why its last `hello` failed. */
2013
2379
  helloErrors = /* @__PURE__ */ new Map();
@@ -2022,13 +2388,16 @@ var Multihelm = class {
2022
2388
  /** What the status listeners were last told: role, master id and conflict. */
2023
2389
  announcedStatus = "";
2024
2390
  masterTimer = null;
2025
- checkingMasters = false;
2391
+ checkingMasters = null;
2026
2392
  checkMastersAgain = false;
2027
2393
  /** Whether the paired peers were asked once since the start, so the role is known. */
2028
2394
  mastersChecked = false;
2029
2395
  pairingTimer = null;
2030
2396
  pollingPairings = false;
2031
2397
  serverId;
2398
+ /** No server takes over before `TAKEOVER_MS` without a master answer, counted from here too. */
2399
+ startedAt = Date.now();
2400
+ vote = null;
2032
2401
  constructor(store, host) {
2033
2402
  this.store = store;
2034
2403
  this.host = host;
@@ -2037,6 +2406,7 @@ var Multihelm = class {
2037
2406
  this.pairedBy = new Map(store.loadPairedBy().map((s) => [s.id, s]));
2038
2407
  }
2039
2408
  start() {
2409
+ this.startedAt = Date.now();
2040
2410
  this.started = true;
2041
2411
  this.stopped = false;
2042
2412
  const tick = () => {
@@ -2051,7 +2421,7 @@ var Multihelm = class {
2051
2421
  }, MASTER_CHECK_INTERVAL_MS);
2052
2422
  this.pairingTimer = setInterval(() => {
2053
2423
  this.pollPairings().catch((error) => {
2054
- this.host.error(`Multihelm: following a pairing request: ${errorText$1(error)}`);
2424
+ this.host.error(`Multihelm: following a pairing request: ${errorText$2(error)}`);
2055
2425
  });
2056
2426
  }, PAIRING_POLL_MS);
2057
2427
  }
@@ -2073,41 +2443,46 @@ var Multihelm = class {
2073
2443
  /**
2074
2444
  * Asks every paired peer whether it is set to be the master. Runs outside
2075
2445
  * the work queue and touches nothing but what it keeps of the answers, so it neither waits
2076
- * for a round nor races one.
2446
+ * for a round nor races one. The takeover facts it keeps on a peer are saved in one
2447
+ * synchronous write of the peers as they are, which no queued step can interleave.
2077
2448
  */
2078
- async checkMasters() {
2079
- if (this.stopped) return;
2449
+ checkMasters() {
2450
+ if (this.stopped) return Promise.resolve();
2080
2451
  if (this.checkingMasters) {
2081
2452
  this.checkMastersAgain = true;
2082
- return;
2083
- }
2084
- this.checkingMasters = true;
2085
- try {
2086
- await Promise.all(this.peers.filter((p) => p.state === "paired" && p.id !== "").map(async (peer) => {
2087
- const { url, ca } = peer;
2088
- const current = () => !this.stopped && this.peers.includes(peer) && peer.url === url && peer.ca === ca;
2089
- let hello;
2090
- try {
2091
- hello = await fetchHello(peer, peer.token, this.helloFrom());
2092
- } catch (error) {
2093
- if (current()) this.helloErrors.set(url, helloErrorText(error));
2094
- return;
2095
- }
2096
- if (!current() || hello.serverId !== peer.id) return;
2097
- this.answered(url, hello);
2098
- if (hello.master) this.masterSeen.set(url, Date.now());
2099
- else this.masterSeen.delete(url);
2100
- }));
2101
- } finally {
2102
- this.checkingMasters = false;
2453
+ return this.checkingMasters;
2103
2454
  }
2104
- if (this.stopped) return;
2105
- this.mastersChecked = true;
2106
- this.announceRole();
2107
- if (this.checkMastersAgain) {
2455
+ this.checkingMasters = this.checkMastersUntilDone().finally(() => {
2456
+ this.checkingMasters = null;
2457
+ });
2458
+ return this.checkingMasters;
2459
+ }
2460
+ async checkMastersUntilDone() {
2461
+ do {
2108
2462
  this.checkMastersAgain = false;
2109
- await this.checkMasters();
2110
- }
2463
+ await this.askForMasters();
2464
+ if (this.stopped) return;
2465
+ this.mastersChecked = true;
2466
+ this.announceRole();
2467
+ } while (this.checkMastersAgain);
2468
+ }
2469
+ async askForMasters() {
2470
+ await Promise.all(this.peers.filter((p) => p.state === "paired" && p.id !== "").map(async (peer) => {
2471
+ const { url, ca } = peer;
2472
+ const current = () => !this.stopped && this.peers.includes(peer) && peer.url === url && peer.ca === ca;
2473
+ let hello;
2474
+ const asked = Date.now();
2475
+ try {
2476
+ hello = await fetchHello(peer, peer.token, this.helloFrom());
2477
+ } catch (error) {
2478
+ if (current()) this.helloErrors.set(url, helloErrorText(error));
2479
+ return;
2480
+ }
2481
+ if (!current() || hello.serverId !== peer.id) return;
2482
+ this.answered(url, hello, asked);
2483
+ if (hello.master) this.masterSeen.set(url, Date.now());
2484
+ else this.masterSeen.delete(url);
2485
+ }));
2111
2486
  }
2112
2487
  /** Whether the role is known: the paired peers were asked since the start. */
2113
2488
  roleKnown() {
@@ -2202,16 +2577,143 @@ var Multihelm = class {
2202
2577
  }
2203
2578
  return candidates.sort((x, y) => x.id < y.id ? -1 : x.id > y.id ? 1 : 0);
2204
2579
  }
2580
+ /** The paired peers that answered within `MASTER_STALE_MS`, with their answer. */
2581
+ seenPeers(now) {
2582
+ const seen = [];
2583
+ for (const peer of this.peers) {
2584
+ const answer = this.answers.get(peer.url);
2585
+ if (peer.state === "paired" && peer.id !== "" && answer?.hello.serverId === peer.id && now - answer.at <= 15e4) seen.push({
2586
+ peer,
2587
+ hello: answer.hello
2588
+ });
2589
+ }
2590
+ return seen;
2591
+ }
2592
+ /**
2593
+ * Whether this server sees most of the boat's servers, itself included. A
2594
+ * tie counts on the side of the server set to be the master, so of two
2595
+ * servers cut apart only that one may be the master. Without a server that may
2596
+ * take over, only the one set to be the master ever is, so it needs none.
2597
+ */
2598
+ hasMajority() {
2599
+ if (!this.takeOverPossible()) return true;
2600
+ const now = Date.now();
2601
+ const total = 1 + this.peers.filter((p) => p.state === "paired" && p.id !== "").length;
2602
+ const seen = 1 + this.seenPeers(now).length;
2603
+ return 2 * seen > total || 2 * seen === total && this.masterCandidates().length > 0;
2604
+ }
2605
+ takeOverPossible() {
2606
+ return (this.host.standby?.() ?? 0) > 0 || this.pairedPeers().some((p) => (p.standby ?? 0) > 0);
2607
+ }
2608
+ pairedPeers() {
2609
+ return this.peers.filter((p) => p.state === "paired" && p.id !== "");
2610
+ }
2611
+ /** The server that should be the master, as this one sees the boat; null while there is none. */
2612
+ elected() {
2613
+ if (!this.hasMajority()) return null;
2614
+ const set = this.masterCandidates()[0];
2615
+ if (set) return {
2616
+ ...set,
2617
+ takingOver: false
2618
+ };
2619
+ const now = Date.now();
2620
+ if (now - Math.max(this.startedAt, ...this.masterSeen.values()) <= 21e4) return null;
2621
+ if (this.pairedPeers().some((p) => p.quorum !== true)) return null;
2622
+ const standbys = [];
2623
+ const own = this.host.standby?.() ?? 0;
2624
+ if (own > 0) standbys.push({
2625
+ id: this.serverId,
2626
+ peer: null,
2627
+ order: own
2628
+ });
2629
+ for (const { peer, hello } of this.seenPeers(now)) if (hello.standby !== void 0 && hello.standby > 0) standbys.push({
2630
+ id: peer.id,
2631
+ peer,
2632
+ order: hello.standby
2633
+ });
2634
+ standbys.sort((x, y) => x.order - y.order || (x.id < y.id ? -1 : x.id > y.id ? 1 : 0));
2635
+ const first = standbys[0];
2636
+ return first ? {
2637
+ id: first.id,
2638
+ peer: first.peer,
2639
+ takingOver: true
2640
+ } : null;
2641
+ }
2642
+ /**
2643
+ * A peer that does not know this server may take over does not count the
2644
+ * majority, and may act as the master on its own.
2645
+ */
2646
+ peersKnowStandby() {
2647
+ const own = this.host.standby?.() ?? 0;
2648
+ return this.pairedPeers().every((p) => p.seesStandby === own);
2649
+ }
2650
+ /** Each server votes for one, so two sides that share servers never both have most votes. */
2651
+ hasMostVotes(tieWins) {
2652
+ const now = Date.now();
2653
+ const total = 1 + this.pairedPeers().length;
2654
+ let votes = this.castVote() === this.serverId ? 1 : 0;
2655
+ for (const peer of this.pairedPeers()) {
2656
+ const answer = this.answers.get(peer.url);
2657
+ if (answer?.hello.serverId === peer.id && answer.hello.elects === this.serverId && now - answer.asked <= 6e4) votes++;
2658
+ }
2659
+ return 2 * votes > total || tieWins && 2 * votes === total;
2660
+ }
2661
+ /** The vote this server gives now: none while it still holds one for another server. */
2662
+ castVote() {
2663
+ const now = Date.now();
2664
+ const choice = this.elected()?.id;
2665
+ if (choice === void 0) return;
2666
+ if (this.actsBesides(choice, now)) return;
2667
+ if (this.vote === null || this.vote.for === choice || now - this.vote.at > 9e4) {
2668
+ this.vote = {
2669
+ for: choice,
2670
+ at: now
2671
+ };
2672
+ return choice;
2673
+ }
2674
+ }
2675
+ actsBesides(choice, now) {
2676
+ if (choice !== this.serverId && this.host.stillRunning?.() === true) return true;
2677
+ return this.seenPeers(now).some(({ peer, hello }) => peer.id !== choice && this.acts(hello));
2678
+ }
2679
+ acts(hello) {
2680
+ return hello.acting ?? hello.master;
2681
+ }
2682
+ /** A server becomes the master only once every server it sees has stopped acting as it. */
2205
2683
  role() {
2206
- return this.masterCandidates()[0]?.peer === null ? "master" : "member";
2684
+ const elected = this.elected();
2685
+ if (elected?.peer !== null) return "member";
2686
+ if (elected.takingOver && (!this.peersKnowStandby() || !this.hasMostVotes(false))) return "member";
2687
+ if (!elected.takingOver && this.takeOverPossible() && !this.hasMostVotes(true)) return "member";
2688
+ return this.seenPeers(Date.now()).some(({ hello }) => this.acts(hello)) ? "member" : "master";
2689
+ }
2690
+ /** This server should be the master, but may not be it now. */
2691
+ electedWithout() {
2692
+ return this.elected()?.peer === null && this.role() !== "master";
2207
2693
  }
2694
+ /** A server this one sees acts as the master, as it may while it stops the plugins there. */
2695
+ otherActs() {
2696
+ return this.seenPeers(Date.now()).some(({ hello }) => this.acts(hello));
2697
+ }
2698
+ /** The master to follow, once it acts as the master; null when this server is it or there is none. */
2208
2699
  master() {
2209
- const peer = this.masterCandidates()[0]?.peer;
2700
+ const peer = this.actingMaster();
2210
2701
  return peer ? this.infoOf(peer) : null;
2211
2702
  }
2703
+ /** Another server should be the master: whatever runs on the master only stops here. */
2704
+ masterElsewhere() {
2705
+ const elected = this.elected();
2706
+ return elected !== null && elected.peer !== null;
2707
+ }
2708
+ actingMaster() {
2709
+ const peer = this.elected()?.peer;
2710
+ if (!peer) return null;
2711
+ const answer = this.answers.get(peer.url);
2712
+ return answer && this.acts(answer.hello) ? peer : null;
2713
+ }
2212
2714
  /** Where to reach the master, with the pairing token; null when this server is it or there is none. */
2213
2715
  masterAccess() {
2214
- const peer = this.masterCandidates()[0]?.peer;
2716
+ const peer = this.actingMaster();
2215
2717
  if (!peer) return null;
2216
2718
  return peer.ca === void 0 ? {
2217
2719
  url: peer.url,
@@ -2243,13 +2745,15 @@ var Multihelm = class {
2243
2745
  const role = this.role();
2244
2746
  const master = this.master();
2245
2747
  const now = `${role}:${master?.id ?? ""}`;
2246
- const status = `${now}:${String(this.masterConflict())}`;
2748
+ const status = `${now}:${String(this.masterConflict())}:${String(this.hasMajority())}`;
2247
2749
  if (now !== this.announcedRole) {
2750
+ const wasActing = this.announcedRole.startsWith("master:");
2248
2751
  this.announcedRole = now;
2752
+ if (wasActing !== (role === "master")) this.checkMasters();
2249
2753
  for (const cb of this.roleListeners) try {
2250
2754
  cb(role, master);
2251
2755
  } catch (error) {
2252
- this.host.error(`Multihelm: a role listener failed: ${errorText$1(error)}`);
2756
+ this.host.error(`Multihelm: a role listener failed: ${errorText$2(error)}`);
2253
2757
  }
2254
2758
  }
2255
2759
  if (status !== this.announcedStatus) {
@@ -2257,7 +2761,7 @@ var Multihelm = class {
2257
2761
  for (const cb of this.statusListeners) try {
2258
2762
  cb();
2259
2763
  } catch (error) {
2260
- this.host.error(`Multihelm: a status listener failed: ${errorText$1(error)}`);
2764
+ this.host.error(`Multihelm: a status listener failed: ${errorText$2(error)}`);
2261
2765
  }
2262
2766
  }
2263
2767
  }
@@ -2267,7 +2771,7 @@ var Multihelm = class {
2267
2771
  try {
2268
2772
  listed = await dataset.definition.list();
2269
2773
  } catch (error) {
2270
- this.host.error(`Multihelm: listing ${id} failed: ${errorText$1(error)}`);
2774
+ this.host.error(`Multihelm: listing ${id} failed: ${errorText$2(error)}`);
2271
2775
  return;
2272
2776
  }
2273
2777
  dataset.listed = new Map(listed.map((e) => [e.key, e]));
@@ -2283,22 +2787,42 @@ var Multihelm = class {
2283
2787
  try {
2284
2788
  file.sha256 = await hashFile(source.path);
2285
2789
  } catch (error) {
2286
- this.host.debug(`Multihelm: cannot hash ${source.path}: ${errorText$1(error)}`);
2790
+ this.host.debug(`Multihelm: cannot hash ${source.path}: ${errorText$2(error)}`);
2287
2791
  }
2288
2792
  }
2289
2793
  }
2290
2794
  this.store.saveLibrary(id, dataset.library);
2291
2795
  }
2292
- hello() {
2796
+ hello(asker) {
2797
+ const peer = asker === void 0 ? void 0 : this.pairedPeers().find((p) => p.id === asker);
2293
2798
  return {
2294
2799
  serverId: this.serverId,
2295
2800
  name: this.host.serverName(),
2296
2801
  protocol: 1,
2297
2802
  datasets: this.datasetIds(),
2298
2803
  master: this.host.isMaster(),
2804
+ ...this.standing(),
2805
+ ...peer ? { seesStandby: peer.standby ?? 0 } : {},
2299
2806
  ...this.versions()
2300
2807
  };
2301
2808
  }
2809
+ standing() {
2810
+ const standby = this.host.standby?.() ?? 0;
2811
+ const elects = this.castVote();
2812
+ return {
2813
+ ...standby > 0 ? { standby } : {},
2814
+ acting: this.acting(),
2815
+ ...elects !== void 0 ? { elects } : {}
2816
+ };
2817
+ }
2818
+ /** Until the plugins that run on the master only have stopped here, this server still acts. */
2819
+ acting() {
2820
+ return this.role() === "master" || this.host.stillRunning?.() === true;
2821
+ }
2822
+ /** Whether the plugins that run on the master only still run here changed: the peers hear at once. */
2823
+ actingChanged() {
2824
+ this.checkMasters();
2825
+ }
2302
2826
  versions() {
2303
2827
  const { signalk, multihelm } = this.host.versions?.() ?? {};
2304
2828
  return {
@@ -2311,15 +2835,26 @@ var Multihelm = class {
2311
2835
  serverId: this.serverId,
2312
2836
  name: this.host.serverName(),
2313
2837
  master: this.host.isMaster(),
2838
+ acting: this.acting(),
2314
2839
  ...this.versions()
2315
2840
  };
2316
2841
  }
2317
- answered(url, hello) {
2842
+ answered(url, hello, asked) {
2318
2843
  this.answers.set(url, {
2319
2844
  at: Date.now(),
2845
+ asked,
2320
2846
  hello
2321
2847
  });
2322
2848
  this.helloErrors.delete(url);
2849
+ const peer = this.peers.find((p) => p.url === url);
2850
+ const quorum = hello.acting !== void 0;
2851
+ if (peer && (peer.standby !== hello.standby || (peer.quorum ?? false) !== quorum || hello.seesStandby !== void 0 && peer.seesStandby !== hello.seesStandby)) {
2852
+ if (hello.standby === void 0) delete peer.standby;
2853
+ else peer.standby = hello.standby;
2854
+ peer.quorum = quorum;
2855
+ if (hello.seesStandby !== void 0) peer.seesStandby = hello.seesStandby;
2856
+ this.store.savePeers(this.peers);
2857
+ }
2323
2858
  }
2324
2859
  /**
2325
2860
  * Notes a server that asked for this one's `hello`. Its last sighting is
@@ -2343,7 +2878,8 @@ var Multihelm = class {
2343
2878
  }
2344
2879
  if (!known || known.name !== server.name || known.signalk !== server.signalk || known.multihelm !== server.multihelm || now - this.pairedBySavedAt >= PAIRED_BY_SAVE_MS) this.savePairedBySoon();
2345
2880
  const peer = this.peers.find((p) => p.state === "paired" && p.id === from.serverId);
2346
- if (peer && from.master !== void 0 && this.masterSeen.has(peer.url) !== from.master) this.checkMasters();
2881
+ const answer = peer && this.answers.get(peer.url)?.hello;
2882
+ if (peer && (from.master !== void 0 && this.masterSeen.has(peer.url) !== from.master || from.acting !== void 0 && (answer === void 0 || this.acts(answer) !== from.acting))) this.checkMasters();
2347
2883
  }
2348
2884
  /** The servers paired with this one, by name. */
2349
2885
  pairedByInfo() {
@@ -2372,7 +2908,7 @@ var Multihelm = class {
2372
2908
  try {
2373
2909
  this.store.savePairedBy([...this.pairedBy.values()]);
2374
2910
  } catch (error) {
2375
- this.host.error(`Multihelm: saving the servers paired with this one: ${errorText$1(error)}`);
2911
+ this.host.error(`Multihelm: saving the servers paired with this one: ${errorText$2(error)}`);
2376
2912
  }
2377
2913
  }
2378
2914
  manifest(datasetId, since) {
@@ -2407,7 +2943,7 @@ var Multihelm = class {
2407
2943
  peer.lastError = "access was revoked on the peer";
2408
2944
  } else {
2409
2945
  if (needsPairingAgain(error)) peer.state = "needs-pairing";
2410
- peer.lastError = connectionText(error) ?? errorText$1(error);
2946
+ peer.lastError = connectionText(error) ?? errorText$2(error);
2411
2947
  }
2412
2948
  this.host.debug(`Multihelm: ${peer.name}: ${peer.lastError}`);
2413
2949
  }
@@ -2446,7 +2982,7 @@ var Multihelm = class {
2446
2982
  const local = library.entries[remote.key];
2447
2983
  if (local && compareVersions(remote.version, local.version) <= 0) return true;
2448
2984
  const fail = (error) => {
2449
- peer.lastError = `${definition.id}: ${remote.key}: ${errorText$1(error)}`;
2985
+ peer.lastError = `${definition.id}: ${remote.key}: ${errorText$2(error)}`;
2450
2986
  this.host.debug(`Multihelm: ${peer.lastError}`);
2451
2987
  return false;
2452
2988
  };
@@ -2660,11 +3196,12 @@ var Multihelm = class {
2660
3196
  this.applyAccessResult(peer, await pollAccess(peer, peer.requestHref));
2661
3197
  if (peer.state === "paired") await this.helloLocked(peer);
2662
3198
  } catch (error) {
2663
- peer.lastError = errorText$1(error);
3199
+ peer.lastError = errorText$2(error);
2664
3200
  }
2665
3201
  }
2666
3202
  async helloLocked(peer) {
2667
3203
  try {
3204
+ const asked = Date.now();
2668
3205
  const hello = await fetchHello(peer, peer.token, this.helloFrom());
2669
3206
  if (hello.serverId === this.serverId) {
2670
3207
  peer.state = "needs-pairing";
@@ -2674,14 +3211,14 @@ var Multihelm = class {
2674
3211
  peer.id = hello.serverId;
2675
3212
  peer.name = hello.name;
2676
3213
  peer.lastSeen = Date.now();
2677
- this.answered(peer.url, hello);
3214
+ this.answered(peer.url, hello, asked);
2678
3215
  if (hello.master) this.masterSeen.set(peer.url, peer.lastSeen);
2679
3216
  else this.masterSeen.delete(peer.url);
2680
3217
  } catch (error) {
2681
3218
  this.helloErrors.set(peer.url, helloErrorText(error));
2682
3219
  if (needsPairingAgain(error)) {
2683
3220
  peer.state = "needs-pairing";
2684
- peer.lastError = connectionText(error) ?? errorText$1(error);
3221
+ peer.lastError = connectionText(error) ?? errorText$2(error);
2685
3222
  }
2686
3223
  }
2687
3224
  }
@@ -2702,18 +3239,20 @@ function helloFrom(req) {
2702
3239
  const signalk = queryString(req, "signalk");
2703
3240
  const multihelm = queryString(req, "multihelm");
2704
3241
  const master = queryString(req, "master");
3242
+ const acting = queryString(req, "acting");
2705
3243
  return {
2706
3244
  serverId,
2707
3245
  name,
2708
3246
  ...master === "1" || master === "0" ? { master: master === "1" } : {},
3247
+ ...acting === "1" || acting === "0" ? { acting: acting === "1" } : {},
2709
3248
  ...VERSION.test(signalk) ? { signalk } : {},
2710
3249
  ...VERSION.test(multihelm) ? { multihelm } : {}
2711
3250
  };
2712
3251
  }
2713
- function errorText(error) {
3252
+ function errorText$1(error) {
2714
3253
  return error instanceof Error ? error.message : String(error);
2715
3254
  }
2716
- function registerRoutes(router, multihelm, discovered, vesselSettings = () => null, masterProxy = () => null, ownAccess = () => null, masterPlugins = () => null, controlAccess = () => null) {
3255
+ function registerRoutes(router, multihelm, discovered, vesselSettings = () => null, masterProxy = () => null, ownAccess = () => null, masterPlugins = () => null, controlAccess = () => null, sharedPlugins = () => null) {
2717
3256
  const scoped = router.access;
2718
3257
  const available = typeof scoped === "function";
2719
3258
  const readonly = available ? scoped.call(router, "readonly") : { get(path, handler) {
@@ -2729,13 +3268,13 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
2729
3268
  try {
2730
3269
  await handler(mh, req, res);
2731
3270
  } catch (error) {
2732
- res.status(500).json({ error: errorText(error) });
3271
+ res.status(500).json({ error: errorText$1(error) });
2733
3272
  }
2734
3273
  };
2735
3274
  readonly.get("/hello", running((mh, req, res) => {
2736
3275
  const from = helloFrom(req);
2737
3276
  if (from) mh.sawPairedServer(from);
2738
- res.json(mh.hello());
3277
+ res.json(mh.hello(from?.serverId));
2739
3278
  }));
2740
3279
  readonly.get("/vessel-settings", running((_mh, _req, res) => {
2741
3280
  const settings = vesselSettings();
@@ -2792,12 +3331,14 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
2792
3331
  role: mh?.role() ?? null,
2793
3332
  master: mh?.master() ?? null,
2794
3333
  masterConflict: mh?.masterConflict() ?? false,
3334
+ majority: mh?.hasMajority() ?? true,
2795
3335
  datasets: mh?.datasetIds() ?? [],
2796
3336
  peers: mh?.peerInfo() ?? [],
2797
3337
  pairedBy: mh?.pairedByInfo() ?? [],
2798
3338
  discovered: mh ? discovered() : [],
2799
3339
  ownAccess: mh ? ownAccess() : null,
2800
3340
  masterPlugins: masterPlugins()?.ids() ?? [],
3341
+ sharedPlugins: sharedPlugins()?.list.ids() ?? [],
2801
3342
  controlAccess: mh ? controlAccess() : null
2802
3343
  };
2803
3344
  res.json(status);
@@ -2811,7 +3352,7 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
2811
3352
  try {
2812
3353
  res.json(await mh.pair(url));
2813
3354
  } catch (error) {
2814
- res.status(400).json({ error: errorText(error) });
3355
+ res.status(400).json({ error: errorText$1(error) });
2815
3356
  }
2816
3357
  }));
2817
3358
  router.delete("/peers", running(async (mh, req, res) => {
@@ -2822,23 +3363,38 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
2822
3363
  const id = queryString(req, "id");
2823
3364
  res.status(mh.forgetPairedBy(id) ? 200 : 404).json({ removed: id });
2824
3365
  }));
2825
- router.put("/master-plugins", async (req, res) => {
3366
+ const putPluginList = (route, lists) => {
3367
+ router.put(route, async (req, res) => {
3368
+ const target = lists();
3369
+ if (!target) {
3370
+ res.status(503).json({ error: "Multihelm is not running" });
3371
+ return;
3372
+ }
3373
+ const ids = parsePluginIds(req.body?.plugins);
3374
+ if (!ids) {
3375
+ res.status(400).json({ error: "plugins must be a list of plugin ids" });
3376
+ return;
3377
+ }
3378
+ const before = target.list.ids();
3379
+ try {
3380
+ await target.list.set(ids);
3381
+ await target.added?.(ids.filter((id) => !before.includes(id)));
3382
+ res.json({ plugins: target.list.ids() });
3383
+ } catch (error) {
3384
+ res.status(500).json({ error: errorText$1(error) });
3385
+ }
3386
+ });
3387
+ };
3388
+ putPluginList("/master-plugins", () => {
2826
3389
  const list = masterPlugins();
2827
- if (!list) {
2828
- res.status(503).json({ error: "Multihelm is not running" });
2829
- return;
2830
- }
2831
- const ids = parsePluginIds(req.body?.plugins);
2832
- if (!ids) {
2833
- res.status(400).json({ error: "plugins must be a list of plugin ids" });
2834
- return;
2835
- }
2836
- try {
2837
- await list.set(ids);
2838
- res.json({ plugins: list.ids() });
2839
- } catch (error) {
2840
- res.status(500).json({ error: errorText(error) });
2841
- }
3390
+ return list ? { list } : null;
3391
+ });
3392
+ putPluginList("/shared-plugins", () => {
3393
+ const shared = sharedPlugins();
3394
+ return shared ? {
3395
+ list: shared.list,
3396
+ added: (ids) => shared.config.seed(ids)
3397
+ } : null;
2842
3398
  });
2843
3399
  router.post("/run", running((mh, _req, res) => {
2844
3400
  mh.runRound();
@@ -2861,7 +3417,7 @@ var RESOURCE_TYPES = [
2861
3417
  "regions",
2862
3418
  "notes"
2863
3419
  ];
2864
- var FILE = "resource.json";
3420
+ var FILE$1 = "resource.json";
2865
3421
  /** What the server's Resources API requires of an id for these types. */
2866
3422
  var RESOURCE_ID = /^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$/;
2867
3423
  /** Added by the provider on every read, not part of the resource. */
@@ -3043,7 +3599,7 @@ function resourcesDataset(host) {
3043
3599
  key: `${type}/${id}`,
3044
3600
  meta: null,
3045
3601
  files: [{
3046
- name: FILE,
3602
+ name: FILE$1,
3047
3603
  path: file,
3048
3604
  size: stat.size,
3049
3605
  mtimeMs: stat.mtimeMs
@@ -3053,7 +3609,7 @@ function resourcesDataset(host) {
3053
3609
  return entries;
3054
3610
  },
3055
3611
  apply: async (entry) => {
3056
- const file = entry.files.find((f) => f.name === FILE);
3612
+ const file = entry.files.find((f) => f.name === FILE$1);
3057
3613
  if (!file || entry.files.length !== 1) throw new Error(`a resource has one file, ${entry.key} has ${String(entry.files.length)}`);
3058
3614
  const { type, id } = splitKey(entry.key);
3059
3615
  const resource = JSON.parse(await fs.promises.readFile(file.path, "utf8"));
@@ -3190,6 +3746,168 @@ var OwnServerAccess = class {
3190
3746
  this.host.store.saveOwnAccess(access);
3191
3747
  }
3192
3748
  };
3749
+ // src/shared-config.ts
3750
+ /**
3751
+ * Plugins whose settings are the same on every server, such as a buddy list
3752
+ * that keeps everything in its plugin settings. Each listed plugin is one
3753
+ * entry of a dataset with no master; its file is the plugin's
3754
+ * `configuration`, read and written through this server's own REST API as
3755
+ * the admin UI does. Whether the plugin runs, and its logging, stay as they
3756
+ * are on each server.
3757
+ *
3758
+ * Only the server where a plugin was added to the list offers its settings
3759
+ * at first; the others wait for them, so adding a plugin never replaces the
3760
+ * settings the user meant to share with another server's.
3761
+ */
3762
+ var SHARED_PLUGINS_DATASET = "signalk-multihelm/shared-plugins";
3763
+ var SHARED_PLUGINS_KEY = "shared-plugins";
3764
+ var PLUGIN_CONFIG_DATASET = "signalk-multihelm/plugin-config";
3765
+ var FILE = "configuration.json";
3766
+ var SEED = "seed";
3767
+ function errorText(error) {
3768
+ return error instanceof Error ? error.message : String(error);
3769
+ }
3770
+ function isPlainObject(value) {
3771
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3772
+ }
3773
+ function pluginConfigUrl(base, id) {
3774
+ return `${base}/plugins/${encodeURIComponent(id)}/config`;
3775
+ }
3776
+ async function exists(file) {
3777
+ try {
3778
+ await fs.promises.access(file);
3779
+ return true;
3780
+ } catch {
3781
+ return false;
3782
+ }
3783
+ }
3784
+ var SharedPluginConfig = class {
3785
+ host;
3786
+ constructor(host) {
3787
+ this.host = host;
3788
+ }
3789
+ /** Plugins newly put on the list here: this server's settings for them go out to the others. */
3790
+ async seed(ids) {
3791
+ for (const id of ids) if (isPluginId(id) && id !== this.host.selfId) {
3792
+ await fs.promises.mkdir(this.entryDir(id), { recursive: true });
3793
+ await fs.promises.writeFile(path.join(this.entryDir(id), SEED), "");
3794
+ }
3795
+ }
3796
+ dataset = {
3797
+ id: PLUGIN_CONFIG_DATASET,
3798
+ isValidKey: (key) => isPluginId(key) && key !== this.host.selfId,
3799
+ list: async () => {
3800
+ const shared = this.shared();
3801
+ await this.forgetUnshared(shared);
3802
+ if (shared.length === 0) return [];
3803
+ const token = await this.host.access.token();
3804
+ const entries = [];
3805
+ for (const id of shared) {
3806
+ if (token !== null) await this.readOwn(id, token);
3807
+ const file = path.join(this.entryDir(id), FILE);
3808
+ try {
3809
+ const stat = await fs.promises.stat(file);
3810
+ entries.push({
3811
+ key: id,
3812
+ meta: null,
3813
+ files: [{
3814
+ name: FILE,
3815
+ path: file,
3816
+ size: stat.size,
3817
+ mtimeMs: stat.mtimeMs
3818
+ }]
3819
+ });
3820
+ } catch {}
3821
+ }
3822
+ return entries;
3823
+ },
3824
+ apply: async (entry) => {
3825
+ const file = entry.files.find((f) => f.name === FILE);
3826
+ if (!file || entry.files.length !== 1) throw new Error(`shared settings have one file, ${String(entry.files.length)} came`);
3827
+ const configuration = JSON.parse(await fs.promises.readFile(file.path, "utf8"));
3828
+ if (!isPlainObject(configuration)) throw new Error(`the shared settings of ${entry.key} are not an object`);
3829
+ this.mustBeShared(entry.key);
3830
+ const token = await this.host.access.token();
3831
+ if (token === null) throw new Error("this server's own access request is not approved yet");
3832
+ const url = pluginConfigUrl(this.host.ownUrl(), entry.key);
3833
+ if (!await exclusivePluginConfig(entry.key, async () => {
3834
+ let options;
3835
+ try {
3836
+ options = await callServer("GET", url, token);
3837
+ } catch (error) {
3838
+ if (error instanceof PeerHttpError && error.status === 404) return false;
3839
+ throw error;
3840
+ }
3841
+ this.mustBeShared(entry.key);
3842
+ await callServer("POST", url, token, {
3843
+ ...isPlainObject(options) ? options : {},
3844
+ configuration
3845
+ });
3846
+ return true;
3847
+ })) {
3848
+ this.host.debug(`Multihelm: ${entry.key}, with shared settings, is not installed here`);
3849
+ return;
3850
+ }
3851
+ await this.writeCopy(entry.key, JSON.stringify(configuration));
3852
+ this.host.debug(`Multihelm: took over the shared settings of ${entry.key}`);
3853
+ },
3854
+ remove: async (key) => {
3855
+ await fs.promises.rm(this.entryDir(key), {
3856
+ recursive: true,
3857
+ force: true
3858
+ });
3859
+ return true;
3860
+ }
3861
+ };
3862
+ mustBeShared(id) {
3863
+ if (!this.shared().includes(id)) throw new Error(`${id} is not on the list of plugins with shared settings`);
3864
+ }
3865
+ shared() {
3866
+ return this.host.ids().filter((id) => isPluginId(id) && id !== this.host.selfId);
3867
+ }
3868
+ entryDir(id) {
3869
+ return path.join(this.host.dir, id);
3870
+ }
3871
+ /** A change made here, or the first settings of a plugin seeded here, becomes this server's copy. */
3872
+ async readOwn(id, token) {
3873
+ const dir = this.entryDir(id);
3874
+ const copy = path.join(dir, FILE);
3875
+ const seeded = await exists(path.join(dir, SEED));
3876
+ const had = await fs.promises.readFile(copy, "utf8").catch(() => null);
3877
+ if (had === null && !seeded) return;
3878
+ let options;
3879
+ try {
3880
+ options = await callServer("GET", pluginConfigUrl(this.host.ownUrl(), id), token);
3881
+ } catch (error) {
3882
+ if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) this.host.access.revoked();
3883
+ if (!(error instanceof PeerHttpError && error.status === 404)) this.host.error(`Multihelm: cannot read the settings of ${id}: ${errorText(error)}`);
3884
+ return;
3885
+ }
3886
+ const configuration = isPlainObject(options) ? options.configuration : void 0;
3887
+ const text = JSON.stringify(isPlainObject(configuration) ? configuration : {});
3888
+ if (text !== had) await this.writeCopy(id, text);
3889
+ }
3890
+ async writeCopy(id, text) {
3891
+ const dir = this.entryDir(id);
3892
+ await fs.promises.mkdir(dir, { recursive: true });
3893
+ const tmp = path.join(dir, `${FILE}.part`);
3894
+ await fs.promises.writeFile(tmp, text);
3895
+ await fs.promises.rename(tmp, path.join(dir, FILE));
3896
+ await fs.promises.rm(path.join(dir, SEED), { force: true });
3897
+ }
3898
+ async forgetUnshared(shared) {
3899
+ let names;
3900
+ try {
3901
+ names = await fs.promises.readdir(this.host.dir);
3902
+ } catch {
3903
+ return;
3904
+ }
3905
+ for (const name of names) if (!shared.includes(name)) await fs.promises.rm(path.join(this.host.dir, name), {
3906
+ recursive: true,
3907
+ force: true
3908
+ });
3909
+ }
3910
+ };
3193
3911
  // src/store.ts
3194
3912
  /**
3195
3913
  * Multihelm state on disk, in the plugin's data dir: this server's id, its
@@ -3216,6 +3934,12 @@ var PeerSchema = Type.Object({
3216
3934
  /** Per dataset, the peer's change sequence this server has applied up to. */
3217
3935
  cursors: Type.Record(Type.String(), Type.Integer({ minimum: 0 })),
3218
3936
  lastSeen: Type.Optional(Type.Number()),
3937
+ /** Its place to take over as master, from its last `hello`; kept so a restart still knows. */
3938
+ standby: Type.Optional(Type.Integer({ minimum: 1 })),
3939
+ /** Its `hello` says whether it acts as the master, so it stops acting without most servers. */
3940
+ quorum: Type.Optional(Type.Boolean()),
3941
+ /** The place to take over that its last `hello` said it keeps for this server. */
3942
+ seesStandby: Type.Optional(Type.Integer({ minimum: 0 })),
3219
3943
  lastSync: Type.Optional(Type.Number()),
3220
3944
  lastError: Type.Optional(Type.String())
3221
3945
  });
@@ -3359,10 +4083,11 @@ function multihelmVersion() {
3359
4083
  }
3360
4084
  var APPROVE_HINT = "approve Multihelm's request under Security -> Access Requests on this server to take the vessel settings over and switch the plugins that run on the master";
3361
4085
  var DENIED_HINT = "the access request on this server was denied, so the vessel settings are not taken over and no plugin is switched for the master; restart the plugin to ask again";
3362
- function statusText(role, master, conflict) {
4086
+ function statusText(role, master, conflict, majority) {
3363
4087
  if (conflict) return `${role === "master" ? "Master" : `Member, master: ${master?.name ?? "?"}`}. More than one server is set to be the master: set one only`;
3364
4088
  if (role === "master") return "Master of the boat's servers";
3365
- return master ? `Member, master: ${master.name}` : "Member, no master found";
4089
+ if (master) return `Member, master: ${master.name}`;
4090
+ return majority ? "Member, no master found" : "Member, no master: too few of the boat's servers are reachable";
3366
4091
  }
3367
4092
  /** Registering is plugin API; withdrawing before the plugin stops is reached on the server's own autopilot API. */
3368
4093
  function autopilotWithdrawal(app) {
@@ -3382,6 +4107,7 @@ function src_default(app) {
3382
4107
  let stopFollowing = null;
3383
4108
  let ownAccess = null;
3384
4109
  let masterPluginList = null;
4110
+ let sharedPlugins = null;
3385
4111
  let masterControl = null;
3386
4112
  function localVesselSettings() {
3387
4113
  const deltas = host.config?.baseDeltaEditor?.deltas;
@@ -3457,10 +4183,14 @@ function src_default(app) {
3457
4183
  start(config) {
3458
4184
  const settings = config;
3459
4185
  const isMaster = settings.master === true;
4186
+ let masterPluginsRunHere = () => false;
4187
+ const standby = typeof settings.takeOver === "number" && Number.isInteger(settings.takeOver) ? Math.max(0, settings.takeOver) : 0;
3460
4188
  const store = new MultihelmStore(app.getDataDirPath());
3461
4189
  const mh = new Multihelm(store, {
3462
4190
  serverName: () => os.hostname(),
3463
4191
  isMaster: () => isMaster,
4192
+ standby: () => standby,
4193
+ stillRunning: () => masterPluginsRunHere(),
3464
4194
  versions: () => ({
3465
4195
  signalk: host.config?.version,
3466
4196
  multihelm: multihelmVersion()
@@ -3502,10 +4232,14 @@ function src_default(app) {
3502
4232
  ownAccess = access;
3503
4233
  const masterPlugins = new MasterOnlyPlugins({
3504
4234
  ids: () => pluginList.ids(),
3505
- wanted: () => !mh.roleKnown() ? null : mh.role() === "master" ? true : mh.master() ? false : null,
4235
+ wanted: () => masterPluginsWanted(mh),
3506
4236
  access,
3507
4237
  ownUrl,
3508
4238
  selfId: PLUGIN_ID,
4239
+ runningChanged: () => {
4240
+ mh.actingChanged();
4241
+ },
4242
+ runningFile: path.join(app.getDataDirPath(), "master-plugins-running.json"),
3509
4243
  debug: (msg) => {
3510
4244
  app.debug(msg);
3511
4245
  },
@@ -3513,12 +4247,36 @@ function src_default(app) {
3513
4247
  app.error(msg);
3514
4248
  }
3515
4249
  });
3516
- const pluginList = new MasterPluginList(path.join(app.getDataDirPath(), "master-plugins"), () => {
4250
+ masterPluginsRunHere = () => masterPlugins.runsHere();
4251
+ const pluginList = new PluginList(path.join(app.getDataDirPath(), "master-plugins"), () => {
3517
4252
  masterPlugins.apply();
3518
4253
  settingsHandle.changed();
3519
4254
  });
3520
4255
  const settingsHandle = mh.registerDataset(pluginList.dataset);
3521
4256
  masterPluginList = pluginList;
4257
+ const sharedConfig = new SharedPluginConfig({
4258
+ ids: () => sharedList.ids(),
4259
+ access,
4260
+ ownUrl,
4261
+ selfId: PLUGIN_ID,
4262
+ dir: path.join(app.getDataDirPath(), "plugin-config"),
4263
+ debug: (msg) => {
4264
+ app.debug(msg);
4265
+ },
4266
+ error: (msg) => {
4267
+ app.error(msg);
4268
+ }
4269
+ });
4270
+ const sharedList = new PluginList(path.join(app.getDataDirPath(), "shared-plugins"), () => {
4271
+ sharedListHandle.changed();
4272
+ sharedConfigHandle.changed();
4273
+ }, SHARED_PLUGINS_DATASET, SHARED_PLUGINS_KEY);
4274
+ const sharedListHandle = mh.registerDataset(sharedList.dataset);
4275
+ const sharedConfigHandle = mh.registerDataset(sharedConfig.dataset);
4276
+ sharedPlugins = {
4277
+ list: sharedList,
4278
+ config: sharedConfig
4279
+ };
3522
4280
  const pluginsTimer = setInterval(() => {
3523
4281
  masterPlugins.apply();
3524
4282
  }, ROUND_INTERVAL_MS);
@@ -3542,7 +4300,7 @@ function src_default(app) {
3542
4300
  }
3543
4301
  });
3544
4302
  const showRole = () => {
3545
- const text = statusText(mh.role(), mh.master(), mh.masterConflict());
4303
+ const text = statusText(mh.role(), mh.master(), mh.masterConflict(), mh.hasMajority());
3546
4304
  if (access.waitingForApproval()) app.setPluginStatus(`${text}; ${APPROVE_HINT}`);
3547
4305
  else if (access.denied()) app.setPluginStatus(`${text}; ${DENIED_HINT}`);
3548
4306
  else app.setPluginStatus(text);
@@ -3632,6 +4390,23 @@ function src_default(app) {
3632
4390
  }
3633
4391
  }) : null;
3634
4392
  course?.start();
4393
+ const notifications = managedNotifications(app.notifications);
4394
+ const alarms = settings.alarmsFromMaster !== false && notifications ? new MasterAlarms({
4395
+ master: () => {
4396
+ const masterAccess = mh.masterAccess();
4397
+ const master = mh.role() === "master" ? null : mh.master();
4398
+ return masterAccess && master ? {
4399
+ id: master.id,
4400
+ access: masterAccess
4401
+ } : null;
4402
+ },
4403
+ control,
4404
+ notifications,
4405
+ debug: (msg) => {
4406
+ app.debug(msg);
4407
+ }
4408
+ }) : null;
4409
+ alarms?.start();
3635
4410
  const stopRoleAutopilot = mh.onRoleChanged(() => {
3636
4411
  autopilot?.roleChanged();
3637
4412
  });
@@ -3641,10 +4416,12 @@ function src_default(app) {
3641
4416
  stopFollowing = () => {
3642
4417
  clearInterval(pluginsTimer);
3643
4418
  stopRolePlugins();
4419
+ masterPlugins.stop();
3644
4420
  settingsHandle.unregister();
3645
4421
  stopRoleAutopilot();
3646
4422
  autopilot?.stop();
3647
4423
  course?.stop();
4424
+ alarms?.stop();
3648
4425
  clearInterval(followTimer);
3649
4426
  stopRoleFollow();
3650
4427
  clearInterval(historyTimer);
@@ -3660,6 +4437,7 @@ function src_default(app) {
3660
4437
  stopFollowing = null;
3661
4438
  ownAccess = null;
3662
4439
  masterPluginList = null;
4440
+ sharedPlugins = null;
3663
4441
  masterControl = null;
3664
4442
  stopRoleStatus?.();
3665
4443
  stopRoleStatus = null;
@@ -3672,7 +4450,7 @@ function src_default(app) {
3672
4450
  discovery = null;
3673
4451
  },
3674
4452
  registerWithRouter(router) {
3675
- registerRoutes(router, () => multihelm, () => discovery?.list() ?? [], localVesselSettings, () => masterProxy, ownAccessState, () => masterPluginList, () => masterControl?.waitingForApproval(multihelm?.role() === "master") ?? null);
4453
+ registerRoutes(router, () => multihelm, () => discovery?.list() ?? [], localVesselSettings, () => masterProxy, ownAccessState, () => masterPluginList, () => masterControl?.waitingForApproval(multihelm?.role() === "master") ?? null, () => sharedPlugins);
3676
4454
  }
3677
4455
  };
3678
4456
  }