@ipab/cli 0.1.0-rc.12 → 0.1.0-rc.14

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.
Files changed (72) hide show
  1. package/dist/builtins/skill.ipab.car +0 -0
  2. package/dist/cli-daemon.d.ts +14 -0
  3. package/dist/cli-daemon.d.ts.map +1 -0
  4. package/dist/cli-daemon.js +400 -0
  5. package/dist/cli-daemon.js.map +1 -0
  6. package/dist/cli.d.ts.map +1 -1
  7. package/dist/cli.js +1260 -1404
  8. package/dist/cli.js.map +1 -1
  9. package/dist/daemon-api.d.ts +80 -0
  10. package/dist/daemon-api.d.ts.map +1 -0
  11. package/dist/daemon-api.js +2411 -0
  12. package/dist/daemon-api.js.map +1 -0
  13. package/dist/daemon-client.d.ts +322 -0
  14. package/dist/daemon-client.d.ts.map +1 -0
  15. package/dist/daemon-client.js +400 -0
  16. package/dist/daemon-client.js.map +1 -0
  17. package/dist/daemon-protocol.d.ts +22 -0
  18. package/dist/daemon-protocol.d.ts.map +1 -0
  19. package/dist/daemon-protocol.js +39 -0
  20. package/dist/daemon-protocol.js.map +1 -0
  21. package/dist/daemon-telemetry.d.ts +86 -0
  22. package/dist/daemon-telemetry.d.ts.map +1 -0
  23. package/dist/daemon-telemetry.js +502 -0
  24. package/dist/daemon-telemetry.js.map +1 -0
  25. package/dist/daemon-ui.d.ts +68 -0
  26. package/dist/daemon-ui.d.ts.map +1 -1
  27. package/dist/daemon-ui.js +283 -4
  28. package/dist/daemon-ui.js.map +1 -1
  29. package/dist/daemon.d.ts +10 -0
  30. package/dist/daemon.d.ts.map +1 -1
  31. package/dist/daemon.js +289 -38
  32. package/dist/daemon.js.map +1 -1
  33. package/dist/identity.d.ts.map +1 -1
  34. package/dist/identity.js +7 -2
  35. package/dist/identity.js.map +1 -1
  36. package/dist/ipc.d.ts +19 -7
  37. package/dist/ipc.d.ts.map +1 -1
  38. package/dist/ipc.js +96 -70
  39. package/dist/ipc.js.map +1 -1
  40. package/dist/pins.d.ts.map +1 -1
  41. package/dist/pins.js +18 -3
  42. package/dist/pins.js.map +1 -1
  43. package/dist/state-storage.d.ts.map +1 -1
  44. package/dist/state-storage.js +2 -1
  45. package/dist/state-storage.js.map +1 -1
  46. package/dist/state.d.ts +1 -1
  47. package/dist/state.d.ts.map +1 -1
  48. package/dist/state.js +3 -2
  49. package/dist/state.js.map +1 -1
  50. package/dist/swarm-files.d.ts.map +1 -1
  51. package/dist/swarm-files.js +7 -2
  52. package/dist/swarm-files.js.map +1 -1
  53. package/dist/swarm.d.ts +10 -1
  54. package/dist/swarm.d.ts.map +1 -1
  55. package/dist/swarm.js +247 -76
  56. package/dist/swarm.js.map +1 -1
  57. package/package.json +4 -4
  58. package/src/cli-daemon.ts +482 -0
  59. package/src/cli.ts +1689 -1948
  60. package/src/daemon-api.ts +3148 -0
  61. package/src/daemon-client.ts +975 -0
  62. package/src/daemon-protocol.ts +61 -0
  63. package/src/daemon-telemetry.ts +656 -0
  64. package/src/daemon-ui.ts +361 -4
  65. package/src/daemon.ts +337 -43
  66. package/src/identity.ts +10 -2
  67. package/src/ipc.ts +113 -79
  68. package/src/pins.ts +23 -3
  69. package/src/state-storage.ts +5 -1
  70. package/src/state.ts +3 -1
  71. package/src/swarm-files.ts +10 -2
  72. package/src/swarm.ts +727 -497
package/dist/swarm.js CHANGED
@@ -39,6 +39,7 @@ import { memberPeers } from "./kubo-peering.js";
39
39
  import { PivotCandidates } from "./kubo-topology.js";
40
40
  import { indexV7UnixfsSwarm, queryLocalSearchIndex, validateSearchParams, } from "./search-index.js";
41
41
  import { queryRemotePivotSearch, rankPivotCandidates, } from "./search-service.js";
42
+ import { DaemonTelemetry, telemetryLogFilename } from "./daemon-telemetry.js";
42
43
  import { DaemonLogBuffer, emptySyncState, pivotReceiptProtocol, redactDaemonText, } from "./daemon-ui.js";
43
44
  import { networkingBinding, pivotLocalStatus, readNetworkingSnapshot, writeNetworkingSnapshot, networkingAccount, } from "./swarm-observations.js";
44
45
  import { seedTemplateNames, seedTemplateSource } from "./template-source.js";
@@ -132,6 +133,15 @@ export const artifactType = {
132
133
  },
133
134
  },
134
135
  };
136
+ function withSwarmLock(context, lockDir, action, signal) {
137
+ if (context.inProcessMutex) {
138
+ return context.inProcessMutex.run(lockDir, async () => {
139
+ signal?.throwIfAborted();
140
+ return action();
141
+ });
142
+ }
143
+ return withPrivateLock(lockDir, action, signal);
144
+ }
135
145
  function withState(context, operation) {
136
146
  if (context.state)
137
147
  return operation(context.state);
@@ -604,7 +614,7 @@ async function inspection(context, url, refresh = false) {
604
614
  ]);
605
615
  let snapshot;
606
616
  if (saved === undefined) {
607
- snapshot = await withPrivateLock(await privateDirectory(context.stateDir, "swarm-inspections"), async () => {
617
+ snapshot = await withSwarmLock(context, await privateDirectory(context.stateDir, "swarm-inspections"), async () => {
608
618
  const { config, variable } = await fetchConfig(context, url);
609
619
  const directory = await memberDirectory(context, url, config);
610
620
  const c = coordinates(url);
@@ -1001,7 +1011,7 @@ export async function accountProfile(context) {
1001
1011
  async function ensureAccountProfile(context, changes = {}) {
1002
1012
  const identity = await contextIdentity(context);
1003
1013
  const dir = await accountProfileDirectory(context, identity.publicKey);
1004
- return withPrivateLock(dir, async () => {
1014
+ return withSwarmLock(context, dir, async () => {
1005
1015
  const existing = await storedAccountProfile(context);
1006
1016
  if (existing &&
1007
1017
  changes.name === undefined &&
@@ -1370,6 +1380,36 @@ export async function swarmDaemon(context, signal, synchronize) {
1370
1380
  }
1371
1381
  return secrets;
1372
1382
  };
1383
+ const telemetry = new DaemonTelemetry({
1384
+ env: context.env,
1385
+ logPath: join(context.stateDir, "swarm-daemon", telemetryLogFilename),
1386
+ secrets: () => collectSecrets(),
1387
+ });
1388
+ const [{ builtinContent }, { DaemonService, KeyedMutex, createDaemonApiHandler },] = await Promise.all([
1389
+ import("./builtins.js"),
1390
+ import("./daemon-api.js"),
1391
+ ]);
1392
+ const ownsDaemonState = !context.state;
1393
+ const builtins = ownsDaemonState ? await builtinContent() : undefined;
1394
+ const daemonState = context.state ??
1395
+ new State(context.stateDir, builtins?.pins ?? [], context.env, (db) => telemetry.wrapDatabase(db, "state"));
1396
+ const daemonStore = new IpfsStore({
1397
+ ...context.store.configuration,
1398
+ singleProcessCoordination: true,
1399
+ onCoordinationEvent: (event) => {
1400
+ telemetry.recordCoordination(event);
1401
+ },
1402
+ onSqlEvent: (event) => {
1403
+ telemetry.recordSql(event);
1404
+ },
1405
+ });
1406
+ const inProcessMutex = context.inProcessMutex ?? new KeyedMutex();
1407
+ const daemonContext = {
1408
+ ...context,
1409
+ state: daemonState,
1410
+ store: daemonStore,
1411
+ inProcessMutex,
1412
+ };
1373
1413
  const redact = (error, session) => error === null
1374
1414
  ? null
1375
1415
  : redactDaemonText(error, collectSecrets(session));
@@ -1377,6 +1417,40 @@ export async function swarmDaemon(context, signal, synchronize) {
1377
1417
  logBuffer.push(text, collectSecrets());
1378
1418
  context.diagnostic?.(text);
1379
1419
  };
1420
+ const dirtyDiscovery = new Set();
1421
+ const wakeState = { dirtyAllDiscovery: false, wakeRequested: false };
1422
+ let wakeSleep;
1423
+ const wakeDaemonLoop = (url) => {
1424
+ if (url)
1425
+ dirtyDiscovery.add(url);
1426
+ else
1427
+ wakeState.dirtyAllDiscovery = true;
1428
+ wakeState.wakeRequested = true;
1429
+ const resolveWake = wakeSleep;
1430
+ wakeSleep = undefined;
1431
+ resolveWake?.();
1432
+ };
1433
+ const daemonService = await DaemonService.create({
1434
+ stateDir: context.stateDir,
1435
+ env: context.env,
1436
+ state: daemonState,
1437
+ store: daemonStore,
1438
+ telemetry,
1439
+ inProcessMutex,
1440
+ diagnostic: emitDiagnostic,
1441
+ ensureDaemon: () => {
1442
+ wakeDaemonLoop();
1443
+ return Promise.resolve();
1444
+ },
1445
+ onSwarmChange: wakeDaemonLoop,
1446
+ ...(context.fetch ? { fetch: context.fetch } : {}),
1447
+ });
1448
+ const shutdownController = new AbortController();
1449
+ const shutdownRequested = () => shutdownController.signal.aborted;
1450
+ const effectiveSignal = AbortSignal.any([
1451
+ signal,
1452
+ shutdownController.signal,
1453
+ ]);
1380
1454
  const buildStatusSnapshot = () => {
1381
1455
  const now = Date.now();
1382
1456
  const urls = [...new Set([...knownAliases.keys(), ...sessions.keys()])];
@@ -1474,10 +1548,17 @@ export async function swarmDaemon(context, signal, synchronize) {
1474
1548
  syncInterval: context.syncInterval ?? 60,
1475
1549
  swarms,
1476
1550
  logs: logBuffer.entries(),
1551
+ observability: telemetry.snapshot(collectSecrets()),
1477
1552
  };
1478
1553
  };
1479
1554
  const closeReadiness = await context.daemonReady?.(buildStatusSnapshot, ({ url }) => {
1480
1555
  uiUrl = url;
1556
+ }, {
1557
+ apiHandler: createDaemonApiHandler(daemonService),
1558
+ onShutdown: () => {
1559
+ shutdownController.abort(new HostError("Daemon shutdown requested.", 0, "SHUTDOWN", "daemon"));
1560
+ },
1561
+ hasActiveWork: () => daemonService.hasActiveRuns(),
1481
1562
  });
1482
1563
  emitDiagnostic(`IPAB daemon running in foreground; Ctrl-C stops management and leaves Kubo running.${uiUrl ? ` Status UI: ${uiUrl}` : ""}`);
1483
1564
  const stopPivotServer = async (session) => {
@@ -1496,7 +1577,9 @@ export async function swarmDaemon(context, signal, synchronize) {
1496
1577
  await session.context.finishRead?.();
1497
1578
  }
1498
1579
  finally {
1499
- await session.context.store.close();
1580
+ if (session.context.store !== daemonStore) {
1581
+ await session.context.store.close();
1582
+ }
1500
1583
  }
1501
1584
  }
1502
1585
  };
@@ -1554,8 +1637,22 @@ export async function swarmDaemon(context, signal, synchronize) {
1554
1637
  await writeNetworkingSnapshot(context.stateDir, url, snapshot);
1555
1638
  };
1556
1639
  try {
1557
- while (!signal.aborted) {
1558
- const registrations = withState(context, (state) => state.swarms());
1640
+ while (!effectiveSignal.aborted) {
1641
+ if (wakeState.dirtyAllDiscovery) {
1642
+ for (const session of sessions.values())
1643
+ session.nextDiscovery = 0;
1644
+ wakeState.dirtyAllDiscovery = false;
1645
+ dirtyDiscovery.clear();
1646
+ }
1647
+ else if (dirtyDiscovery.size > 0) {
1648
+ for (const dirtyUrl of dirtyDiscovery) {
1649
+ const session = sessions.get(dirtyUrl);
1650
+ if (session)
1651
+ session.nextDiscovery = 0;
1652
+ }
1653
+ dirtyDiscovery.clear();
1654
+ }
1655
+ const registrations = withState(daemonContext, (state) => state.swarms());
1559
1656
  knownAliases = new Map(registrations.map((entry) => [entry.cid, entry.alias]));
1560
1657
  const urls = new Set(registrations.map((entry) => entry.cid));
1561
1658
  for (const url of sessions.keys())
@@ -1565,14 +1662,14 @@ export async function swarmDaemon(context, signal, synchronize) {
1565
1662
  await closeSession(session);
1566
1663
  sessions.delete(url);
1567
1664
  }
1568
- await boundedMap(registrations, async ({ cid: url }) => {
1665
+ await boundedMap(registrations, async ({ cid: url }) => telemetry.runWithContext({ source: "daemon-bg", operation: "swarm-tick", swarm: url }, async () => {
1569
1666
  let session = sessions.get(url);
1570
1667
  if (!session) {
1571
1668
  session = {
1572
1669
  context: {
1573
- ...context,
1670
+ ...daemonContext,
1574
1671
  diagnostic: emitDiagnostic,
1575
- store: new IpfsStore(context.store.configuration),
1672
+ store: daemonStore.scope(),
1576
1673
  forceRefresh: true,
1577
1674
  },
1578
1675
  candidates: new PivotCandidates(),
@@ -1593,12 +1690,13 @@ export async function swarmDaemon(context, signal, synchronize) {
1593
1690
  if (session.record?.config && context.pivot === undefined) {
1594
1691
  const self = session.record.config.members.find((member) => member.publicKey === session.record.account);
1595
1692
  const c = coordinates(url);
1596
- const profile = parseProfile((await client(session.context, c.service).read(c.scopeId, self.profileId, { signal })).value, self.peerId);
1693
+ const profile = parseProfile((await client(session.context, c.service).read(c.scopeId, self.profileId, { signal: effectiveSignal })).value, self.peerId);
1597
1694
  if ((profile.pivot ?? false) !== session.pivot)
1598
1695
  session.nextDiscovery = 0;
1599
1696
  }
1600
- if (Date.now() >= session.nextDiscovery || session.healthy < 1) {
1601
- const record = await approvedMembership(session.context, url, signal);
1697
+ if (Date.now() >= session.nextDiscovery ||
1698
+ session.healthy < 1) {
1699
+ const record = await approvedMembership(session.context, url, effectiveSignal);
1602
1700
  const c = coordinates(url);
1603
1701
  const scope = nodeScope(c.service, record.config.scopeId);
1604
1702
  const existing = await readPrivate(join(context.stateDir, "swarm-nodes", scope), "node.json");
@@ -1615,7 +1713,9 @@ export async function swarmDaemon(context, signal, synchronize) {
1615
1713
  delete session.node;
1616
1714
  }
1617
1715
  session.record = record;
1618
- const result = await privateSource(session.context, record, signal, session.candidates);
1716
+ if (context.pivot === undefined)
1717
+ delete session.context.pivot;
1718
+ const result = await privateSource(session.context, record, effectiveSignal, session.candidates);
1619
1719
  session.node = result.node;
1620
1720
  session.pivot = result.pivot;
1621
1721
  session.context.pivot = result.pivot;
@@ -1631,7 +1731,7 @@ export async function swarmDaemon(context, signal, synchronize) {
1631
1731
  return;
1632
1732
  const currentRecord = session.record;
1633
1733
  const currentSelf = currentRecord.config.members.find((member) => member.publicKey === currentRecord.account);
1634
- if (!(await nodeReady(session.node, signal, session.context.fetch))) {
1734
+ if (!(await nodeReady(session.node, effectiveSignal, session.context.fetch))) {
1635
1735
  if (session.pivotServer)
1636
1736
  session.pivotServer.listening = false;
1637
1737
  const currentDesired = memberPeers(currentSelf.peerId, session.candidates.active(), []);
@@ -1639,7 +1739,7 @@ export async function swarmDaemon(context, signal, synchronize) {
1639
1739
  self: currentSelf.peerId,
1640
1740
  pivot: session.pivot ?? false,
1641
1741
  peers: currentDesired,
1642
- signal,
1742
+ signal: effectiveSignal,
1643
1743
  });
1644
1744
  session.selected = new Set(currentDesired.map(({ ID }) => ID));
1645
1745
  session.context.node = session.node;
@@ -1650,10 +1750,10 @@ export async function swarmDaemon(context, signal, synchronize) {
1650
1750
  let success = false;
1651
1751
  let error = null;
1652
1752
  try {
1653
- success = await probePeer(session.node, id, addresses, signal);
1753
+ success = await probePeer(session.node, id, addresses, effectiveSignal);
1654
1754
  }
1655
1755
  catch (cause) {
1656
- signal.throwIfAborted();
1756
+ effectiveSignal.throwIfAborted();
1657
1757
  error = message(cause);
1658
1758
  emitDiagnostic(`[${url}] Pivot probe ${id}: ${message(cause)}`);
1659
1759
  }
@@ -1675,12 +1775,12 @@ export async function swarmDaemon(context, signal, synchronize) {
1675
1775
  self: self.peerId,
1676
1776
  pivot: session.pivot ?? false,
1677
1777
  peers: desired,
1678
- signal,
1778
+ signal: effectiveSignal,
1679
1779
  });
1680
1780
  session.selected = new Set(desired.map(({ ID }) => ID));
1681
1781
  session.context.node = session.node;
1682
1782
  try {
1683
- const peers = await nodeConnections(session.node, signal);
1783
+ const peers = await nodeConnections(session.node, effectiveSignal);
1684
1784
  session.connections = {
1685
1785
  observedAt: Date.now(),
1686
1786
  error: null,
@@ -1688,7 +1788,7 @@ export async function swarmDaemon(context, signal, synchronize) {
1688
1788
  };
1689
1789
  }
1690
1790
  catch (cause) {
1691
- signal.throwIfAborted();
1791
+ effectiveSignal.throwIfAborted();
1692
1792
  session.connections = {
1693
1793
  observedAt: session.connections?.observedAt ?? null,
1694
1794
  error: message(cause).slice(0, 2048),
@@ -1706,8 +1806,16 @@ export async function swarmDaemon(context, signal, synchronize) {
1706
1806
  await stopPivotServer(session);
1707
1807
  const pivotNode = session.node;
1708
1808
  const mounted = await mountPivotServer(pivotNode, {
1709
- status: (requestSignal) => pivotStatus({ ...session.context, node: pivotNode }, url, requestSignal),
1710
- replicate: async (request, requestSignal) => {
1809
+ status: (requestSignal) => telemetry.runWithContext({
1810
+ source: "pivot-rpc",
1811
+ operation: "GET /v1/status",
1812
+ swarm: url,
1813
+ }, () => pivotStatus({ ...session.context, node: pivotNode }, url, requestSignal)),
1814
+ replicate: (request, requestSignal) => telemetry.runWithContext({
1815
+ source: "pivot-rpc",
1816
+ operation: "POST /v1/replicate",
1817
+ swarm: url,
1818
+ }, async () => {
1711
1819
  const requestContext = {
1712
1820
  ...session.context,
1713
1821
  node: pivotNode,
@@ -1719,13 +1827,17 @@ export async function swarmDaemon(context, signal, synchronize) {
1719
1827
  session.context.pivotSyncError =
1720
1828
  requestContext.pivotSyncError ?? null;
1721
1829
  }
1722
- },
1723
- receipt: (receiptRequest, requestSignal) => handlePivotReceiptRequest({ ...session.context, node: pivotNode }, url, receiptRequest, requestSignal),
1830
+ }),
1831
+ receipt: (receiptRequest, requestSignal) => telemetry.runWithContext({
1832
+ source: "pivot-rpc",
1833
+ operation: "POST /v1/receipt",
1834
+ swarm: url,
1835
+ }, () => handlePivotReceiptRequest({ ...session.context, node: pivotNode }, url, receiptRequest, requestSignal)),
1724
1836
  search: (params) => withState(session.context, (state) => queryLocalSearchIndex(state, url, params)),
1725
1837
  ...(context.diagnostic
1726
1838
  ? { diagnostic: context.diagnostic }
1727
1839
  : {}),
1728
- }, session.context.fetch, signal);
1840
+ }, session.context.fetch, effectiveSignal);
1729
1841
  session.pivotServer = {
1730
1842
  server: mounted,
1731
1843
  nodeApi: session.node.api,
@@ -1735,7 +1847,7 @@ export async function swarmDaemon(context, signal, synchronize) {
1735
1847
  };
1736
1848
  }
1737
1849
  else {
1738
- const remounted = await ensurePivotListener(session.node, session.pivotServer.server.address, signal, session.context.fetch);
1850
+ const remounted = await ensurePivotListener(session.node, session.pivotServer.server.address, effectiveSignal, session.context.fetch);
1739
1851
  session.pivotServer.listening = true;
1740
1852
  if (remounted) {
1741
1853
  emitDiagnostic(`[${url}] Re-mounted Pivot P2P listener ${pivotReceiptProtocol} -> ${session.pivotServer.server.address}.`);
@@ -1760,14 +1872,15 @@ export async function swarmDaemon(context, signal, synchronize) {
1760
1872
  const remoteReadinessDue = onlineRemotePivots.some((peerId) => {
1761
1873
  const entry = session.context.pivotReadiness?.[peerId];
1762
1874
  return (!entry ||
1763
- now - entry.observedAt >= pivotReadinessRefreshIntervalMs);
1875
+ now - entry.observedAt >=
1876
+ pivotReadinessRefreshIntervalMs);
1764
1877
  });
1765
1878
  const replicationDue = now >= (session.nextReplication ?? 0);
1766
1879
  if ((onlineRemotePivots.length > 0 &&
1767
1880
  (remoteReadinessDue || replicationDue)) ||
1768
1881
  (remoteOnline.length > 0 && replicationDue)) {
1769
1882
  session.nextReplication = now + replicationIntervalMs;
1770
- await replicateSwarm(session.context, url, signal, {
1883
+ await replicateSwarm(session.context, url, effectiveSignal, {
1771
1884
  automatic: true,
1772
1885
  onlinePeers: online,
1773
1886
  });
@@ -1781,22 +1894,23 @@ export async function swarmDaemon(context, signal, synchronize) {
1781
1894
  if (pivotSyncDue) {
1782
1895
  session.nextPivotSync = now + replicationIntervalMs;
1783
1896
  try {
1784
- await syncPivotPublications(session.context, url, signal);
1897
+ await syncPivotPublications(session.context, url, effectiveSignal);
1785
1898
  }
1786
1899
  finally {
1787
- if (!signal.aborted) {
1788
- const status = await pivotStatus(session.context, url, signal);
1900
+ if (!effectiveSignal.aborted) {
1901
+ const status = await pivotStatus(session.context, url, effectiveSignal);
1789
1902
  session.context.pivotReadiness ??= {};
1790
- session.context.pivotReadiness[session.node.peerId] = {
1791
- observedAt: Date.now(),
1792
- status,
1793
- error: null,
1794
- };
1903
+ session.context.pivotReadiness[session.node.peerId] =
1904
+ {
1905
+ observedAt: Date.now(),
1906
+ status,
1907
+ error: null,
1908
+ };
1795
1909
  }
1796
1910
  }
1797
1911
  }
1798
1912
  else if (selfReadinessDue) {
1799
- const status = await pivotStatus(session.context, url, signal);
1913
+ const status = await pivotStatus(session.context, url, effectiveSignal);
1800
1914
  session.context.pivotReadiness ??= {};
1801
1915
  session.context.pivotReadiness[session.node.peerId] = {
1802
1916
  observedAt: Date.now(),
@@ -1807,7 +1921,7 @@ export async function swarmDaemon(context, signal, synchronize) {
1807
1921
  }
1808
1922
  }
1809
1923
  catch (cause) {
1810
- if (signal.aborted)
1924
+ if (effectiveSignal.aborted)
1811
1925
  return;
1812
1926
  if (!pivotListenerVerified && session.pivotServer)
1813
1927
  session.pivotServer.listening = false;
@@ -1828,7 +1942,7 @@ export async function swarmDaemon(context, signal, synchronize) {
1828
1942
  }
1829
1943
  if (synchronize &&
1830
1944
  session.node &&
1831
- !signal.aborted &&
1945
+ !effectiveSignal.aborted &&
1832
1946
  Date.now() >= session.nextSync) {
1833
1947
  let deferIsolatedPivot = false;
1834
1948
  if (session.pivot &&
@@ -1837,10 +1951,12 @@ export async function swarmDaemon(context, signal, synchronize) {
1837
1951
  session.record?.config) {
1838
1952
  try {
1839
1953
  const c = coordinates(url);
1840
- const head = headValue(await client(session.context, c.service).read(c.scopeId, session.record.config.headId, { signal }));
1954
+ const head = headValue(await client(session.context, c.service).read(c.scopeId, session.record.config.headId, { signal: effectiveSignal }));
1841
1955
  deferIsolatedPivot = !(await hasLocalBlock(session.context.store, head.root));
1842
1956
  }
1843
1957
  catch (cause) {
1958
+ if (shutdownController.signal.aborted)
1959
+ return;
1844
1960
  signal.throwIfAborted();
1845
1961
  emitDiagnostic(`[${url}] Isolated Pivot HEAD check failed: ${message(cause)}`);
1846
1962
  }
@@ -1856,7 +1972,7 @@ export async function swarmDaemon(context, signal, synchronize) {
1856
1972
  try {
1857
1973
  const summary = await raceAbort(synchronize(session.context, url, (partial) => {
1858
1974
  reported = partial;
1859
- }), signal);
1975
+ }), effectiveSignal);
1860
1976
  const applied = summary ?? reported;
1861
1977
  if (applied) {
1862
1978
  session.sync = {
@@ -1879,6 +1995,8 @@ export async function swarmDaemon(context, signal, synchronize) {
1879
1995
  }
1880
1996
  }
1881
1997
  catch (cause) {
1998
+ if (shutdownController.signal.aborted)
1999
+ return;
1882
2000
  signal.throwIfAborted();
1883
2001
  const detail = message(cause);
1884
2002
  emitDiagnostic(`[${url}] Swarm sync failed; will retry next interval: ${detail}`);
@@ -1897,46 +2015,98 @@ export async function swarmDaemon(context, signal, synchronize) {
1897
2015
  }
1898
2016
  }
1899
2017
  }
1900
- await persist(url, session, true);
1901
- });
2018
+ if (!effectiveSignal.aborted) {
2019
+ await persist(url, session, true);
2020
+ }
2021
+ }));
2022
+ if (shutdownRequested())
2023
+ break;
2024
+ signal.throwIfAborted();
2025
+ if (wakeState.wakeRequested) {
2026
+ wakeState.wakeRequested = false;
2027
+ continue;
2028
+ }
2029
+ const sleepController = new AbortController();
2030
+ const onWake = () => {
2031
+ sleepController.abort();
2032
+ };
2033
+ wakeSleep = onWake;
1902
2034
  try {
1903
2035
  const nextSync = synchronize
1904
2036
  ? Math.min(...[...sessions.values()]
1905
2037
  .filter((session) => session.node)
1906
2038
  .map((session) => Math.max(0, session.nextSync - Date.now())))
1907
2039
  : Infinity;
1908
- await delay(Math.min(30_000 + Math.random() * 15_000, nextSync), undefined, { signal });
2040
+ await delay(Math.min(30_000 + Math.random() * 15_000, nextSync), undefined, {
2041
+ signal: AbortSignal.any([
2042
+ effectiveSignal,
2043
+ sleepController.signal,
2044
+ ]),
2045
+ });
1909
2046
  }
1910
2047
  catch {
2048
+ if (shutdownRequested())
2049
+ break;
1911
2050
  signal.throwIfAborted();
1912
2051
  }
2052
+ finally {
2053
+ if (wakeSleep === onWake)
2054
+ wakeSleep = undefined;
2055
+ wakeState.wakeRequested = false;
2056
+ }
1913
2057
  }
1914
2058
  }
1915
2059
  finally {
1916
2060
  try {
1917
- for (const [url, session] of sessions) {
2061
+ await closeReadiness?.();
2062
+ }
2063
+ finally {
2064
+ try {
2065
+ for (const [url, session] of sessions) {
2066
+ try {
2067
+ await persist(url, session, false);
2068
+ }
2069
+ finally {
2070
+ await closeSession(session);
2071
+ }
2072
+ }
2073
+ }
2074
+ finally {
1918
2075
  try {
1919
- await persist(url, session, false);
2076
+ await daemonService.close();
1920
2077
  }
1921
2078
  finally {
1922
- await closeSession(session);
2079
+ try {
2080
+ await telemetry.flush();
2081
+ }
2082
+ finally {
2083
+ try {
2084
+ await daemonStore.close();
2085
+ }
2086
+ finally {
2087
+ if (ownsDaemonState)
2088
+ daemonState.close();
2089
+ }
2090
+ }
1923
2091
  }
1924
2092
  }
1925
2093
  }
1926
- finally {
1927
- await closeReadiness?.();
1928
- }
1929
2094
  }
1930
2095
  }, signal, 1);
1931
2096
  }
2097
+ const derivedLocalStores = new WeakSet();
1932
2098
  async function activate(context, record) {
1933
2099
  const { node, peers, source } = await privateSource(context, record);
1934
2100
  if (context.node?.api !== node.api ||
1935
2101
  context.sourcePeers?.length !== peers.length ||
1936
2102
  peers.some((peer, i) => context.sourcePeers?.[i] !== peer)) {
1937
- const store = context.store.withLocalSource(source);
1938
- await context.store.close();
2103
+ const previous = context.store;
2104
+ const store = previous.withLocalSource(source);
2105
+ derivedLocalStores.add(store);
1939
2106
  context.store = store;
2107
+ if (derivedLocalStores.has(previous)) {
2108
+ await previous.close();
2109
+ }
1940
2110
  context.sourcePeers = peers;
1941
2111
  }
1942
2112
  context.node = node;
@@ -2091,7 +2261,7 @@ export async function writeNamesHead(context, url, head, root, cid) {
2091
2261
  return head.write(root, cid, uniqueId());
2092
2262
  }
2093
2263
  const lock = await privateDirectory(await directory(context), `state-pin-${createHash("sha256").update(url).digest("hex")}`);
2094
- return withPrivateLock(lock, async () => {
2264
+ return withSwarmLock(context, lock, async () => {
2095
2265
  if (context.confirmPublication) {
2096
2266
  try {
2097
2267
  await context.confirmPublication(url, root);
@@ -2109,9 +2279,6 @@ export async function writeNamesHead(context, url, head, root, cid) {
2109
2279
  catch (cause) {
2110
2280
  throw new HostError(`Pivot replication failed; HEAD was not changed: ${message(cause)}`, 1, "PIVOT_PIN_FAILED", "publication");
2111
2281
  }
2112
- if (receipt === null) {
2113
- return head.write(root, cid, idempotencyKey);
2114
- }
2115
2282
  return head.writeWithReceipt(receipt);
2116
2283
  });
2117
2284
  }
@@ -2122,22 +2289,18 @@ async function requestPivotWriteReceipt(context, url, root, ifCid, idempotencyKe
2122
2289
  const members = await memberDirectory(context, url, config);
2123
2290
  const pivots = members.filter(({ member, profile }) => memberIsPivot(config, member, profile));
2124
2291
  if (!pivots.length)
2125
- throw new HostError("No Pivot nodes are declared. Declare an independent member with swarm profile --pivot true before publishing; HEAD was not changed.");
2292
+ throw new HostError("No Pivot nodes are declared. Declare an authorized Pivot with swarm profile --pivot true before publishing; HEAD was not changed.");
2293
+ const self = pivots.find(({ member }) => member.publicKey === record.account &&
2294
+ (record.account === config.owner ||
2295
+ record.secret?.certificate.body.write.includes(config.headId)));
2126
2296
  const remote = pivots.filter(({ member }) => member.publicKey !== record.account);
2127
- if (!remote.length) {
2128
- if (members.length === 1 &&
2129
- members[0].member.publicKey === record.account &&
2130
- record.account === config.owner) {
2131
- context.diagnostic?.(`[${url}] Solo self-Pivot Swarm detected; publishing ${root} directly without remote Pivot receipt.`);
2132
- return null;
2133
- }
2134
- throw new HostError("Publication requires an independent Pivot node. Declare another member with swarm profile --pivot true; HEAD was not changed.");
2135
- }
2297
+ if (!self && !remote.length)
2298
+ throw new HostError("Publication requires an authorized Pivot. Ask the Owner to grant Pivot HEAD authority; HEAD was not changed.");
2136
2299
  const authorized = remote.filter(({ member }) => member.publicKey === config.owner ||
2137
2300
  (config.v === 3
2138
2301
  ? member.role === "pivot"
2139
2302
  : member.pivotAuthority === true));
2140
- const candidates = authorized.length
2303
+ const remoteCandidates = authorized.length
2141
2304
  ? [
2142
2305
  ...authorized,
2143
2306
  ...remote.filter(({ member }) => member.publicKey !== config.owner &&
@@ -2145,6 +2308,7 @@ async function requestPivotWriteReceipt(context, url, root, ifCid, idempotencyKe
2145
2308
  member.pivotAuthority === undefined),
2146
2309
  ]
2147
2310
  : remote;
2311
+ const candidates = self ? [self, ...remoteCandidates] : remoteCandidates;
2148
2312
  if (!context.requestPivotReceipt && !context.node)
2149
2313
  throw new HostError("State pin requires an active publishing node.");
2150
2314
  const c = coordinates(url);
@@ -2165,15 +2329,18 @@ async function requestPivotWriteReceipt(context, url, root, ifCid, idempotencyKe
2165
2329
  const errors = [];
2166
2330
  for (const pivot of candidates) {
2167
2331
  try {
2168
- const receipt = context.requestPivotReceipt
2169
- ? await context.requestPivotReceipt(pivot, request, signal)
2170
- : await requestPivotReceiptOverP2p(context.node, pivot.member.peerId, pivot.profile.addresses, request, signal, context.fetch);
2332
+ const local = pivot === self;
2333
+ const receipt = local
2334
+ ? await handlePivotReceiptRequest(context, url, request, signal)
2335
+ : context.requestPivotReceipt
2336
+ ? await context.requestPivotReceipt(pivot, request, signal)
2337
+ : await requestPivotReceiptOverP2p(context.node, pivot.member.peerId, pivot.profile.addresses, request, signal, context.fetch);
2171
2338
  if (JSON.stringify(receipt.value) !== JSON.stringify({ root }) ||
2172
2339
  receipt.ifCid !== ifCid ||
2173
2340
  receipt.idempotencyKey !== idempotencyKey ||
2174
2341
  receipt.subject !== pivot.member.publicKey)
2175
2342
  throw new HostError(`Pivot ${pivot.member.publicKey} returned a receipt that does not match this publication.`);
2176
- context.diagnostic?.(`[${url}] Received HEAD write receipt from Pivot ${pivot.profile.name} (${pivot.member.publicKey}).`);
2343
+ context.diagnostic?.(`[${url}] Received HEAD write receipt from ${local ? "local" : "remote"} Pivot ${pivot.profile.name} (${pivot.member.publicKey})${local ? "; no independent replica is confirmed" : ""}.`);
2177
2344
  return receipt;
2178
2345
  }
2179
2346
  catch (cause) {
@@ -2182,7 +2349,7 @@ async function requestPivotWriteReceipt(context, url, root, ifCid, idempotencyKe
2182
2349
  context.diagnostic?.(`[${url}] Pivot receipt request to ${pivot.member.publicKey} failed: ${detail}`);
2183
2350
  }
2184
2351
  }
2185
- throw new HostError(`No authorized independent Pivot issued a HEAD write receipt for publication ${root} (${errors.join("; ")}); HEAD was not changed.`);
2352
+ throw new HostError(`No authorized Pivot issued a HEAD write receipt for publication ${root} (${errors.join("; ")}); HEAD was not changed.`);
2186
2353
  }
2187
2354
  export async function handlePivotReceiptRequest(context, url, input, signal) {
2188
2355
  rejectLocalSwarm(url, "Pivot receipt RPC");
@@ -2217,7 +2384,7 @@ export async function handlePivotReceiptRequest(context, url, input, signal) {
2217
2384
  const source = context.store.withLocalSource(kuboSource(node, peers, context.diagnostic, context.env.IPAB_SWARM_DIAL_DEBUG === "1"));
2218
2385
  try {
2219
2386
  if (CID.parse(request.root).code === dagPb.code) {
2220
- if (peers.length > 0)
2387
+ if (peers.length > 0 && member.peerId !== node.peerId)
2221
2388
  await probePeer(node, member.peerId, peers, signal).catch(() => false);
2222
2389
  await readSnapshot(source, request.root, url);
2223
2390
  await pinPublication(source, [request.root], node, signal, context.fetch);
@@ -3247,9 +3414,10 @@ export async function lazyPrivateSource(context, url, account, basis) {
3247
3414
  return source;
3248
3415
  };
3249
3416
  // Same lock order as Owner rotation: credentials first, then the node.
3250
- return withPrivateLock(await directory(scoped), authorize, signal);
3417
+ return withSwarmLock(context, await directory(scoped), authorize, signal);
3251
3418
  };
3252
- const store = context.store.withLocalSource({
3419
+ const previous = context.store;
3420
+ const store = previous.withLocalSource({
3253
3421
  block: {
3254
3422
  async get(cid, options = {}) {
3255
3423
  const signal = options.signal
@@ -3262,8 +3430,11 @@ export async function lazyPrivateSource(context, url, account, basis) {
3262
3430
  },
3263
3431
  },
3264
3432
  });
3265
- await context.store.close();
3433
+ derivedLocalStores.add(store);
3266
3434
  context.store = store;
3435
+ if (derivedLocalStores.has(previous)) {
3436
+ await previous.close();
3437
+ }
3267
3438
  delete context.node;
3268
3439
  delete context.sourcePeers;
3269
3440
  context.finishRead = async () => {
@@ -5192,7 +5363,7 @@ export async function syncPivotReplicationAndIndex(context, configUrl, header, s
5192
5363
  if (!context.pivot || !isV7Snapshot(header.snapshot))
5193
5364
  return;
5194
5365
  const lock = await privateDirectory(context.stateDir, `pivot-index-${createHash("sha256").update(configUrl).digest("hex")}`);
5195
- return withPrivateLock(lock, () => updatePivotReplicationAndIndex(context, configUrl, header, signal), signal);
5366
+ return withSwarmLock(context, lock, () => updatePivotReplicationAndIndex(context, configUrl, header, signal), signal);
5196
5367
  }
5197
5368
  async function updatePivotReplicationAndIndex(context, configUrl, header, signal) {
5198
5369
  const headCid = CID.parse(header.stateCid).toV1().toString();