@serfab/cadre-core 1.19.1 → 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 (103) hide show
  1. package/dist/cadre-node.d.ts +53 -14
  2. package/dist/cadre-node.js +97 -30
  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-stream.js +2 -1
  10. package/dist/control-stream.js.map +1 -1
  11. package/dist/describe-thrown.d.ts +12 -0
  12. package/dist/describe-thrown.js +59 -0
  13. package/dist/describe-thrown.js.map +1 -0
  14. package/dist/edge-node/dissolve.d.ts +1 -1
  15. package/dist/edge-node/dissolve.js +1 -1
  16. package/dist/edge-node/dissolve.js.map +1 -1
  17. package/dist/edge-node/edge-join.js +2 -1
  18. package/dist/edge-node/edge-join.js.map +1 -1
  19. package/dist/edge-node/edge-node.js +2 -1
  20. package/dist/edge-node/edge-node.js.map +1 -1
  21. package/dist/edge-node/strand-move.d.ts +0 -2
  22. package/dist/edge-node/strand-move.js +1 -4
  23. package/dist/edge-node/strand-move.js.map +1 -1
  24. package/dist/edge-node/strands.js +2 -1
  25. package/dist/edge-node/strands.js.map +1 -1
  26. package/dist/enrollment.js +2 -1
  27. package/dist/enrollment.js.map +1 -1
  28. package/dist/index.d.ts +3 -1
  29. package/dist/index.js +3 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/member-redemption.js +3 -9
  32. package/dist/member-redemption.js.map +1 -1
  33. package/dist/node-local-snapshot.js +2 -1
  34. package/dist/node-local-snapshot.js.map +1 -1
  35. package/dist/peer-dial.js +3 -2
  36. package/dist/peer-dial.js.map +1 -1
  37. package/dist/pending-join-runner.d.ts +29 -2
  38. package/dist/pending-join-runner.js +60 -20
  39. package/dist/pending-join-runner.js.map +1 -1
  40. package/dist/push-notifier-apns.js +8 -7
  41. package/dist/push-notifier-apns.js.map +1 -1
  42. package/dist/push-notifier-fcm.js +6 -5
  43. package/dist/push-notifier-fcm.js.map +1 -1
  44. package/dist/push-notifier-shared.d.ts +0 -2
  45. package/dist/push-notifier-shared.js +4 -4
  46. package/dist/push-notifier-shared.js.map +1 -1
  47. package/dist/relay-reservation.js +4 -3
  48. package/dist/relay-reservation.js.map +1 -1
  49. package/dist/strand-addr-protocol.js +2 -1
  50. package/dist/strand-addr-protocol.js.map +1 -1
  51. package/dist/strand-app-schema-report.d.ts +53 -0
  52. package/dist/strand-app-schema-report.js +77 -0
  53. package/dist/strand-app-schema-report.js.map +1 -0
  54. package/dist/strand-database.d.ts +9 -5
  55. package/dist/strand-database.js +12 -6
  56. package/dist/strand-database.js.map +1 -1
  57. package/dist/strand-first-sync-gate.js +4 -3
  58. package/dist/strand-first-sync-gate.js.map +1 -1
  59. package/dist/strand-formation-protocol.js +4 -3
  60. package/dist/strand-formation-protocol.js.map +1 -1
  61. package/dist/strand-instance-manager.d.ts +8 -2
  62. package/dist/strand-instance-manager.js +8 -6
  63. package/dist/strand-instance-manager.js.map +1 -1
  64. package/dist/strand-membership-reconciler.js +9 -11
  65. package/dist/strand-membership-reconciler.js.map +1 -1
  66. package/dist/strand-move.js +4 -6
  67. package/dist/strand-move.js.map +1 -1
  68. package/dist/strand-offline.d.ts +10 -39
  69. package/dist/strand-offline.js +9 -54
  70. package/dist/strand-offline.js.map +1 -1
  71. package/dist/types.d.ts +7 -5
  72. package/dist/types.js.map +1 -1
  73. package/package.json +8 -8
  74. package/src/cadre-node.ts +11528 -11456
  75. package/src/control-database.ts +5594 -5592
  76. package/src/control-protocol-guard.ts +3 -2
  77. package/src/control-stream.ts +2 -1
  78. package/src/describe-thrown.ts +60 -0
  79. package/src/edge-node/dissolve.ts +2 -1
  80. package/src/edge-node/edge-join.ts +1 -1
  81. package/src/edge-node/edge-node.ts +2 -1
  82. package/src/edge-node/strand-move.ts +1 -5
  83. package/src/edge-node/strands.ts +74 -73
  84. package/src/enrollment.ts +2 -1
  85. package/src/index.ts +924 -917
  86. package/src/member-redemption.ts +3 -9
  87. package/src/node-local-snapshot.ts +2 -1
  88. package/src/peer-dial.ts +605 -604
  89. package/src/pending-join-runner.ts +68 -22
  90. package/src/push-notifier-apns.ts +8 -7
  91. package/src/push-notifier-fcm.ts +6 -5
  92. package/src/push-notifier-shared.ts +5 -5
  93. package/src/relay-reservation.ts +1212 -1211
  94. package/src/strand-addr-protocol.ts +2 -1
  95. package/src/strand-app-schema-report.ts +115 -0
  96. package/src/strand-database.ts +474 -466
  97. package/src/strand-first-sync-gate.ts +600 -599
  98. package/src/strand-formation-protocol.ts +4 -3
  99. package/src/strand-instance-manager.ts +2219 -2210
  100. package/src/strand-membership-reconciler.ts +942 -945
  101. package/src/strand-move.ts +594 -597
  102. package/src/strand-offline.ts +11 -80
  103. package/src/types.ts +2962 -2960
@@ -86,6 +86,7 @@ import { OWNER_GRANT_PROTOCOL } from './owner-grant-protocol.js';
86
86
  import { WAKE_PROTOCOL } from './strand-wake-protocol.js';
87
87
  import { STRAND_ADDR_PROTOCOL } from './strand-addr-protocol.js';
88
88
  import { withTimeout } from './control-stream.js';
89
+ import { describeThrown } from './describe-thrown.js';
89
90
 
90
91
  const log = debug('sereus:cadre:control-protocol-guard');
91
92
 
@@ -337,7 +338,7 @@ class ControlProtocolGuard {
337
338
  );
338
339
  return member === true ? undefined : 'not an authorized member';
339
340
  } catch (error) {
340
- return `membership check failed: ${error instanceof Error ? error.message : String(error)}`;
341
+ return `membership check failed: ${describeThrown(error)}`;
341
342
  }
342
343
  }
343
344
 
@@ -348,7 +349,7 @@ class ControlProtocolGuard {
348
349
  ? undefined
349
350
  : 'not in the authorized-member snapshot';
350
351
  } catch (error) {
351
- return `snapshot check threw: ${error instanceof Error ? error.message : String(error)}`;
352
+ return `snapshot check threw: ${describeThrown(error)}`;
352
353
  }
353
354
  }
354
355
  }
@@ -24,6 +24,7 @@
24
24
  */
25
25
 
26
26
  import debug from 'debug';
27
+ import { toError } from './describe-thrown.js';
27
28
 
28
29
  const log = debug('sereus:cadre:control-stream');
29
30
 
@@ -159,7 +160,7 @@ export async function exchangeFrame<T>(
159
160
  await stream.close();
160
161
  return await readResponse(stream);
161
162
  } catch (err) {
162
- resetStream(err instanceof Error ? err : new Error(String(err)));
163
+ resetStream(toError(err));
163
164
  throw err;
164
165
  } finally {
165
166
  signal.removeEventListener('abort', onAbort);
@@ -0,0 +1,60 @@
1
+ /** An object's description lands in status payloads and logs, so a huge one is cut to this length. */
2
+ const MAX_OBJECT_DESCRIPTION_LENGTH = 500;
3
+
4
+ /**
5
+ * Text for a caught value, for an error message, a status field or a log line.
6
+ *
7
+ * `String()` reads `[object Object]` for anything that is not an `Error`, and a failed WebSocket on
8
+ * React Native rejects with its error event, so a relay reservation's status could not say why it
9
+ * kept retrying (gotchoices/sereus#54). An `Error` gives its `message` unchanged, because specs and
10
+ * users match on that text; `cause` and `AggregateError.errors` are not walked. Platform-neutral:
11
+ * it is in the root entry every runtime loads.
12
+ */
13
+ export function describeThrown(value: unknown): string {
14
+ if (value instanceof Error) return value.message;
15
+ if (typeof value === 'object' && value !== null) return bounded(describeObject(value));
16
+ return String(value);
17
+ }
18
+
19
+ /** A caught value as an `Error`, for a status, an event or a list of failures that carries one; anything else keeps it as `cause`. */
20
+ export function toError(value: unknown): Error {
21
+ return value instanceof Error ? value : new Error(describeThrown(value), { cause: value });
22
+ }
23
+
24
+ function describeObject(value: object): string {
25
+ return describeKnownFields(value) ?? stringifyObject(value) ?? String(value);
26
+ }
27
+
28
+ /**
29
+ * The fields a browser or React Native `Event` / `CloseEvent` carries (`type`, `message`, `code`,
30
+ * `reason`), and libp2p's plain-object rejections (`code`, `message`). Read by property access, so
31
+ * the getters on `Event.prototype` count. Only non-empty strings are used, and a number for `code`
32
+ * (a `CloseEvent`'s); a field holding anything else is skipped.
33
+ */
34
+ function describeKnownFields(value: object): string | undefined {
35
+ const fields = value as { readonly type?: unknown; readonly message?: unknown; readonly reason?: unknown; readonly code?: unknown };
36
+ const text = [fields.type, fields.message, fields.reason].filter(isNonEmptyString).join(': ');
37
+ const code = typeof fields.code === 'number' || isNonEmptyString(fields.code) ? String(fields.code) : undefined;
38
+ if (code === undefined) return text === '' ? undefined : text;
39
+ return text === '' ? `code ${code}` : `${text} (code ${code})`;
40
+ }
41
+
42
+ /** The value as JSON, or nothing when that says nothing (`{}`) or cannot be made (a cycle, a BigInt). */
43
+ function stringifyObject(value: object): string | undefined {
44
+ try {
45
+ const json: string | undefined = JSON.stringify(value);
46
+ return json === '{}' ? undefined : json;
47
+ } catch {
48
+ // Not reported: the value being described is the failure that matters, and `String()` follows.
49
+ return undefined;
50
+ }
51
+ }
52
+
53
+ function bounded(text: string): string {
54
+ if (text.length <= MAX_OBJECT_DESCRIPTION_LENGTH) return text;
55
+ return `${text.slice(0, MAX_OBJECT_DESCRIPTION_LENGTH - 1)}…`;
56
+ }
57
+
58
+ function isNonEmptyString(value: unknown): value is string {
59
+ return typeof value === 'string' && value !== '';
60
+ }
@@ -20,7 +20,8 @@ import type { KeyStore } from '../key-store.js';
20
20
  import { bootstrapPeersKvKey, enrolledMachinesKvKey, strandNetworkKvKey, type NodeLocalKv } from './node-local.js';
21
21
  import type { RemovableSlot } from './platform.js';
22
22
  import { parseSavedStart, serializeSavedStart, type EdgeNodeOptions } from './options.js';
23
- import { toError, type PendingStrandMove, type StrandMoveRecords } from './strand-move.js';
23
+ import type { PendingStrandMove, StrandMoveRecords } from './strand-move.js';
24
+ import { toError } from '../describe-thrown.js';
24
25
 
25
26
  /** How `EdgeNode.dissolveFormerParty` runs. */
26
27
  export interface DissolveFormerPartyOptions {
@@ -20,10 +20,10 @@ import {
20
20
  adoptMovesInto,
21
21
  deferredOutcome,
22
22
  joinMoveRecord,
23
- toError,
24
23
  type StrandMoveOutcome,
25
24
  type StrandMoveRecords,
26
25
  } from './strand-move.js';
26
+ import { toError } from '../describe-thrown.js';
27
27
 
28
28
  /** The part of the edge-node runtime a join drives. Every call runs inside the join's own transition. */
29
29
  export interface JoinRuntime {
@@ -69,7 +69,8 @@ import {
69
69
  import { parseSavedStart, serializeSavedStart, startAfterRemoval, type EdgeNodeOptions, type NoiseCryptoMode, type SavedStart } from './options.js';
70
70
  import { redeemOwnerGrantText, type OwnerGrantRuntime, type RedeemedOwnerGrant } from './owner-grant.js';
71
71
  import { DEFAULT_EDGE_NODE_NAMES, type EdgeNodeNames, type EdgeNodePlatform, type RemovableSlot } from './platform.js';
72
- 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';
73
74
 
74
75
  export type EdgeNodeStatus =
75
76
  | { state: 'stopped' }
@@ -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,73 +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. Optimystic 1.20.0 raises this failure as `PromiseShortfallError` and
44
- * keeps the sentence unchanged as a contract, so the match holds; moving to the type is the second arm
45
- * of backlog `debt-control-write-retry-matches-the-shortfall-by-type`.
46
- */
47
- const SUPER_MAJORITY_FAILURE = /Failed to get super-majority/i;
48
-
49
- /**
50
- * Run a write, retrying only on the transient super-majority failure the first writes after a lone
51
- * restart hit (v1.9 release notes): `attempts` tries, `delayMs` apart. Any other error, and the
52
- * last attempt's, propagates.
53
- */
54
- export async function retryAfterRestart<T>(
55
- write: () => Promise<T>,
56
- options: { attempts?: number; delayMs?: number } = {},
57
- ): Promise<T> {
58
- const attempts = options.attempts ?? 5;
59
- const delayMs = options.delayMs ?? 3_000;
60
- for (let attempt = 1; ; attempt++) {
61
- try {
62
- return await write();
63
- } catch (err) {
64
- if (!isTransientWriteFailure(err) || attempt >= attempts) throw err;
65
- console.info(`[cadre-core/edge-node] write attempt ${attempt} lacked a super-majority; retrying in ${delayMs} ms`);
66
- await new Promise((resolve) => setTimeout(resolve, delayMs));
67
- }
68
- }
69
- }
70
-
71
- function isTransientWriteFailure(err: unknown): boolean {
72
- return SUPER_MAJORITY_FAILURE.test(err instanceof Error ? err.message : String(err));
73
- }
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
  }