The best way to control Claude Code, Codex and more from any computer or phone

main
ts 146 lines 4 KB
Raw
1 // Alchemy modifications are licensed under Apache-2.0.
2 // This file includes third-party code; see /THIRD_PARTY_LICENSES.md.
3 import { ms } from "itty-time";
4 import { DelayFunctionError } from "./retries.ts";
5 import type {
6 WorkflowDelayDuration,
7 WorkflowDelayFunction,
8 WorkflowDynamicDelayContext,
9 } from "cloudflare:workers";
10
11 export const DEFAULT_RETRY_DELAY_MS = 1000;
12
13 export const DELAY_FUNCTION_TIMEOUT_MS = ms("5 seconds");
14
15 type DelayLogger = {
16 warn(...msgs: unknown[]): void;
17 debug(...msgs: unknown[]): void;
18 };
19
20 type Waiter = (ms: number, opts?: { signal?: AbortSignal }) => Promise<void>;
21
22 /**
23 * Signal-aware wrapper around the global `scheduler.wait`.
24 *
25 * Passing `{ signal }` lets workerd cancel the native timer. Without that,
26 * completed waits stay in the isolate's 10,000-timer quota until their original
27 * deadline (issue #15788). An aborted signal resolves the returned promise
28 * rather than rejecting, matching callers that treat abort as "stop waiting".
29 */
30 export function schedulerWait(
31 durationMs: number,
32 opts?: { signal?: AbortSignal }
33 ): Promise<void> {
34 const signal = opts?.signal;
35 if (signal?.aborted) {
36 return Promise.resolve();
37 }
38 const safeDuration = Math.max(0, durationMs);
39 const wait =
40 signal === undefined
41 ? scheduler.wait(safeDuration)
42 : scheduler.wait(safeDuration, { signal });
43 return wait.then(
44 () => undefined,
45 (error: unknown) => {
46 if (signal?.aborted) {
47 return;
48 }
49 throw error;
50 }
51 );
52 }
53
54 type AbortRaceResult<T> = { aborted: true } | { aborted: false; value: T };
55
56 export async function raceAgainstAbort<T>(
57 promise: Promise<T>,
58 signal: AbortSignal
59 ): Promise<AbortRaceResult<T>> {
60 const resultPromise = promise.then(
61 (value): AbortRaceResult<T> => ({
62 aborted: false,
63 value,
64 })
65 );
66 if (signal.aborted) {
67 // Observe a later rejection from the losing promise so it doesn't become
68 // an unhandled rejection after returning the already-aborted result.
69 void resultPromise.catch(() => undefined);
70 return { aborted: true };
71 }
72
73 let resolveAbort: ((result: AbortRaceResult<T>) => void) | undefined;
74 const abortPromise = new Promise<AbortRaceResult<T>>((resolve) => {
75 resolveAbort = resolve;
76 });
77 const onAbort = (): void => resolveAbort?.({ aborted: true });
78 signal.addEventListener("abort", onAbort, { once: true });
79
80 try {
81 return await Promise.race([resultPromise, abortPromise]);
82 } finally {
83 signal.removeEventListener("abort", onAbort);
84 }
85 }
86
87 export async function invokeDelayFunction(
88 delay: WorkflowDelayFunction,
89 input: WorkflowDynamicDelayContext,
90 options: {
91 timeoutMs: number;
92 wait: Waiter;
93 signal?: AbortSignal;
94 logger?: DelayLogger;
95 }
96 ): Promise<WorkflowDelayDuration> {
97 const { wait, signal, logger } = options;
98 const logFields = { step: input.ctx.step.name, attempt: input.ctx.attempt };
99
100 const settled = new AbortController();
101 const timeoutSignal = signal
102 ? AbortSignal.any([signal, settled.signal])
103 : settled.signal;
104
105 type Raced =
106 | { timedOut: true }
107 | { timedOut: false; value: WorkflowDelayDuration };
108
109 try {
110 const result = await Promise.race<Raced>([
111 Promise.resolve(delay(input)).then((value) => ({
112 timedOut: false,
113 value,
114 })),
115 wait(options.timeoutMs, { signal: timeoutSignal })
116 .then((): Raced => ({ timedOut: true }))
117 .catch((): Raced => ({ timedOut: true })),
118 ]);
119 if (result.timedOut) {
120 if (signal?.aborted) {
121 logger?.debug(
122 "delay function aborted by engine shutdown; using default delay",
123 logFields
124 );
125 return DEFAULT_RETRY_DELAY_MS;
126 }
127 logger?.warn(
128 `delay function did not resolve within ${options.timeoutMs}ms`,
129 logFields
130 );
131 throw new DelayFunctionError(
132 `did not return within ${options.timeoutMs / 1000} seconds`
133 );
134 }
135 return result.value;
136 } catch (e) {
137 if (e instanceof DelayFunctionError) {
138 throw e;
139 }
140 const message = e instanceof Error ? e.message : String(e);
141 logger?.warn("delay function threw", { ...logFields, error: message });
142 throw new DelayFunctionError(`threw an error: ${message}`);
143 } finally {
144 settled.abort();
145 }
146 }