@vampgg/utils 1.0.0-beta.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.
@@ -0,0 +1,99 @@
1
+ import { BebopRecord } from "bebop";
2
+ import { BebopContentType, Credential, Deadline, TempoError } from "@tempojs/common";
3
+ import { BaseChannel, CallCredential, CallOptions, ClientContext, MethodInfo, RetryPolicy, TempoChannelOptions } from "@tempojs/client";
4
+
5
+ //#region src/worker-channel.d.ts
6
+ /**
7
+ * Represents a Tempo channel for communication with a worker thread.
8
+ */
9
+ declare class TempoWorkerChannel extends BaseChannel {
10
+ static readonly defaultMaxRetryAttempts: number;
11
+ static readonly defaultCredential: CallCredential;
12
+ static readonly defaultContentType: BebopContentType;
13
+ private readonly _worker;
14
+ private readonly events;
15
+ private readonly userAgent;
16
+ private _open;
17
+ private _ready;
18
+ private _resolveReady?;
19
+ private _rejectReady?;
20
+ readonly pending: Map<string, (e: unknown) => void>;
21
+ private closed;
22
+ get worker(): Bun.Worker;
23
+ get ready(): Promise<void>;
24
+ /**
25
+ * Constructs a new TempoChannel instance.
26
+ *
27
+ * @param {URL} target - The target URL for the channel.
28
+ * @param {TempoChannelOptions} options - The configuration options for the channel.
29
+ * @protected
30
+ */
31
+ constructor(url: string, options?: TempoChannelOptions);
32
+ /**
33
+ * Tear down the channel: reject every in-flight call and a pending `ready`,
34
+ * remove all listeners, and terminate the owned worker. Idempotent.
35
+ */
36
+ close(reason?: TempoError): void;
37
+ removeCredential(): Promise<void>;
38
+ getCredential(): Promise<Credential | undefined>;
39
+ /**
40
+ * Executes a function with retries according to the provided retry policy.
41
+ * The function will be retried if it fails with a TempoError and its status code is included in the retryableStatusCodes of the retry policy.
42
+ * If a deadline is provided, the deadline for each attempt will be managed by the provided deadline, but the deadline will not be reset upon each retry.
43
+ *
44
+ * @template T - The type of the result returned by the function.
45
+ * @param {((retryAttempt: number) => Promise<T>)} func - A function that returns a Promise with a result. The function will receive a number indicating the current retry attempt.
46
+ * @param {RetryPolicy} retryPolicy - An object defining the retry policy, including maxAttempts, initialBackoff, maxBackoff, backoffMultiplier, and retryableStatusCodes.
47
+ * @param {Deadline} [deadline] - An optional deadline object that manages the timeout for each attempt.
48
+ * @param {AbortController} [abortController] - An optional AbortController instance to cancel the function execution.
49
+ * @returns {Promise<T>} - A Promise that resolves with the result of the function if it completes within the deadline and retry policy constraints.
50
+ * @throws {Error} - If the function execution fails and the error does not match the retry policy, or if the maximum number of attempts is reached without a successful result.
51
+ */
52
+ executeWithRetry<T>(func: (retryAttempt: number) => Promise<T>, retryPolicy: RetryPolicy, deadline?: Deadline, abortController?: AbortController): Promise<T>;
53
+ private fetchUnary;
54
+ private fetchClientStream;
55
+ private fetchServerStream;
56
+ private fetchDuplexStream;
57
+ /**
58
+ * Creates a `RequestInit` object for a given payload, context, method and optional call options.
59
+ * This object can be used to make an HTTP request using the Fetch API.
60
+ *
61
+ * @private
62
+ * @param {Uint8Array} payload - The payload to be sent in the request.
63
+ * @param {ClientContext} context - The context of the client making the request.
64
+ * @param {MethodInfo<BebopRecord, BebopRecord>} method - Information about the method being called.
65
+ * @param {CallOptions | undefined} options - Optional configuration for the call.
66
+ * @returns {Promise<RequestInit>} A Promise resolving to the created `RequestInit` object.
67
+ * @throws {TempoError} Throws an error if there's a problem while getting the credential header.
68
+ */
69
+ private createRequest;
70
+ /**
71
+ * Processes the headers of the response from the server, validating their integrity and correctness.
72
+ * Also sets the incoming metadata from the response headers to the provided context.
73
+ *
74
+ * @private
75
+ * @param {Response} response - The response received from the server.
76
+ * @param {ClientContext} context - The context of the client making the request.
77
+ * @param {MethodType} methodType - The type of method being called.
78
+ * @throws {TempoError} Throws an error if any validation checks fail or if there's a problem parsing or storing credentials.
79
+ */
80
+ private processResponseHeaders;
81
+ /**
82
+ * {@inheritDoc BaseChannel.startUnary}
83
+ */
84
+ startUnary<TRequest extends BebopRecord, TResponse extends BebopRecord>(request: TRequest, context: ClientContext, method: MethodInfo<TRequest, TResponse>, options?: CallOptions): Promise<TResponse>;
85
+ /**
86
+ * {@inheritDoc BaseChannel.startClientStream}
87
+ */
88
+ startClientStream<TRequest extends BebopRecord, TResponse extends BebopRecord>(generator: () => AsyncGenerator<TRequest, void, undefined>, context: ClientContext, method: MethodInfo<TRequest, TResponse>, options?: CallOptions): Promise<TResponse>;
89
+ /**
90
+ * {@inheritDoc BaseChannel.startServerStream}
91
+ */
92
+ startServerStream<TRequest extends BebopRecord, TResponse extends BebopRecord>(request: TRequest, context: ClientContext, method: MethodInfo<TRequest, TResponse>, options?: CallOptions): Promise<AsyncGenerator<TResponse, void, undefined>>;
93
+ /**
94
+ * {@inheritDoc BaseChannel.startDuplexStream}
95
+ */
96
+ startDuplexStream<TRequest extends BebopRecord, TResponse extends BebopRecord>(generator: () => AsyncGenerator<TRequest, void, undefined>, context: ClientContext, method: MethodInfo<TRequest, TResponse>, options?: CallOptions): Promise<AsyncGenerator<TResponse, void, undefined>>;
97
+ }
98
+ //#endregion
99
+ export { TempoWorkerChannel };
@@ -0,0 +1,419 @@
1
+ import { Message } from "./bebop.mjs";
2
+ import { createEventIterator } from "./create-event-iterator.mjs";
3
+ import { createDuplexIterator } from "./create-duplex-iterator.mjs";
4
+ import { ConsoleLogger, ExecutionEnvironment, Metadata, TempoError, TempoStatusCode, TempoUtil, TempoVersion } from "@tempojs/common";
5
+ import { BaseChannel, InsecureChannelCredential } from "@tempojs/client";
6
+ import { EventEmitter } from "tseep";
7
+ //#region src/worker-channel.ts
8
+ /**
9
+ * Represents a Tempo channel for communication with a worker thread.
10
+ */
11
+ var TempoWorkerChannel = class TempoWorkerChannel extends BaseChannel {
12
+ static defaultMaxRetryAttempts = 5;
13
+ static defaultCredential = InsecureChannelCredential.create();
14
+ static defaultContentType = "bebop";
15
+ _worker;
16
+ events = new EventEmitter();
17
+ userAgent;
18
+ _open = false;
19
+ _ready;
20
+ _resolveReady;
21
+ _rejectReady;
22
+ pending = /* @__PURE__ */ new Map();
23
+ closed = false;
24
+ get worker() {
25
+ return this._worker;
26
+ }
27
+ get ready() {
28
+ return this._ready;
29
+ }
30
+ /**
31
+ * Constructs a new TempoChannel instance.
32
+ *
33
+ * @param {URL} target - The target URL for the channel.
34
+ * @param {TempoChannelOptions} options - The configuration options for the channel.
35
+ * @protected
36
+ */
37
+ constructor(url, options = {}) {
38
+ super(new URL(url, "worker://"), options.logger ?? new ConsoleLogger("TempoWorkerChannel"), options.contentType ?? TempoWorkerChannel.defaultContentType);
39
+ this.logger.trace("creating new TempoWorkerChannel");
40
+ this.userAgent = TempoUtil.buildUserAgent("javascript", TempoVersion, void 0, { runtime: TempoUtil.getEnvironmentName() });
41
+ this._ready = new Promise((resolve, reject) => {
42
+ this._resolveReady = resolve;
43
+ this._rejectReady = reject;
44
+ });
45
+ this._ready.catch(() => {});
46
+ const worker = this._worker = new Worker(url);
47
+ worker.addEventListener("message", (ev) => {
48
+ const resolveReadyOnce = () => {
49
+ if (!this._open) {
50
+ this._open = true;
51
+ this._resolveReady?.();
52
+ }
53
+ };
54
+ if (!ev.data.length) {
55
+ resolveReadyOnce();
56
+ return;
57
+ }
58
+ const message = Message.decode(ev.data);
59
+ if (message.messageId === "__ready__") {
60
+ resolveReadyOnce();
61
+ return;
62
+ }
63
+ resolveReadyOnce();
64
+ if (!message.methodId) {
65
+ this.logger.trace("ignoring control frame without methodId");
66
+ return;
67
+ }
68
+ const messageId = message.messageId;
69
+ this.logger.trace(`received new message ${messageId}`);
70
+ this.events.emit(messageId, message);
71
+ });
72
+ worker.addEventListener("open", (e) => {
73
+ this.logger.trace(`opened TempoWorkerChannel for ${url} / ${this.userAgent}`, { event: e });
74
+ });
75
+ worker.addEventListener("close", (e) => {
76
+ this.logger.trace(`closed TempoWorkerChannel for ${url} / ${this.userAgent}`, { event: e });
77
+ this.close(new TempoError(TempoStatusCode.UNAVAILABLE, "channel closed"));
78
+ });
79
+ worker.addEventListener("error", () => {
80
+ this.close(new TempoError(TempoStatusCode.UNAVAILABLE, "channel transport error"));
81
+ });
82
+ this.logger.debug(`created new TempoWorkerChannel`);
83
+ }
84
+ /**
85
+ * Tear down the channel: reject every in-flight call and a pending `ready`,
86
+ * remove all listeners, and terminate the owned worker. Idempotent.
87
+ */
88
+ close(reason) {
89
+ if (this.closed) return;
90
+ this.closed = true;
91
+ const err = reason ?? new TempoError(TempoStatusCode.CANCELLED, "channel disposed");
92
+ this._rejectReady?.(err);
93
+ for (const reject of this.pending.values()) reject(err);
94
+ this.pending.clear();
95
+ this.events.removeAllListeners();
96
+ try {
97
+ this._worker.terminate();
98
+ } catch {}
99
+ }
100
+ async removeCredential() {}
101
+ async getCredential() {}
102
+ /**
103
+ * Executes a function with retries according to the provided retry policy.
104
+ * The function will be retried if it fails with a TempoError and its status code is included in the retryableStatusCodes of the retry policy.
105
+ * If a deadline is provided, the deadline for each attempt will be managed by the provided deadline, but the deadline will not be reset upon each retry.
106
+ *
107
+ * @template T - The type of the result returned by the function.
108
+ * @param {((retryAttempt: number) => Promise<T>)} func - A function that returns a Promise with a result. The function will receive a number indicating the current retry attempt.
109
+ * @param {RetryPolicy} retryPolicy - An object defining the retry policy, including maxAttempts, initialBackoff, maxBackoff, backoffMultiplier, and retryableStatusCodes.
110
+ * @param {Deadline} [deadline] - An optional deadline object that manages the timeout for each attempt.
111
+ * @param {AbortController} [abortController] - An optional AbortController instance to cancel the function execution.
112
+ * @returns {Promise<T>} - A Promise that resolves with the result of the function if it completes within the deadline and retry policy constraints.
113
+ * @throws {Error} - If the function execution fails and the error does not match the retry policy, or if the maximum number of attempts is reached without a successful result.
114
+ */
115
+ async executeWithRetry(func, retryPolicy, deadline, abortController) {
116
+ let attempt = 0;
117
+ let lastError;
118
+ const execute = deadline ? (retryAttempt) => deadline.executeWithinDeadline(async () => await func(retryAttempt), abortController) : (retryAttempt) => func(retryAttempt);
119
+ while (attempt < retryPolicy.maxAttempts) try {
120
+ return await execute(attempt);
121
+ } catch (error) {
122
+ if (!(error instanceof Error)) throw new TempoError(TempoStatusCode.UNKNOWN, `unexpected error`, { data: error });
123
+ lastError = error;
124
+ if (!(error instanceof TempoError) || !retryPolicy.retryableStatusCodes.includes(error.status)) throw error;
125
+ const backoffWithJitter = Math.min(retryPolicy.initialBackoff.multiply(Math.pow(retryPolicy.backoffMultiplier, attempt)).totalMilliseconds, retryPolicy.maxBackoff.totalMilliseconds) * (Math.random() * .5 + .75);
126
+ await new Promise((resolve) => setTimeout(resolve, backoffWithJitter));
127
+ attempt++;
128
+ }
129
+ if (abortController && lastError !== void 0 && !(lastError instanceof Error && lastError.name === "AbortError") && !(lastError instanceof TempoError && lastError.status === TempoStatusCode.ABORTED)) abortController.abort();
130
+ return Promise.reject(lastError || new TempoError(TempoStatusCode.DEADLINE_EXCEEDED, "Failed to execute function with retry policy"));
131
+ }
132
+ async fetchUnary(init, options) {
133
+ const messageId = init.messageId;
134
+ let listener;
135
+ let onAbort;
136
+ const cleanup = () => {
137
+ this.events.off(messageId, listener);
138
+ if (onAbort) options?.controller?.signal.removeEventListener("abort", onAbort);
139
+ this.pending.delete(messageId);
140
+ };
141
+ return await new Promise((resolve, reject) => {
142
+ listener = (message) => resolve(message);
143
+ this.pending.set(messageId, reject);
144
+ if (options?.controller) {
145
+ onAbort = () => reject(new TempoError(TempoStatusCode.ABORTED, "RPC fetch aborted", {}));
146
+ options.controller.signal.addEventListener("abort", onAbort, { once: true });
147
+ }
148
+ this.events.on(messageId, listener);
149
+ const frame = Message.encode(init).slice();
150
+ this.worker.postMessage(frame, [frame.buffer]);
151
+ }).finally(cleanup);
152
+ }
153
+ async fetchClientStream(init, method, generator, options) {
154
+ const messageId = init.messageId;
155
+ let listener;
156
+ let onAbort;
157
+ const cleanup = () => {
158
+ this.events.off(messageId, listener);
159
+ if (onAbort) options?.controller?.signal.removeEventListener("abort", onAbort);
160
+ this.pending.delete(messageId);
161
+ };
162
+ return await new Promise((resolve, reject) => {
163
+ listener = (message) => resolve(message);
164
+ this.pending.set(messageId, reject);
165
+ if (options?.controller) {
166
+ onAbort = () => reject(new TempoError(TempoStatusCode.ABORTED, "RPC fetch aborted", {}));
167
+ options.controller.signal.addEventListener("abort", onAbort, { once: true });
168
+ }
169
+ this.events.on(messageId, listener);
170
+ runGenerator.call(this).catch(reject);
171
+ async function runGenerator() {
172
+ for await (const value of generator()) {
173
+ const frame = Message.encode(Message({
174
+ ...init,
175
+ data: new Uint8Array(value.encode())
176
+ })).slice();
177
+ this.worker.postMessage(frame, [frame.buffer]);
178
+ }
179
+ const frame = Message.encode(Message({
180
+ ...init,
181
+ status: TempoStatusCode.CANCELLED,
182
+ data: new Uint8Array()
183
+ })).slice();
184
+ this.worker.postMessage(frame, [frame.buffer]);
185
+ }
186
+ }).finally(cleanup);
187
+ }
188
+ fetchServerStream(init, context, method, options) {
189
+ const messageId = init.messageId;
190
+ return createEventIterator(({ emit, cancel, error }) => {
191
+ let terminated = false;
192
+ let onAbort;
193
+ const eventHandler = async (message) => {
194
+ try {
195
+ if (message.status === TempoStatusCode.CANCELLED) {
196
+ terminated = true;
197
+ cancel();
198
+ return;
199
+ }
200
+ this.processResponseHeaders(message, context, method.type);
201
+ const requestData = message.data;
202
+ const record = method.deserialize(requestData);
203
+ if (this.hooks !== void 0) await this.hooks.executeDecodeHooks(context, record);
204
+ emit(record);
205
+ } catch (e) {
206
+ error(e);
207
+ }
208
+ };
209
+ if (options?.controller) {
210
+ onAbort = () => error(new TempoError(TempoStatusCode.ABORTED, "RPC fetch aborted", {}));
211
+ options.controller.signal.addEventListener("abort", onAbort, { once: true });
212
+ }
213
+ this.events.on(messageId, eventHandler);
214
+ const frame = Message.encode(init).slice();
215
+ this.worker.postMessage(frame, [frame.buffer]);
216
+ return () => {
217
+ this.events.off(messageId, eventHandler);
218
+ if (onAbort) options?.controller?.signal.removeEventListener("abort", onAbort);
219
+ if (terminated || this.closed) return;
220
+ const cancelMessage = {
221
+ messageId,
222
+ methodId: init.methodId,
223
+ status: TempoStatusCode.CANCELLED,
224
+ data: new Uint8Array(),
225
+ timestamp: /* @__PURE__ */ new Date()
226
+ };
227
+ const cancelFrame = Message.encode(cancelMessage).slice();
228
+ this.worker.postMessage(cancelFrame, [cancelFrame.buffer]);
229
+ };
230
+ });
231
+ }
232
+ fetchDuplexStream(init, context, method, generator, options) {
233
+ const messageId = init.messageId;
234
+ return createDuplexIterator(generator(), (value) => {
235
+ const frame = Message.encode(Message({
236
+ ...init,
237
+ data: new Uint8Array(method.serialize(value))
238
+ })).slice();
239
+ this.worker.postMessage(frame, [frame.buffer]);
240
+ }, ({ emit, cancel, error }) => {
241
+ let onAbort;
242
+ const eventHandler = async (message) => {
243
+ try {
244
+ if (message.status === TempoStatusCode.CANCELLED) {
245
+ cancel();
246
+ return;
247
+ }
248
+ this.processResponseHeaders(message, context, method.type);
249
+ const requestData = message.data;
250
+ const record = method.deserialize(requestData);
251
+ if (this.hooks !== void 0) await this.hooks.executeDecodeHooks(context, record);
252
+ emit(record);
253
+ } catch (e) {
254
+ error(e);
255
+ }
256
+ };
257
+ if (options?.controller) {
258
+ onAbort = () => error(new TempoError(TempoStatusCode.ABORTED, "RPC fetch aborted", {}));
259
+ options.controller.signal.addEventListener("abort", onAbort, { once: true });
260
+ }
261
+ this.events.on(messageId, eventHandler);
262
+ return () => {
263
+ this.events.off(messageId, eventHandler);
264
+ if (onAbort) options?.controller?.signal.removeEventListener("abort", onAbort);
265
+ };
266
+ });
267
+ }
268
+ /**
269
+ * Creates a `RequestInit` object for a given payload, context, method and optional call options.
270
+ * This object can be used to make an HTTP request using the Fetch API.
271
+ *
272
+ * @private
273
+ * @param {Uint8Array} payload - The payload to be sent in the request.
274
+ * @param {ClientContext} context - The context of the client making the request.
275
+ * @param {MethodInfo<BebopRecord, BebopRecord>} method - Information about the method being called.
276
+ * @param {CallOptions | undefined} options - Optional configuration for the call.
277
+ * @returns {Promise<RequestInit>} A Promise resolving to the created `RequestInit` object.
278
+ * @throws {TempoError} Throws an error if there's a problem while getting the credential header.
279
+ */
280
+ createRequest(payload, _context, method, options) {
281
+ const customMetadata = new Metadata();
282
+ customMetadata.set("path", `/${method.service}/${method.name}`);
283
+ customMetadata.set("service-name", method.service);
284
+ if (ExecutionEnvironment.isBrowser || ExecutionEnvironment.isWebWorker) customMetadata.set("x-user-agent", this.userAgent);
285
+ else customMetadata.set("user-agent", this.userAgent);
286
+ const requestInit = {
287
+ messageId: Bun.randomUUIDv7(),
288
+ methodId: method.id,
289
+ data: new Uint8Array(payload),
290
+ timestamp: /* @__PURE__ */ new Date()
291
+ };
292
+ if (options?.deadline) requestInit.deadline = new Date(options.deadline.toUnixTimestamp());
293
+ return requestInit;
294
+ }
295
+ /**
296
+ * Processes the headers of the response from the server, validating their integrity and correctness.
297
+ * Also sets the incoming metadata from the response headers to the provided context.
298
+ *
299
+ * @private
300
+ * @param {Response} response - The response received from the server.
301
+ * @param {ClientContext} context - The context of the client making the request.
302
+ * @param {MethodType} methodType - The type of method being called.
303
+ * @throws {TempoError} Throws an error if any validation checks fail or if there's a problem parsing or storing credentials.
304
+ */
305
+ processResponseHeaders(response, _context, _methodType) {
306
+ const statusCode = response.status;
307
+ if (statusCode === void 0) throw new TempoError(TempoStatusCode.UNKNOWN, "tempo-status missing from response.");
308
+ if (statusCode !== TempoStatusCode.OK && statusCode !== TempoStatusCode.CANCELLED) {
309
+ let tempoMessage = response.msg;
310
+ if (!tempoMessage) tempoMessage = "unknown error";
311
+ throw new TempoError(statusCode, tempoMessage);
312
+ }
313
+ }
314
+ /**
315
+ * {@inheritDoc BaseChannel.startUnary}
316
+ */
317
+ async startUnary(request, context, method, options) {
318
+ try {
319
+ const requestData = request.encode();
320
+ if (this.hooks !== void 0) await this.hooks.executeRequestHooks(context);
321
+ const requestInit = this.createRequest(requestData, context, method, options);
322
+ let response;
323
+ if (options?.retryPolicy) response = await this.executeWithRetry(async (retryAttempt) => {
324
+ if (retryAttempt > 0) requestInit.previousAttempts = retryAttempt;
325
+ return await this.fetchUnary(requestInit);
326
+ }, options.retryPolicy, options.deadline, options.controller);
327
+ else if (options?.deadline) response = await options.deadline.executeWithinDeadline(async () => {
328
+ return await this.fetchUnary(requestInit, options);
329
+ }, options.controller);
330
+ else response = await this.fetchUnary(requestInit, options);
331
+ this.processResponseHeaders(response, context, method.type);
332
+ if (this.hooks !== void 0) await this.hooks.executeResponseHooks(context);
333
+ const responseData = response.data;
334
+ const record = method.deserialize(responseData);
335
+ if (this.hooks !== void 0) await this.hooks.executeDecodeHooks(context, record);
336
+ return record;
337
+ } catch (e) {
338
+ if (this.hooks !== void 0 && e instanceof Error) await this.hooks.executeErrorHooks(context, e);
339
+ if (e instanceof TempoError) throw e;
340
+ if (e instanceof Error) if (e.name === "AbortError") throw new TempoError(TempoStatusCode.ABORTED, "RPC fetch aborted", e);
341
+ else throw new TempoError(TempoStatusCode.UNKNOWN, "an unknown error occurred", e);
342
+ throw new TempoError(TempoStatusCode.UNKNOWN, "an unknown error occurred", { data: e });
343
+ }
344
+ }
345
+ /**
346
+ * {@inheritDoc BaseChannel.startClientStream}
347
+ */
348
+ async startClientStream(generator, context, method, options) {
349
+ try {
350
+ if (this.hooks !== void 0) await this.hooks.executeRequestHooks(context);
351
+ const requestInit = this.createRequest(new Uint8Array(), context, method, options);
352
+ let response;
353
+ if (options?.deadline) response = await options.deadline.executeWithinDeadline(async () => {
354
+ return await this.fetchClientStream(requestInit, method, generator, options);
355
+ }, options.controller);
356
+ else response = await this.fetchClientStream(requestInit, method, generator, options);
357
+ this.processResponseHeaders(response, context, method.type);
358
+ const responseData = response.data;
359
+ const record = this.deserializeResponse(responseData, method);
360
+ if (this.hooks !== void 0) await this.hooks.executeDecodeHooks(context, record);
361
+ return record;
362
+ } catch (e) {
363
+ if (this.hooks !== void 0 && e instanceof Error) await this.hooks.executeErrorHooks(context, e);
364
+ if (e instanceof TempoError) throw e;
365
+ if (e instanceof Error) if (e.name === "AbortError") throw new TempoError(TempoStatusCode.ABORTED, "RPC fetch aborted", e);
366
+ else throw new TempoError(TempoStatusCode.UNKNOWN, "an unknown error occurred", e);
367
+ throw new TempoError(TempoStatusCode.UNKNOWN, "an unknown error occurred", { data: e });
368
+ }
369
+ }
370
+ /**
371
+ * {@inheritDoc BaseChannel.startServerStream}
372
+ */
373
+ async startServerStream(request, context, method, options) {
374
+ try {
375
+ const requestData = request.encode();
376
+ if (this.hooks !== void 0) await this.hooks.executeRequestHooks(context);
377
+ const requestInit = this.createRequest(requestData, context, method, options);
378
+ let response;
379
+ if (options?.retryPolicy) response = await this.executeWithRetry(async (retryAttempt) => {
380
+ if (retryAttempt > 0) requestInit.previousAttempts = retryAttempt;
381
+ return this.fetchServerStream(requestInit, context, method, options);
382
+ }, options.retryPolicy, options.deadline, options.controller);
383
+ else if (options?.deadline) response = await options.deadline.executeWithinDeadline(async () => {
384
+ return this.fetchServerStream(requestInit, context, method, options);
385
+ }, options.controller);
386
+ else response = this.fetchServerStream(requestInit, context, method, options);
387
+ return response;
388
+ } catch (e) {
389
+ if (this.hooks !== void 0 && e instanceof Error) await this.hooks.executeErrorHooks(context, e);
390
+ if (e instanceof TempoError) throw e;
391
+ if (e instanceof Error) if (e.name === "AbortError") throw new TempoError(TempoStatusCode.ABORTED, "RPC fetch aborted", e);
392
+ else throw new TempoError(TempoStatusCode.UNKNOWN, "an unknown error occurred", e);
393
+ throw new TempoError(TempoStatusCode.UNKNOWN, "an unknown error occurred", { data: e });
394
+ }
395
+ }
396
+ /**
397
+ * {@inheritDoc BaseChannel.startDuplexStream}
398
+ */
399
+ async startDuplexStream(generator, context, method, options) {
400
+ try {
401
+ if (this.hooks !== void 0) await this.hooks.executeRequestHooks(context);
402
+ const requestInit = this.createRequest(new Uint8Array(), context, method, options);
403
+ let response;
404
+ if (options?.deadline) response = await options.deadline.executeWithinDeadline(async () => {
405
+ return this.fetchDuplexStream(requestInit, context, method, generator, options);
406
+ }, options.controller);
407
+ else response = this.fetchDuplexStream(requestInit, context, method, generator, options);
408
+ return response;
409
+ } catch (e) {
410
+ if (this.hooks !== void 0 && e instanceof Error) await this.hooks.executeErrorHooks(context, e);
411
+ if (e instanceof TempoError) throw e;
412
+ if (e instanceof Error) if (e.name === "AbortError") throw new TempoError(TempoStatusCode.ABORTED, "RPC fetch aborted", e);
413
+ else throw new TempoError(TempoStatusCode.UNKNOWN, "an unknown error occurred", e);
414
+ throw new TempoError(TempoStatusCode.UNKNOWN, "an unknown error occurred", { data: e });
415
+ }
416
+ }
417
+ };
418
+ //#endregion
419
+ export { TempoWorkerChannel };
@@ -0,0 +1,26 @@
1
+ import { Message } from "./bebop.mjs";
2
+ import { TempoLogger } from "@tempojs/common";
3
+ import { AuthInterceptor, BaseRouter, ServiceRegistry, TempoRouterConfiguration } from "@tempojs/server";
4
+
5
+ //#region src/worker-router.d.ts
6
+ declare class TempoWorkerRouter<TEnv> extends BaseRouter<Buffer, TEnv, Message> {
7
+ private readonly events;
8
+ private readonly clientStreams;
9
+ private readonly serverStreams;
10
+ constructor(logger: TempoLogger, registry: ServiceRegistry, configuration?: TempoRouterConfiguration, authInterceptor?: AuthInterceptor);
11
+ private setAuthContext;
12
+ private invokeUnaryMethod;
13
+ private invokeClientStreamMethod;
14
+ private invokeServerStreamMethod;
15
+ private invokeDuplexStreamMethod;
16
+ /**
17
+ * Tear down all open streams for this connection (driven by the host
18
+ * close/error lifecycle). Returns each server-stream generator and emits a
19
+ * synthetic CANCELLED to each client/duplex stream, then clears listeners.
20
+ */
21
+ closeConnection(): Promise<void>;
22
+ process(req: Uint8Array, response: Message, env: TEnv): Promise<void>;
23
+ handle(_request: string | Buffer, _env: TEnv): Promise<Message>;
24
+ }
25
+ //#endregion
26
+ export { TempoWorkerRouter };