signalk-multihelm 0.7.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
  };
@@ -381,7 +390,7 @@ function isActive(state) {
381
390
  function isRecord$5(value) {
382
391
  return typeof value === "object" && value !== null && !Array.isArray(value);
383
392
  }
384
- function errorText$7(error) {
393
+ function errorText$8(error) {
385
394
  return error instanceof Error ? error.message : String(error);
386
395
  }
387
396
  function activeAlarms(listing) {
@@ -439,7 +448,7 @@ var MasterAlarms = class {
439
448
  try {
440
449
  await this.syncOnce();
441
450
  } catch (error) {
442
- this.host.debug(`Multihelm: the alarms from the master: ${errorText$7(error)}`);
451
+ this.host.debug(`Multihelm: the alarms from the master: ${errorText$8(error)}`);
443
452
  } finally {
444
453
  this.running = false;
445
454
  }
@@ -462,7 +471,7 @@ var MasterAlarms = class {
462
471
  const here = this.alarmHere(path, alarm, master.id);
463
472
  seen.set(here.id, await this.keepInStep(master, here, alarm));
464
473
  } catch (error) {
465
- this.host.debug(`Multihelm: the master's alarm ${path}: ${errorText$7(error)}`);
474
+ this.host.debug(`Multihelm: the master's alarm ${path}: ${errorText$8(error)}`);
466
475
  }
467
476
  }
468
477
  this.seen = seen;
@@ -562,7 +571,7 @@ var MasterAlarms = class {
562
571
  await callPeer("POST", master.access, `${NOTIFICATIONS_PATH}/${encodeURIComponent(alarm.id)}/${action}`, token);
563
572
  } catch (error) {
564
573
  if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) this.host.control.revoked(master.id, token);
565
- this.host.debug(`Multihelm: sending the ${action} of ${alarm.path} to the master: ${errorText$7(error)}`);
574
+ this.host.debug(`Multihelm: sending the ${action} of ${alarm.path} to the master: ${errorText$8(error)}`);
566
575
  return false;
567
576
  }
568
577
  this.host.debug(`Multihelm: sent the ${action} of ${alarm.path} to the master`);
@@ -573,7 +582,7 @@ var MasterAlarms = class {
573
582
  for (const alarm of activeAlarms(notifications.list())) if (isMirror(alarm) && !keep(alarm)) try {
574
583
  notifications.clear(alarm.id);
575
584
  } catch (error) {
576
- this.host.debug(`Multihelm: clearing ${alarm.path}: ${errorText$7(error)}`);
585
+ this.host.debug(`Multihelm: clearing ${alarm.path}: ${errorText$8(error)}`);
577
586
  }
578
587
  }
579
588
  };
@@ -601,7 +610,7 @@ var AutopilotError = class extends Error {
601
610
  this.statusCode = statusCode;
602
611
  }
603
612
  };
604
- function errorText$6(error) {
613
+ function errorText$7(error) {
605
614
  return error instanceof Error ? error.message : String(error);
606
615
  }
607
616
  function isRecord$4(value) {
@@ -665,7 +674,7 @@ var MasterAutopilot = class {
665
674
  try {
666
675
  answer = await callPeer("GET", master.access, AUTOPILOTS_PATH, master.access.token);
667
676
  } catch (error) {
668
- this.host.debug(`Multihelm: the master's autopilots: ${errorText$6(error)}`);
677
+ this.host.debug(`Multihelm: the master's autopilots: ${errorText$7(error)}`);
669
678
  return;
670
679
  }
671
680
  const devices = isRecord$4(answer) ? Object.keys(answer).sort() : [];
@@ -686,7 +695,7 @@ var MasterAutopilot = class {
686
695
  try {
687
696
  info = asInfo(await this.read(master, device, ""));
688
697
  } catch (error) {
689
- 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)}`);
690
699
  continue;
691
700
  }
692
701
  if (withdrawals !== this.withdrawals) return;
@@ -744,12 +753,12 @@ var MasterAutopilot = class {
744
753
  }
745
754
  run(work) {
746
755
  work().catch((error) => {
747
- this.host.error(`Multihelm: the master's autopilot: ${errorText$6(error)}`);
756
+ this.host.error(`Multihelm: the master's autopilot: ${errorText$7(error)}`);
748
757
  });
749
758
  }
750
759
  asAutopilotError(error) {
751
760
  if (error instanceof AutopilotError) return error;
752
- 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)}`);
753
762
  }
754
763
  provider = {
755
764
  getData: async (device) => asInfo(await this.read(this.masterOrFail(), device, "")),
@@ -779,7 +788,7 @@ var MasterAutopilot = class {
779
788
  };
780
789
  };
781
790
  // src/master-control.ts
782
- function errorText$5(error) {
791
+ function errorText$6(error) {
783
792
  return error instanceof Error ? error.message : String(error);
784
793
  }
785
794
  var MasterControlAccess = class {
@@ -829,7 +838,7 @@ var MasterControlAccess = class {
829
838
  try {
830
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");
831
840
  } catch (error) {
832
- 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)}`);
833
842
  return null;
834
843
  }
835
844
  if (this.host.currentMaster() !== master.id) return null;
@@ -894,7 +903,7 @@ var COURSE_POLL_MS = 1e3;
894
903
  function isRecord$3(value) {
895
904
  return typeof value === "object" && value !== null && !Array.isArray(value);
896
905
  }
897
- function errorText$4(error) {
906
+ function errorText$5(error) {
898
907
  return error instanceof Error ? error.message : String(error);
899
908
  }
900
909
  function asPosition(value) {
@@ -987,7 +996,7 @@ var MasterCourse = class {
987
996
  try {
988
997
  await this.syncOnce();
989
998
  } catch (error) {
990
- 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)}`);
991
1000
  } finally {
992
1001
  this.running = false;
993
1002
  }
@@ -1199,6 +1208,13 @@ var ConfigSchema = Type.Object({
1199
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.",
1200
1209
  default: false
1201
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
+ }),
1202
1218
  syncResources: Type.Boolean({
1203
1219
  title: "Keep routes and waypoints in step",
1204
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.",
@@ -1426,7 +1442,7 @@ function parseVesselSettings(raw) {
1426
1442
  * restart, with this server's admin device token on itself. Metadata of a path the
1427
1443
  * master has none for stays as it is, unless it was the master's before.
1428
1444
  */
1429
- function errorText$3(error) {
1445
+ function errorText$4(error) {
1430
1446
  return error instanceof Error ? error.message : String(error);
1431
1447
  }
1432
1448
  /** A master where none are set yet would wipe the ones a server kept from before Multihelm. */
@@ -1494,7 +1510,7 @@ var MasterFollower = class {
1494
1510
  try {
1495
1511
  remote = parseVesselSettings(await fetchVesselSettings(master, master.token));
1496
1512
  } catch (error) {
1497
- 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)}`);
1498
1514
  return;
1499
1515
  }
1500
1516
  if (!remote) return;
@@ -1523,7 +1539,7 @@ var MasterFollower = class {
1523
1539
  }
1524
1540
  } catch (error) {
1525
1541
  if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) this.host.access.revoked();
1526
- 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)}`);
1527
1543
  }
1528
1544
  if (followMeta) this.saveFollowedMeta();
1529
1545
  }
@@ -1535,7 +1551,7 @@ var MasterFollower = class {
1535
1551
  this.host.store.saveFollowedMeta(paths);
1536
1552
  this.followedMetaSaved = text;
1537
1553
  } catch (error) {
1538
- 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)}`);
1539
1555
  }
1540
1556
  }
1541
1557
  prioritiesToWrite(remote, local) {
@@ -1561,9 +1577,12 @@ var MasterFollower = class {
1561
1577
  */
1562
1578
  var SETTINGS_DATASET = "signalk-multihelm/settings";
1563
1579
  var MASTER_PLUGINS_KEY = "master-plugins";
1564
- var FILE$1 = "plugins.json";
1565
- var PLUGIN_ID$1 = /^[\w.@-]{1,100}$/;
1580
+ var FILE$2 = "plugins.json";
1581
+ var PLUGIN_ID$1 = /^[\w@-][\w.@-]{0,99}$/;
1566
1582
  var MAX_PLUGINS = 100;
1583
+ function isPluginId(id) {
1584
+ return PLUGIN_ID$1.test(id);
1585
+ }
1567
1586
  function parsePluginIds(raw) {
1568
1587
  if (!Array.isArray(raw) || raw.length > MAX_PLUGINS) return null;
1569
1588
  const ids = [];
@@ -1573,20 +1592,26 @@ function parsePluginIds(raw) {
1573
1592
  }
1574
1593
  return [...new Set(ids)].sort();
1575
1594
  }
1576
- function errorText$2(error) {
1595
+ function errorText$3(error) {
1577
1596
  return error instanceof Error ? error.message : String(error);
1578
1597
  }
1579
- /** The list, kept in a file of its own under `dir`, since a dataset entry is made of files. */
1580
- 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 {
1581
1600
  onChange;
1601
+ datasetId;
1602
+ key;
1582
1603
  file;
1583
1604
  current;
1584
1605
  /** Writes one after the other, so two cannot share the temporary file or publish out of order. */
1585
1606
  writes = Promise.resolve();
1586
- constructor(dir, onChange) {
1607
+ dataset;
1608
+ constructor(dir, onChange, datasetId = SETTINGS_DATASET, key = MASTER_PLUGINS_KEY) {
1587
1609
  this.onChange = onChange;
1588
- this.file = path.join(dir, FILE$1);
1610
+ this.datasetId = datasetId;
1611
+ this.key = key;
1612
+ this.file = path.join(dir, FILE$2);
1589
1613
  this.current = this.read();
1614
+ this.dataset = this.define();
1590
1615
  }
1591
1616
  ids() {
1592
1617
  return this.current;
@@ -1594,42 +1619,44 @@ var MasterPluginList = class {
1594
1619
  set(ids) {
1595
1620
  return this.queued(() => this.write(ids));
1596
1621
  }
1597
- dataset = {
1598
- id: SETTINGS_DATASET,
1599
- isValidKey: (key) => key === MASTER_PLUGINS_KEY,
1600
- list: async () => {
1601
- let stat;
1602
- try {
1603
- stat = await fs.promises.stat(this.file);
1604
- } catch {
1605
- 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;
1606
1657
  }
1607
- return [{
1608
- key: MASTER_PLUGINS_KEY,
1609
- meta: null,
1610
- files: [{
1611
- name: FILE$1,
1612
- path: this.file,
1613
- size: stat.size,
1614
- mtimeMs: stat.mtimeMs
1615
- }]
1616
- }];
1617
- },
1618
- apply: async (entry) => {
1619
- const file = entry.files.find((f) => f.name === FILE$1);
1620
- if (!file || entry.files.length !== 1) throw new Error(`the plugin list has one file, ${String(entry.files.length)} came`);
1621
- const ids = parsePluginIds(JSON.parse(await fs.promises.readFile(file.path, "utf8")));
1622
- if (!ids) throw new Error("not a list of plugin ids");
1623
- await this.queued(() => this.write(ids));
1624
- },
1625
- remove: async () => {
1626
- await this.queued(async () => {
1627
- await fs.promises.rm(this.file, { force: true });
1628
- this.changed([]);
1629
- });
1630
- return true;
1631
- }
1632
- };
1658
+ };
1659
+ }
1633
1660
  queued(work) {
1634
1661
  const result = this.writes.then(work);
1635
1662
  this.writes = result.catch(() => void 0);
@@ -1664,27 +1691,115 @@ var MasterPluginList = class {
1664
1691
  if (JSON.stringify(ids) !== before) this.onChange();
1665
1692
  }
1666
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
+ }
1667
1715
  function pluginUrl(base, id, rest = "") {
1668
1716
  return `${base}/plugins/${encodeURIComponent(id)}${rest}`;
1669
1717
  }
1670
1718
  /** Switches the listed plugins on this server to what its role wants; one run at a time. */
1671
1719
  var MasterOnlyPlugins = class {
1672
1720
  host;
1673
- running = false;
1721
+ busy = false;
1674
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;
1675
1730
  constructor(host) {
1676
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;
1677
1791
  }
1678
1792
  apply() {
1679
- if (this.running) {
1793
+ if (this.stopped) return;
1794
+ if (this.busy) {
1680
1795
  this.again = true;
1681
1796
  return;
1682
1797
  }
1683
- this.running = true;
1798
+ this.busy = true;
1684
1799
  this.applyOnce().catch((error) => {
1685
- 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)}`);
1686
1801
  }).finally(() => {
1687
- this.running = false;
1802
+ this.busy = false;
1688
1803
  if (this.again) {
1689
1804
  this.again = false;
1690
1805
  this.apply();
@@ -1694,32 +1809,43 @@ var MasterOnlyPlugins = class {
1694
1809
  async applyOnce() {
1695
1810
  const wanted = this.host.wanted();
1696
1811
  const ids = this.host.ids().filter((id) => id !== this.host.selfId);
1697
- if (wanted === null || ids.length === 0) return;
1812
+ if (ids.length === 0) return;
1698
1813
  const token = await this.host.access.token();
1699
1814
  if (token === null) return;
1700
1815
  const base = this.host.ownUrl();
1701
1816
  for (const id of ids) try {
1702
- if ((await callServer("GET", pluginUrl(base, id), token))?.enabled === wanted) continue;
1703
- const options = await callServer("GET", pluginUrl(base, id, "/config"), token);
1704
- if (this.host.wanted() !== wanted) return;
1705
- if (!this.host.ids().includes(id)) continue;
1706
- const body = typeof options === "object" && options !== null && !Array.isArray(options) ? {
1707
- ...options,
1708
- enabled: wanted
1709
- } : { enabled: wanted };
1710
- await callServer("POST", pluginUrl(base, id, "/config"), token, body);
1711
- 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;
1712
1837
  } catch (error) {
1713
1838
  if (error instanceof PeerHttpError && error.status === 404) {
1714
1839
  this.host.debug(`Multihelm: ${id}, set to run on the master only, is not installed here`);
1840
+ this.mark(id, false);
1715
1841
  continue;
1716
1842
  }
1717
1843
  if (error instanceof PeerHttpError && (error.status === 401 || error.status === 403)) {
1718
1844
  this.host.access.revoked();
1719
- 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)}`);
1720
1846
  return;
1721
1847
  }
1722
- 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)}`);
1723
1849
  }
1724
1850
  }
1725
1851
  };
@@ -2166,6 +2292,7 @@ var MASTER_CHECK_INTERVAL_MS = 3e4;
2166
2292
  * recently, so a few missed answers do not move the role.
2167
2293
  */
2168
2294
  var MASTER_STALE_MS = 5 * MASTER_CHECK_INTERVAL_MS;
2295
+ 2 * MASTER_CHECK_INTERVAL_MS;
2169
2296
  /** Every peer asks every 30 s, so a sighting is saved only now and then. */
2170
2297
  var PAIRED_BY_SAVE_MS = 6e5;
2171
2298
  /** Without security anyone may ask, so writes of that list are gathered, never one per request. */
@@ -2179,7 +2306,7 @@ async function hashFile(file) {
2179
2306
  await pipeline(fs.createReadStream(file), hash);
2180
2307
  return hash.digest("hex");
2181
2308
  }
2182
- function errorText$1(error) {
2309
+ function errorText$2(error) {
2183
2310
  return error instanceof Error ? error.message : String(error);
2184
2311
  }
2185
2312
  /** What Node calls a certificate chain that does not lead to a certificate it trusts. */
@@ -2212,7 +2339,7 @@ function connectionText(error) {
2212
2339
  }
2213
2340
  /** Said without the address, which the panel shows anyway. */
2214
2341
  function helloErrorText(error) {
2215
- if (!(error instanceof PeerHttpError)) return connectionText(error) ?? errorText$1(error);
2342
+ if (!(error instanceof PeerHttpError)) return connectionText(error) ?? errorText$2(error);
2216
2343
  switch (error.status) {
2217
2344
  case 404: return "Multihelm is not running there";
2218
2345
  case 401:
@@ -2246,6 +2373,7 @@ var Multihelm = class {
2246
2373
  /** Peer URL → when it last answered as set to be the master. */
2247
2374
  masterSeen = /* @__PURE__ */ new Map();
2248
2375
  /** Peer URL → its last `hello`, and when. */
2376
+ /** `asked`: when the request for the answer went out. */
2249
2377
  answers = /* @__PURE__ */ new Map();
2250
2378
  /** Peer URL → why its last `hello` failed. */
2251
2379
  helloErrors = /* @__PURE__ */ new Map();
@@ -2260,13 +2388,16 @@ var Multihelm = class {
2260
2388
  /** What the status listeners were last told: role, master id and conflict. */
2261
2389
  announcedStatus = "";
2262
2390
  masterTimer = null;
2263
- checkingMasters = false;
2391
+ checkingMasters = null;
2264
2392
  checkMastersAgain = false;
2265
2393
  /** Whether the paired peers were asked once since the start, so the role is known. */
2266
2394
  mastersChecked = false;
2267
2395
  pairingTimer = null;
2268
2396
  pollingPairings = false;
2269
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;
2270
2401
  constructor(store, host) {
2271
2402
  this.store = store;
2272
2403
  this.host = host;
@@ -2275,6 +2406,7 @@ var Multihelm = class {
2275
2406
  this.pairedBy = new Map(store.loadPairedBy().map((s) => [s.id, s]));
2276
2407
  }
2277
2408
  start() {
2409
+ this.startedAt = Date.now();
2278
2410
  this.started = true;
2279
2411
  this.stopped = false;
2280
2412
  const tick = () => {
@@ -2289,7 +2421,7 @@ var Multihelm = class {
2289
2421
  }, MASTER_CHECK_INTERVAL_MS);
2290
2422
  this.pairingTimer = setInterval(() => {
2291
2423
  this.pollPairings().catch((error) => {
2292
- this.host.error(`Multihelm: following a pairing request: ${errorText$1(error)}`);
2424
+ this.host.error(`Multihelm: following a pairing request: ${errorText$2(error)}`);
2293
2425
  });
2294
2426
  }, PAIRING_POLL_MS);
2295
2427
  }
@@ -2311,41 +2443,46 @@ var Multihelm = class {
2311
2443
  /**
2312
2444
  * Asks every paired peer whether it is set to be the master. Runs outside
2313
2445
  * the work queue and touches nothing but what it keeps of the answers, so it neither waits
2314
- * 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.
2315
2448
  */
2316
- async checkMasters() {
2317
- if (this.stopped) return;
2449
+ checkMasters() {
2450
+ if (this.stopped) return Promise.resolve();
2318
2451
  if (this.checkingMasters) {
2319
2452
  this.checkMastersAgain = true;
2320
- return;
2453
+ return this.checkingMasters;
2321
2454
  }
2322
- this.checkingMasters = true;
2323
- try {
2324
- await Promise.all(this.peers.filter((p) => p.state === "paired" && p.id !== "").map(async (peer) => {
2325
- const { url, ca } = peer;
2326
- const current = () => !this.stopped && this.peers.includes(peer) && peer.url === url && peer.ca === ca;
2327
- let hello;
2328
- try {
2329
- hello = await fetchHello(peer, peer.token, this.helloFrom());
2330
- } catch (error) {
2331
- if (current()) this.helloErrors.set(url, helloErrorText(error));
2332
- return;
2333
- }
2334
- if (!current() || hello.serverId !== peer.id) return;
2335
- this.answered(url, hello);
2336
- if (hello.master) this.masterSeen.set(url, Date.now());
2337
- else this.masterSeen.delete(url);
2338
- }));
2339
- } finally {
2340
- this.checkingMasters = false;
2341
- }
2342
- if (this.stopped) return;
2343
- this.mastersChecked = true;
2344
- this.announceRole();
2345
- if (this.checkMastersAgain) {
2455
+ this.checkingMasters = this.checkMastersUntilDone().finally(() => {
2456
+ this.checkingMasters = null;
2457
+ });
2458
+ return this.checkingMasters;
2459
+ }
2460
+ async checkMastersUntilDone() {
2461
+ do {
2346
2462
  this.checkMastersAgain = false;
2347
- await this.checkMasters();
2348
- }
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
+ }));
2349
2486
  }
2350
2487
  /** Whether the role is known: the paired peers were asked since the start. */
2351
2488
  roleKnown() {
@@ -2440,16 +2577,143 @@ var Multihelm = class {
2440
2577
  }
2441
2578
  return candidates.sort((x, y) => x.id < y.id ? -1 : x.id > y.id ? 1 : 0);
2442
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. */
2443
2683
  role() {
2444
- 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";
2445
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. */
2446
2699
  master() {
2447
- const peer = this.masterCandidates()[0]?.peer;
2700
+ const peer = this.actingMaster();
2448
2701
  return peer ? this.infoOf(peer) : null;
2449
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
+ }
2450
2714
  /** Where to reach the master, with the pairing token; null when this server is it or there is none. */
2451
2715
  masterAccess() {
2452
- const peer = this.masterCandidates()[0]?.peer;
2716
+ const peer = this.actingMaster();
2453
2717
  if (!peer) return null;
2454
2718
  return peer.ca === void 0 ? {
2455
2719
  url: peer.url,
@@ -2481,13 +2745,15 @@ var Multihelm = class {
2481
2745
  const role = this.role();
2482
2746
  const master = this.master();
2483
2747
  const now = `${role}:${master?.id ?? ""}`;
2484
- const status = `${now}:${String(this.masterConflict())}`;
2748
+ const status = `${now}:${String(this.masterConflict())}:${String(this.hasMajority())}`;
2485
2749
  if (now !== this.announcedRole) {
2750
+ const wasActing = this.announcedRole.startsWith("master:");
2486
2751
  this.announcedRole = now;
2752
+ if (wasActing !== (role === "master")) this.checkMasters();
2487
2753
  for (const cb of this.roleListeners) try {
2488
2754
  cb(role, master);
2489
2755
  } catch (error) {
2490
- this.host.error(`Multihelm: a role listener failed: ${errorText$1(error)}`);
2756
+ this.host.error(`Multihelm: a role listener failed: ${errorText$2(error)}`);
2491
2757
  }
2492
2758
  }
2493
2759
  if (status !== this.announcedStatus) {
@@ -2495,7 +2761,7 @@ var Multihelm = class {
2495
2761
  for (const cb of this.statusListeners) try {
2496
2762
  cb();
2497
2763
  } catch (error) {
2498
- this.host.error(`Multihelm: a status listener failed: ${errorText$1(error)}`);
2764
+ this.host.error(`Multihelm: a status listener failed: ${errorText$2(error)}`);
2499
2765
  }
2500
2766
  }
2501
2767
  }
@@ -2505,7 +2771,7 @@ var Multihelm = class {
2505
2771
  try {
2506
2772
  listed = await dataset.definition.list();
2507
2773
  } catch (error) {
2508
- this.host.error(`Multihelm: listing ${id} failed: ${errorText$1(error)}`);
2774
+ this.host.error(`Multihelm: listing ${id} failed: ${errorText$2(error)}`);
2509
2775
  return;
2510
2776
  }
2511
2777
  dataset.listed = new Map(listed.map((e) => [e.key, e]));
@@ -2521,22 +2787,42 @@ var Multihelm = class {
2521
2787
  try {
2522
2788
  file.sha256 = await hashFile(source.path);
2523
2789
  } catch (error) {
2524
- this.host.debug(`Multihelm: cannot hash ${source.path}: ${errorText$1(error)}`);
2790
+ this.host.debug(`Multihelm: cannot hash ${source.path}: ${errorText$2(error)}`);
2525
2791
  }
2526
2792
  }
2527
2793
  }
2528
2794
  this.store.saveLibrary(id, dataset.library);
2529
2795
  }
2530
- hello() {
2796
+ hello(asker) {
2797
+ const peer = asker === void 0 ? void 0 : this.pairedPeers().find((p) => p.id === asker);
2531
2798
  return {
2532
2799
  serverId: this.serverId,
2533
2800
  name: this.host.serverName(),
2534
2801
  protocol: 1,
2535
2802
  datasets: this.datasetIds(),
2536
2803
  master: this.host.isMaster(),
2804
+ ...this.standing(),
2805
+ ...peer ? { seesStandby: peer.standby ?? 0 } : {},
2537
2806
  ...this.versions()
2538
2807
  };
2539
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
+ }
2540
2826
  versions() {
2541
2827
  const { signalk, multihelm } = this.host.versions?.() ?? {};
2542
2828
  return {
@@ -2549,15 +2835,26 @@ var Multihelm = class {
2549
2835
  serverId: this.serverId,
2550
2836
  name: this.host.serverName(),
2551
2837
  master: this.host.isMaster(),
2838
+ acting: this.acting(),
2552
2839
  ...this.versions()
2553
2840
  };
2554
2841
  }
2555
- answered(url, hello) {
2842
+ answered(url, hello, asked) {
2556
2843
  this.answers.set(url, {
2557
2844
  at: Date.now(),
2845
+ asked,
2558
2846
  hello
2559
2847
  });
2560
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
+ }
2561
2858
  }
2562
2859
  /**
2563
2860
  * Notes a server that asked for this one's `hello`. Its last sighting is
@@ -2581,7 +2878,8 @@ var Multihelm = class {
2581
2878
  }
2582
2879
  if (!known || known.name !== server.name || known.signalk !== server.signalk || known.multihelm !== server.multihelm || now - this.pairedBySavedAt >= PAIRED_BY_SAVE_MS) this.savePairedBySoon();
2583
2880
  const peer = this.peers.find((p) => p.state === "paired" && p.id === from.serverId);
2584
- 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();
2585
2883
  }
2586
2884
  /** The servers paired with this one, by name. */
2587
2885
  pairedByInfo() {
@@ -2610,7 +2908,7 @@ var Multihelm = class {
2610
2908
  try {
2611
2909
  this.store.savePairedBy([...this.pairedBy.values()]);
2612
2910
  } catch (error) {
2613
- 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)}`);
2614
2912
  }
2615
2913
  }
2616
2914
  manifest(datasetId, since) {
@@ -2645,7 +2943,7 @@ var Multihelm = class {
2645
2943
  peer.lastError = "access was revoked on the peer";
2646
2944
  } else {
2647
2945
  if (needsPairingAgain(error)) peer.state = "needs-pairing";
2648
- peer.lastError = connectionText(error) ?? errorText$1(error);
2946
+ peer.lastError = connectionText(error) ?? errorText$2(error);
2649
2947
  }
2650
2948
  this.host.debug(`Multihelm: ${peer.name}: ${peer.lastError}`);
2651
2949
  }
@@ -2684,7 +2982,7 @@ var Multihelm = class {
2684
2982
  const local = library.entries[remote.key];
2685
2983
  if (local && compareVersions(remote.version, local.version) <= 0) return true;
2686
2984
  const fail = (error) => {
2687
- peer.lastError = `${definition.id}: ${remote.key}: ${errorText$1(error)}`;
2985
+ peer.lastError = `${definition.id}: ${remote.key}: ${errorText$2(error)}`;
2688
2986
  this.host.debug(`Multihelm: ${peer.lastError}`);
2689
2987
  return false;
2690
2988
  };
@@ -2898,11 +3196,12 @@ var Multihelm = class {
2898
3196
  this.applyAccessResult(peer, await pollAccess(peer, peer.requestHref));
2899
3197
  if (peer.state === "paired") await this.helloLocked(peer);
2900
3198
  } catch (error) {
2901
- peer.lastError = errorText$1(error);
3199
+ peer.lastError = errorText$2(error);
2902
3200
  }
2903
3201
  }
2904
3202
  async helloLocked(peer) {
2905
3203
  try {
3204
+ const asked = Date.now();
2906
3205
  const hello = await fetchHello(peer, peer.token, this.helloFrom());
2907
3206
  if (hello.serverId === this.serverId) {
2908
3207
  peer.state = "needs-pairing";
@@ -2912,14 +3211,14 @@ var Multihelm = class {
2912
3211
  peer.id = hello.serverId;
2913
3212
  peer.name = hello.name;
2914
3213
  peer.lastSeen = Date.now();
2915
- this.answered(peer.url, hello);
3214
+ this.answered(peer.url, hello, asked);
2916
3215
  if (hello.master) this.masterSeen.set(peer.url, peer.lastSeen);
2917
3216
  else this.masterSeen.delete(peer.url);
2918
3217
  } catch (error) {
2919
3218
  this.helloErrors.set(peer.url, helloErrorText(error));
2920
3219
  if (needsPairingAgain(error)) {
2921
3220
  peer.state = "needs-pairing";
2922
- peer.lastError = connectionText(error) ?? errorText$1(error);
3221
+ peer.lastError = connectionText(error) ?? errorText$2(error);
2923
3222
  }
2924
3223
  }
2925
3224
  }
@@ -2940,18 +3239,20 @@ function helloFrom(req) {
2940
3239
  const signalk = queryString(req, "signalk");
2941
3240
  const multihelm = queryString(req, "multihelm");
2942
3241
  const master = queryString(req, "master");
3242
+ const acting = queryString(req, "acting");
2943
3243
  return {
2944
3244
  serverId,
2945
3245
  name,
2946
3246
  ...master === "1" || master === "0" ? { master: master === "1" } : {},
3247
+ ...acting === "1" || acting === "0" ? { acting: acting === "1" } : {},
2947
3248
  ...VERSION.test(signalk) ? { signalk } : {},
2948
3249
  ...VERSION.test(multihelm) ? { multihelm } : {}
2949
3250
  };
2950
3251
  }
2951
- function errorText(error) {
3252
+ function errorText$1(error) {
2952
3253
  return error instanceof Error ? error.message : String(error);
2953
3254
  }
2954
- 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) {
2955
3256
  const scoped = router.access;
2956
3257
  const available = typeof scoped === "function";
2957
3258
  const readonly = available ? scoped.call(router, "readonly") : { get(path, handler) {
@@ -2967,13 +3268,13 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
2967
3268
  try {
2968
3269
  await handler(mh, req, res);
2969
3270
  } catch (error) {
2970
- res.status(500).json({ error: errorText(error) });
3271
+ res.status(500).json({ error: errorText$1(error) });
2971
3272
  }
2972
3273
  };
2973
3274
  readonly.get("/hello", running((mh, req, res) => {
2974
3275
  const from = helloFrom(req);
2975
3276
  if (from) mh.sawPairedServer(from);
2976
- res.json(mh.hello());
3277
+ res.json(mh.hello(from?.serverId));
2977
3278
  }));
2978
3279
  readonly.get("/vessel-settings", running((_mh, _req, res) => {
2979
3280
  const settings = vesselSettings();
@@ -3030,12 +3331,14 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
3030
3331
  role: mh?.role() ?? null,
3031
3332
  master: mh?.master() ?? null,
3032
3333
  masterConflict: mh?.masterConflict() ?? false,
3334
+ majority: mh?.hasMajority() ?? true,
3033
3335
  datasets: mh?.datasetIds() ?? [],
3034
3336
  peers: mh?.peerInfo() ?? [],
3035
3337
  pairedBy: mh?.pairedByInfo() ?? [],
3036
3338
  discovered: mh ? discovered() : [],
3037
3339
  ownAccess: mh ? ownAccess() : null,
3038
3340
  masterPlugins: masterPlugins()?.ids() ?? [],
3341
+ sharedPlugins: sharedPlugins()?.list.ids() ?? [],
3039
3342
  controlAccess: mh ? controlAccess() : null
3040
3343
  };
3041
3344
  res.json(status);
@@ -3049,7 +3352,7 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
3049
3352
  try {
3050
3353
  res.json(await mh.pair(url));
3051
3354
  } catch (error) {
3052
- res.status(400).json({ error: errorText(error) });
3355
+ res.status(400).json({ error: errorText$1(error) });
3053
3356
  }
3054
3357
  }));
3055
3358
  router.delete("/peers", running(async (mh, req, res) => {
@@ -3060,23 +3363,38 @@ function registerRoutes(router, multihelm, discovered, vesselSettings = () => nu
3060
3363
  const id = queryString(req, "id");
3061
3364
  res.status(mh.forgetPairedBy(id) ? 200 : 404).json({ removed: id });
3062
3365
  }));
3063
- 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", () => {
3064
3389
  const list = masterPlugins();
3065
- if (!list) {
3066
- res.status(503).json({ error: "Multihelm is not running" });
3067
- return;
3068
- }
3069
- const ids = parsePluginIds(req.body?.plugins);
3070
- if (!ids) {
3071
- res.status(400).json({ error: "plugins must be a list of plugin ids" });
3072
- return;
3073
- }
3074
- try {
3075
- await list.set(ids);
3076
- res.json({ plugins: list.ids() });
3077
- } catch (error) {
3078
- res.status(500).json({ error: errorText(error) });
3079
- }
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;
3080
3398
  });
3081
3399
  router.post("/run", running((mh, _req, res) => {
3082
3400
  mh.runRound();
@@ -3099,7 +3417,7 @@ var RESOURCE_TYPES = [
3099
3417
  "regions",
3100
3418
  "notes"
3101
3419
  ];
3102
- var FILE = "resource.json";
3420
+ var FILE$1 = "resource.json";
3103
3421
  /** What the server's Resources API requires of an id for these types. */
3104
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}$/;
3105
3423
  /** Added by the provider on every read, not part of the resource. */
@@ -3281,7 +3599,7 @@ function resourcesDataset(host) {
3281
3599
  key: `${type}/${id}`,
3282
3600
  meta: null,
3283
3601
  files: [{
3284
- name: FILE,
3602
+ name: FILE$1,
3285
3603
  path: file,
3286
3604
  size: stat.size,
3287
3605
  mtimeMs: stat.mtimeMs
@@ -3291,7 +3609,7 @@ function resourcesDataset(host) {
3291
3609
  return entries;
3292
3610
  },
3293
3611
  apply: async (entry) => {
3294
- const file = entry.files.find((f) => f.name === FILE);
3612
+ const file = entry.files.find((f) => f.name === FILE$1);
3295
3613
  if (!file || entry.files.length !== 1) throw new Error(`a resource has one file, ${entry.key} has ${String(entry.files.length)}`);
3296
3614
  const { type, id } = splitKey(entry.key);
3297
3615
  const resource = JSON.parse(await fs.promises.readFile(file.path, "utf8"));
@@ -3428,6 +3746,168 @@ var OwnServerAccess = class {
3428
3746
  this.host.store.saveOwnAccess(access);
3429
3747
  }
3430
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
+ };
3431
3911
  // src/store.ts
3432
3912
  /**
3433
3913
  * Multihelm state on disk, in the plugin's data dir: this server's id, its
@@ -3454,6 +3934,12 @@ var PeerSchema = Type.Object({
3454
3934
  /** Per dataset, the peer's change sequence this server has applied up to. */
3455
3935
  cursors: Type.Record(Type.String(), Type.Integer({ minimum: 0 })),
3456
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 })),
3457
3943
  lastSync: Type.Optional(Type.Number()),
3458
3944
  lastError: Type.Optional(Type.String())
3459
3945
  });
@@ -3597,10 +4083,11 @@ function multihelmVersion() {
3597
4083
  }
3598
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";
3599
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";
3600
- function statusText(role, master, conflict) {
4086
+ function statusText(role, master, conflict, majority) {
3601
4087
  if (conflict) return `${role === "master" ? "Master" : `Member, master: ${master?.name ?? "?"}`}. More than one server is set to be the master: set one only`;
3602
4088
  if (role === "master") return "Master of the boat's servers";
3603
- 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";
3604
4091
  }
3605
4092
  /** Registering is plugin API; withdrawing before the plugin stops is reached on the server's own autopilot API. */
3606
4093
  function autopilotWithdrawal(app) {
@@ -3620,6 +4107,7 @@ function src_default(app) {
3620
4107
  let stopFollowing = null;
3621
4108
  let ownAccess = null;
3622
4109
  let masterPluginList = null;
4110
+ let sharedPlugins = null;
3623
4111
  let masterControl = null;
3624
4112
  function localVesselSettings() {
3625
4113
  const deltas = host.config?.baseDeltaEditor?.deltas;
@@ -3695,10 +4183,14 @@ function src_default(app) {
3695
4183
  start(config) {
3696
4184
  const settings = config;
3697
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;
3698
4188
  const store = new MultihelmStore(app.getDataDirPath());
3699
4189
  const mh = new Multihelm(store, {
3700
4190
  serverName: () => os.hostname(),
3701
4191
  isMaster: () => isMaster,
4192
+ standby: () => standby,
4193
+ stillRunning: () => masterPluginsRunHere(),
3702
4194
  versions: () => ({
3703
4195
  signalk: host.config?.version,
3704
4196
  multihelm: multihelmVersion()
@@ -3740,10 +4232,14 @@ function src_default(app) {
3740
4232
  ownAccess = access;
3741
4233
  const masterPlugins = new MasterOnlyPlugins({
3742
4234
  ids: () => pluginList.ids(),
3743
- wanted: () => !mh.roleKnown() ? null : mh.role() === "master" ? true : mh.master() ? false : null,
4235
+ wanted: () => masterPluginsWanted(mh),
3744
4236
  access,
3745
4237
  ownUrl,
3746
4238
  selfId: PLUGIN_ID,
4239
+ runningChanged: () => {
4240
+ mh.actingChanged();
4241
+ },
4242
+ runningFile: path.join(app.getDataDirPath(), "master-plugins-running.json"),
3747
4243
  debug: (msg) => {
3748
4244
  app.debug(msg);
3749
4245
  },
@@ -3751,12 +4247,36 @@ function src_default(app) {
3751
4247
  app.error(msg);
3752
4248
  }
3753
4249
  });
3754
- 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"), () => {
3755
4252
  masterPlugins.apply();
3756
4253
  settingsHandle.changed();
3757
4254
  });
3758
4255
  const settingsHandle = mh.registerDataset(pluginList.dataset);
3759
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
+ };
3760
4280
  const pluginsTimer = setInterval(() => {
3761
4281
  masterPlugins.apply();
3762
4282
  }, ROUND_INTERVAL_MS);
@@ -3780,7 +4300,7 @@ function src_default(app) {
3780
4300
  }
3781
4301
  });
3782
4302
  const showRole = () => {
3783
- const text = statusText(mh.role(), mh.master(), mh.masterConflict());
4303
+ const text = statusText(mh.role(), mh.master(), mh.masterConflict(), mh.hasMajority());
3784
4304
  if (access.waitingForApproval()) app.setPluginStatus(`${text}; ${APPROVE_HINT}`);
3785
4305
  else if (access.denied()) app.setPluginStatus(`${text}; ${DENIED_HINT}`);
3786
4306
  else app.setPluginStatus(text);
@@ -3896,6 +4416,7 @@ function src_default(app) {
3896
4416
  stopFollowing = () => {
3897
4417
  clearInterval(pluginsTimer);
3898
4418
  stopRolePlugins();
4419
+ masterPlugins.stop();
3899
4420
  settingsHandle.unregister();
3900
4421
  stopRoleAutopilot();
3901
4422
  autopilot?.stop();
@@ -3916,6 +4437,7 @@ function src_default(app) {
3916
4437
  stopFollowing = null;
3917
4438
  ownAccess = null;
3918
4439
  masterPluginList = null;
4440
+ sharedPlugins = null;
3919
4441
  masterControl = null;
3920
4442
  stopRoleStatus?.();
3921
4443
  stopRoleStatus = null;
@@ -3928,7 +4450,7 @@ function src_default(app) {
3928
4450
  discovery = null;
3929
4451
  },
3930
4452
  registerWithRouter(router) {
3931
- 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);
3932
4454
  }
3933
4455
  };
3934
4456
  }