@reeve-iot/workload-client 0.0.0-stage → 1.0.1

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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +180 -2
  3. package/dist/index.d.ts +12 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +11 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/session/MessageDeduplicator.d.ts +22 -0
  8. package/dist/session/MessageDeduplicator.d.ts.map +1 -0
  9. package/dist/session/MessageDeduplicator.js +49 -0
  10. package/dist/session/MessageDeduplicator.js.map +1 -0
  11. package/dist/session/SessionDataKind.d.ts +13 -0
  12. package/dist/session/SessionDataKind.d.ts.map +1 -0
  13. package/dist/session/SessionDataKind.js +11 -0
  14. package/dist/session/SessionDataKind.js.map +1 -0
  15. package/dist/session/SessionEnvelope.d.ts +40 -0
  16. package/dist/session/SessionEnvelope.d.ts.map +1 -0
  17. package/dist/session/SessionEnvelope.js +9 -0
  18. package/dist/session/SessionEnvelope.js.map +1 -0
  19. package/dist/session/SessionProtocol.d.ts +61 -0
  20. package/dist/session/SessionProtocol.d.ts.map +1 -0
  21. package/dist/session/SessionProtocol.js +283 -0
  22. package/dist/session/SessionProtocol.js.map +1 -0
  23. package/dist/session/WorkloadSessionClient.d.ts +114 -0
  24. package/dist/session/WorkloadSessionClient.d.ts.map +1 -0
  25. package/dist/session/WorkloadSessionClient.js +462 -0
  26. package/dist/session/WorkloadSessionClient.js.map +1 -0
  27. package/dist/session/backoff.d.ts +32 -0
  28. package/dist/session/backoff.d.ts.map +1 -0
  29. package/dist/session/backoff.js +54 -0
  30. package/dist/session/backoff.js.map +1 -0
  31. package/dist/session/owner.d.ts +34 -0
  32. package/dist/session/owner.d.ts.map +1 -0
  33. package/dist/session/owner.js +2 -0
  34. package/dist/session/owner.js.map +1 -0
  35. package/dist/session/rest.d.ts +83 -0
  36. package/dist/session/rest.d.ts.map +1 -0
  37. package/dist/session/rest.js +140 -0
  38. package/dist/session/rest.js.map +1 -0
  39. package/dist/session/transport.d.ts +51 -0
  40. package/dist/session/transport.d.ts.map +1 -0
  41. package/dist/session/transport.js +190 -0
  42. package/dist/session/transport.js.map +1 -0
  43. package/dist/session/types.d.ts +114 -0
  44. package/dist/session/types.d.ts.map +1 -0
  45. package/dist/session/types.js +19 -0
  46. package/dist/session/types.js.map +1 -0
  47. package/dist/tls/caCertificate.d.ts +5 -0
  48. package/dist/tls/caCertificate.d.ts.map +1 -0
  49. package/dist/tls/caCertificate.js +26 -0
  50. package/dist/tls/caCertificate.js.map +1 -0
  51. package/dist/tls/trustedCaCertificates.d.ts +4 -0
  52. package/dist/tls/trustedCaCertificates.d.ts.map +1 -0
  53. package/dist/tls/trustedCaCertificates.js +16 -0
  54. package/dist/tls/trustedCaCertificates.js.map +1 -0
  55. package/package.json +63 -4
  56. package/src/index.ts +59 -0
  57. package/src/session/MessageDeduplicator.ts +55 -0
  58. package/src/session/SessionDataKind.ts +14 -0
  59. package/src/session/SessionEnvelope.ts +32 -0
  60. package/src/session/SessionProtocol.ts +351 -0
  61. package/src/session/WorkloadSessionClient.ts +597 -0
  62. package/src/session/backoff.ts +68 -0
  63. package/src/session/owner.ts +39 -0
  64. package/src/session/rest.ts +228 -0
  65. package/src/session/transport.ts +224 -0
  66. package/src/session/types.ts +130 -0
  67. package/src/tls/caCertificate.ts +29 -0
  68. package/src/tls/trustedCaCertificates.ts +18 -0
@@ -0,0 +1,597 @@
1
+ import { ReconnectBackoff, type ReconnectBackoffOptions } from './backoff.js';
2
+ import { MessageDeduplicator } from './MessageDeduplicator.js';
3
+ import { MAX_FRAME_BYTES, SessionProtocol } from './SessionProtocol.js';
4
+ import { SESSION_DATA_KINDS } from './SessionDataKind.js';
5
+ import { SessionFrameType } from './types.js';
6
+ import type { SessionEnvelope } from './SessionEnvelope.js';
7
+ import type {
8
+ AdapterCommandResponse,
9
+ AdapterHealthMessage,
10
+ DeviceStateMessage,
11
+ DiscoveredDeviceMessage,
12
+ HelloAckFrame,
13
+ HelloFrame,
14
+ ProtocolRange,
15
+ } from './types.js';
16
+ import { WsWorkloadClientTransport } from './transport.js';
17
+ import type { WorkloadClientTransport, WorkloadClientTransportFactory } from './transport.js';
18
+ import type { WorkloadSessionOwner, WorkloadSessionObserver } from './owner.js';
19
+
20
+ /** The native protocol version this client speaks (mirrors .NET `ProtocolConstants.Version`). */
21
+ export const PROTOCOL_VERSION = '1';
22
+
23
+ const DEFAULT_HEARTBEAT_MS = 30_000;
24
+ const MIN_HEARTBEAT_MS = 1_000;
25
+ const DEFAULT_OUTBOUND_CAPACITY = 1024;
26
+ const SNAPSHOT_OBSERVATION_KIND = 'snapshot';
27
+
28
+ /** Configuration for a {@link WorkloadSessionClient}, sourced from the per-workload secret + bootstrap
29
+ * env. Mirrors the .NET `WorkloadSessionOptions`. */
30
+ export interface WorkloadSessionClientOptions {
31
+ /** The gateway WS URL, `wss://…/ws/workloads/{instanceId}`. Only used by the default transport factory. */
32
+ gatewayUrl: string;
33
+ /** The per-instance gateway credential (`rwt_…`), sent as a bearer header only. Only used by the default transport factory. */
34
+ token: string;
35
+ /** The instance id claimed in the HELLO frame. MUST match the URL's `{instanceId}` and the token's bound instance. */
36
+ instanceId: string;
37
+ /** The adapter's application version, echoed in HELLO (`appVersion`). */
38
+ appVersion: string;
39
+ /** The `REEVE_SPEC_HASH` echoed in HELLO (`specHash`) — the HealthGate identity anchor. */
40
+ specHash: string;
41
+ /** Optional API-schema tag echoed in HELLO (`apiSchema`). */
42
+ apiSchema?: string;
43
+ /** The protocol range this sidecar speaks natively. Defaults to `{version:"1",minSupported:"1"}`. */
44
+ protocol?: ProtocolRange;
45
+
46
+ /** The adapter callback contract. Required. */
47
+ owner: WorkloadSessionOwner;
48
+ /** Optional lifecycle callbacks. */
49
+ observer?: WorkloadSessionObserver;
50
+
51
+ /** Reconnect base delay in ms (default ~500). */
52
+ backoffBaseMs?: number;
53
+ /** Reconnect delay cap in ms (default 30000). A session that served at least this long, or one the gateway ended
54
+ * with a CLOSE frame after the handshake, resets the backoff to its base delay. One that drops sooner keeps
55
+ * climbing, so a server that keeps dropping fresh sessions is retried no faster than the backoff allows. */
56
+ backoffMaxMs?: number;
57
+ /** How long (ms) to wait for the server's HELLO_ACK before treating the attempt as failed. Default 10000. */
58
+ helloAckTimeoutMs?: number;
59
+ /** De-dup window size for inbound frames. Default 4096. */
60
+ deduplicatorCapacity?: number;
61
+ /** Bounded outbound queue capacity; newest is dropped when full, and a fresh snapshot follows once the backlog
62
+ * drains. Default 1024. */
63
+ outboundCapacity?: number;
64
+
65
+ /** Injected transport factory. Defaults to a real `ws` transport built from `gatewayUrl` + `token`. */
66
+ transportFactory?: WorkloadClientTransportFactory;
67
+ /** Injected inter-attempt delay `(ms, signal) => Promise`. Defaults to a real timer. */
68
+ delay?: (ms: number, signal: AbortSignal) => Promise<void>;
69
+ /** Injected heartbeat cadence delay `(ms, signal) => Promise`. Defaults to a real timer. */
70
+ heartbeatDelay?: (ms: number, signal: AbortSignal) => Promise<void>;
71
+ /** Injected backoff sample source in [0,1). Defaults to Math.random. */
72
+ backoffSample?: () => number;
73
+ /** Injected monotonic clock in ms that times a session against `backoffMaxMs`. Defaults to `performance.now`. */
74
+ now?: () => number;
75
+ }
76
+
77
+ /** The reference WS session client for the workload gateway: a sidecar implements only
78
+ * {@link WorkloadSessionOwner}, and this owns connect, HELLO, snapshot-on-reconnect and backoff. */
79
+ export class WorkloadSessionClient {
80
+ private readonly options: WorkloadSessionClientOptions;
81
+ private readonly owner: WorkloadSessionOwner;
82
+ private readonly observer: WorkloadSessionObserver;
83
+ private readonly transportFactory: WorkloadClientTransportFactory;
84
+ private readonly backoff: ReconnectBackoff;
85
+ private readonly delay: (ms: number, signal: AbortSignal) => Promise<void>;
86
+ private readonly heartbeatDelay: (ms: number, signal: AbortSignal) => Promise<void>;
87
+ private readonly helloAckTimeoutMs: number;
88
+ private readonly deduplicatorCapacity: number;
89
+ private readonly outboundCapacity: number;
90
+ private readonly protocol: ProtocolRange;
91
+ private readonly healthySessionMs: number;
92
+ private readonly now: () => number;
93
+
94
+ private outbound: Uint8Array[] = [];
95
+ private resyncPending = false;
96
+ private lastHealth: AdapterHealthMessage | undefined;
97
+ private outboundWaiter: (() => void) | undefined;
98
+
99
+ private runController: AbortController | undefined;
100
+ private running = false;
101
+ private runPromise: Promise<void> | undefined;
102
+
103
+ constructor(options: WorkloadSessionClientOptions) {
104
+ if (options.owner === undefined || options.owner === null) {
105
+ throw new TypeError('options.owner is required.');
106
+ }
107
+ this.options = options;
108
+ this.owner = options.owner;
109
+ this.observer = options.observer ?? {};
110
+ this.protocol = options.protocol ?? { version: PROTOCOL_VERSION, minSupported: PROTOCOL_VERSION };
111
+ this.helloAckTimeoutMs = options.helloAckTimeoutMs ?? 10_000;
112
+ this.deduplicatorCapacity = options.deduplicatorCapacity ?? MessageDeduplicator.DEFAULT_CAPACITY;
113
+ this.outboundCapacity = options.outboundCapacity ?? DEFAULT_OUTBOUND_CAPACITY;
114
+ this.delay = options.delay ?? realDelay;
115
+ this.heartbeatDelay = options.heartbeatDelay ?? realDelay;
116
+
117
+ const backoffOpts: ReconnectBackoffOptions = {};
118
+ if (options.backoffBaseMs !== undefined) backoffOpts.baseMs = options.backoffBaseMs;
119
+ if (options.backoffMaxMs !== undefined) backoffOpts.maxMs = options.backoffMaxMs;
120
+ if (options.backoffSample !== undefined) backoffOpts.sample = options.backoffSample;
121
+ this.backoff = new ReconnectBackoff(backoffOpts);
122
+ this.healthySessionMs = options.backoffMaxMs ?? ReconnectBackoff.DEFAULT_MAX_MS;
123
+ this.now = options.now ?? (() => performance.now());
124
+
125
+ this.transportFactory = options.transportFactory ?? defaultTransportFactory(
126
+ options.gatewayUrl,
127
+ options.token,
128
+ this.observer.onInboundQueueOverflow === undefined
129
+ ? undefined
130
+ : () => this.observer.onInboundQueueOverflow?.(),
131
+ );
132
+ }
133
+
134
+ /** Enqueues a device-state DATA frame. Returns `false` if dropped (queue full); the client then sends a fresh
135
+ * snapshot from {@link WorkloadSessionOwner.buildSnapshot} once the backlog drains, followed by the last health
136
+ * published, so the drop is repaired without a reconnect. */
137
+ publishState(state: DeviceStateMessage): boolean {
138
+ return this.enqueue(SessionProtocol.serializeToUtf8Bytes(SessionProtocol.createDataState(state)));
139
+ }
140
+
141
+ /** Enqueues a discovered-device DATA frame. Returns `false` if dropped (queue full). */
142
+ publishDiscovered(discovered: DiscoveredDeviceMessage): boolean {
143
+ return this.enqueue(SessionProtocol.serializeToUtf8Bytes(SessionProtocol.createDataDiscovered(discovered)));
144
+ }
145
+
146
+ /** Enqueues an adapter-health DATA frame. Returns `false` if dropped (queue full). */
147
+ publishHealth(health: AdapterHealthMessage): boolean {
148
+ this.lastHealth = health;
149
+ return this.enqueue(SessionProtocol.serializeToUtf8Bytes(SessionProtocol.createDataHealth(health)));
150
+ }
151
+
152
+ /** Enqueues a DATA frame of a private `dataKind`, which the gateway hands to the plugin's data-frame ingestor and
153
+ * replicates to the replicas that observe that kind. Best-effort: no snapshot carries it, so a frame the full queue
154
+ * drops (returns `false`) or one discarded with the queue at the next connect is not re-sent. A kind that carries
155
+ * current state is re-published from {@link WorkloadSessionObserver.onSnapshotSent}, which runs after the snapshot of
156
+ * every connect and of every repair. Throws a `RangeError` for a blank kind or a reserved one (`state`, `discovered`,
157
+ * `health`, `snapshot`); the well-known kinds have their own methods. Also throws a `RangeError` for a frame above
158
+ * `MAX_FRAME_BYTES`, since the gateway closes a session that sends one. */
159
+ publishData(payload: unknown, dataKind: string): boolean {
160
+ if (dataKind.trim().length === 0 || SESSION_DATA_KINDS.has(dataKind) || dataKind === SNAPSHOT_OBSERVATION_KIND) {
161
+ throw new RangeError(`The data kind '${dataKind}' is blank or reserved; publish a well-known kind through its own method.`);
162
+ }
163
+ const frame = SessionProtocol.serializeToUtf8Bytes(SessionProtocol.createData(payload, dataKind));
164
+ if (frame.length > MAX_FRAME_BYTES) {
165
+ throw new RangeError(`The '${dataKind}' frame is ${frame.length} bytes, above the gateway's ${MAX_FRAME_BYTES}-byte frame limit.`);
166
+ }
167
+ return this.enqueue(frame);
168
+ }
169
+
170
+ /** Starts the connect→HELLO→snapshot→serve loop in the background, reconnecting with backoff+jitter
171
+ * until {@link stop}, which awaits the loop's completion. */
172
+ start(): void {
173
+ if (this.running) {
174
+ throw new Error('WorkloadSessionClient is already running.');
175
+ }
176
+ this.running = true;
177
+ this.runController = new AbortController();
178
+ this.runPromise = this.runAsync(this.runController.signal);
179
+ }
180
+
181
+ /** Signals the loop to stop and awaits its clean shutdown. Idempotent. */
182
+ async stop(): Promise<void> {
183
+ if (!this.running) {
184
+ return;
185
+ }
186
+ this.running = false;
187
+ this.runController?.abort();
188
+ this.wakeOutbound();
189
+ try {
190
+ await this.runPromise;
191
+ } finally {
192
+ this.runController = undefined;
193
+ this.runPromise = undefined;
194
+ }
195
+ }
196
+
197
+ /** The connect→HELLO→snapshot→serve loop, exposed so a caller can `await` it directly. Returns only
198
+ * on abort. */
199
+ async runAsync(stoppingSignal: AbortSignal): Promise<void> {
200
+ while (!stoppingSignal.aborted) {
201
+ let healthy = false;
202
+ try {
203
+ healthy = await this.runOneSession(stoppingSignal);
204
+ } catch (err) {
205
+ if (stoppingSignal.aborted) return;
206
+ this.observer.onSessionFaulted?.(err);
207
+ }
208
+
209
+ if (stoppingSignal.aborted) return;
210
+
211
+ if (healthy) {
212
+ this.backoff.reset();
213
+ }
214
+
215
+ const waitMs = this.backoff.nextDelayMs();
216
+ this.observer.onReconnectScheduled?.(this.backoff.attempt, waitMs);
217
+ try {
218
+ await this.delay(waitMs, stoppingSignal);
219
+ } catch {
220
+ if (stoppingSignal.aborted) return;
221
+ }
222
+ }
223
+ }
224
+
225
+ private async runOneSession(stoppingSignal: AbortSignal): Promise<boolean> {
226
+ const transport = this.transportFactory.create();
227
+ try {
228
+ try {
229
+ await transport.connect(stoppingSignal);
230
+ } catch (err) {
231
+ if (stoppingSignal.aborted) throw err;
232
+ this.observer.onConnectFailed?.(err);
233
+ return false;
234
+ }
235
+
236
+ const hello: HelloFrame = {
237
+ instanceId: this.options.instanceId,
238
+ appVersion: this.options.appVersion,
239
+ specHash: this.options.specHash,
240
+ protocol: this.protocol,
241
+ };
242
+ if (this.options.apiSchema !== undefined) hello.apiSchema = this.options.apiSchema;
243
+ await transport.send(SessionProtocol.serializeToUtf8Bytes(SessionProtocol.createHello(hello)), stoppingSignal);
244
+
245
+ const ack = await this.awaitHelloAck(transport, stoppingSignal);
246
+ if (ack === undefined) {
247
+ await transport.close(1002, 'no hello-ack');
248
+ return false;
249
+ }
250
+
251
+ this.observer.onSessionEstablished?.();
252
+ const heartbeatMs = negotiateHeartbeatMs(ack.heartbeatSeconds);
253
+
254
+ this.drainOutbound();
255
+ this.resyncPending = false;
256
+ const snapshot = await this.owner.buildSnapshot(stoppingSignal);
257
+ for (const frame of SessionProtocol.createSnapshotFrames(snapshot)) {
258
+ await transport.send(SessionProtocol.serializeToUtf8Bytes(frame), stoppingSignal);
259
+ }
260
+ this.observer.onSnapshotSent?.(snapshot);
261
+ if (this.lastHealth !== undefined) {
262
+ await transport.send(SessionProtocol.serializeToUtf8Bytes(SessionProtocol.createDataHealth(this.lastHealth)), stoppingSignal);
263
+ }
264
+
265
+ const servingSince = this.now();
266
+ const sessionController = new AbortController();
267
+ const linkedAbort = () => sessionController.abort();
268
+ linkAbort(stoppingSignal, linkedAbort);
269
+ const deduplicator = new MessageDeduplicator(this.deduplicatorCapacity);
270
+ const sendState = { chain: Promise.resolve() };
271
+
272
+ const sessionSignal = sessionController.signal;
273
+ const send = this.pumpOutbound(transport, sendState, sessionSignal);
274
+ const receive = this.receiveLoop(transport, sendState, deduplicator, sessionSignal);
275
+ const heartbeat = this.selfHeartbeatLoop(transport, sendState, heartbeatMs, sessionSignal);
276
+
277
+ let closedByGateway = false;
278
+ try {
279
+ await Promise.race([send, receive, heartbeat]);
280
+ } finally {
281
+ sessionController.abort();
282
+ stoppingSignal.removeEventListener('abort', linkedAbort);
283
+ this.wakeOutbound();
284
+ await transport.close(1000, 'session ending');
285
+ const [, received] = await Promise.allSettled([send, receive, heartbeat]);
286
+ closedByGateway = received.status === 'fulfilled' && received.value;
287
+ }
288
+
289
+ // A CLOSE frame after the handshake is the gateway asking for a reconnect (a plugin instance start wants a
290
+ // fresh snapshot), not a failure, so it does not climb the backoff. A drop, a reauth or a rejection still does
291
+ // until a session has served for the backoff cap.
292
+ return closedByGateway || this.now() - servingSince >= this.healthySessionMs;
293
+ } finally {
294
+ await transport.dispose();
295
+ }
296
+ }
297
+
298
+ private async awaitHelloAck(
299
+ transport: WorkloadClientTransport,
300
+ stoppingSignal: AbortSignal,
301
+ ): Promise<HelloAckFrame | undefined> {
302
+ const deadline = new AbortController();
303
+ const onStop = () => deadline.abort();
304
+ linkAbort(stoppingSignal, onStop);
305
+ const timer = setTimeout(() => deadline.abort(), this.helloAckTimeoutMs);
306
+ try {
307
+ while (!deadline.signal.aborted) {
308
+ let raw: Uint8Array | null;
309
+ try {
310
+ raw = await transport.receive(deadline.signal);
311
+ } catch {
312
+ return undefined;
313
+ }
314
+ if (raw === null) {
315
+ return undefined;
316
+ }
317
+
318
+ const parsed = SessionProtocol.parseBytes(raw);
319
+ if (!parsed.isSuccess) {
320
+ continue;
321
+ }
322
+ const env = parsed.envelope;
323
+ switch (env.type) {
324
+ case SessionFrameType.HelloAck: {
325
+ const read = SessionProtocol.tryReadHelloAck(env);
326
+ return read.isSuccess
327
+ ? read.payload
328
+ : { protocol: this.protocol, heartbeatSeconds: DEFAULT_HEARTBEAT_MS / 1000 };
329
+ }
330
+ case SessionFrameType.Error:
331
+ case SessionFrameType.Close:
332
+ return undefined;
333
+ default:
334
+ continue;
335
+ }
336
+ }
337
+ } finally {
338
+ clearTimeout(timer);
339
+ stoppingSignal.removeEventListener('abort', onStop);
340
+ }
341
+ return undefined;
342
+ }
343
+
344
+ private async selfHeartbeatLoop(
345
+ transport: WorkloadClientTransport,
346
+ sendState: SendState,
347
+ intervalMs: number,
348
+ signal: AbortSignal,
349
+ ): Promise<void> {
350
+ try {
351
+ while (!signal.aborted) {
352
+ await this.heartbeatDelay(intervalMs, signal);
353
+ if (signal.aborted) return;
354
+ await this.sendSerialized(transport, sendState, SessionProtocol.createHeartbeat(), signal);
355
+ }
356
+ } catch {
357
+ }
358
+ }
359
+
360
+ private async pumpOutbound(
361
+ transport: WorkloadClientTransport,
362
+ sendState: SendState,
363
+ signal: AbortSignal,
364
+ ): Promise<void> {
365
+ try {
366
+ while (!signal.aborted) {
367
+ if (this.outbound.length === 0 && this.resyncPending) {
368
+ this.resyncPending = false;
369
+ await this.resync(transport, sendState, signal);
370
+ continue;
371
+ }
372
+ if (this.outbound.length === 0) {
373
+ await this.waitForOutbound(signal);
374
+ if (signal.aborted) return;
375
+ }
376
+ const frame = this.outbound.shift();
377
+ if (frame === undefined) {
378
+ continue;
379
+ }
380
+ await this.sendBytes(transport, sendState, frame, signal);
381
+ }
382
+ } catch {
383
+ }
384
+ }
385
+
386
+ private async receiveLoop(
387
+ transport: WorkloadClientTransport,
388
+ sendState: SendState,
389
+ deduplicator: MessageDeduplicator,
390
+ signal: AbortSignal,
391
+ ): Promise<boolean> {
392
+ try {
393
+ while (!signal.aborted) {
394
+ const raw = await transport.receive(signal);
395
+ if (raw === null) {
396
+ return false;
397
+ }
398
+ const parsed = SessionProtocol.parseBytes(raw);
399
+ if (!parsed.isSuccess) {
400
+ continue;
401
+ }
402
+ await this.dispatch(transport, sendState, deduplicator, parsed.envelope, signal);
403
+ }
404
+ } catch (error) {
405
+ if (error instanceof SessionClosedByPeerError) {
406
+ return true;
407
+ }
408
+ }
409
+ return false;
410
+ }
411
+
412
+ private async dispatch(
413
+ transport: WorkloadClientTransport,
414
+ sendState: SendState,
415
+ deduplicator: MessageDeduplicator,
416
+ envelope: SessionEnvelope,
417
+ signal: AbortSignal,
418
+ ): Promise<void> {
419
+ switch (envelope.type) {
420
+ case SessionFrameType.Heartbeat:
421
+ await this.sendSerialized(transport, sendState, SessionProtocol.createHeartbeat(), signal);
422
+ return;
423
+
424
+ case SessionFrameType.Ack:
425
+ case SessionFrameType.HelloAck:
426
+ return;
427
+
428
+ case SessionFrameType.Reauth:
429
+ this.observer.onReauthRequested?.(SessionProtocol.tryReadReauth(envelope).payload?.reason);
430
+ throw new ReauthReconnectError();
431
+
432
+ case SessionFrameType.Close:
433
+ this.observer.onServerClose?.(SessionProtocol.tryReadClose(envelope).payload?.reason);
434
+ throw new SessionClosedByPeerError();
435
+
436
+ case SessionFrameType.Command:
437
+ await this.handleCommand(transport, sendState, deduplicator, envelope, signal);
438
+ return;
439
+
440
+ default:
441
+ await this.sendSerialized(transport, sendState, SessionProtocol.createAck(envelope.messageId), signal);
442
+ return;
443
+ }
444
+ }
445
+
446
+ private async handleCommand(
447
+ transport: WorkloadClientTransport,
448
+ sendState: SendState,
449
+ deduplicator: MessageDeduplicator,
450
+ envelope: SessionEnvelope,
451
+ signal: AbortSignal,
452
+ ): Promise<void> {
453
+ await this.sendSerialized(transport, sendState, SessionProtocol.createAck(envelope.messageId), signal);
454
+ if (!deduplicator.trySee(envelope.messageId)) {
455
+ return;
456
+ }
457
+
458
+ const read = SessionProtocol.tryReadCommand(envelope);
459
+ if (!read.isSuccess) {
460
+ return;
461
+ }
462
+ const command = read.payload;
463
+
464
+ let response: AdapterCommandResponse;
465
+ try {
466
+ response = await this.owner.handleCommand(command, signal);
467
+ } catch (err) {
468
+ if (signal.aborted) throw err;
469
+ response = {
470
+ correlationId: command.correlationId,
471
+ success: false,
472
+ errorCode: 'handler_error',
473
+ errorMessage: err instanceof Error ? err.message : String(err),
474
+ };
475
+ }
476
+ await this.sendSerialized(transport, sendState, SessionProtocol.createCommandResponse(response), signal);
477
+ }
478
+
479
+ private sendSerialized(
480
+ transport: WorkloadClientTransport,
481
+ sendState: SendState,
482
+ envelope: SessionEnvelope,
483
+ signal: AbortSignal,
484
+ ): Promise<void> {
485
+ return this.sendBytes(transport, sendState, SessionProtocol.serializeToUtf8Bytes(envelope), signal);
486
+ }
487
+
488
+ private sendBytes(transport: WorkloadClientTransport, sendState: SendState, frame: Uint8Array, signal: AbortSignal): Promise<void> {
489
+ const next = sendState.chain.then(() => transport.send(frame, signal));
490
+ sendState.chain = next.catch(() => undefined);
491
+ return next;
492
+ }
493
+
494
+ private async resync(transport: WorkloadClientTransport, sendState: SendState, signal: AbortSignal): Promise<void> {
495
+ const snapshot = await this.owner.buildSnapshot(signal);
496
+ for (const frame of SessionProtocol.createSnapshotFrames(snapshot)) {
497
+ await this.sendSerialized(transport, sendState, frame, signal);
498
+ }
499
+ this.observer.onSnapshotSent?.(snapshot);
500
+ if (this.lastHealth !== undefined) {
501
+ await this.sendSerialized(transport, sendState, SessionProtocol.createDataHealth(this.lastHealth), signal);
502
+ }
503
+ }
504
+
505
+ private enqueue(frame: Uint8Array): boolean {
506
+ if (this.outbound.length >= this.outboundCapacity) {
507
+ this.resyncPending = true;
508
+ return false;
509
+ }
510
+ this.outbound.push(frame);
511
+ this.wakeOutbound();
512
+ return true;
513
+ }
514
+
515
+ private drainOutbound(): void {
516
+ this.outbound = [];
517
+ }
518
+
519
+ private waitForOutbound(signal: AbortSignal): Promise<void> {
520
+ if (this.outbound.length > 0 || signal.aborted) {
521
+ return Promise.resolve();
522
+ }
523
+ return new Promise<void>((resolve) => {
524
+ const onAbort = () => {
525
+ this.outboundWaiter = undefined;
526
+ resolve();
527
+ };
528
+ signal.addEventListener('abort', onAbort, { once: true });
529
+ this.outboundWaiter = () => {
530
+ signal.removeEventListener('abort', onAbort);
531
+ resolve();
532
+ };
533
+ });
534
+ }
535
+
536
+ private wakeOutbound(): void {
537
+ const waiter = this.outboundWaiter;
538
+ if (waiter !== undefined) {
539
+ this.outboundWaiter = undefined;
540
+ waiter();
541
+ }
542
+ }
543
+ }
544
+
545
+ interface SendState {
546
+ chain: Promise<void>;
547
+ }
548
+
549
+ class SessionClosedByPeerError extends Error {}
550
+
551
+ class ReauthReconnectError extends Error {}
552
+
553
+ function linkAbort(signal: AbortSignal, onAbort: () => void): void {
554
+ if (signal.aborted) {
555
+ onAbort();
556
+ return;
557
+ }
558
+ signal.addEventListener('abort', onAbort, { once: true });
559
+ }
560
+
561
+ function negotiateHeartbeatMs(heartbeatSeconds: number): number {
562
+ if (!(heartbeatSeconds > 0)) {
563
+ return DEFAULT_HEARTBEAT_MS;
564
+ }
565
+ const ms = heartbeatSeconds * 1000;
566
+ return ms < MIN_HEARTBEAT_MS ? MIN_HEARTBEAT_MS : ms;
567
+ }
568
+
569
+ function realDelay(ms: number, signal: AbortSignal): Promise<void> {
570
+ return new Promise<void>((resolve, reject) => {
571
+ if (signal.aborted) {
572
+ reject(new Error('aborted'));
573
+ return;
574
+ }
575
+ const timer = setTimeout(() => {
576
+ signal.removeEventListener('abort', onAbort);
577
+ resolve();
578
+ }, ms);
579
+ const onAbort = () => {
580
+ clearTimeout(timer);
581
+ reject(new Error('aborted'));
582
+ };
583
+ signal.addEventListener('abort', onAbort, { once: true });
584
+ });
585
+ }
586
+
587
+ function defaultTransportFactory(
588
+ gatewayUrl: string,
589
+ token: string,
590
+ onInboundQueueOverflow?: () => void,
591
+ ): WorkloadClientTransportFactory {
592
+ return {
593
+ create(): WorkloadClientTransport {
594
+ return new WsWorkloadClientTransport(gatewayUrl, token, onInboundQueueOverflow);
595
+ },
596
+ };
597
+ }
@@ -0,0 +1,68 @@
1
+ /** Exponential backoff with FULL JITTER for gateway reconnection: the delay is drawn uniformly from
2
+ * `[0, min(cap, base·2^attempt)]`. Pure given an injected `sample`, so tests can assert the bounds. */
3
+ export interface ReconnectBackoffOptions {
4
+ /** The attempt-0 ceiling in ms; doubled each attempt until `maxMs`. Default 500. */
5
+ baseMs?: number;
6
+ /** The hard cap on the ceiling in ms. Default 30000. */
7
+ maxMs?: number;
8
+ /** A sample source returning a value in [0, 1) (defaults to Math.random). Injected so tests pin the draw. */
9
+ sample?: () => number;
10
+ }
11
+
12
+ export class ReconnectBackoff {
13
+ /** Default first-attempt ceiling. */
14
+ static readonly DEFAULT_BASE_MS = 500;
15
+ /** Default maximum ceiling. */
16
+ static readonly DEFAULT_MAX_MS = 30_000;
17
+
18
+ private readonly baseMs: number;
19
+ private readonly maxMs: number;
20
+ private readonly nextUnitSample: () => number;
21
+ private attemptCount = 0;
22
+
23
+ constructor(options: ReconnectBackoffOptions = {}) {
24
+ const b = options.baseMs ?? ReconnectBackoff.DEFAULT_BASE_MS;
25
+ const m = options.maxMs ?? ReconnectBackoff.DEFAULT_MAX_MS;
26
+ if (!(b > 0)) {
27
+ throw new RangeError(`Base delay must be positive (got ${b}).`);
28
+ }
29
+ if (m < b) {
30
+ throw new RangeError(`Max delay must be >= base delay (got max=${m}, base=${b}).`);
31
+ }
32
+ this.baseMs = b;
33
+ this.maxMs = m;
34
+ this.nextUnitSample = options.sample ?? Math.random;
35
+ }
36
+
37
+ /** The number of failed attempts recorded so far (the exponent for the next ceiling). */
38
+ get attempt(): number {
39
+ return this.attemptCount;
40
+ }
41
+
42
+ /** The deterministic ceiling for a zero-based attempt: `min(cap, base·2^n)`. The exponent is clamped so
43
+ * `2^n` cannot overflow on a pathologically long outage. */
44
+ ceilingForMs(attemptNumber: number): number {
45
+ if (attemptNumber < 0) {
46
+ throw new RangeError(`Attempt must be non-negative (got ${attemptNumber}).`);
47
+ }
48
+ const exponent = Math.min(attemptNumber, 62);
49
+ const scaled = this.baseMs * 2 ** exponent;
50
+ return Number.isFinite(scaled) ? Math.min(scaled, this.maxMs) : this.maxMs;
51
+ }
52
+
53
+ /** Produces the next backoff delay in ms and advances the attempt counter. Call once per failed connection
54
+ * attempt. */
55
+ nextDelayMs(): number {
56
+ const ceiling = this.ceilingForMs(this.attemptCount);
57
+ this.attemptCount++;
58
+ let sample = this.nextUnitSample();
59
+ if (!(sample >= 0)) sample = 0;
60
+ else if (sample >= 1) sample = 1 - Number.EPSILON;
61
+ return ceiling * sample;
62
+ }
63
+
64
+ /** Resets the attempt counter after a successful connect, so the next outage starts at the base ceiling. */
65
+ reset(): void {
66
+ this.attemptCount = 0;
67
+ }
68
+ }