@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,221 @@
|
|
|
1
|
+
/** The self-scoped sidecar→backend REST client. Reaching this surface is gated on a consented
|
|
2
|
+
* `privileges.callsBackendRest`; the token is a bearer header ONLY and is never logged. */
|
|
3
|
+
|
|
4
|
+
/** Mirrors the backend `WorkloadSelfResponse` DTO field-for-field; secret parameter values arrive already
|
|
5
|
+
* MASKED to the `"***"` sentinel, never plaintext. */
|
|
6
|
+
export interface WorkloadSelfConfig {
|
|
7
|
+
/** The caller instance's identity — the token→instance binding target. */
|
|
8
|
+
instanceId: string;
|
|
9
|
+
/** The module this instance belongs to. */
|
|
10
|
+
moduleId: string;
|
|
11
|
+
/** The manifest workload id this instance materializes. */
|
|
12
|
+
workloadId: string;
|
|
13
|
+
/** SHA-256 of the desired (rendered) spec — the sidecar's `REEVE_SPEC_HASH`; null before first render. */
|
|
14
|
+
specHash: string | null;
|
|
15
|
+
/** The deploying module/app version (`REEVE_APP_VERSION`); null for an adopted pre-Workloads image. */
|
|
16
|
+
appVersion: string | null;
|
|
17
|
+
/** The effective session-gateway base URL the sidecar dials (`REEVE_GATEWAY_URL`); null when unset. */
|
|
18
|
+
gatewayUrl: string | null;
|
|
19
|
+
/** The backend's externally-reachable base URL (`bootstrap:backendBaseUrl`); null when unset. */
|
|
20
|
+
backendBaseUrl: string | null;
|
|
21
|
+
/** RESOLVED install-time parameters. Any value the manifest does not positively declare a non-password
|
|
22
|
+
* type is already MASKED by the backend, so this fails closed. */
|
|
23
|
+
parameters: Record<string, string | null>;
|
|
24
|
+
/** Service-DNS host of each SIBLING workload, keyed by `workloadId`. Excludes the caller's own. */
|
|
25
|
+
siblingWorkloadHosts: Record<string, string>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** A subset of WHATWG `fetch`, narrow enough that a test can inject a stub without DOM lib types. */
|
|
29
|
+
export type FetchLike = (
|
|
30
|
+
url: string,
|
|
31
|
+
init: {
|
|
32
|
+
method: string;
|
|
33
|
+
headers: Record<string, string>;
|
|
34
|
+
signal?: AbortSignal;
|
|
35
|
+
},
|
|
36
|
+
) => Promise<FetchLikeResponse>;
|
|
37
|
+
|
|
38
|
+
/** The subset of the `fetch` Response {@link WorkloadRestClient} consumes. */
|
|
39
|
+
export interface FetchLikeResponse {
|
|
40
|
+
readonly ok: boolean;
|
|
41
|
+
readonly status: number;
|
|
42
|
+
json(): Promise<unknown>;
|
|
43
|
+
text(): Promise<string>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Options for a {@link WorkloadRestClient}. */
|
|
47
|
+
export interface WorkloadRestClientOptions {
|
|
48
|
+
/** The backend's externally-reachable base URL. The self path is appended; a trailing slash is tolerated. */
|
|
49
|
+
backendBaseUrl: string;
|
|
50
|
+
/** The per-instance workload credential (`rwt_…`) — sent as a bearer header only, never logged. */
|
|
51
|
+
token: string;
|
|
52
|
+
/** Injected `fetch` seam. Defaults to the runtime global `fetch` (Node ≥18). */
|
|
53
|
+
fetch?: FetchLike;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Base error for {@link WorkloadRestClient}. Deliberately captures the token in no field or message. */
|
|
57
|
+
export class WorkloadRestError extends Error {
|
|
58
|
+
/** The HTTP status code, or `0` for a transport/parse fault with no response. */
|
|
59
|
+
readonly status: number;
|
|
60
|
+
|
|
61
|
+
constructor(message: string, status: number) {
|
|
62
|
+
super(message);
|
|
63
|
+
this.name = 'WorkloadRestError';
|
|
64
|
+
this.status = status;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Thrown on a 403: the flag, not the token, authorizes REST. Typed so a sidecar can tell "not consented"
|
|
69
|
+
* from a transient failure and stop retrying. */
|
|
70
|
+
export class WorkloadNotConsentedError extends WorkloadRestError {
|
|
71
|
+
constructor(message = 'The workload instance has not consented to the callsBackendRest privilege.') {
|
|
72
|
+
super(message, 403);
|
|
73
|
+
this.name = 'WorkloadNotConsentedError';
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Thrown on a 401. Typed so a sidecar can trigger a re-provision rather than treat it as a config problem. */
|
|
78
|
+
export class WorkloadUnauthorizedError extends WorkloadRestError {
|
|
79
|
+
constructor(message = 'The workload token was rejected (missing, expired, or revoked).') {
|
|
80
|
+
super(message, 401);
|
|
81
|
+
this.name = 'WorkloadUnauthorizedError';
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const SELF_PATH = '/api/workloads/self';
|
|
86
|
+
|
|
87
|
+
const REQUIRED_SELF_FIELDS = [
|
|
88
|
+
'instanceId',
|
|
89
|
+
'moduleId',
|
|
90
|
+
'workloadId',
|
|
91
|
+
'parameters',
|
|
92
|
+
'siblingWorkloadHosts',
|
|
93
|
+
] as const;
|
|
94
|
+
|
|
95
|
+
function parseSelfConfig(body: unknown, status: number): WorkloadSelfConfig {
|
|
96
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
|
|
97
|
+
throw new WorkloadRestError('The workload self response was not a JSON object.', status);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const record = body as Record<string, unknown>;
|
|
101
|
+
const missing = REQUIRED_SELF_FIELDS.filter((key) => record[key] === undefined || record[key] === null);
|
|
102
|
+
if (missing.length > 0) {
|
|
103
|
+
throw new WorkloadRestError(
|
|
104
|
+
`The workload self response is missing required field(s): ${missing.join(', ')}. ` +
|
|
105
|
+
'The host is older than this client.',
|
|
106
|
+
status,
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return body as WorkloadSelfConfig;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The reference client for the self-scoped sidecar→backend surface. Header-only auth; token never logged. */
|
|
114
|
+
export class WorkloadRestClient {
|
|
115
|
+
private readonly baseUrl: string;
|
|
116
|
+
private readonly token: string;
|
|
117
|
+
private readonly fetchImpl: FetchLike;
|
|
118
|
+
|
|
119
|
+
constructor(options: WorkloadRestClientOptions) {
|
|
120
|
+
const backendBaseUrl = options.backendBaseUrl?.trim();
|
|
121
|
+
if (!backendBaseUrl) {
|
|
122
|
+
throw new WorkloadRestError('backendBaseUrl is required.', 0);
|
|
123
|
+
}
|
|
124
|
+
if (!options.token) {
|
|
125
|
+
throw new WorkloadRestError('token is required.', 0);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const resolvedFetch = options.fetch ?? (globalThis as { fetch?: FetchLike }).fetch;
|
|
129
|
+
if (typeof resolvedFetch !== 'function') {
|
|
130
|
+
throw new WorkloadRestError(
|
|
131
|
+
'No fetch implementation available; pass options.fetch or run on Node >=18.',
|
|
132
|
+
0,
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
this.baseUrl = backendBaseUrl.replace(/\/+$/, '');
|
|
137
|
+
this.token = options.token;
|
|
138
|
+
this.fetchImpl = resolvedFetch;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Builds a client from the bootstrap environment, throwing on the first missing variable: a misconfigured
|
|
142
|
+
* sidecar must fail loudly. */
|
|
143
|
+
static fromEnvironment(
|
|
144
|
+
env: Record<string, string | undefined> = (globalThis as { process?: { env?: Record<string, string | undefined> } })
|
|
145
|
+
.process?.env ?? {},
|
|
146
|
+
fetchImpl?: FetchLike,
|
|
147
|
+
): WorkloadRestClient {
|
|
148
|
+
const backendBaseUrl = env[WorkloadRestEnvVars.BackendBaseUrl];
|
|
149
|
+
if (!backendBaseUrl || !backendBaseUrl.trim()) {
|
|
150
|
+
throw new WorkloadRestError(
|
|
151
|
+
`Required workload environment variable '${WorkloadRestEnvVars.BackendBaseUrl}' is missing or blank.`,
|
|
152
|
+
0,
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
const token = env[WorkloadRestEnvVars.WorkloadToken];
|
|
156
|
+
if (!token || !token.trim()) {
|
|
157
|
+
throw new WorkloadRestError(
|
|
158
|
+
`Required workload environment variable '${WorkloadRestEnvVars.WorkloadToken}' is missing or blank.`,
|
|
159
|
+
0,
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const options: WorkloadRestClientOptions = { backendBaseUrl, token };
|
|
164
|
+
if (fetchImpl) {
|
|
165
|
+
options.fetch = fetchImpl;
|
|
166
|
+
}
|
|
167
|
+
return new WorkloadRestClient(options);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Self-scoped by construction: the backend reads the target from the token's bound instance, never from a
|
|
171
|
+
* caller-supplied id. Throws a typed error on 403 and 401, {@link WorkloadRestError} otherwise. */
|
|
172
|
+
async getSelf(signal?: AbortSignal): Promise<WorkloadSelfConfig> {
|
|
173
|
+
const init: Parameters<FetchLike>[1] = {
|
|
174
|
+
method: 'GET',
|
|
175
|
+
headers: {
|
|
176
|
+
Authorization: `Bearer ${this.token}`,
|
|
177
|
+
Accept: 'application/json',
|
|
178
|
+
},
|
|
179
|
+
};
|
|
180
|
+
if (signal) {
|
|
181
|
+
init.signal = signal;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
let response: FetchLikeResponse;
|
|
185
|
+
try {
|
|
186
|
+
response = await this.fetchImpl(this.baseUrl + SELF_PATH, init);
|
|
187
|
+
} catch {
|
|
188
|
+
throw new WorkloadRestError('The workload self request failed before a response was received.', 0);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (response.ok) {
|
|
192
|
+
let body: unknown;
|
|
193
|
+
try {
|
|
194
|
+
body = await response.json();
|
|
195
|
+
} catch {
|
|
196
|
+
throw new WorkloadRestError('The workload self response was not valid JSON.', response.status);
|
|
197
|
+
}
|
|
198
|
+
return parseSelfConfig(body, response.status);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (response.status === 403) {
|
|
202
|
+
throw new WorkloadNotConsentedError();
|
|
203
|
+
}
|
|
204
|
+
if (response.status === 401) {
|
|
205
|
+
throw new WorkloadUnauthorizedError();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
throw new WorkloadRestError(
|
|
209
|
+
`The workload self request failed with HTTP ${response.status}.`,
|
|
210
|
+
response.status,
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** The bootstrap env-var names this client reads, mirroring .NET's `WorkloadSessionOptions.EnvVars`. */
|
|
216
|
+
export const WorkloadRestEnvVars = {
|
|
217
|
+
/** `bootstrap:backendBaseUrl` → the backend's externally-reachable base URL. */
|
|
218
|
+
BackendBaseUrl: 'REEVE_BACKEND_URL',
|
|
219
|
+
/** The per-instance workload credential (`rwt_…`). */
|
|
220
|
+
WorkloadToken: 'REEVE_WORKLOAD_TOKEN',
|
|
221
|
+
} as const;
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { WebSocket } from 'ws';
|
|
2
|
+
|
|
3
|
+
/** One instance models one connection attempt; the send/receive pair carry whole session frames (one
|
|
4
|
+
* envelope per call). The client discards a transport after a disconnect and asks the factory for a fresh one. */
|
|
5
|
+
export interface WorkloadClientTransport {
|
|
6
|
+
/** Opens the connection, presenting the bearer credential in the `Authorization` header only — never the
|
|
7
|
+
* query string. Rejects on failure so the caller's reconnect loop treats it like any other fault. */
|
|
8
|
+
connect(signal: AbortSignal): Promise<void>;
|
|
9
|
+
|
|
10
|
+
/** Sends one complete session frame (already serialized to UTF-8 wire bytes) as a single text message. */
|
|
11
|
+
send(utf8Frame: Uint8Array, signal: AbortSignal): Promise<void>;
|
|
12
|
+
|
|
13
|
+
/** Receives the next complete inbound message. Resolves `null` when the peer closed the connection. */
|
|
14
|
+
receive(signal: AbortSignal): Promise<Uint8Array | null>;
|
|
15
|
+
|
|
16
|
+
/** Best-effort orderly close; never rejects (a peer that has already vanished is not an error). */
|
|
17
|
+
close(code: number, reason: string): Promise<void>;
|
|
18
|
+
|
|
19
|
+
/** Releases resources for this connection attempt. */
|
|
20
|
+
dispose(): Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Mints a fresh transport per connection attempt. The token supplier is re-read per {@link create} so a
|
|
24
|
+
* reauth-driven reconnect picks up a rotated credential. */
|
|
25
|
+
export interface WorkloadClientTransportFactory {
|
|
26
|
+
/** Creates (but does not yet connect) a transport for the next attempt. */
|
|
27
|
+
create(): WorkloadClientTransport;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const WS_NORMAL_CLOSURE = 1000;
|
|
31
|
+
const INBOUND_HIGH_WATER_FRAMES = 64;
|
|
32
|
+
const INBOUND_HIGH_WATER_BYTES = 256 * 1024;
|
|
33
|
+
const INBOUND_LOW_WATER_FRAMES = 16;
|
|
34
|
+
const INBOUND_LOW_WATER_BYTES = 64 * 1024;
|
|
35
|
+
const INBOUND_HARD_CAP_FRAMES = 1024;
|
|
36
|
+
const INBOUND_HARD_CAP_BYTES = 4 * 1024 * 1024;
|
|
37
|
+
const MAX_INBOUND_MESSAGE_BYTES = INBOUND_HARD_CAP_BYTES;
|
|
38
|
+
|
|
39
|
+
/** The production transport over the `ws` library. Each `message` event is one complete session frame, since
|
|
40
|
+
* the sender emits one envelope per send. */
|
|
41
|
+
export class WsWorkloadClientTransport implements WorkloadClientTransport {
|
|
42
|
+
private socket: WebSocket | undefined;
|
|
43
|
+
private readonly inbound: Array<Uint8Array | null> = [];
|
|
44
|
+
private inboundBytes = 0;
|
|
45
|
+
private inboundWaiter: ((value: Uint8Array | null) => void) | undefined;
|
|
46
|
+
private closed = false;
|
|
47
|
+
private pausedByUs = false;
|
|
48
|
+
|
|
49
|
+
constructor(
|
|
50
|
+
private readonly url: string,
|
|
51
|
+
private readonly token: string,
|
|
52
|
+
private readonly onInboundQueueOverflow?: () => void,
|
|
53
|
+
) {}
|
|
54
|
+
|
|
55
|
+
connect(signal: AbortSignal): Promise<void> {
|
|
56
|
+
return new Promise<void>((resolve, reject) => {
|
|
57
|
+
const socket = new WebSocket(this.url, {
|
|
58
|
+
headers: { Authorization: `Bearer ${this.token}` },
|
|
59
|
+
maxPayload: MAX_INBOUND_MESSAGE_BYTES,
|
|
60
|
+
});
|
|
61
|
+
this.socket = socket;
|
|
62
|
+
|
|
63
|
+
const onAbort = () => {
|
|
64
|
+
socket.terminate();
|
|
65
|
+
reject(new Error('connect aborted'));
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
socket.once('open', () => {
|
|
69
|
+
signal.removeEventListener('abort', onAbort);
|
|
70
|
+
resolve();
|
|
71
|
+
});
|
|
72
|
+
socket.once('error', (err) => {
|
|
73
|
+
signal.removeEventListener('abort', onAbort);
|
|
74
|
+
reject(err);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
if (signal.aborted) {
|
|
78
|
+
onAbort();
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
82
|
+
|
|
83
|
+
socket.on('message', (data: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => {
|
|
84
|
+
void isBinary;
|
|
85
|
+
const bytes = toBytes(data);
|
|
86
|
+
this.enqueue(bytes);
|
|
87
|
+
});
|
|
88
|
+
socket.on('close', () => {
|
|
89
|
+
this.closed = true;
|
|
90
|
+
this.enqueue(null);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
send(utf8Frame: Uint8Array, _signal: AbortSignal): Promise<void> {
|
|
96
|
+
void _signal;
|
|
97
|
+
return new Promise<void>((resolve, reject) => {
|
|
98
|
+
const socket = this.socket;
|
|
99
|
+
if (socket === undefined || socket.readyState !== WebSocket.OPEN) {
|
|
100
|
+
reject(new Error('transport not open'));
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
socket.send(Buffer.from(utf8Frame).toString('utf-8'), (err) => {
|
|
104
|
+
if (err) reject(err);
|
|
105
|
+
else resolve();
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
receive(signal: AbortSignal): Promise<Uint8Array | null> {
|
|
111
|
+
if (this.inbound.length > 0) {
|
|
112
|
+
const value = this.inbound.shift() ?? null;
|
|
113
|
+
if (value !== null) this.inboundBytes -= value.byteLength;
|
|
114
|
+
if (
|
|
115
|
+
this.pausedByUs &&
|
|
116
|
+
this.inbound.length <= INBOUND_LOW_WATER_FRAMES &&
|
|
117
|
+
this.inboundBytes <= INBOUND_LOW_WATER_BYTES
|
|
118
|
+
) {
|
|
119
|
+
this.pausedByUs = false;
|
|
120
|
+
this.socket?.resume();
|
|
121
|
+
}
|
|
122
|
+
return Promise.resolve(value);
|
|
123
|
+
}
|
|
124
|
+
if (this.closed) {
|
|
125
|
+
return Promise.resolve(null);
|
|
126
|
+
}
|
|
127
|
+
return new Promise<Uint8Array | null>((resolve, reject) => {
|
|
128
|
+
const onAbort = () => {
|
|
129
|
+
this.inboundWaiter = undefined;
|
|
130
|
+
reject(new Error('receive aborted'));
|
|
131
|
+
};
|
|
132
|
+
if (signal.aborted) {
|
|
133
|
+
onAbort();
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
137
|
+
this.inboundWaiter = (value) => {
|
|
138
|
+
signal.removeEventListener('abort', onAbort);
|
|
139
|
+
resolve(value);
|
|
140
|
+
};
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async close(code: number = WS_NORMAL_CLOSURE, reason: string = ''): Promise<void> {
|
|
145
|
+
try {
|
|
146
|
+
this.socket?.close(code, reason);
|
|
147
|
+
} catch {
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async dispose(): Promise<void> {
|
|
152
|
+
try {
|
|
153
|
+
const socket = this.socket;
|
|
154
|
+
socket?.removeAllListeners();
|
|
155
|
+
socket?.on('error', () => undefined);
|
|
156
|
+
socket?.terminate();
|
|
157
|
+
} catch {
|
|
158
|
+
}
|
|
159
|
+
this.socket = undefined;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
private enqueue(value: Uint8Array | null): void {
|
|
163
|
+
if (value !== null && this.closed) return;
|
|
164
|
+
const waiter = this.inboundWaiter;
|
|
165
|
+
if (waiter !== undefined) {
|
|
166
|
+
this.inboundWaiter = undefined;
|
|
167
|
+
waiter(value);
|
|
168
|
+
} else {
|
|
169
|
+
if (
|
|
170
|
+
value !== null &&
|
|
171
|
+
(this.inbound.length + 1 > INBOUND_HARD_CAP_FRAMES ||
|
|
172
|
+
this.inboundBytes + value.byteLength > INBOUND_HARD_CAP_BYTES)
|
|
173
|
+
) {
|
|
174
|
+
this.closed = true;
|
|
175
|
+
if (this.onInboundQueueOverflow === undefined) {
|
|
176
|
+
console.warn(
|
|
177
|
+
`Workload WebSocket inbound queue exceeded ${INBOUND_HARD_CAP_FRAMES} frames or ${INBOUND_HARD_CAP_BYTES} bytes; closing session`,
|
|
178
|
+
);
|
|
179
|
+
} else {
|
|
180
|
+
try {
|
|
181
|
+
this.onInboundQueueOverflow();
|
|
182
|
+
} catch {
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
this.inbound.push(null);
|
|
186
|
+
this.socket?.close(1013, 'inbound queue limit exceeded');
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
this.inbound.push(value);
|
|
190
|
+
if (value !== null) this.inboundBytes += value.byteLength;
|
|
191
|
+
if (
|
|
192
|
+
!this.pausedByUs &&
|
|
193
|
+
(this.inbound.length >= INBOUND_HIGH_WATER_FRAMES || this.inboundBytes >= INBOUND_HIGH_WATER_BYTES)
|
|
194
|
+
) {
|
|
195
|
+
this.pausedByUs = true;
|
|
196
|
+
this.socket?.pause();
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function toBytes(data: Buffer | ArrayBuffer | Buffer[]): Uint8Array {
|
|
203
|
+
if (Array.isArray(data)) {
|
|
204
|
+
return new Uint8Array(Buffer.concat(data));
|
|
205
|
+
}
|
|
206
|
+
if (data instanceof ArrayBuffer) {
|
|
207
|
+
return new Uint8Array(data);
|
|
208
|
+
}
|
|
209
|
+
return new Uint8Array(data);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The production transport factory: one transport per attempt, re-reading the token from the supplier each
|
|
213
|
+
* time so a reauth-driven reconnect picks up a rotated credential. */
|
|
214
|
+
export class WsWorkloadClientTransportFactory implements WorkloadClientTransportFactory {
|
|
215
|
+
constructor(
|
|
216
|
+
private readonly url: string,
|
|
217
|
+
private readonly readToken: () => string,
|
|
218
|
+
private readonly onInboundQueueOverflow?: () => void,
|
|
219
|
+
) {}
|
|
220
|
+
|
|
221
|
+
create(): WorkloadClientTransport {
|
|
222
|
+
return new WsWorkloadClientTransport(this.url, this.readToken(), this.onInboundQueueOverflow);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/** Wire models ported from the .NET `Reeve.Adapters.Protocol` models. Field names are the CAMELCASE wire
|
|
2
|
+
* names, byte-compatible with the camelCase serialization the real gateway speaks. */
|
|
3
|
+
|
|
4
|
+
/** The frame discriminator, serialized as a stable camelCase STRING on the wire (never an integer). */
|
|
5
|
+
export const SessionFrameType = {
|
|
6
|
+
Hello: 'hello',
|
|
7
|
+
HelloAck: 'helloAck',
|
|
8
|
+
Heartbeat: 'heartbeat',
|
|
9
|
+
Ack: 'ack',
|
|
10
|
+
Snapshot: 'snapshot',
|
|
11
|
+
Data: 'data',
|
|
12
|
+
Command: 'command',
|
|
13
|
+
CommandResponse: 'commandResponse',
|
|
14
|
+
Reauth: 'reauth',
|
|
15
|
+
Close: 'close',
|
|
16
|
+
Error: 'error',
|
|
17
|
+
} as const;
|
|
18
|
+
|
|
19
|
+
export type SessionFrameType = (typeof SessionFrameType)[keyof typeof SessionFrameType];
|
|
20
|
+
|
|
21
|
+
/** The set of recognized frame-type wire strings, for parse-time validation. */
|
|
22
|
+
export const SESSION_FRAME_TYPES: ReadonlySet<string> = new Set(Object.values(SessionFrameType));
|
|
23
|
+
|
|
24
|
+
/** `version` is the protocol this component speaks natively; `minSupported` is the floor it accepts from
|
|
25
|
+
* its peer. */
|
|
26
|
+
export interface ProtocolRange {
|
|
27
|
+
version: string;
|
|
28
|
+
minSupported: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Client → server, first frame after connecting. */
|
|
32
|
+
export interface HelloFrame {
|
|
33
|
+
instanceId: string;
|
|
34
|
+
appVersion: string;
|
|
35
|
+
specHash: string;
|
|
36
|
+
protocol: ProtocolRange;
|
|
37
|
+
/** Optional API-schema tag; omitted from the wire when undefined. */
|
|
38
|
+
apiSchema?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Server → client acceptance of a HELLO; carries the negotiated heartbeat cadence + optional session id. */
|
|
42
|
+
export interface HelloAckFrame {
|
|
43
|
+
protocol: ProtocolRange;
|
|
44
|
+
heartbeatSeconds: number;
|
|
45
|
+
sessionId?: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Server → client request to re-present credentials. */
|
|
49
|
+
export interface ReauthFrame {
|
|
50
|
+
reason?: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Acknowledgement of a previously received frame, referenced by its `messageId` (at-least-once delivery). */
|
|
54
|
+
export interface AckFrame {
|
|
55
|
+
ackedMessageId: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Orderly session termination with an optional human-readable reason. */
|
|
59
|
+
export interface CloseFrame {
|
|
60
|
+
reason?: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A protocol-level error notification (e.g. HELLO rejected) that need not close the socket. */
|
|
64
|
+
export interface ErrorFrame {
|
|
65
|
+
code: string;
|
|
66
|
+
message?: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Self-reported adapter status (spec Models.cs `AdapterStatus`, serialized as a string enum). */
|
|
70
|
+
export type AdapterStatus = 'Online' | 'Offline' | 'Degraded' | 'PermissionDenied';
|
|
71
|
+
|
|
72
|
+
/** Incremental adapter-health payload (a DATA frame with `dataKind:"health"`). */
|
|
73
|
+
export interface AdapterHealthMessage {
|
|
74
|
+
adapterType: string;
|
|
75
|
+
instanceId: string;
|
|
76
|
+
status: AdapterStatus;
|
|
77
|
+
version: string;
|
|
78
|
+
capabilities: string[];
|
|
79
|
+
lastErrorMessage?: string;
|
|
80
|
+
/** ISO-8601 timestamp (.NET `DateTimeOffset?`). */
|
|
81
|
+
timestamp?: string;
|
|
82
|
+
metadata?: Record<string, string>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Incremental discovered-device payload (a DATA frame with `dataKind:"discovered"`). */
|
|
86
|
+
export interface DiscoveredDeviceMessage {
|
|
87
|
+
externalId: string;
|
|
88
|
+
vendor: string;
|
|
89
|
+
productId?: string;
|
|
90
|
+
model?: string;
|
|
91
|
+
friendlyName?: string;
|
|
92
|
+
capabilities?: string[];
|
|
93
|
+
metadata?: Record<string, unknown>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Incremental device-state payload (a DATA frame with `dataKind:"state"`). */
|
|
97
|
+
export interface DeviceStateMessage {
|
|
98
|
+
externalId: string;
|
|
99
|
+
telemetry: Record<string, unknown>;
|
|
100
|
+
signalQuality?: number;
|
|
101
|
+
/** ISO-8601 timestamp (.NET `DateTimeOffset?`). */
|
|
102
|
+
timestamp?: string;
|
|
103
|
+
sequenceNumber?: number;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Server → client control command targeting the adapter. `correlationId` is a GUID string. */
|
|
107
|
+
export interface AdapterCommand {
|
|
108
|
+
commandKind: string;
|
|
109
|
+
correlationId: string;
|
|
110
|
+
payloadJson?: string;
|
|
111
|
+
/** ISO-8601 expiry (.NET `DateTimeOffset?`). */
|
|
112
|
+
expiresAtUtc?: string;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Client → server response to a previously issued command. `correlationId` is a GUID string. */
|
|
116
|
+
export interface AdapterCommandResponse {
|
|
117
|
+
correlationId: string;
|
|
118
|
+
success: boolean;
|
|
119
|
+
errorCode?: string;
|
|
120
|
+
errorMessage?: string;
|
|
121
|
+
payloadJson?: string;
|
|
122
|
+
durationMs?: number;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The full-state bundle a sidecar MUST push after (re)connect and HELLO, before resuming incremental
|
|
126
|
+
* DATA: reconnection is resync, not replay. */
|
|
127
|
+
export interface SnapshotPayload {
|
|
128
|
+
devices: DiscoveredDeviceMessage[];
|
|
129
|
+
states: DeviceStateMessage[];
|
|
130
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { X509Certificate } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
const CERTIFICATE_BLOCK = /-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----/g;
|
|
4
|
+
|
|
5
|
+
export class CaCertificateError extends Error {
|
|
6
|
+
constructor(message: string) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = 'CaCertificateError';
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function readCaCertificates(value: string): string[] {
|
|
13
|
+
const normalized = value.replace(/\\n/g, '\n').replace(/\r/g, '');
|
|
14
|
+
const blocks = [...normalized.matchAll(CERTIFICATE_BLOCK)];
|
|
15
|
+
const remainder = normalized.replace(CERTIFICATE_BLOCK, '').trim();
|
|
16
|
+
|
|
17
|
+
if (blocks.length === 0 || remainder.length > 0) {
|
|
18
|
+
throw new CaCertificateError('REEVE_TRUSTED_CA_CERTIFICATES must contain only PEM certificates');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
return blocks.map((block) => {
|
|
22
|
+
const pem = `-----BEGIN CERTIFICATE-----\n${(block[1] ?? '').replace(/\s+/g, '')}\n-----END CERTIFICATE-----\n`;
|
|
23
|
+
try {
|
|
24
|
+
return new X509Certificate(pem).toString();
|
|
25
|
+
} catch {
|
|
26
|
+
throw new CaCertificateError('REEVE_TRUSTED_CA_CERTIFICATES contains an invalid PEM certificate');
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import * as tls from 'node:tls';
|
|
2
|
+
import { CaCertificateError, readCaCertificates } from './caCertificate.js';
|
|
3
|
+
|
|
4
|
+
export { CaCertificateError, readCaCertificates };
|
|
5
|
+
|
|
6
|
+
export function applyTrustedCaCertificates(value = process.env.REEVE_TRUSTED_CA_CERTIFICATES): void {
|
|
7
|
+
if (value === undefined || value.trim() === '') return;
|
|
8
|
+
|
|
9
|
+
const certificates = readCaCertificates(value);
|
|
10
|
+
const getCertificates = tls.getCACertificates;
|
|
11
|
+
const setCertificates = tls.setDefaultCACertificates;
|
|
12
|
+
if (typeof getCertificates !== 'function' || typeof setCertificates !== 'function') {
|
|
13
|
+
throw new CaCertificateError('Applying REEVE_TRUSTED_CA_CERTIFICATES requires a newer Node.js version');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const defaults = getCertificates.call(tls, 'default');
|
|
17
|
+
setCertificates.call(tls, [...defaults, ...certificates]);
|
|
18
|
+
}
|