@serfab/cadre-core 1.19.0 → 1.20.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.
Files changed (131) hide show
  1. package/dist/cadre-node.d.ts +118 -16
  2. package/dist/cadre-node.js +210 -31
  3. package/dist/cadre-node.js.map +1 -1
  4. package/dist/control-database.d.ts +2 -1
  5. package/dist/control-database.js +128 -126
  6. package/dist/control-database.js.map +1 -1
  7. package/dist/control-protocol-guard.js +3 -2
  8. package/dist/control-protocol-guard.js.map +1 -1
  9. package/dist/control-read-retry.d.ts +19 -16
  10. package/dist/control-read-retry.js +22 -54
  11. package/dist/control-read-retry.js.map +1 -1
  12. package/dist/control-retry.d.ts +50 -6
  13. package/dist/control-retry.js +53 -6
  14. package/dist/control-retry.js.map +1 -1
  15. package/dist/control-stream.js +2 -1
  16. package/dist/control-stream.js.map +1 -1
  17. package/dist/control-write-retry.d.ts +24 -16
  18. package/dist/control-write-retry.js +58 -30
  19. package/dist/control-write-retry.js.map +1 -1
  20. package/dist/describe-thrown.d.ts +12 -0
  21. package/dist/describe-thrown.js +59 -0
  22. package/dist/describe-thrown.js.map +1 -0
  23. package/dist/edge-node/config.d.ts +8 -2
  24. package/dist/edge-node/config.js +5 -1
  25. package/dist/edge-node/config.js.map +1 -1
  26. package/dist/edge-node/dissolve.d.ts +1 -1
  27. package/dist/edge-node/dissolve.js +1 -1
  28. package/dist/edge-node/dissolve.js.map +1 -1
  29. package/dist/edge-node/edge-join.js +4 -1
  30. package/dist/edge-node/edge-join.js.map +1 -1
  31. package/dist/edge-node/edge-node.d.ts +10 -0
  32. package/dist/edge-node/edge-node.js +54 -9
  33. package/dist/edge-node/edge-node.js.map +1 -1
  34. package/dist/edge-node/options.d.ts +11 -2
  35. package/dist/edge-node/options.js +11 -4
  36. package/dist/edge-node/options.js.map +1 -1
  37. package/dist/edge-node/platform.d.ts +15 -3
  38. package/dist/edge-node/strand-move.d.ts +0 -2
  39. package/dist/edge-node/strand-move.js +1 -4
  40. package/dist/edge-node/strand-move.js.map +1 -1
  41. package/dist/edge-node/strands.js +5 -3
  42. package/dist/edge-node/strands.js.map +1 -1
  43. package/dist/enrollment.js +2 -1
  44. package/dist/enrollment.js.map +1 -1
  45. package/dist/index.d.ts +6 -2
  46. package/dist/index.js +9 -1
  47. package/dist/index.js.map +1 -1
  48. package/dist/member-redemption.js +3 -9
  49. package/dist/member-redemption.js.map +1 -1
  50. package/dist/node-local-snapshot.js +2 -1
  51. package/dist/node-local-snapshot.js.map +1 -1
  52. package/dist/peer-dial.js +3 -2
  53. package/dist/peer-dial.js.map +1 -1
  54. package/dist/pending-join-runner.d.ts +29 -2
  55. package/dist/pending-join-runner.js +60 -20
  56. package/dist/pending-join-runner.js.map +1 -1
  57. package/dist/push-notifier-apns.js +8 -7
  58. package/dist/push-notifier-apns.js.map +1 -1
  59. package/dist/push-notifier-fcm.js +6 -5
  60. package/dist/push-notifier-fcm.js.map +1 -1
  61. package/dist/push-notifier-shared.d.ts +0 -2
  62. package/dist/push-notifier-shared.js +4 -4
  63. package/dist/push-notifier-shared.js.map +1 -1
  64. package/dist/relay-reservation.js +4 -3
  65. package/dist/relay-reservation.js.map +1 -1
  66. package/dist/strand-addr-protocol.js +2 -1
  67. package/dist/strand-addr-protocol.js.map +1 -1
  68. package/dist/strand-app-schema-report.d.ts +53 -0
  69. package/dist/strand-app-schema-report.js +77 -0
  70. package/dist/strand-app-schema-report.js.map +1 -0
  71. package/dist/strand-database.d.ts +60 -0
  72. package/dist/strand-database.js +93 -0
  73. package/dist/strand-database.js.map +1 -1
  74. package/dist/strand-first-sync-gate.js +4 -3
  75. package/dist/strand-first-sync-gate.js.map +1 -1
  76. package/dist/strand-formation-protocol.js +4 -3
  77. package/dist/strand-formation-protocol.js.map +1 -1
  78. package/dist/strand-instance-manager.d.ts +73 -2
  79. package/dist/strand-instance-manager.js +112 -9
  80. package/dist/strand-instance-manager.js.map +1 -1
  81. package/dist/strand-membership-reconciler.d.ts +13 -1
  82. package/dist/strand-membership-reconciler.js +25 -16
  83. package/dist/strand-membership-reconciler.js.map +1 -1
  84. package/dist/strand-membership-writer.d.ts +16 -2
  85. package/dist/strand-membership-writer.js +54 -8
  86. package/dist/strand-membership-writer.js.map +1 -1
  87. package/dist/strand-move.js +4 -6
  88. package/dist/strand-move.js.map +1 -1
  89. package/dist/strand-offline.d.ts +102 -0
  90. package/dist/strand-offline.js +97 -0
  91. package/dist/strand-offline.js.map +1 -0
  92. package/dist/types.d.ts +37 -0
  93. package/dist/types.js.map +1 -1
  94. package/package.json +8 -8
  95. package/src/cadre-node.ts +230 -31
  96. package/src/control-database.ts +5594 -5592
  97. package/src/control-protocol-guard.ts +3 -2
  98. package/src/control-read-retry.ts +22 -58
  99. package/src/control-retry.ts +54 -6
  100. package/src/control-stream.ts +2 -1
  101. package/src/control-write-retry.ts +58 -30
  102. package/src/describe-thrown.ts +60 -0
  103. package/src/edge-node/config.ts +11 -2
  104. package/src/edge-node/dissolve.ts +2 -1
  105. package/src/edge-node/edge-join.ts +2 -1
  106. package/src/edge-node/edge-node.ts +57 -7
  107. package/src/edge-node/options.ts +20 -4
  108. package/src/edge-node/platform.ts +15 -3
  109. package/src/edge-node/strand-move.ts +1 -5
  110. package/src/edge-node/strands.ts +74 -72
  111. package/src/enrollment.ts +2 -1
  112. package/src/index.ts +27 -1
  113. package/src/member-redemption.ts +3 -9
  114. package/src/node-local-snapshot.ts +2 -1
  115. package/src/peer-dial.ts +605 -604
  116. package/src/pending-join-runner.ts +68 -22
  117. package/src/push-notifier-apns.ts +8 -7
  118. package/src/push-notifier-fcm.ts +6 -5
  119. package/src/push-notifier-shared.ts +5 -5
  120. package/src/relay-reservation.ts +1212 -1211
  121. package/src/strand-addr-protocol.ts +2 -1
  122. package/src/strand-app-schema-report.ts +115 -0
  123. package/src/strand-database.ts +123 -1
  124. package/src/strand-first-sync-gate.ts +600 -599
  125. package/src/strand-formation-protocol.ts +4 -3
  126. package/src/strand-instance-manager.ts +137 -10
  127. package/src/strand-membership-reconciler.ts +942 -928
  128. package/src/strand-membership-writer.ts +61 -14
  129. package/src/strand-move.ts +594 -597
  130. package/src/strand-offline.ts +178 -0
  131. package/src/types.ts +36 -0
@@ -38,6 +38,7 @@ import type {
38
38
  RemoveOwnerOptions,
39
39
  } from '../types.js';
40
40
  import type { Libp2pTransports, NoiseCryptoInterface } from '@optimystic/db-p2p';
41
+ import type { StrandOfflineMode } from '../strand-offline.js';
41
42
  import { circuitRelayTransport } from '@libp2p/circuit-relay-v2';
42
43
  import { webSockets } from '@libp2p/websockets';
43
44
  import { buildEdgeNodeConfig, requireOwnerKeyLabel, runOwnerGenesis, wireJoinedOwnerKey, type OwnerGenesisResult } from './config.js';
@@ -68,7 +69,8 @@ import {
68
69
  import { parseSavedStart, serializeSavedStart, startAfterRemoval, type EdgeNodeOptions, type NoiseCryptoMode, type SavedStart } from './options.js';
69
70
  import { redeemOwnerGrantText, type OwnerGrantRuntime, type RedeemedOwnerGrant } from './owner-grant.js';
70
71
  import { DEFAULT_EDGE_NODE_NAMES, type EdgeNodeNames, type EdgeNodePlatform, type RemovableSlot } from './platform.js';
71
- import { adoptMoveRecord, adoptMovesInto, pendingMove, StrandMoveRecords, toError, type PendingStrandMove, type StrandMoveOutcome } from './strand-move.js';
72
+ import { adoptMoveRecord, adoptMovesInto, pendingMove, StrandMoveRecords, type PendingStrandMove, type StrandMoveOutcome } from './strand-move.js';
73
+ import { toError } from '../describe-thrown.js';
72
74
 
73
75
  export type EdgeNodeStatus =
74
76
  | { state: 'stopped' }
@@ -167,6 +169,15 @@ export interface EdgeNode {
167
169
  * is built. `autoStart` is not cleared on the way, so a crash mid-restart still starts again.
168
170
  */
169
171
  restart(options: EdgeNodeOptions): Promise<CadreNode>;
172
+ /**
173
+ * Change the app's offline mode ({@link EdgeNodeOptions.strandOfflineMode}) without a restart:
174
+ * every strand the running node runs takes it at once (`CadreNode.setStrandOfflineMode`), so
175
+ * does each strand it starts later, and the saved start keeps it, so the next start, a
176
+ * background restart and a push wake start every strand in it. In turn with start, stop and
177
+ * join. Throws while no node runs, and on a platform with no offline journal
178
+ * (`EdgeNodeStorage.offlineJournal`).
179
+ */
180
+ setStrandOfflineMode(mode: StrandOfflineMode): Promise<void>;
170
181
  /**
171
182
  * Join the cadre `credential` names: this app's one node moves to that party, keeping its
172
183
  * identity, so the peer id an owner targeted is the one that redeems. A machine invitation
@@ -362,6 +373,8 @@ class EdgeNodeRuntime implements EdgeNode, JoinRuntime, OwnerGrantRuntime {
362
373
  */
363
374
  private transitions: Promise<unknown> = Promise.resolve();
364
375
  private currentStatus: EdgeNodeStatus = { state: 'stopped' };
376
+ /** The mode {@link setStrandOfflineMode} set on the running node, which it was not built with; null until then. */
377
+ private changedOfflineMode: { node: CadreNode; mode: StrandOfflineMode } | null = null;
365
378
  private lastUnfinishedRemoval: UnfinishedRemoval | null = null;
366
379
  private readonly subscriptions = new Set<Subscription>();
367
380
  private readonly statusListeners = new Set<(status: EdgeNodeStatus) => void>();
@@ -424,6 +437,19 @@ class EdgeNodeRuntime implements EdgeNode, JoinRuntime, OwnerGrantRuntime {
424
437
  });
425
438
  }
426
439
 
440
+ setStrandOfflineMode(mode: StrandOfflineMode): Promise<void> {
441
+ return this.inTurn(async () => {
442
+ const node = this.node;
443
+ const running = this.options;
444
+ if (!node || !running) throw new Error('Cannot set the offline mode: the edge node is not running');
445
+ if (!this.platform.storage.offlineJournal) throw new Error('Cannot set the offline mode: this platform keeps no offline journal');
446
+ for (const strandId of node.getStrands().keys()) node.setStrandOfflineMode(strandId, mode);
447
+ this.changedOfflineMode = { node, mode };
448
+ this.runningOptions = { ...running, strandOfflineMode: mode };
449
+ await this.saveRunningStart(this.runningOptions);
450
+ });
451
+ }
452
+
427
453
  joinCadre(credential: JoinCredential, options: JoinCadreOptions = {}): Promise<JoinCadreResult> {
428
454
  // A start called from here on runs after this join rather than joining a start it replaces.
429
455
  this.starting = null;
@@ -670,6 +696,7 @@ class EdgeNodeRuntime implements EdgeNode, JoinRuntime, OwnerGrantRuntime {
670
696
  this.current = node;
671
697
  for (const subscription of this.subscriptions) subscription.attach(node);
672
698
  this.watchRemoval(node);
699
+ this.followOfflineMode(node);
673
700
  await node.start();
674
701
  return { node, resolved };
675
702
  }
@@ -740,19 +767,22 @@ class EdgeNodeRuntime implements EdgeNode, JoinRuntime, OwnerGrantRuntime {
740
767
  * build's default does not change a device that already ran. Options naming no `origin`
741
768
  * take the saved start's `origin` and `formerPartyId` when it is for the same party, so a
742
769
  * party this app joined, started again from a hand-typed party id, does not run owner genesis.
770
+ * Options naming no `strandOfflineMode` take the saved start's, whatever its party: the mode is
771
+ * the app's choice ({@link setStrandOfflineMode}), and a start built from a form or from options
772
+ * held since before that choice would otherwise drop it.
743
773
  */
744
774
  private async resolveOptions(options: EdgeNodeOptions): Promise<EdgeNodeOptions> {
745
775
  requireOwnerKeyLabel(options.ownerKeyLabel);
746
776
  const resolved = { ...options };
747
777
  const defaultMode = this.platform.noiseCrypto?.defaultMode;
748
778
  if (resolved.noiseCryptoMode === undefined && defaultMode !== undefined) resolved.noiseCryptoMode = defaultMode;
749
- if (resolved.origin === undefined) {
750
- const saved = (await this.readSavedStart())?.options;
751
- if (saved?.partyId === resolved.partyId) {
752
- if (saved.origin !== undefined) resolved.origin = saved.origin;
753
- if (saved.formerPartyId !== undefined) resolved.formerPartyId = saved.formerPartyId;
754
- }
779
+ if (resolved.origin !== undefined && resolved.strandOfflineMode !== undefined) return resolved;
780
+ const saved = (await this.readSavedStart())?.options;
781
+ if (resolved.origin === undefined && saved?.partyId === resolved.partyId) {
782
+ if (saved.origin !== undefined) resolved.origin = saved.origin;
783
+ if (saved.formerPartyId !== undefined) resolved.formerPartyId = saved.formerPartyId;
755
784
  }
785
+ if (resolved.strandOfflineMode === undefined && saved?.strandOfflineMode !== undefined) resolved.strandOfflineMode = saved.strandOfflineMode;
756
786
  return resolved;
757
787
  }
758
788
 
@@ -770,6 +800,7 @@ class EdgeNodeRuntime implements EdgeNode, JoinRuntime, OwnerGrantRuntime {
770
800
  noiseCrypto: this.buildNoiseCrypto(options.noiseCryptoMode),
771
801
  keyStore: this.keyStore,
772
802
  storageProvider: (scope) => platform.storage.rawStorage(scope),
803
+ offlineJournal: platform.storage.offlineJournal?.bind(platform.storage),
773
804
  transports: (platform.transports ?? defaultTransports)(relayAddrs),
774
805
  listenAddrs: platform.listenAddrs?.(relayAddrs) ?? [],
775
806
  allowPrivateDial: platform.allowPrivateDial ?? true,
@@ -861,6 +892,24 @@ class EdgeNodeRuntime implements EdgeNode, JoinRuntime, OwnerGrantRuntime {
861
892
  });
862
893
  }
863
894
 
895
+ /**
896
+ * A strand that starts after {@link setStrandOfflineMode} changed the mode takes the new one:
897
+ * the node applies the mode it was built with (`strandOffline.initialMode`) to every launch.
898
+ */
899
+ // NOTE: this, and setStrandOfflineMode's loop, override a mode an app set on one strand with
900
+ // `CadreNode.setStrandOfflineMode`; if an app ever mixes per-strand modes with this call, keep the per-strand ones.
901
+ private followOfflineMode(node: CadreNode): void {
902
+ node.on('strand:started', ({ strandId }) => {
903
+ const changed = this.changedOfflineMode;
904
+ if (changed?.node !== node) return;
905
+ try {
906
+ node.setStrandOfflineMode(strandId, changed.mode);
907
+ } catch (err) {
908
+ console.warn(`[cadre-core/edge-node] strand ${strandId} started in the mode the node was built with, not ${changed.mode}:`, err);
909
+ }
910
+ });
911
+ }
912
+
864
913
  /**
865
914
  * In turn with start, stop and join: stop the removed party's node, point the saved start away
866
915
  * from that party, delete its local storage and report `removed`. A node of another party, started
@@ -944,6 +993,7 @@ class EdgeNodeRuntime implements EdgeNode, JoinRuntime, OwnerGrantRuntime {
944
993
  const stopping = this.current;
945
994
  this.current = null;
946
995
  this.runningOptions = null;
996
+ this.changedOfflineMode = null;
947
997
  try {
948
998
  if (stopping) {
949
999
  for (const subscription of this.subscriptions) subscription.detach(stopping);
@@ -9,6 +9,8 @@
9
9
  * start the node unattended.
10
10
  */
11
11
 
12
+ import type { StrandOfflineMode } from '../strand-offline.js';
13
+
12
14
  /**
13
15
  * How much of Noise's crypto the platform replaces (`EdgeNodePlatform.noiseCrypto`): none, the
14
16
  * per-frame hash and cipher, or those and the handshake's key exchange too. Named here, apart from
@@ -47,6 +49,13 @@ export interface EdgeNodeOptions {
47
49
  * stays on disk under its own names, for moving its strands and dissolving the old cadre.
48
50
  */
49
51
  formerPartyId?: string;
52
+ /**
53
+ * The offline mode every strand starts in (`CadreNodeConfig.strandOffline.initialMode`); absent,
54
+ * the saved start's, else `'online'`. Read only on a platform with an offline journal (`EdgeNodeStorage.offlineJournal`).
55
+ * `EdgeNode.setStrandOfflineMode` changes it while running, and saves it; `CadreNode.setStrandOfflineMode`
56
+ * changes one strand's mode until the process exits.
57
+ */
58
+ strandOfflineMode?: StrandOfflineMode;
50
59
  }
51
60
 
52
61
  /** Whether this app founded its party, or joined it by invitation. */
@@ -73,10 +82,11 @@ export interface SavedStart {
73
82
  * store, which every start reads.
74
83
  */
75
84
  export function startAfterRemoval(saved: SavedStart): SavedStart | undefined {
76
- const { partyId, formerPartyId, relayAddrs, noiseCryptoMode } = saved.options;
85
+ const { partyId, formerPartyId, relayAddrs, noiseCryptoMode, strandOfflineMode } = saved.options;
77
86
  if (formerPartyId === undefined || formerPartyId === partyId) return undefined;
78
87
  const options: EdgeNodeOptions = { partyId: formerPartyId, bootstrapAddrs: [], relayAddrs, origin: 'founded' };
79
88
  if (noiseCryptoMode !== undefined) options.noiseCryptoMode = noiseCryptoMode;
89
+ if (strandOfflineMode !== undefined) options.strandOfflineMode = strandOfflineMode;
80
90
  return { options, autoStart: false, ...(saved.writtenBy !== undefined && { writtenBy: saved.writtenBy }) };
81
91
  }
82
92
 
@@ -99,12 +109,13 @@ interface StartRecord {
99
109
  origin?: EdgeNodeOrigin;
100
110
  formerPartyId?: string;
101
111
  ownerKeyLabel?: string;
112
+ strandOfflineMode?: StrandOfflineMode;
102
113
  autoStart: boolean;
103
114
  writtenBy?: string;
104
115
  }
105
116
 
106
117
  export function serializeSavedStart(saved: SavedStart): string {
107
- const { partyId, bootstrapAddrs, relayAddrs, noiseCryptoMode, origin, formerPartyId, ownerKeyLabel } = saved.options;
118
+ const { partyId, bootstrapAddrs, relayAddrs, noiseCryptoMode, origin, formerPartyId, ownerKeyLabel, strandOfflineMode } = saved.options;
108
119
  const record: StartRecord = {
109
120
  version: RECORD_VERSION,
110
121
  partyId,
@@ -114,6 +125,7 @@ export function serializeSavedStart(saved: SavedStart): string {
114
125
  origin,
115
126
  formerPartyId,
116
127
  ownerKeyLabel,
128
+ strandOfflineMode,
117
129
  autoStart: saved.autoStart,
118
130
  writtenBy: saved.writtenBy,
119
131
  };
@@ -125,8 +137,9 @@ export function serializeSavedStart(saved: SavedStart): string {
125
137
  *
126
138
  * Only the party id is worth discarding a record over. A malformed optional field falls back to
127
139
  * its default — `[]` for an address list, the build default for the Noise mode, absent for
128
- * `origin`, `formerPartyId` and `ownerKeyLabel`, `false` for `autoStart` — so a damaged record still keeps the
129
- * app in its party, at worst needing the user to start the node by hand.
140
+ * `origin`, `formerPartyId`, `ownerKeyLabel` and `strandOfflineMode` (which is `'online'`), `false`
141
+ * for `autoStart` — so a damaged record still keeps the app in its party, at worst needing the
142
+ * user to start the node by hand.
130
143
  */
131
144
  export function parseSavedStart(text: string | undefined): SavedStart | undefined {
132
145
  if (text === undefined) return undefined;
@@ -148,6 +161,9 @@ export function parseSavedStart(text: string | undefined): SavedStart | undefine
148
161
  options.formerPartyId = record.formerPartyId;
149
162
  }
150
163
  if (typeof record.ownerKeyLabel === 'string') options.ownerKeyLabel = record.ownerKeyLabel;
164
+ if (record.strandOfflineMode === 'online' || record.strandOfflineMode === 'offline') {
165
+ options.strandOfflineMode = record.strandOfflineMode;
166
+ }
151
167
  const saved: SavedStart = { options, autoStart: record.autoStart === true };
152
168
  if (typeof record.writtenBy === 'string') saved.writtenBy = record.writtenBy;
153
169
  return saved;
@@ -4,7 +4,7 @@
4
4
  * for it. Fixed for the app's lifetime.
5
5
  */
6
6
 
7
- import type { IRawStorage, Libp2pTransports, NoiseCryptoInterface } from '@optimystic/db-p2p';
7
+ import type { IKVStore, IRawStorage, Libp2pTransports, NoiseCryptoInterface } from '@optimystic/db-p2p';
8
8
  import type { KeyStore } from '../key-store.js';
9
9
  import type { DurableSlot } from '../node-local-snapshot.js';
10
10
  import type { CadreNodeConfig } from '../types.js';
@@ -123,6 +123,17 @@ export interface EdgeNodeStorage {
123
123
  * strand stops.
124
124
  */
125
125
  rawStorage(scope: string): IRawStorage;
126
+ /**
127
+ * A strand's offline journal (`CadreNodeConfig.strandOffline.journal`), kept in the strand
128
+ * scope's own database beside its blocks: the journal's keys are all under
129
+ * `optimystic-offline/`, a node key-value namespace the platform stores apart from blocks. The
130
+ * same instance for the same scope until {@link close}, which flushes and closes it with the
131
+ * scope's handle; cadre-core asks again on every rebuild of the strand, and a second store over
132
+ * one handle would not see the first one's unflushed writes. {@link destroyScope} closes it too.
133
+ * A rejection fails the strand's build. Absent: no offline mode on this platform
134
+ * (`setStrandOfflineMode` throws `StrandOfflineUnavailableError`).
135
+ */
136
+ offlineJournal?(scope: string): Promise<IKVStore>;
126
137
  /** Delete a scope's storage. No handle on it may be open. Resolves when it is gone or was absent. */
127
138
  destroyScope(scope: string): Promise<void>;
128
139
  /**
@@ -132,8 +143,9 @@ export interface EdgeNodeStorage {
132
143
  */
133
144
  nodeLocal(): NodeLocalKv;
134
145
  /**
135
- * Flush and close the node-local store, then close every handle {@link rawStorage} opened. A
136
- * failure closing one is logged and the rest still close; the call does not reject.
146
+ * Flush and close the node-local store and every {@link offlineJournal}, then close every
147
+ * handle {@link rawStorage} opened. A failure closing one is logged and the rest still close;
148
+ * the call does not reject.
137
149
  */
138
150
  close(): Promise<void>;
139
151
  /**
@@ -15,6 +15,7 @@ import type { StrandBundle, StrandMoveReport } from '../strand-move.js';
15
15
  import type { CadreNode } from '../cadre-node.js';
16
16
  import type { KeyId, KeyStore } from '../key-store.js';
17
17
  import { isOwnerGrant, type JoinCredential } from './join-credential.js';
18
+ import { toError } from '../describe-thrown.js';
18
19
  import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
19
20
 
20
21
  /** How a join's strand move settled: `JoinCadreResult.strandMove`. */
@@ -210,11 +211,6 @@ export function deferredOutcome(err: unknown): StrandMoveOutcome {
210
211
  return { state: 'deferred', reason: 'adoption-failed', error: toError(err) };
211
212
  }
212
213
 
213
- /** A thrown value as an `Error`, for a status or outcome that carries one. */
214
- export function toError(err: unknown): Error {
215
- return err instanceof Error ? err : new Error(String(err));
216
- }
217
-
218
214
  export function pendingMove(record: StrandMoveRecord): PendingStrandMove {
219
215
  const settled = new Set([...record.moved, ...record.refused.map((entry) => entry.strandId)]);
220
216
  return {
@@ -1,72 +1,74 @@
1
- /**
2
- * Strand helpers every edge app needs around a running node, from sereus-chat's bring-up.
3
- */
4
-
5
- import { StrandAwaitingFirstSyncError } from '../strand-first-sync-gate.js';
6
- import type { CadreNode } from '../cadre-node.js';
7
- import type { StrandConfig, StrandInstance } from '../types.js';
8
-
9
- /** Default patience for {@link attachStrandWhenWritable}: generous enough that running out means something is wrong. */
10
- export const DEFAULT_STRAND_PATIENCE_MS = 240_000;
11
-
12
- /**
13
- * `addStrand`, then keep waiting when the first sync outlasts its budget.
14
- *
15
- * `addStrand` rejects with `StrandAwaitingFirstSyncError` when the first sync has not finished,
16
- * and leaves the strand launched and syncing: the timeout is a progress report, not an outcome.
17
- * Measured on a link with a 1.8 s round trip, a first sync completed at about 150 s against a
18
- * 120 s budget. So this waits for the strand to become writable, and rejects only when it has not
19
- * within `patienceMs`.
20
- */
21
- export async function attachStrandWhenWritable(
22
- node: CadreNode,
23
- config: StrandConfig,
24
- options: { patienceMs?: number } = {},
25
- ): Promise<StrandInstance> {
26
- try {
27
- return await node.addStrand(config);
28
- } catch (err) {
29
- if (!(err instanceof StrandAwaitingFirstSyncError)) throw err;
30
- const patienceMs = options.patienceMs ?? DEFAULT_STRAND_PATIENCE_MS;
31
- console.info(
32
- `[cadre-core/edge-node] first sync of ${config.strandRow.Id} still arriving; ` +
33
- `waiting up to ${patienceMs / 1000} s for it to become writable`,
34
- );
35
- return await node.whenStrandWritable(config.strandRow.Id, { timeoutMs: patienceMs });
36
- }
37
- }
38
-
39
- /**
40
- * Optimystic's cluster coordinator reports a write that could not gather enough approvals this
41
- * way. It is transient right after a node restarts alone: its cohort has not reconnected yet.
42
- *
43
- * NOTE: matched on the message because Optimystic throws a plain `Error` here. If it gains a typed
44
- * error, match on that instead — a reworded message would silently stop the retries.
45
- */
46
- const SUPER_MAJORITY_FAILURE = /Failed to get super-majority/i;
47
-
48
- /**
49
- * Run a write, retrying only on the transient super-majority failure the first writes after a lone
50
- * restart hit (v1.9 release notes): `attempts` tries, `delayMs` apart. Any other error, and the
51
- * last attempt's, propagates.
52
- */
53
- export async function retryAfterRestart<T>(
54
- write: () => Promise<T>,
55
- options: { attempts?: number; delayMs?: number } = {},
56
- ): Promise<T> {
57
- const attempts = options.attempts ?? 5;
58
- const delayMs = options.delayMs ?? 3_000;
59
- for (let attempt = 1; ; attempt++) {
60
- try {
61
- return await write();
62
- } catch (err) {
63
- if (!isTransientWriteFailure(err) || attempt >= attempts) throw err;
64
- console.info(`[cadre-core/edge-node] write attempt ${attempt} lacked a super-majority; retrying in ${delayMs} ms`);
65
- await new Promise((resolve) => setTimeout(resolve, delayMs));
66
- }
67
- }
68
- }
69
-
70
- function isTransientWriteFailure(err: unknown): boolean {
71
- return SUPER_MAJORITY_FAILURE.test(err instanceof Error ? err.message : String(err));
72
- }
1
+ /**
2
+ * Strand helpers every edge app needs around a running node, from sereus-chat's bring-up.
3
+ */
4
+
5
+ import { StrandAwaitingFirstSyncError } from '../strand-first-sync-gate.js';
6
+ import type { CadreNode } from '../cadre-node.js';
7
+ import type { StrandConfig, StrandInstance } from '../types.js';
8
+ import { describeThrown } from '../describe-thrown.js';
9
+
10
+ /** Default patience for {@link attachStrandWhenWritable}: generous enough that running out means something is wrong. */
11
+ export const DEFAULT_STRAND_PATIENCE_MS = 240_000;
12
+
13
+ /**
14
+ * `addStrand`, then keep waiting when the first sync outlasts its budget.
15
+ *
16
+ * `addStrand` rejects with `StrandAwaitingFirstSyncError` when the first sync has not finished,
17
+ * and leaves the strand launched and syncing: the timeout is a progress report, not an outcome.
18
+ * Measured on a link with a 1.8 s round trip, a first sync completed at about 150 s against a
19
+ * 120 s budget. So this waits for the strand to become writable, and rejects only when it has not
20
+ * within `patienceMs`.
21
+ */
22
+ export async function attachStrandWhenWritable(
23
+ node: CadreNode,
24
+ config: StrandConfig,
25
+ options: { patienceMs?: number } = {},
26
+ ): Promise<StrandInstance> {
27
+ try {
28
+ return await node.addStrand(config);
29
+ } catch (err) {
30
+ if (!(err instanceof StrandAwaitingFirstSyncError)) throw err;
31
+ const patienceMs = options.patienceMs ?? DEFAULT_STRAND_PATIENCE_MS;
32
+ console.info(
33
+ `[cadre-core/edge-node] first sync of ${config.strandRow.Id} still arriving; ` +
34
+ `waiting up to ${patienceMs / 1000} s for it to become writable`,
35
+ );
36
+ return await node.whenStrandWritable(config.strandRow.Id, { timeoutMs: patienceMs });
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Optimystic's cluster coordinator reports a write that could not gather enough approvals this
42
+ * way. It is transient right after a node restarts alone: its cohort has not reconnected yet.
43
+ *
44
+ * NOTE: matched on the message. Optimystic 1.20.0 raises this failure as `PromiseShortfallError` and
45
+ * keeps the sentence unchanged as a contract, so the match holds; moving to the type is the second arm
46
+ * of backlog `debt-control-write-retry-matches-the-shortfall-by-type`.
47
+ */
48
+ const SUPER_MAJORITY_FAILURE = /Failed to get super-majority/i;
49
+
50
+ /**
51
+ * Run a write, retrying only on the transient super-majority failure the first writes after a lone
52
+ * restart hit (v1.9 release notes): `attempts` tries, `delayMs` apart. Any other error, and the
53
+ * last attempt's, propagates.
54
+ */
55
+ export async function retryAfterRestart<T>(
56
+ write: () => Promise<T>,
57
+ options: { attempts?: number; delayMs?: number } = {},
58
+ ): Promise<T> {
59
+ const attempts = options.attempts ?? 5;
60
+ const delayMs = options.delayMs ?? 3_000;
61
+ for (let attempt = 1; ; attempt++) {
62
+ try {
63
+ return await write();
64
+ } catch (err) {
65
+ if (!isTransientWriteFailure(err) || attempt >= attempts) throw err;
66
+ console.info(`[cadre-core/edge-node] write attempt ${attempt} lacked a super-majority; retrying in ${delayMs} ms`);
67
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
68
+ }
69
+ }
70
+ }
71
+
72
+ function isTransientWriteFailure(err: unknown): boolean {
73
+ return SUPER_MAJORITY_FAILURE.test(describeThrown(err));
74
+ }
package/src/enrollment.ts CHANGED
@@ -6,6 +6,7 @@ import type {
6
6
  MemberRegistration,
7
7
  MemberRegistrationResult
8
8
  } from './types.js';
9
+ import { describeThrown } from './describe-thrown.js';
9
10
 
10
11
  const log = debug('sereus:cadre:enrollment');
11
12
 
@@ -151,7 +152,7 @@ export class EnrollmentService {
151
152
  log('Member %s successfully registered in strand %s', key, strandId);
152
153
  return { success: true };
153
154
  } catch (error) {
154
- const message = error instanceof Error ? error.message : String(error);
155
+ const message = describeThrown(error);
155
156
  log('Failed to register member %s: %s', key, message);
156
157
  return { success: false, reason: `Registration failed: ${message}` };
157
158
  }
package/src/index.ts CHANGED
@@ -4,6 +4,10 @@ export * from './types.js';
4
4
  // Canonical JSON serialization (shared signing payload format)
5
5
  export { canonicalJson } from './canonical-json.js';
6
6
 
7
+ // Text for a caught value that may not be an Error (every package that turns one into a message
8
+ // uses this; `yarn lint` flags the `String(err)` fallback it replaces)
9
+ export { describeThrown } from './describe-thrown.js';
10
+
7
11
  // Main CadreNode class
8
12
  export { CadreNode, CADRE_INVITATION_DEFAULT_TTL_MS, OWNER_GRANT_DEFAULT_TTL_MS } from './cadre-node.js';
9
13
 
@@ -213,9 +217,30 @@ export {
213
217
  } from './storage-scope.js';
214
218
 
215
219
  // Strand database
216
- export { StrandDatabase, type StrandDatabaseConfig } from './strand-database.js';
220
+ export { StrandDatabase, type StrandDatabaseConfig, type StrandDatabaseOffline } from './strand-database.js';
217
221
  export type { StrandCommitDurability, StrandCommitHeld } from './strand-commit-durability.js';
218
222
 
223
+ // Offline mode on strands (`CadreNodeConfig.strandOffline`, `CadreNode.setStrandOfflineMode`,
224
+ // `StrandDatabase.offline`): a commit resolves once the transaction is queued on this machine.
225
+ export {
226
+ StrandOfflineUnavailableError,
227
+ StrandQueueNotEmptyError,
228
+ type StrandLeaveOptions,
229
+ type StrandOfflineConfig,
230
+ type StrandOfflineMode,
231
+ type StrandOfflineQueue,
232
+ type StrandOfflineListeners,
233
+ type StrandOfflineStatus,
234
+ type StrandQueueState
235
+ } from './strand-offline.js';
236
+ export {
237
+ type StrandAppSchemaState,
238
+ type StrandAppSchemaDeferred,
239
+ type StrandAppSchemaListeners
240
+ } from './strand-app-schema-report.js';
241
+ // What `StrandOfflineQueue.discard` throws, so an app need not depend on Optimystic to tell them apart.
242
+ export { EntryNotDiscardableError, UnknownEntryError } from '@optimystic/db-core';
243
+
219
244
  // Strand management
220
245
  export {
221
246
  StrandWatcher,
@@ -382,6 +407,7 @@ export {
382
407
  sealStrand,
383
408
  isStrandSealed,
384
409
  StrandTransactionBusyError,
410
+ StrandOfflineQueueBusyError,
385
411
  STRAND_ENGINE,
386
412
  STRAND_ENGINE_VERSION,
387
413
  type FounderBootstrapParams,
@@ -31,6 +31,7 @@ import { requireEd25519PublicKeyB64 } from './ed25519-key.js';
31
31
  import { dialAddr, nextMacrotask, trailingPeerId } from './peer-dial.js';
32
32
  import { chainMessages } from './control-retry.js';
33
33
  import { isRetriableControlWriteFailure } from './control-write-retry.js';
34
+ import { toError } from './describe-thrown.js';
34
35
  import type { CadreJoinProgress } from './types.js';
35
36
 
36
37
  const log = debug('sereus:cadre:member-redemption');
@@ -424,13 +425,6 @@ function isRefusal<Accepted>(reply: Accepted | RedemptionRefusalFrame): reply is
424
425
  return (reply as { accepted?: unknown }).accepted === false;
425
426
  }
426
427
 
427
- function asError(error: unknown): Error {
428
- if (error instanceof Error) return error;
429
- // A WebSocket transport rejects a refused dial with an `ErrorEvent`, whose text is its `message`.
430
- const message = (error as { message?: unknown } | null)?.message;
431
- return new Error(typeof message === 'string' && message.length > 0 ? message : String(error), { cause: error });
432
- }
433
-
434
428
  /**
435
429
  * Run `op` with a signal that aborts when either `deadline` or the caller's `signal` does.
436
430
  * Relayed by hand rather than with `AbortSignal.any`, which the phone runtimes lack.
@@ -491,8 +485,8 @@ async function dialOnce<Accepted>(node: Libp2p, options: MemberRedemptionOptions
491
485
  } catch (error) {
492
486
  // The caller's abort cut this attempt short; its reason, not the cut, is the answer.
493
487
  options.signal?.throwIfAborted();
494
- log('%s redemption via %s failed before an answer (%s); trying the next address', options.label, addr, asError(error).message);
495
- outcomes.push({ addr, error: asError(error) });
488
+ log('%s redemption via %s failed before an answer (%s); trying the next address', options.label, addr, toError(error).message);
489
+ outcomes.push({ addr, error: toError(error) });
496
490
  continue;
497
491
  }
498
492
  if (isRefusal(reply)) {
@@ -29,6 +29,7 @@
29
29
  * (`file-durable-slot.ts`) is what stays behind the `*-store-file` subpaths.
30
30
  */
31
31
  import debug from 'debug';
32
+ import { describeThrown } from './describe-thrown.js';
32
33
 
33
34
  const log = debug('sereus:cadre:node-local-snapshot');
34
35
 
@@ -231,7 +232,7 @@ async function loadEntries<E>(
231
232
  // slot is what knows the platform detail worth acting on (which file, which
232
233
  // database).
233
234
  throw new Error(
234
- `failed to read the ${spec.label} for party ${partyId}: ${error instanceof Error ? error.message : String(error)}`,
235
+ `failed to read the ${spec.label} for party ${partyId}: ${describeThrown(error)}`,
235
236
  { cause: error }
236
237
  );
237
238
  }