@reeve-iot/workload-client 0.0.0-stage → 1.0.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.
- package/LICENSE +21 -0
- package/README.md +179 -2
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/session/MessageDeduplicator.d.ts +22 -0
- package/dist/session/MessageDeduplicator.d.ts.map +1 -0
- package/dist/session/MessageDeduplicator.js +49 -0
- package/dist/session/MessageDeduplicator.js.map +1 -0
- package/dist/session/SessionDataKind.d.ts +13 -0
- package/dist/session/SessionDataKind.d.ts.map +1 -0
- package/dist/session/SessionDataKind.js +11 -0
- package/dist/session/SessionDataKind.js.map +1 -0
- package/dist/session/SessionEnvelope.d.ts +40 -0
- package/dist/session/SessionEnvelope.d.ts.map +1 -0
- package/dist/session/SessionEnvelope.js +9 -0
- package/dist/session/SessionEnvelope.js.map +1 -0
- package/dist/session/SessionProtocol.d.ts +61 -0
- package/dist/session/SessionProtocol.d.ts.map +1 -0
- package/dist/session/SessionProtocol.js +283 -0
- package/dist/session/SessionProtocol.js.map +1 -0
- package/dist/session/WorkloadSessionClient.d.ts +114 -0
- package/dist/session/WorkloadSessionClient.d.ts.map +1 -0
- package/dist/session/WorkloadSessionClient.js +453 -0
- package/dist/session/WorkloadSessionClient.js.map +1 -0
- package/dist/session/backoff.d.ts +32 -0
- package/dist/session/backoff.d.ts.map +1 -0
- package/dist/session/backoff.js +54 -0
- package/dist/session/backoff.js.map +1 -0
- package/dist/session/owner.d.ts +34 -0
- package/dist/session/owner.d.ts.map +1 -0
- package/dist/session/owner.js +2 -0
- package/dist/session/owner.js.map +1 -0
- package/dist/session/rest.d.ts +83 -0
- package/dist/session/rest.d.ts.map +1 -0
- package/dist/session/rest.js +133 -0
- package/dist/session/rest.js.map +1 -0
- package/dist/session/transport.d.ts +51 -0
- package/dist/session/transport.d.ts.map +1 -0
- package/dist/session/transport.js +190 -0
- package/dist/session/transport.js.map +1 -0
- package/dist/session/types.d.ts +114 -0
- package/dist/session/types.d.ts.map +1 -0
- package/dist/session/types.js +19 -0
- package/dist/session/types.js.map +1 -0
- package/dist/tls/caCertificate.d.ts +5 -0
- package/dist/tls/caCertificate.d.ts.map +1 -0
- package/dist/tls/caCertificate.js +26 -0
- package/dist/tls/caCertificate.js.map +1 -0
- package/dist/tls/trustedCaCertificates.d.ts +4 -0
- package/dist/tls/trustedCaCertificates.d.ts.map +1 -0
- package/dist/tls/trustedCaCertificates.js +16 -0
- package/dist/tls/trustedCaCertificates.js.map +1 -0
- package/package.json +63 -4
- package/src/index.ts +59 -0
- package/src/session/MessageDeduplicator.ts +55 -0
- package/src/session/SessionDataKind.ts +14 -0
- package/src/session/SessionEnvelope.ts +32 -0
- package/src/session/SessionProtocol.ts +351 -0
- package/src/session/WorkloadSessionClient.ts +588 -0
- package/src/session/backoff.ts +68 -0
- package/src/session/owner.ts +39 -0
- package/src/session/rest.ts +221 -0
- package/src/session/transport.ts +224 -0
- package/src/session/types.ts +130 -0
- package/src/tls/caCertificate.ts +29 -0
- package/src/tls/trustedCaCertificates.ts +18 -0
|
@@ -0,0 +1,588 @@
|
|
|
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 resets the backoff to
|
|
54
|
+
* its base delay; one the gateway closes sooner keeps climbing, so a server that keeps closing fresh sessions is
|
|
55
|
+
* 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
|
+
try {
|
|
278
|
+
await Promise.race([send, receive, heartbeat]);
|
|
279
|
+
} finally {
|
|
280
|
+
sessionController.abort();
|
|
281
|
+
stoppingSignal.removeEventListener('abort', linkedAbort);
|
|
282
|
+
this.wakeOutbound();
|
|
283
|
+
await transport.close(1000, 'session ending');
|
|
284
|
+
await Promise.allSettled([send, receive, heartbeat]);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
return this.now() - servingSince >= this.healthySessionMs;
|
|
288
|
+
} finally {
|
|
289
|
+
await transport.dispose();
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
private async awaitHelloAck(
|
|
294
|
+
transport: WorkloadClientTransport,
|
|
295
|
+
stoppingSignal: AbortSignal,
|
|
296
|
+
): Promise<HelloAckFrame | undefined> {
|
|
297
|
+
const deadline = new AbortController();
|
|
298
|
+
const onStop = () => deadline.abort();
|
|
299
|
+
linkAbort(stoppingSignal, onStop);
|
|
300
|
+
const timer = setTimeout(() => deadline.abort(), this.helloAckTimeoutMs);
|
|
301
|
+
try {
|
|
302
|
+
while (!deadline.signal.aborted) {
|
|
303
|
+
let raw: Uint8Array | null;
|
|
304
|
+
try {
|
|
305
|
+
raw = await transport.receive(deadline.signal);
|
|
306
|
+
} catch {
|
|
307
|
+
return undefined;
|
|
308
|
+
}
|
|
309
|
+
if (raw === null) {
|
|
310
|
+
return undefined;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const parsed = SessionProtocol.parseBytes(raw);
|
|
314
|
+
if (!parsed.isSuccess) {
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
const env = parsed.envelope;
|
|
318
|
+
switch (env.type) {
|
|
319
|
+
case SessionFrameType.HelloAck: {
|
|
320
|
+
const read = SessionProtocol.tryReadHelloAck(env);
|
|
321
|
+
return read.isSuccess
|
|
322
|
+
? read.payload
|
|
323
|
+
: { protocol: this.protocol, heartbeatSeconds: DEFAULT_HEARTBEAT_MS / 1000 };
|
|
324
|
+
}
|
|
325
|
+
case SessionFrameType.Error:
|
|
326
|
+
case SessionFrameType.Close:
|
|
327
|
+
return undefined;
|
|
328
|
+
default:
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
} finally {
|
|
333
|
+
clearTimeout(timer);
|
|
334
|
+
stoppingSignal.removeEventListener('abort', onStop);
|
|
335
|
+
}
|
|
336
|
+
return undefined;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private async selfHeartbeatLoop(
|
|
340
|
+
transport: WorkloadClientTransport,
|
|
341
|
+
sendState: SendState,
|
|
342
|
+
intervalMs: number,
|
|
343
|
+
signal: AbortSignal,
|
|
344
|
+
): Promise<void> {
|
|
345
|
+
try {
|
|
346
|
+
while (!signal.aborted) {
|
|
347
|
+
await this.heartbeatDelay(intervalMs, signal);
|
|
348
|
+
if (signal.aborted) return;
|
|
349
|
+
await this.sendSerialized(transport, sendState, SessionProtocol.createHeartbeat(), signal);
|
|
350
|
+
}
|
|
351
|
+
} catch {
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
private async pumpOutbound(
|
|
356
|
+
transport: WorkloadClientTransport,
|
|
357
|
+
sendState: SendState,
|
|
358
|
+
signal: AbortSignal,
|
|
359
|
+
): Promise<void> {
|
|
360
|
+
try {
|
|
361
|
+
while (!signal.aborted) {
|
|
362
|
+
if (this.outbound.length === 0 && this.resyncPending) {
|
|
363
|
+
this.resyncPending = false;
|
|
364
|
+
await this.resync(transport, sendState, signal);
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
if (this.outbound.length === 0) {
|
|
368
|
+
await this.waitForOutbound(signal);
|
|
369
|
+
if (signal.aborted) return;
|
|
370
|
+
}
|
|
371
|
+
const frame = this.outbound.shift();
|
|
372
|
+
if (frame === undefined) {
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
await this.sendBytes(transport, sendState, frame, signal);
|
|
376
|
+
}
|
|
377
|
+
} catch {
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
private async receiveLoop(
|
|
382
|
+
transport: WorkloadClientTransport,
|
|
383
|
+
sendState: SendState,
|
|
384
|
+
deduplicator: MessageDeduplicator,
|
|
385
|
+
signal: AbortSignal,
|
|
386
|
+
): Promise<void> {
|
|
387
|
+
try {
|
|
388
|
+
while (!signal.aborted) {
|
|
389
|
+
const raw = await transport.receive(signal);
|
|
390
|
+
if (raw === null) {
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
const parsed = SessionProtocol.parseBytes(raw);
|
|
394
|
+
if (!parsed.isSuccess) {
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
await this.dispatch(transport, sendState, deduplicator, parsed.envelope, signal);
|
|
398
|
+
}
|
|
399
|
+
} catch {
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
private async dispatch(
|
|
404
|
+
transport: WorkloadClientTransport,
|
|
405
|
+
sendState: SendState,
|
|
406
|
+
deduplicator: MessageDeduplicator,
|
|
407
|
+
envelope: SessionEnvelope,
|
|
408
|
+
signal: AbortSignal,
|
|
409
|
+
): Promise<void> {
|
|
410
|
+
switch (envelope.type) {
|
|
411
|
+
case SessionFrameType.Heartbeat:
|
|
412
|
+
await this.sendSerialized(transport, sendState, SessionProtocol.createHeartbeat(), signal);
|
|
413
|
+
return;
|
|
414
|
+
|
|
415
|
+
case SessionFrameType.Ack:
|
|
416
|
+
case SessionFrameType.HelloAck:
|
|
417
|
+
return;
|
|
418
|
+
|
|
419
|
+
case SessionFrameType.Reauth:
|
|
420
|
+
this.observer.onReauthRequested?.(SessionProtocol.tryReadReauth(envelope).payload?.reason);
|
|
421
|
+
throw new ReauthReconnectError();
|
|
422
|
+
|
|
423
|
+
case SessionFrameType.Close:
|
|
424
|
+
this.observer.onServerClose?.(SessionProtocol.tryReadClose(envelope).payload?.reason);
|
|
425
|
+
throw new SessionClosedByPeerError();
|
|
426
|
+
|
|
427
|
+
case SessionFrameType.Command:
|
|
428
|
+
await this.handleCommand(transport, sendState, deduplicator, envelope, signal);
|
|
429
|
+
return;
|
|
430
|
+
|
|
431
|
+
default:
|
|
432
|
+
await this.sendSerialized(transport, sendState, SessionProtocol.createAck(envelope.messageId), signal);
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
private async handleCommand(
|
|
438
|
+
transport: WorkloadClientTransport,
|
|
439
|
+
sendState: SendState,
|
|
440
|
+
deduplicator: MessageDeduplicator,
|
|
441
|
+
envelope: SessionEnvelope,
|
|
442
|
+
signal: AbortSignal,
|
|
443
|
+
): Promise<void> {
|
|
444
|
+
await this.sendSerialized(transport, sendState, SessionProtocol.createAck(envelope.messageId), signal);
|
|
445
|
+
if (!deduplicator.trySee(envelope.messageId)) {
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
const read = SessionProtocol.tryReadCommand(envelope);
|
|
450
|
+
if (!read.isSuccess) {
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
const command = read.payload;
|
|
454
|
+
|
|
455
|
+
let response: AdapterCommandResponse;
|
|
456
|
+
try {
|
|
457
|
+
response = await this.owner.handleCommand(command, signal);
|
|
458
|
+
} catch (err) {
|
|
459
|
+
if (signal.aborted) throw err;
|
|
460
|
+
response = {
|
|
461
|
+
correlationId: command.correlationId,
|
|
462
|
+
success: false,
|
|
463
|
+
errorCode: 'handler_error',
|
|
464
|
+
errorMessage: err instanceof Error ? err.message : String(err),
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
await this.sendSerialized(transport, sendState, SessionProtocol.createCommandResponse(response), signal);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
private sendSerialized(
|
|
471
|
+
transport: WorkloadClientTransport,
|
|
472
|
+
sendState: SendState,
|
|
473
|
+
envelope: SessionEnvelope,
|
|
474
|
+
signal: AbortSignal,
|
|
475
|
+
): Promise<void> {
|
|
476
|
+
return this.sendBytes(transport, sendState, SessionProtocol.serializeToUtf8Bytes(envelope), signal);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
private sendBytes(transport: WorkloadClientTransport, sendState: SendState, frame: Uint8Array, signal: AbortSignal): Promise<void> {
|
|
480
|
+
const next = sendState.chain.then(() => transport.send(frame, signal));
|
|
481
|
+
sendState.chain = next.catch(() => undefined);
|
|
482
|
+
return next;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
private async resync(transport: WorkloadClientTransport, sendState: SendState, signal: AbortSignal): Promise<void> {
|
|
486
|
+
const snapshot = await this.owner.buildSnapshot(signal);
|
|
487
|
+
for (const frame of SessionProtocol.createSnapshotFrames(snapshot)) {
|
|
488
|
+
await this.sendSerialized(transport, sendState, frame, signal);
|
|
489
|
+
}
|
|
490
|
+
this.observer.onSnapshotSent?.(snapshot);
|
|
491
|
+
if (this.lastHealth !== undefined) {
|
|
492
|
+
await this.sendSerialized(transport, sendState, SessionProtocol.createDataHealth(this.lastHealth), signal);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
private enqueue(frame: Uint8Array): boolean {
|
|
497
|
+
if (this.outbound.length >= this.outboundCapacity) {
|
|
498
|
+
this.resyncPending = true;
|
|
499
|
+
return false;
|
|
500
|
+
}
|
|
501
|
+
this.outbound.push(frame);
|
|
502
|
+
this.wakeOutbound();
|
|
503
|
+
return true;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
private drainOutbound(): void {
|
|
507
|
+
this.outbound = [];
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
private waitForOutbound(signal: AbortSignal): Promise<void> {
|
|
511
|
+
if (this.outbound.length > 0 || signal.aborted) {
|
|
512
|
+
return Promise.resolve();
|
|
513
|
+
}
|
|
514
|
+
return new Promise<void>((resolve) => {
|
|
515
|
+
const onAbort = () => {
|
|
516
|
+
this.outboundWaiter = undefined;
|
|
517
|
+
resolve();
|
|
518
|
+
};
|
|
519
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
520
|
+
this.outboundWaiter = () => {
|
|
521
|
+
signal.removeEventListener('abort', onAbort);
|
|
522
|
+
resolve();
|
|
523
|
+
};
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
private wakeOutbound(): void {
|
|
528
|
+
const waiter = this.outboundWaiter;
|
|
529
|
+
if (waiter !== undefined) {
|
|
530
|
+
this.outboundWaiter = undefined;
|
|
531
|
+
waiter();
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
interface SendState {
|
|
537
|
+
chain: Promise<void>;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
class SessionClosedByPeerError extends Error {}
|
|
541
|
+
|
|
542
|
+
class ReauthReconnectError extends Error {}
|
|
543
|
+
|
|
544
|
+
function linkAbort(signal: AbortSignal, onAbort: () => void): void {
|
|
545
|
+
if (signal.aborted) {
|
|
546
|
+
onAbort();
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function negotiateHeartbeatMs(heartbeatSeconds: number): number {
|
|
553
|
+
if (!(heartbeatSeconds > 0)) {
|
|
554
|
+
return DEFAULT_HEARTBEAT_MS;
|
|
555
|
+
}
|
|
556
|
+
const ms = heartbeatSeconds * 1000;
|
|
557
|
+
return ms < MIN_HEARTBEAT_MS ? MIN_HEARTBEAT_MS : ms;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function realDelay(ms: number, signal: AbortSignal): Promise<void> {
|
|
561
|
+
return new Promise<void>((resolve, reject) => {
|
|
562
|
+
if (signal.aborted) {
|
|
563
|
+
reject(new Error('aborted'));
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
const timer = setTimeout(() => {
|
|
567
|
+
signal.removeEventListener('abort', onAbort);
|
|
568
|
+
resolve();
|
|
569
|
+
}, ms);
|
|
570
|
+
const onAbort = () => {
|
|
571
|
+
clearTimeout(timer);
|
|
572
|
+
reject(new Error('aborted'));
|
|
573
|
+
};
|
|
574
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
function defaultTransportFactory(
|
|
579
|
+
gatewayUrl: string,
|
|
580
|
+
token: string,
|
|
581
|
+
onInboundQueueOverflow?: () => void,
|
|
582
|
+
): WorkloadClientTransportFactory {
|
|
583
|
+
return {
|
|
584
|
+
create(): WorkloadClientTransport {
|
|
585
|
+
return new WsWorkloadClientTransport(gatewayUrl, token, onInboundQueueOverflow);
|
|
586
|
+
},
|
|
587
|
+
};
|
|
588
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { AdapterCommand, AdapterCommandResponse, SnapshotPayload } from './types.js';
|
|
2
|
+
|
|
3
|
+
/** The adapter-side contract the client calls back into: a sidecar implements this once and the client owns all
|
|
4
|
+
* transport mechanics. The client drives snapshot-on-reconnect, so an adapter physically cannot skip it. */
|
|
5
|
+
export interface WorkloadSessionOwner {
|
|
6
|
+
/** Builds the full current state to push immediately after (re)connect and HELLO, and again on a live session
|
|
7
|
+
* once a frame the full outbound queue dropped has to be repaired. MUST reflect live state at call time, not a
|
|
8
|
+
* cached handshake-time value. */
|
|
9
|
+
buildSnapshot(signal: AbortSignal): Promise<SnapshotPayload> | SnapshotPayload;
|
|
10
|
+
|
|
11
|
+
/** Handles an inbound COMMAND. Do not throw for an unsupported command — return an unsuccessful response
|
|
12
|
+
* carrying the correlation id, so the caller's correlation wait always resolves. */
|
|
13
|
+
handleCommand(
|
|
14
|
+
command: AdapterCommand,
|
|
15
|
+
signal: AbortSignal,
|
|
16
|
+
): Promise<AdapterCommandResponse> | AdapterCommandResponse;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Lifecycle callbacks the client raises so a sidecar can log or meter session events. All are optional and
|
|
20
|
+
* best-effort; a throwing callback must not crash the client. */
|
|
21
|
+
export interface WorkloadSessionObserver {
|
|
22
|
+
/** The transport connected and the server accepted HELLO (HELLO_ACK received). */
|
|
23
|
+
onSessionEstablished?(): void;
|
|
24
|
+
/** A full-state snapshot was pushed: after every (re)connect, and on a live session after a frame the full
|
|
25
|
+
* outbound queue dropped was repaired. `onSessionEstablished` alone marks a new session. */
|
|
26
|
+
onSnapshotSent?(snapshot: SnapshotPayload): void;
|
|
27
|
+
/** The connect attempt itself failed (before any handshake). */
|
|
28
|
+
onConnectFailed?(error: unknown): void;
|
|
29
|
+
/** The established session faulted/ended and will be retried. */
|
|
30
|
+
onSessionFaulted?(error: unknown): void;
|
|
31
|
+
/** A reconnect was scheduled after `delayMs` (attempt number is post-increment). */
|
|
32
|
+
onReconnectScheduled?(attempt: number, delayMs: number): void;
|
|
33
|
+
/** The server sent a `reauth` frame (near-expiry re-present). */
|
|
34
|
+
onReauthRequested?(reason: string | undefined): void;
|
|
35
|
+
/** The server sent a CLOSE frame with an optional reason. */
|
|
36
|
+
onServerClose?(reason: string | undefined): void;
|
|
37
|
+
/** The transport closed after its bounded inbound queue overflowed. */
|
|
38
|
+
onInboundQueueOverflow?(): void;
|
|
39
|
+
}
|