@serfab/cadre-core 0.10.0 → 0.11.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 (105) hide show
  1. package/README.md +255 -255
  2. package/dist/cadre-node.d.ts +203 -28
  3. package/dist/cadre-node.js +445 -84
  4. package/dist/cadre-node.js.map +1 -1
  5. package/dist/control-cohort.d.ts +26 -0
  6. package/dist/control-cohort.js +26 -0
  7. package/dist/control-cohort.js.map +1 -1
  8. package/dist/control-database.d.ts +82 -117
  9. package/dist/control-database.js +217 -295
  10. package/dist/control-database.js.map +1 -1
  11. package/dist/control-formation-recorder.d.ts +8 -7
  12. package/dist/control-formation-recorder.js +8 -7
  13. package/dist/control-formation-recorder.js.map +1 -1
  14. package/dist/control-schema.d.ts +1 -1
  15. package/dist/control-schema.js +789 -774
  16. package/dist/control-schema.js.map +1 -1
  17. package/dist/control-write-retry.d.ts +15 -5
  18. package/dist/control-write-retry.js +19 -18
  19. package/dist/control-write-retry.js.map +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/peer-addr-book.d.ts +92 -0
  24. package/dist/peer-addr-book.js +220 -0
  25. package/dist/peer-addr-book.js.map +1 -0
  26. package/dist/seed-bootstrap.d.ts +7 -0
  27. package/dist/seed-bootstrap.js +15 -13
  28. package/dist/seed-bootstrap.js.map +1 -1
  29. package/dist/strand-cohort.d.ts +4 -37
  30. package/dist/strand-cohort.js +4 -15
  31. package/dist/strand-cohort.js.map +1 -1
  32. package/dist/strand-database.d.ts +11 -16
  33. package/dist/strand-database.js +19 -7
  34. package/dist/strand-database.js.map +1 -1
  35. package/dist/strand-formation-manager.d.ts +8 -8
  36. package/dist/strand-formation-manager.js +15 -18
  37. package/dist/strand-formation-manager.js.map +1 -1
  38. package/dist/strand-instance-manager.d.ts +52 -21
  39. package/dist/strand-instance-manager.js +100 -34
  40. package/dist/strand-instance-manager.js.map +1 -1
  41. package/dist/strand-membership-writer.d.ts +6 -4
  42. package/dist/strand-membership-writer.js +38 -36
  43. package/dist/strand-membership-writer.js.map +1 -1
  44. package/dist/types.d.ts +39 -31
  45. package/dist/types.js.map +1 -1
  46. package/package.json +8 -7
  47. package/src/arachnode-stub.ts +159 -159
  48. package/src/bootstrap-peer-store-file.ts +44 -44
  49. package/src/bootstrap-peer-store.ts +172 -172
  50. package/src/cadre-node.ts +5158 -4771
  51. package/src/canonical-json.ts +30 -30
  52. package/src/control-authorization.ts +114 -114
  53. package/src/control-cohort.ts +130 -103
  54. package/src/control-database.ts +2406 -2506
  55. package/src/control-formation-recorder.ts +305 -304
  56. package/src/control-schema.ts +801 -786
  57. package/src/control-stream.ts +205 -205
  58. package/src/control-write-retry.ts +483 -473
  59. package/src/delegate-admission.ts +302 -302
  60. package/src/device-token.ts +94 -94
  61. package/src/diagnostics/connection-path.ts +277 -277
  62. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  63. package/src/ed25519-key.ts +134 -134
  64. package/src/enrollment.ts +199 -199
  65. package/src/file-durable-slot.ts +61 -61
  66. package/src/formation-approval.ts +604 -604
  67. package/src/fs-atomic.ts +107 -107
  68. package/src/hibernation-manager.ts +437 -437
  69. package/src/identity-key.ts +109 -109
  70. package/src/index.ts +1 -0
  71. package/src/key-store-file.ts +132 -132
  72. package/src/key-store.ts +99 -99
  73. package/src/membership-connection-gater.ts +204 -204
  74. package/src/node-local-snapshot.ts +260 -260
  75. package/src/peer-addr-book.ts +250 -0
  76. package/src/peer-authorization.ts +259 -259
  77. package/src/peer-record.ts +164 -164
  78. package/src/push-credentials.ts +84 -84
  79. package/src/push-node.ts +64 -64
  80. package/src/push-notifier-apns.ts +247 -247
  81. package/src/push-notifier-fcm.ts +220 -220
  82. package/src/push-notifier-shared.ts +28 -28
  83. package/src/push-notifier.ts +52 -52
  84. package/src/relay-addrs.ts +111 -111
  85. package/src/relay-reservation.ts +823 -823
  86. package/src/seed-bootstrap.ts +15 -15
  87. package/src/seed-trust-policy.ts +140 -140
  88. package/src/strand-addr-protocol.ts +441 -441
  89. package/src/strand-backfill.ts +366 -366
  90. package/src/strand-cohort.ts +38 -77
  91. package/src/strand-database.ts +202 -204
  92. package/src/strand-formation-manager.ts +491 -494
  93. package/src/strand-formation-protocol.ts +692 -692
  94. package/src/strand-instance-manager.ts +108 -50
  95. package/src/strand-member-key.ts +39 -39
  96. package/src/strand-member-registry.ts +182 -182
  97. package/src/strand-membership-writer.ts +1432 -1430
  98. package/src/strand-solicitation.ts +472 -472
  99. package/src/strand-transport-key.ts +58 -58
  100. package/src/strand-wake-payload.ts +32 -32
  101. package/src/strand-wake-protocol.ts +314 -314
  102. package/src/strand-watcher.ts +314 -314
  103. package/src/trusted-owner-store-file.ts +41 -41
  104. package/src/trusted-owner-store.ts +171 -171
  105. package/src/types.ts +1309 -1303
@@ -1,314 +1,314 @@
1
- import debug from 'debug';
2
- import type { StrandFilter, StrandRow } from './types.js';
3
-
4
- const log = debug('sereus:cadre:strand-watcher');
5
-
6
- /**
7
- * Outcome of evaluating a strand against the current filter.
8
- * - `pass`: admit (final)
9
- * - `reject`: exclude
10
- * - `defer`: admit provisionally; sAppId not yet known, re-evaluate next poll
11
- */
12
- type FilterDecision = 'pass' | 'reject' | 'defer';
13
-
14
- /**
15
- * Ceiling on the retry delay for a strand whose launch keeps failing. Attempts
16
- * are never abandoned — the failure this backoff exists for (a transient network
17
- * or storage fault) can last a long time — but a permanently-unlaunchable strand
18
- * must not re-attempt on every poll and storm the host app with `strand:error`.
19
- */
20
- const MAX_RETRY_BACKOFF_MS = 5 * 60 * 1000;
21
-
22
- /** Per-strand consecutive-failure state driving the launch retry backoff. */
23
- interface StrandFailureState {
24
- /** Consecutive `onStrandAdded` failures since the last success. */
25
- failures: number;
26
- /** Earliest wall-clock time (ms) at which the next attempt may run. */
27
- nextAttemptAt: number;
28
- }
29
-
30
- /**
31
- * Extended strand row that includes the sAppId for filtering purposes.
32
- * The sAppId is provided by the hosting application, not from the control network.
33
- */
34
- export interface StrandRowWithApp extends StrandRow {
35
- /** sApp ID if known (for filtering) */
36
- sAppId?: string;
37
- }
38
-
39
- /**
40
- * Callback for strand changes
41
- */
42
- export interface StrandWatcherCallbacks {
43
- onStrandAdded: (strand: StrandRow) => Promise<void>;
44
- onStrandRemoved: (strandId: string) => Promise<void>;
45
- }
46
-
47
- /**
48
- * Interface for querying strands from control network
49
- */
50
- export interface StrandQueryable {
51
- queryStrands(): Promise<StrandRow[]>;
52
- }
53
-
54
- /**
55
- * Interface for looking up sAppId for a strand (for filtering)
56
- */
57
- export interface SAppIdLookup {
58
- /** Get the sAppId for a strand, if known */
59
- getSAppId(strandId: string): string | undefined;
60
- }
61
-
62
- /**
63
- * Watches the control network's Strand table for changes and triggers
64
- * strand instance start/stop via callbacks.
65
- *
66
- * Uses polling until Optimystic supports reactive subscriptions.
67
- */
68
- export class StrandWatcher {
69
- private readonly filter: StrandFilter;
70
- private readonly pollInterval: number;
71
- private readonly callbacks: StrandWatcherCallbacks;
72
- private readonly queryable: StrandQueryable;
73
- private readonly sAppIdLookup?: SAppIdLookup;
74
- /**
75
- * Wall-clock source for the retry backoff. Read fresh at each use rather than
76
- * snapshotted per poll: a poll awaits `onStrandAdded`, and a launch that fails
77
- * slowly (e.g. a dial timeout) would otherwise be scheduled off the clock as it
78
- * read *before* the attempt, putting `nextAttemptAt` in the past. Injectable so
79
- * tests can advance time deterministically without fake timers.
80
- */
81
- private readonly now: () => number;
82
-
83
- private knownStrands: Map<string, StrandRow> = new Map();
84
- /** Ids admitted under a `defer` decision; re-evaluated each poll until they resolve. */
85
- private provisional: Set<string> = new Set();
86
- /** Ids whose last launch attempt threw, with the backoff gating their retry. */
87
- private failureStates: Map<string, StrandFailureState> = new Map();
88
- private pollTimer: ReturnType<typeof setInterval> | null = null;
89
- private initialPollTimer: ReturnType<typeof setTimeout> | null = null;
90
- private running = false;
91
-
92
- constructor(
93
- queryable: StrandQueryable,
94
- callbacks: StrandWatcherCallbacks,
95
- filter: StrandFilter = { mode: 'all' },
96
- pollInterval: number = 5000,
97
- sAppIdLookup?: SAppIdLookup,
98
- now: () => number = Date.now
99
- ) {
100
- this.queryable = queryable;
101
- this.callbacks = callbacks;
102
- this.filter = filter;
103
- this.pollInterval = pollInterval;
104
- this.sAppIdLookup = sAppIdLookup;
105
- this.now = now;
106
- log('StrandWatcher created with filter: %o, interval: %dms', filter, pollInterval);
107
- }
108
-
109
- /**
110
- * Evaluate a strand against the current filter, distinguishing a not-yet-known
111
- * sAppId (`defer`) from a known non-match (`reject`). A `defer` admission is
112
- * provisional and re-checked on subsequent polls.
113
- */
114
- private evaluateFilter(strand: StrandRow): FilterDecision {
115
- switch (this.filter.mode) {
116
- case 'all':
117
- return 'pass';
118
- case 'none':
119
- return 'reject';
120
- case 'strandId':
121
- return strand.Id === this.filter.strandId ? 'pass' : 'reject';
122
- case 'sAppId': {
123
- if (!this.sAppIdLookup) {
124
- // No way to ever decide - admit permanently (no lookup configured).
125
- return 'pass';
126
- }
127
- const sAppId = this.sAppIdLookup.getSAppId(strand.Id);
128
- if (sAppId === undefined) {
129
- // sAppId not yet known - admit provisionally and re-evaluate next poll.
130
- log('sAppId unknown for strand %s - deferring filter decision', strand.Id);
131
- return 'defer';
132
- }
133
- const matches = sAppId === this.filter.sAppId;
134
- log('sAppId filter: strand %s has sAppId %s, filter wants %s, match=%s',
135
- strand.Id, sAppId, this.filter.sAppId, matches);
136
- return matches ? 'pass' : 'reject';
137
- }
138
- default:
139
- return 'pass';
140
- }
141
- }
142
-
143
- /**
144
- * Record a failed launch attempt and schedule when the strand may be retried:
145
- * `pollInterval * 2^(failures-1)`, capped at {@link MAX_RETRY_BACKOFF_MS}.
146
- */
147
- private recordFailure(strandId: string): void {
148
- const failures = (this.failureStates.get(strandId)?.failures ?? 0) + 1;
149
- const delay = Math.min(this.pollInterval * 2 ** (failures - 1), MAX_RETRY_BACKOFF_MS);
150
- this.failureStates.set(strandId, { failures, nextAttemptAt: this.now() + delay });
151
- log('Strand %s launch failed (%d consecutive) - next attempt in %dms', strandId, failures, delay);
152
- }
153
-
154
- /**
155
- * Poll for strand changes.
156
- */
157
- private async poll(): Promise<void> {
158
- if (!this.running) return;
159
-
160
- try {
161
- const currentStrands = await this.queryable.queryStrands();
162
- const currentMap = new Map(currentStrands.map(s => [s.Id, s]));
163
-
164
- // Find added strands
165
- for (const strand of currentStrands) {
166
- if (this.knownStrands.has(strand.Id)) continue;
167
- const failure = this.failureStates.get(strand.Id);
168
- // Clock read per candidate, not once per poll: an earlier strand's launch
169
- // may have taken a long time, and this one's gate must reflect that.
170
- if (failure && this.now() < failure.nextAttemptAt) continue; // backing off after a failed launch
171
- const decision = this.evaluateFilter(strand);
172
- if (decision === 'reject') continue;
173
- log('Strand added: %s', strand.Id);
174
- // Set BEFORE the await: this doubles as the in-flight guard that stops the
175
- // interval timer from starting a second concurrent launch for the same strand.
176
- this.knownStrands.set(strand.Id, strand);
177
- if (decision === 'defer') {
178
- // Provisional admission: sAppId unknown, re-check on later polls.
179
- this.provisional.add(strand.Id);
180
- }
181
- try {
182
- await this.callbacks.onStrandAdded(strand);
183
- this.failureStates.delete(strand.Id);
184
- } catch (error) {
185
- log('Error handling strand add for %s: %o', strand.Id, error);
186
- // A failed launch leaves nothing running (StrandInstanceManager drops the
187
- // record), so forget the strand and let a later poll retry it — gated by
188
- // the backoff recorded here.
189
- this.knownStrands.delete(strand.Id);
190
- this.provisional.delete(strand.Id);
191
- this.recordFailure(strand.Id);
192
- }
193
- }
194
-
195
- // Re-evaluate provisional admissions whose sAppId may now be resolvable.
196
- // Snapshot ids so we can mutate provisional/knownStrands inside the loop.
197
- for (const strandId of [...this.provisional]) {
198
- const strand = currentMap.get(strandId);
199
- if (!strand) continue; // handled by the removed-strand loop below
200
- const decision = this.evaluateFilter(strand);
201
- if (decision === 'pass') {
202
- // Resolved to a match - admission is now final.
203
- this.provisional.delete(strandId);
204
- } else if (decision === 'reject') {
205
- // Resolved to a non-match - stop the provisionally-admitted strand.
206
- log('Provisional strand rejected on re-evaluation: %s', strandId);
207
- this.knownStrands.delete(strandId);
208
- this.provisional.delete(strandId);
209
- try {
210
- await this.callbacks.onStrandRemoved(strandId);
211
- } catch (error) {
212
- log('Error handling strand remove for %s: %o', strandId, error);
213
- }
214
- }
215
- // decision === 'defer': still unknown, leave provisional for next poll.
216
- }
217
-
218
- // Find removed strands. A strand whose launch failed is no longer in
219
- // knownStrands, so it correctly never fires onStrandRemoved — nothing was
220
- // ever started for it.
221
- for (const [strandId] of this.knownStrands) {
222
- if (!currentMap.has(strandId)) {
223
- log('Strand removed: %s', strandId);
224
- this.knownStrands.delete(strandId);
225
- this.provisional.delete(strandId);
226
- try {
227
- await this.callbacks.onStrandRemoved(strandId);
228
- } catch (error) {
229
- log('Error handling strand remove for %s: %o', strandId, error);
230
- }
231
- }
232
- }
233
-
234
- // Drop backoff state for strands whose control-network row is gone; a row
235
- // that reappears is a fresh strand and gets a fresh first attempt.
236
- for (const strandId of [...this.failureStates.keys()]) {
237
- if (!currentMap.has(strandId)) {
238
- this.failureStates.delete(strandId);
239
- }
240
- }
241
- } catch (error) {
242
- log('Error polling strands: %o', error);
243
- }
244
- }
245
-
246
- /**
247
- * Start watching for strand changes
248
- */
249
- async start(): Promise<void> {
250
- if (this.running) {
251
- log('StrandWatcher already running');
252
- return;
253
- }
254
-
255
- log('Starting StrandWatcher');
256
- this.running = true;
257
-
258
- // Set up periodic polling
259
- this.pollTimer = setInterval(() => {
260
- void this.poll();
261
- }, this.pollInterval);
262
-
263
- // Defer the first poll so start() doesn't block the caller.
264
- // Strands added via addStrand() typically arrive after start() completes.
265
- this.initialPollTimer = setTimeout(() => {
266
- this.initialPollTimer = null;
267
- void this.poll();
268
- }, 100);
269
-
270
- log('StrandWatcher started');
271
- }
272
-
273
- /**
274
- * Stop watching for strand changes
275
- */
276
- async stop(): Promise<void> {
277
- if (!this.running) {
278
- return;
279
- }
280
-
281
- log('Stopping StrandWatcher');
282
- this.running = false;
283
-
284
- if (this.initialPollTimer) {
285
- clearTimeout(this.initialPollTimer);
286
- this.initialPollTimer = null;
287
- }
288
-
289
- if (this.pollTimer) {
290
- clearInterval(this.pollTimer);
291
- this.pollTimer = null;
292
- }
293
-
294
- this.knownStrands.clear();
295
- this.provisional.clear();
296
- this.failureStates.clear();
297
- log('StrandWatcher stopped');
298
- }
299
-
300
- /**
301
- * Get currently known strands
302
- */
303
- getKnownStrands(): Map<string, StrandRow> {
304
- return new Map(this.knownStrands);
305
- }
306
-
307
- /**
308
- * Force an immediate poll (useful for testing)
309
- */
310
- async forcePoll(): Promise<void> {
311
- await this.poll();
312
- }
313
- }
314
-
1
+ import debug from 'debug';
2
+ import type { StrandFilter, StrandRow } from './types.js';
3
+
4
+ const log = debug('sereus:cadre:strand-watcher');
5
+
6
+ /**
7
+ * Outcome of evaluating a strand against the current filter.
8
+ * - `pass`: admit (final)
9
+ * - `reject`: exclude
10
+ * - `defer`: admit provisionally; sAppId not yet known, re-evaluate next poll
11
+ */
12
+ type FilterDecision = 'pass' | 'reject' | 'defer';
13
+
14
+ /**
15
+ * Ceiling on the retry delay for a strand whose launch keeps failing. Attempts
16
+ * are never abandoned — the failure this backoff exists for (a transient network
17
+ * or storage fault) can last a long time — but a permanently-unlaunchable strand
18
+ * must not re-attempt on every poll and storm the host app with `strand:error`.
19
+ */
20
+ const MAX_RETRY_BACKOFF_MS = 5 * 60 * 1000;
21
+
22
+ /** Per-strand consecutive-failure state driving the launch retry backoff. */
23
+ interface StrandFailureState {
24
+ /** Consecutive `onStrandAdded` failures since the last success. */
25
+ failures: number;
26
+ /** Earliest wall-clock time (ms) at which the next attempt may run. */
27
+ nextAttemptAt: number;
28
+ }
29
+
30
+ /**
31
+ * Extended strand row that includes the sAppId for filtering purposes.
32
+ * The sAppId is provided by the hosting application, not from the control network.
33
+ */
34
+ export interface StrandRowWithApp extends StrandRow {
35
+ /** sApp ID if known (for filtering) */
36
+ sAppId?: string;
37
+ }
38
+
39
+ /**
40
+ * Callback for strand changes
41
+ */
42
+ export interface StrandWatcherCallbacks {
43
+ onStrandAdded: (strand: StrandRow) => Promise<void>;
44
+ onStrandRemoved: (strandId: string) => Promise<void>;
45
+ }
46
+
47
+ /**
48
+ * Interface for querying strands from control network
49
+ */
50
+ export interface StrandQueryable {
51
+ queryStrands(): Promise<StrandRow[]>;
52
+ }
53
+
54
+ /**
55
+ * Interface for looking up sAppId for a strand (for filtering)
56
+ */
57
+ export interface SAppIdLookup {
58
+ /** Get the sAppId for a strand, if known */
59
+ getSAppId(strandId: string): string | undefined;
60
+ }
61
+
62
+ /**
63
+ * Watches the control network's Strand table for changes and triggers
64
+ * strand instance start/stop via callbacks.
65
+ *
66
+ * Uses polling until Optimystic supports reactive subscriptions.
67
+ */
68
+ export class StrandWatcher {
69
+ private readonly filter: StrandFilter;
70
+ private readonly pollInterval: number;
71
+ private readonly callbacks: StrandWatcherCallbacks;
72
+ private readonly queryable: StrandQueryable;
73
+ private readonly sAppIdLookup?: SAppIdLookup;
74
+ /**
75
+ * Wall-clock source for the retry backoff. Read fresh at each use rather than
76
+ * snapshotted per poll: a poll awaits `onStrandAdded`, and a launch that fails
77
+ * slowly (e.g. a dial timeout) would otherwise be scheduled off the clock as it
78
+ * read *before* the attempt, putting `nextAttemptAt` in the past. Injectable so
79
+ * tests can advance time deterministically without fake timers.
80
+ */
81
+ private readonly now: () => number;
82
+
83
+ private knownStrands: Map<string, StrandRow> = new Map();
84
+ /** Ids admitted under a `defer` decision; re-evaluated each poll until they resolve. */
85
+ private provisional: Set<string> = new Set();
86
+ /** Ids whose last launch attempt threw, with the backoff gating their retry. */
87
+ private failureStates: Map<string, StrandFailureState> = new Map();
88
+ private pollTimer: ReturnType<typeof setInterval> | null = null;
89
+ private initialPollTimer: ReturnType<typeof setTimeout> | null = null;
90
+ private running = false;
91
+
92
+ constructor(
93
+ queryable: StrandQueryable,
94
+ callbacks: StrandWatcherCallbacks,
95
+ filter: StrandFilter = { mode: 'all' },
96
+ pollInterval: number = 5000,
97
+ sAppIdLookup?: SAppIdLookup,
98
+ now: () => number = Date.now
99
+ ) {
100
+ this.queryable = queryable;
101
+ this.callbacks = callbacks;
102
+ this.filter = filter;
103
+ this.pollInterval = pollInterval;
104
+ this.sAppIdLookup = sAppIdLookup;
105
+ this.now = now;
106
+ log('StrandWatcher created with filter: %o, interval: %dms', filter, pollInterval);
107
+ }
108
+
109
+ /**
110
+ * Evaluate a strand against the current filter, distinguishing a not-yet-known
111
+ * sAppId (`defer`) from a known non-match (`reject`). A `defer` admission is
112
+ * provisional and re-checked on subsequent polls.
113
+ */
114
+ private evaluateFilter(strand: StrandRow): FilterDecision {
115
+ switch (this.filter.mode) {
116
+ case 'all':
117
+ return 'pass';
118
+ case 'none':
119
+ return 'reject';
120
+ case 'strandId':
121
+ return strand.Id === this.filter.strandId ? 'pass' : 'reject';
122
+ case 'sAppId': {
123
+ if (!this.sAppIdLookup) {
124
+ // No way to ever decide - admit permanently (no lookup configured).
125
+ return 'pass';
126
+ }
127
+ const sAppId = this.sAppIdLookup.getSAppId(strand.Id);
128
+ if (sAppId === undefined) {
129
+ // sAppId not yet known - admit provisionally and re-evaluate next poll.
130
+ log('sAppId unknown for strand %s - deferring filter decision', strand.Id);
131
+ return 'defer';
132
+ }
133
+ const matches = sAppId === this.filter.sAppId;
134
+ log('sAppId filter: strand %s has sAppId %s, filter wants %s, match=%s',
135
+ strand.Id, sAppId, this.filter.sAppId, matches);
136
+ return matches ? 'pass' : 'reject';
137
+ }
138
+ default:
139
+ return 'pass';
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Record a failed launch attempt and schedule when the strand may be retried:
145
+ * `pollInterval * 2^(failures-1)`, capped at {@link MAX_RETRY_BACKOFF_MS}.
146
+ */
147
+ private recordFailure(strandId: string): void {
148
+ const failures = (this.failureStates.get(strandId)?.failures ?? 0) + 1;
149
+ const delay = Math.min(this.pollInterval * 2 ** (failures - 1), MAX_RETRY_BACKOFF_MS);
150
+ this.failureStates.set(strandId, { failures, nextAttemptAt: this.now() + delay });
151
+ log('Strand %s launch failed (%d consecutive) - next attempt in %dms', strandId, failures, delay);
152
+ }
153
+
154
+ /**
155
+ * Poll for strand changes.
156
+ */
157
+ private async poll(): Promise<void> {
158
+ if (!this.running) return;
159
+
160
+ try {
161
+ const currentStrands = await this.queryable.queryStrands();
162
+ const currentMap = new Map(currentStrands.map(s => [s.Id, s]));
163
+
164
+ // Find added strands
165
+ for (const strand of currentStrands) {
166
+ if (this.knownStrands.has(strand.Id)) continue;
167
+ const failure = this.failureStates.get(strand.Id);
168
+ // Clock read per candidate, not once per poll: an earlier strand's launch
169
+ // may have taken a long time, and this one's gate must reflect that.
170
+ if (failure && this.now() < failure.nextAttemptAt) continue; // backing off after a failed launch
171
+ const decision = this.evaluateFilter(strand);
172
+ if (decision === 'reject') continue;
173
+ log('Strand added: %s', strand.Id);
174
+ // Set BEFORE the await: this doubles as the in-flight guard that stops the
175
+ // interval timer from starting a second concurrent launch for the same strand.
176
+ this.knownStrands.set(strand.Id, strand);
177
+ if (decision === 'defer') {
178
+ // Provisional admission: sAppId unknown, re-check on later polls.
179
+ this.provisional.add(strand.Id);
180
+ }
181
+ try {
182
+ await this.callbacks.onStrandAdded(strand);
183
+ this.failureStates.delete(strand.Id);
184
+ } catch (error) {
185
+ log('Error handling strand add for %s: %o', strand.Id, error);
186
+ // A failed launch leaves nothing running (StrandInstanceManager drops the
187
+ // record), so forget the strand and let a later poll retry it — gated by
188
+ // the backoff recorded here.
189
+ this.knownStrands.delete(strand.Id);
190
+ this.provisional.delete(strand.Id);
191
+ this.recordFailure(strand.Id);
192
+ }
193
+ }
194
+
195
+ // Re-evaluate provisional admissions whose sAppId may now be resolvable.
196
+ // Snapshot ids so we can mutate provisional/knownStrands inside the loop.
197
+ for (const strandId of [...this.provisional]) {
198
+ const strand = currentMap.get(strandId);
199
+ if (!strand) continue; // handled by the removed-strand loop below
200
+ const decision = this.evaluateFilter(strand);
201
+ if (decision === 'pass') {
202
+ // Resolved to a match - admission is now final.
203
+ this.provisional.delete(strandId);
204
+ } else if (decision === 'reject') {
205
+ // Resolved to a non-match - stop the provisionally-admitted strand.
206
+ log('Provisional strand rejected on re-evaluation: %s', strandId);
207
+ this.knownStrands.delete(strandId);
208
+ this.provisional.delete(strandId);
209
+ try {
210
+ await this.callbacks.onStrandRemoved(strandId);
211
+ } catch (error) {
212
+ log('Error handling strand remove for %s: %o', strandId, error);
213
+ }
214
+ }
215
+ // decision === 'defer': still unknown, leave provisional for next poll.
216
+ }
217
+
218
+ // Find removed strands. A strand whose launch failed is no longer in
219
+ // knownStrands, so it correctly never fires onStrandRemoved — nothing was
220
+ // ever started for it.
221
+ for (const [strandId] of this.knownStrands) {
222
+ if (!currentMap.has(strandId)) {
223
+ log('Strand removed: %s', strandId);
224
+ this.knownStrands.delete(strandId);
225
+ this.provisional.delete(strandId);
226
+ try {
227
+ await this.callbacks.onStrandRemoved(strandId);
228
+ } catch (error) {
229
+ log('Error handling strand remove for %s: %o', strandId, error);
230
+ }
231
+ }
232
+ }
233
+
234
+ // Drop backoff state for strands whose control-network row is gone; a row
235
+ // that reappears is a fresh strand and gets a fresh first attempt.
236
+ for (const strandId of [...this.failureStates.keys()]) {
237
+ if (!currentMap.has(strandId)) {
238
+ this.failureStates.delete(strandId);
239
+ }
240
+ }
241
+ } catch (error) {
242
+ log('Error polling strands: %o', error);
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Start watching for strand changes
248
+ */
249
+ async start(): Promise<void> {
250
+ if (this.running) {
251
+ log('StrandWatcher already running');
252
+ return;
253
+ }
254
+
255
+ log('Starting StrandWatcher');
256
+ this.running = true;
257
+
258
+ // Set up periodic polling
259
+ this.pollTimer = setInterval(() => {
260
+ void this.poll();
261
+ }, this.pollInterval);
262
+
263
+ // Defer the first poll so start() doesn't block the caller.
264
+ // Strands added via addStrand() typically arrive after start() completes.
265
+ this.initialPollTimer = setTimeout(() => {
266
+ this.initialPollTimer = null;
267
+ void this.poll();
268
+ }, 100);
269
+
270
+ log('StrandWatcher started');
271
+ }
272
+
273
+ /**
274
+ * Stop watching for strand changes
275
+ */
276
+ async stop(): Promise<void> {
277
+ if (!this.running) {
278
+ return;
279
+ }
280
+
281
+ log('Stopping StrandWatcher');
282
+ this.running = false;
283
+
284
+ if (this.initialPollTimer) {
285
+ clearTimeout(this.initialPollTimer);
286
+ this.initialPollTimer = null;
287
+ }
288
+
289
+ if (this.pollTimer) {
290
+ clearInterval(this.pollTimer);
291
+ this.pollTimer = null;
292
+ }
293
+
294
+ this.knownStrands.clear();
295
+ this.provisional.clear();
296
+ this.failureStates.clear();
297
+ log('StrandWatcher stopped');
298
+ }
299
+
300
+ /**
301
+ * Get currently known strands
302
+ */
303
+ getKnownStrands(): Map<string, StrandRow> {
304
+ return new Map(this.knownStrands);
305
+ }
306
+
307
+ /**
308
+ * Force an immediate poll (useful for testing)
309
+ */
310
+ async forcePoll(): Promise<void> {
311
+ await this.poll();
312
+ }
313
+ }
314
+