spool-sdk 0.0.0-stage → 0.2.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 +202 -0
- package/README.md +149 -2
- package/dist/backoff.d.ts +15 -0
- package/dist/backoff.js +51 -0
- package/dist/backoff.js.map +1 -0
- package/dist/channel.d.ts +13 -0
- package/dist/channel.js +46 -0
- package/dist/channel.js.map +1 -0
- package/dist/context.d.ts +221 -0
- package/dist/context.js +331 -0
- package/dist/context.js.map +1 -0
- package/dist/duration.d.ts +22 -0
- package/dist/duration.js +39 -0
- package/dist/duration.js.map +1 -0
- package/dist/errors.d.ts +115 -0
- package/dist/errors.js +143 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/json.d.ts +8 -0
- package/dist/json.js +24 -0
- package/dist/json.js.map +1 -0
- package/dist/logger.d.ts +9 -0
- package/dist/logger.js +12 -0
- package/dist/logger.js.map +1 -0
- package/dist/proto/workers_pb.d.ts +900 -0
- package/dist/proto/workers_pb.js +168 -0
- package/dist/worker.d.ts +51 -0
- package/dist/worker.js +543 -0
- package/dist/worker.js.map +1 -0
- package/dist/workflow.d.ts +13 -0
- package/dist/workflow.js +10 -0
- package/dist/workflow.js.map +1 -0
- package/package.json +49 -3
- package/src/backoff.ts +66 -0
- package/src/channel.ts +45 -0
- package/src/context.ts +604 -0
- package/src/duration.ts +50 -0
- package/src/errors.ts +164 -0
- package/src/index.ts +26 -0
- package/src/json.ts +23 -0
- package/src/logger.ts +19 -0
- package/src/worker.ts +658 -0
- package/src/workflow.ts +20 -0
package/src/worker.ts
ADDED
|
@@ -0,0 +1,658 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { hostname } from "node:os";
|
|
3
|
+
import { create, fromJson, toJson, type MessageInitShape } from "@bufbuild/protobuf";
|
|
4
|
+
import { ValueSchema } from "@bufbuild/protobuf/wkt";
|
|
5
|
+
import { createClient, type Transport } from "@connectrpc/connect";
|
|
6
|
+
import { createConnectTransport } from "@connectrpc/connect-node";
|
|
7
|
+
import {
|
|
8
|
+
ConnectRequestSchema,
|
|
9
|
+
WorkerService,
|
|
10
|
+
type Ack,
|
|
11
|
+
type ClaimedTask,
|
|
12
|
+
type ConnectRequest,
|
|
13
|
+
type ConnectResponse,
|
|
14
|
+
type Failure,
|
|
15
|
+
} from "@spool/proto/spool/v1/workers_pb";
|
|
16
|
+
import { abortable, backoffDelay, sleep, type BackoffPolicy } from "./backoff.js";
|
|
17
|
+
import { Channel } from "./channel.js";
|
|
18
|
+
import {
|
|
19
|
+
DEFAULT_MAX_ATTEMPTS,
|
|
20
|
+
describe,
|
|
21
|
+
RunContext,
|
|
22
|
+
type RecordedStep,
|
|
23
|
+
type StepFailure,
|
|
24
|
+
} from "./context.js";
|
|
25
|
+
import {
|
|
26
|
+
DisconnectedError,
|
|
27
|
+
LeaseLostError,
|
|
28
|
+
NonRetryableError,
|
|
29
|
+
RequestFailedError,
|
|
30
|
+
RunSleepingError,
|
|
31
|
+
RunThrottledError,
|
|
32
|
+
RunWaitingError,
|
|
33
|
+
StepFailedError,
|
|
34
|
+
StepMismatchError,
|
|
35
|
+
WorkerStoppedError,
|
|
36
|
+
isRunStop,
|
|
37
|
+
} from "./errors.js";
|
|
38
|
+
import { toStoredJson } from "./json.js";
|
|
39
|
+
import { consoleLogger, type Logger } from "./logger.js";
|
|
40
|
+
import type { Workflow } from "./workflow.js";
|
|
41
|
+
|
|
42
|
+
type RequestInit = MessageInitShape<typeof ConnectRequestSchema>;
|
|
43
|
+
type RequestKind = NonNullable<RequestInit["kind"]>;
|
|
44
|
+
type Reply = Extract<ConnectResponse["kind"], { case: "ack" | "failure" | "heartbeatAck" }>;
|
|
45
|
+
|
|
46
|
+
/** The engine renews at most this many leases per heartbeat. */
|
|
47
|
+
const MAX_CONCURRENCY = 1000;
|
|
48
|
+
/** The step name a failure thrown outside any step is recorded under. */
|
|
49
|
+
const OUTSIDE_A_STEP = "(outside a step)";
|
|
50
|
+
/** After a half-close, how long the engine gets to end the stream before it is cut. */
|
|
51
|
+
const CLOSE_GRACE_MS = 5000;
|
|
52
|
+
|
|
53
|
+
interface WorkerSettings {
|
|
54
|
+
/** The workflows this worker runs. Names must be unique. */
|
|
55
|
+
readonly workflows: readonly Workflow<never>[];
|
|
56
|
+
/** Runs at once; the engine never sends more. Default 10. */
|
|
57
|
+
readonly concurrency?: number;
|
|
58
|
+
/** Default "default". */
|
|
59
|
+
readonly queue?: string;
|
|
60
|
+
/** Who holds the leases; stable across reconnects. Default: host, pid and a random suffix. */
|
|
61
|
+
readonly workerId?: string;
|
|
62
|
+
readonly logger?: Logger;
|
|
63
|
+
/** Delays between reconnects and between resends of a request. */
|
|
64
|
+
readonly backoff?: Partial<BackoffPolicy>;
|
|
65
|
+
/** How long stop() lets running runs finish before abandoning them. Default 30 s. */
|
|
66
|
+
readonly drainTimeoutMs?: number;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export type WorkerOptions = WorkerSettings &
|
|
70
|
+
(
|
|
71
|
+
| { readonly url: string; readonly apiKey: string }
|
|
72
|
+
/** A ready-made transport, for custom TLS, interceptors or tests. Needs HTTP/2. */
|
|
73
|
+
| { readonly transport: Transport }
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
interface ActiveRun {
|
|
77
|
+
readonly taskId: bigint;
|
|
78
|
+
readonly attempt: number;
|
|
79
|
+
readonly controller: AbortController;
|
|
80
|
+
/** Requests for this run awaiting the engine's reply; see #heartbeat. */
|
|
81
|
+
inFlight: number;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** One stream to the engine. Replies are matched to requests by id. */
|
|
85
|
+
class Connection {
|
|
86
|
+
readonly requests = new Channel<ConnectRequest>();
|
|
87
|
+
readonly abort = new AbortController();
|
|
88
|
+
readonly #pending = new Map<bigint, (reply: Reply | DisconnectedError) => void>();
|
|
89
|
+
#open = true;
|
|
90
|
+
#heartbeat: NodeJS.Timeout | undefined;
|
|
91
|
+
#heartbeatInFlight = false;
|
|
92
|
+
isReady = false;
|
|
93
|
+
|
|
94
|
+
send(request: RequestInit): void {
|
|
95
|
+
this.requests.push(create(ConnectRequestSchema, request));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Resolves with the ack or failure; rejects with DisconnectedError if the stream ends first. */
|
|
99
|
+
request(requestId: bigint, kind: RequestKind): Promise<Reply> {
|
|
100
|
+
if (!this.#open) return Promise.reject(new DisconnectedError());
|
|
101
|
+
return new Promise((resolve, reject) => {
|
|
102
|
+
this.#pending.set(requestId, (reply) => {
|
|
103
|
+
if (reply instanceof DisconnectedError) reject(reply);
|
|
104
|
+
else resolve(reply);
|
|
105
|
+
});
|
|
106
|
+
this.send({ kind });
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
settle(reply: Reply): void {
|
|
111
|
+
const waiter = this.#pending.get(reply.value.requestId);
|
|
112
|
+
this.#pending.delete(reply.value.requestId);
|
|
113
|
+
waiter?.(reply);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
startHeartbeat(intervalMs: number, beat: () => Promise<void>): void {
|
|
117
|
+
this.#heartbeat = setInterval(() => {
|
|
118
|
+
// A slow engine must not pile up heartbeats; the next tick tries again.
|
|
119
|
+
if (this.#heartbeatInFlight) return;
|
|
120
|
+
this.#heartbeatInFlight = true;
|
|
121
|
+
void beat().finally(() => {
|
|
122
|
+
this.#heartbeatInFlight = false;
|
|
123
|
+
});
|
|
124
|
+
}, intervalMs);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The worker sends nothing more; the engine ends the stream once it has answered. */
|
|
128
|
+
finish(): void {
|
|
129
|
+
this.requests.close();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
close(): void {
|
|
133
|
+
this.#open = false;
|
|
134
|
+
clearInterval(this.#heartbeat);
|
|
135
|
+
this.requests.close();
|
|
136
|
+
for (const waiter of this.#pending.values()) waiter(new DisconnectedError());
|
|
137
|
+
this.#pending.clear();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Runs workflows for the engine. It keeps one stream open, reconnecting with backoff when
|
|
143
|
+
* it drops, and pulls as many tasks as it has free slots. Each task runs its workflow
|
|
144
|
+
* from the top, with recorded steps answered from the journal. Heartbeats renew the leases
|
|
145
|
+
* of running runs; a run whose lease is lost is stopped before its next step.
|
|
146
|
+
*
|
|
147
|
+
* Execution is at least once: a step whose report never reached the engine runs again on
|
|
148
|
+
* the next attempt. Give side effects an idempotency key.
|
|
149
|
+
*/
|
|
150
|
+
export class Worker {
|
|
151
|
+
readonly workerId: string;
|
|
152
|
+
readonly #workflows: ReadonlyMap<string, Workflow<never>>;
|
|
153
|
+
readonly #transport: Transport;
|
|
154
|
+
readonly #concurrency: number;
|
|
155
|
+
readonly #queue: string;
|
|
156
|
+
readonly #logger: Logger;
|
|
157
|
+
readonly #backoff: BackoffPolicy;
|
|
158
|
+
readonly #drainTimeoutMs: number;
|
|
159
|
+
readonly #runs = new Map<bigint, ActiveRun>();
|
|
160
|
+
/** Aborted once the worker has stopped for good: no reconnects, no new runs. */
|
|
161
|
+
readonly #closed = new AbortController();
|
|
162
|
+
#connection: Connection | undefined;
|
|
163
|
+
#connectionChanged = Promise.withResolvers<undefined>();
|
|
164
|
+
#runFinished = Promise.withResolvers<undefined>();
|
|
165
|
+
#draining = false;
|
|
166
|
+
#loop: Promise<void> | undefined;
|
|
167
|
+
#nextRequestId = 1n;
|
|
168
|
+
|
|
169
|
+
constructor(options: WorkerOptions) {
|
|
170
|
+
const names = options.workflows.map((w) => w.name);
|
|
171
|
+
if (names.length === 0) throw new Error("a worker needs at least one workflow");
|
|
172
|
+
if (new Set(names).size !== names.length) throw new Error("workflow names must be unique");
|
|
173
|
+
const concurrency = options.concurrency ?? 10;
|
|
174
|
+
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
|
|
175
|
+
throw new Error(`concurrency must be an integer from 1 to ${String(MAX_CONCURRENCY)}`);
|
|
176
|
+
}
|
|
177
|
+
this.#workflows = new Map(options.workflows.map((w) => [w.name, w]));
|
|
178
|
+
this.#transport =
|
|
179
|
+
"transport" in options
|
|
180
|
+
? options.transport
|
|
181
|
+
: createConnectTransport({
|
|
182
|
+
baseUrl: options.url,
|
|
183
|
+
httpVersion: "2",
|
|
184
|
+
useBinaryFormat: true,
|
|
185
|
+
interceptors: [
|
|
186
|
+
(next) => (request) => {
|
|
187
|
+
request.header.set("authorization", `Bearer ${options.apiKey}`);
|
|
188
|
+
return next(request);
|
|
189
|
+
},
|
|
190
|
+
],
|
|
191
|
+
});
|
|
192
|
+
this.#concurrency = concurrency;
|
|
193
|
+
this.#queue = options.queue ?? "default";
|
|
194
|
+
this.workerId =
|
|
195
|
+
options.workerId ?? `${hostname()}-${String(process.pid)}-${randomUUID().slice(0, 8)}`;
|
|
196
|
+
this.#logger = options.logger ?? consoleLogger;
|
|
197
|
+
this.#backoff = { baseMs: 100, capMs: 5000, ...options.backoff };
|
|
198
|
+
this.#drainTimeoutMs = options.drainTimeoutMs ?? 30_000;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Connects and starts taking work. Returns at once; the worker runs until stop(). */
|
|
202
|
+
start(): void {
|
|
203
|
+
if (this.#loop !== undefined) throw new Error("the worker was already started");
|
|
204
|
+
this.#loop = this.#connectLoop();
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Stops taking work, lets running runs finish (up to drainTimeoutMs, after which they are
|
|
209
|
+
* abandoned and their leases expire), then closes the stream.
|
|
210
|
+
*/
|
|
211
|
+
async stop(): Promise<void> {
|
|
212
|
+
const loop = this.#loop;
|
|
213
|
+
if (loop === undefined) return;
|
|
214
|
+
if (!this.#draining) {
|
|
215
|
+
this.#draining = true;
|
|
216
|
+
await this.#drain();
|
|
217
|
+
this.#closed.abort(new WorkerStoppedError());
|
|
218
|
+
const connection = this.#connection;
|
|
219
|
+
connection?.finish();
|
|
220
|
+
const cut = setTimeout(() => {
|
|
221
|
+
connection?.abort.abort();
|
|
222
|
+
}, CLOSE_GRACE_MS);
|
|
223
|
+
await loop;
|
|
224
|
+
clearTimeout(cut);
|
|
225
|
+
}
|
|
226
|
+
await loop;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Runs currently in progress, for monitoring. */
|
|
230
|
+
get activeRuns(): number {
|
|
231
|
+
return this.#runs.size;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async #drain(): Promise<void> {
|
|
235
|
+
const timedOut = new AbortController();
|
|
236
|
+
const timer = setTimeout(() => {
|
|
237
|
+
timedOut.abort();
|
|
238
|
+
}, this.#drainTimeoutMs);
|
|
239
|
+
const expired = new Promise<void>((resolve) => {
|
|
240
|
+
timedOut.signal.addEventListener("abort", () => {
|
|
241
|
+
resolve();
|
|
242
|
+
});
|
|
243
|
+
});
|
|
244
|
+
// Tasks already pulled can still arrive while draining; they run too.
|
|
245
|
+
while (this.#runs.size > 0 && !timedOut.signal.aborted) {
|
|
246
|
+
await Promise.race([this.#runFinished.promise, expired]);
|
|
247
|
+
}
|
|
248
|
+
clearTimeout(timer);
|
|
249
|
+
for (const run of this.#runs.values()) run.controller.abort(new WorkerStoppedError());
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async #connectLoop(): Promise<void> {
|
|
253
|
+
let failures = 0;
|
|
254
|
+
while (!this.#isClosed()) {
|
|
255
|
+
const connection = new Connection();
|
|
256
|
+
connection.send({
|
|
257
|
+
kind: {
|
|
258
|
+
case: "hello",
|
|
259
|
+
value: {
|
|
260
|
+
workerId: this.workerId,
|
|
261
|
+
workflows: [...this.#workflows.keys()],
|
|
262
|
+
queue: this.#queue,
|
|
263
|
+
pull: this.#freeSlots(),
|
|
264
|
+
},
|
|
265
|
+
},
|
|
266
|
+
});
|
|
267
|
+
this.#setConnection(connection);
|
|
268
|
+
let error: unknown;
|
|
269
|
+
try {
|
|
270
|
+
await this.#serve(connection);
|
|
271
|
+
} catch (caught) {
|
|
272
|
+
error = caught;
|
|
273
|
+
}
|
|
274
|
+
connection.close();
|
|
275
|
+
this.#setConnection(undefined);
|
|
276
|
+
if (this.#isClosed()) return;
|
|
277
|
+
|
|
278
|
+
// Runs keep going while disconnected; their reports wait for the next connection.
|
|
279
|
+
this.#logger.warn(
|
|
280
|
+
{ workerId: this.workerId, err: error, activeRuns: this.#runs.size },
|
|
281
|
+
error === undefined ? "the engine closed the stream" : "the stream to the engine failed",
|
|
282
|
+
);
|
|
283
|
+
if (connection.isReady) failures = 0;
|
|
284
|
+
try {
|
|
285
|
+
await sleep(backoffDelay(failures, this.#backoff), this.#closed.signal);
|
|
286
|
+
} catch {
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
failures += 1;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
async #serve(connection: Connection): Promise<void> {
|
|
294
|
+
const client = createClient(WorkerService, this.#transport);
|
|
295
|
+
for await (const response of client.connect(connection.requests, {
|
|
296
|
+
signal: connection.abort.signal,
|
|
297
|
+
})) {
|
|
298
|
+
const { kind } = response;
|
|
299
|
+
switch (kind.case) {
|
|
300
|
+
case "ready":
|
|
301
|
+
connection.isReady = true;
|
|
302
|
+
this.#logger.info({ workerId: this.workerId }, "connected to the engine");
|
|
303
|
+
connection.startHeartbeat(kind.value.heartbeatIntervalMs, () =>
|
|
304
|
+
this.#heartbeat(connection),
|
|
305
|
+
);
|
|
306
|
+
break;
|
|
307
|
+
case "task":
|
|
308
|
+
this.#startRun(kind.value);
|
|
309
|
+
break;
|
|
310
|
+
case "ack":
|
|
311
|
+
case "failure":
|
|
312
|
+
case "heartbeatAck":
|
|
313
|
+
connection.settle(kind);
|
|
314
|
+
break;
|
|
315
|
+
case undefined:
|
|
316
|
+
// A message kind from a newer engine; nothing here depends on it.
|
|
317
|
+
break;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
#setConnection(connection: Connection | undefined): void {
|
|
323
|
+
this.#connection = connection;
|
|
324
|
+
const changed = this.#connectionChanged;
|
|
325
|
+
this.#connectionChanged = Promise.withResolvers<undefined>();
|
|
326
|
+
changed.resolve(undefined);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** A method, not a property read, so the loop re-reads it after each await. */
|
|
330
|
+
#isClosed(): boolean {
|
|
331
|
+
return this.#closed.signal.aborted;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
#freeSlots(): number {
|
|
335
|
+
return this.#draining ? 0 : Math.max(0, this.#concurrency - this.#runs.size);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** A slot came free: ask for one more task. While disconnected the next hello counts it. */
|
|
339
|
+
#releaseSlot(): void {
|
|
340
|
+
if (this.#draining) return;
|
|
341
|
+
this.#connection?.send({ kind: { case: "pull", value: { count: 1 } } });
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Renews the leases of running runs. Sent even with none: it is also the keep-alive that
|
|
346
|
+
* stops the engine closing an idle stream (an empty heartbeat costs it no database work).
|
|
347
|
+
*/
|
|
348
|
+
async #heartbeat(connection: Connection): Promise<void> {
|
|
349
|
+
const runs = [...this.#runs.values()];
|
|
350
|
+
const requestId = this.#nextRequestId++;
|
|
351
|
+
let reply: Reply;
|
|
352
|
+
try {
|
|
353
|
+
reply = await connection.request(requestId, {
|
|
354
|
+
case: "heartbeat",
|
|
355
|
+
value: {
|
|
356
|
+
requestId,
|
|
357
|
+
leases: runs.map((run) => ({ taskId: run.taskId, attempt: run.attempt })),
|
|
358
|
+
},
|
|
359
|
+
});
|
|
360
|
+
} catch {
|
|
361
|
+
// The stream dropped; the next connection heartbeats.
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
if (reply.case !== "heartbeatAck") {
|
|
365
|
+
this.#logger.warn(
|
|
366
|
+
{ workerId: this.workerId, code: reply.case === "failure" ? reply.value.code : reply.case },
|
|
367
|
+
"heartbeat failed",
|
|
368
|
+
);
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
for (const lost of reply.value.lost) {
|
|
372
|
+
const run = this.#runs.get(lost.taskId);
|
|
373
|
+
// A run with a request in flight is left to that request's reply. The request may be
|
|
374
|
+
// what ended the lease, such as a completion the engine committed before this
|
|
375
|
+
// heartbeat looked; if the lease was really lost, the reply says so (LEASE_LOST).
|
|
376
|
+
if (run?.attempt === lost.attempt && run.inFlight === 0) {
|
|
377
|
+
run.controller.abort(new LeaseLostError());
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
#startRun(task: ClaimedTask): void {
|
|
383
|
+
const fields = {
|
|
384
|
+
workerId: this.workerId,
|
|
385
|
+
runId: task.runId,
|
|
386
|
+
taskId: String(task.taskId),
|
|
387
|
+
attempt: task.attempt,
|
|
388
|
+
workflow: task.workflow,
|
|
389
|
+
};
|
|
390
|
+
if (this.#closed.signal.aborted) {
|
|
391
|
+
this.#logger.warn(fields, "task arrived after the worker stopped; its lease will expire");
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
const workflow = this.#workflows.get(task.workflow);
|
|
395
|
+
const journal = task.journal.map((entry) => ({
|
|
396
|
+
seq: entry.seq,
|
|
397
|
+
name: entry.name,
|
|
398
|
+
output: entry.output === undefined ? null : toJson(ValueSchema, entry.output),
|
|
399
|
+
}));
|
|
400
|
+
if (workflow === undefined || journal.some((entry, index) => entry.seq !== index)) {
|
|
401
|
+
// The engine only sends listed workflows and complete journals; this is a bug.
|
|
402
|
+
this.#logger.error(fields, "task cannot be run; its lease will expire");
|
|
403
|
+
this.#releaseSlot();
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const previous = this.#runs.get(task.taskId);
|
|
408
|
+
if (previous !== undefined) {
|
|
409
|
+
// This worker lost the lease and claimed the task again: the old attempt is stale.
|
|
410
|
+
previous.controller.abort(new LeaseLostError());
|
|
411
|
+
this.#releaseSlot();
|
|
412
|
+
}
|
|
413
|
+
const run: ActiveRun = {
|
|
414
|
+
taskId: task.taskId,
|
|
415
|
+
attempt: task.attempt,
|
|
416
|
+
controller: new AbortController(),
|
|
417
|
+
inFlight: 0,
|
|
418
|
+
};
|
|
419
|
+
this.#runs.set(task.taskId, run);
|
|
420
|
+
void this.#execute(task, workflow, journal, run, fields).finally(() => {
|
|
421
|
+
if (this.#runs.get(task.taskId) === run) {
|
|
422
|
+
this.#runs.delete(task.taskId);
|
|
423
|
+
this.#releaseSlot();
|
|
424
|
+
}
|
|
425
|
+
const finished = this.#runFinished;
|
|
426
|
+
this.#runFinished = Promise.withResolvers<undefined>();
|
|
427
|
+
finished.resolve(undefined);
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
async #execute(
|
|
432
|
+
task: ClaimedTask,
|
|
433
|
+
workflow: Workflow<never>,
|
|
434
|
+
journal: RecordedStep[],
|
|
435
|
+
run: ActiveRun,
|
|
436
|
+
fields: Record<string, unknown>,
|
|
437
|
+
): Promise<void> {
|
|
438
|
+
const { controller } = run;
|
|
439
|
+
const { signal } = controller;
|
|
440
|
+
const deliver = (
|
|
441
|
+
build: (requestId: bigint) => RequestKind,
|
|
442
|
+
log: Record<string, unknown>,
|
|
443
|
+
): Promise<Ack> => this.#deliver(build, signal, log, run);
|
|
444
|
+
const lease = { taskId: task.taskId, attempt: task.attempt };
|
|
445
|
+
const recordFailure = async (failure: StepFailure) => {
|
|
446
|
+
await deliver(
|
|
447
|
+
(requestId) => ({
|
|
448
|
+
case: "stepFailure",
|
|
449
|
+
value: { requestId, ...lease, ...failure },
|
|
450
|
+
}),
|
|
451
|
+
{ ...fields, stepSeq: failure.seq },
|
|
452
|
+
);
|
|
453
|
+
};
|
|
454
|
+
const ctx = new RunContext({
|
|
455
|
+
runId: task.runId,
|
|
456
|
+
workflow: task.workflow,
|
|
457
|
+
attempt: task.attempt,
|
|
458
|
+
signal,
|
|
459
|
+
journal,
|
|
460
|
+
record: async (step) => {
|
|
461
|
+
await deliver(
|
|
462
|
+
(requestId) => ({
|
|
463
|
+
case: "step",
|
|
464
|
+
value: {
|
|
465
|
+
requestId,
|
|
466
|
+
...lease,
|
|
467
|
+
seq: step.seq,
|
|
468
|
+
name: step.name,
|
|
469
|
+
output: fromJson(ValueSchema, step.output),
|
|
470
|
+
durationMs: step.durationMs,
|
|
471
|
+
...(step.llm === undefined ? {} : { llm: step.llm }),
|
|
472
|
+
},
|
|
473
|
+
}),
|
|
474
|
+
{ ...fields, stepSeq: step.seq },
|
|
475
|
+
);
|
|
476
|
+
},
|
|
477
|
+
recordFailure,
|
|
478
|
+
sendTokens: (seq, text) => {
|
|
479
|
+
// Not answered, so not tracked: text sent while disconnected is simply lost.
|
|
480
|
+
this.#connection?.send({
|
|
481
|
+
kind: { case: "llmTokens", value: { ...lease, seq, text } },
|
|
482
|
+
});
|
|
483
|
+
},
|
|
484
|
+
recordSleep: async (sleep) => {
|
|
485
|
+
await deliver(
|
|
486
|
+
(requestId) => ({
|
|
487
|
+
case: "sleep",
|
|
488
|
+
value: { requestId, ...lease, ...sleep, durationMs: BigInt(sleep.durationMs) },
|
|
489
|
+
}),
|
|
490
|
+
{ ...fields, stepSeq: sleep.seq },
|
|
491
|
+
);
|
|
492
|
+
},
|
|
493
|
+
recordThrottle: async (throttle) => {
|
|
494
|
+
const ack = await deliver(
|
|
495
|
+
(requestId) => ({ case: "throttle", value: { requestId, ...lease, ...throttle } }),
|
|
496
|
+
{ ...fields, stepSeq: throttle.seq },
|
|
497
|
+
);
|
|
498
|
+
return Number(ack.waitMs);
|
|
499
|
+
},
|
|
500
|
+
recordWait: async (wait) => {
|
|
501
|
+
await deliver(
|
|
502
|
+
(requestId) => ({
|
|
503
|
+
case: "waitForEvent",
|
|
504
|
+
value: { requestId, ...lease, ...wait, timeoutMs: BigInt(wait.timeoutMs) },
|
|
505
|
+
}),
|
|
506
|
+
{ ...fields, stepSeq: wait.seq },
|
|
507
|
+
);
|
|
508
|
+
},
|
|
509
|
+
stop: (reason) => {
|
|
510
|
+
controller.abort(reason);
|
|
511
|
+
},
|
|
512
|
+
});
|
|
513
|
+
const started = performance.now();
|
|
514
|
+
try {
|
|
515
|
+
this.#logger.debug({ ...fields, recordedSteps: journal.length }, "run started");
|
|
516
|
+
const input = task.input === undefined ? null : toJson(ValueSchema, task.input);
|
|
517
|
+
// The input is whatever JSON the run was triggered with; workflow() documents that
|
|
518
|
+
// its type is not checked at runtime.
|
|
519
|
+
const result = await workflow.run(ctx, input as never);
|
|
520
|
+
const output = toStoredJson(result, "the workflow's output");
|
|
521
|
+
signal.throwIfAborted();
|
|
522
|
+
await deliver(
|
|
523
|
+
(requestId) => ({
|
|
524
|
+
case: "completion",
|
|
525
|
+
value: { requestId, ...lease, output: fromJson(ValueSchema, output) },
|
|
526
|
+
}),
|
|
527
|
+
fields,
|
|
528
|
+
);
|
|
529
|
+
this.#logger.info(fields, "run completed");
|
|
530
|
+
} catch (error) {
|
|
531
|
+
if (isRunStop(error) || error instanceof StepFailedError || signal.aborted) {
|
|
532
|
+
this.#logStop(signal.aborted ? signal.reason : error, fields);
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
if (error instanceof StepMismatchError) {
|
|
536
|
+
this.#logStop(error, fields);
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
// Thrown by workflow code outside any step: charged to the step it was about to run,
|
|
540
|
+
// so it is retried and bounded like a step failure instead of looping forever.
|
|
541
|
+
try {
|
|
542
|
+
const retryable = !(error instanceof NonRetryableError);
|
|
543
|
+
await recordFailure({
|
|
544
|
+
seq: ctx.nextSeq,
|
|
545
|
+
name: OUTSIDE_A_STEP,
|
|
546
|
+
error: describe(error),
|
|
547
|
+
retryable,
|
|
548
|
+
maxAttempts: DEFAULT_MAX_ATTEMPTS,
|
|
549
|
+
durationMs: Math.round(performance.now() - started),
|
|
550
|
+
});
|
|
551
|
+
this.#logStop(new StepFailedError(OUTSIDE_A_STEP, retryable, { cause: error }), fields);
|
|
552
|
+
} catch (reportError) {
|
|
553
|
+
this.#logStop(reportError, fields);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
#logStop(error: unknown, fields: Record<string, unknown>): void {
|
|
559
|
+
if (error instanceof RunSleepingError) {
|
|
560
|
+
this.#logger.info({ ...fields, sleepMs: error.durationMs }, "run sleeping");
|
|
561
|
+
} else if (error instanceof RunThrottledError) {
|
|
562
|
+
this.#logger.info(
|
|
563
|
+
{ ...fields, rateLimit: error.key, waitMs: error.waitMs },
|
|
564
|
+
"run waiting for a rate limit",
|
|
565
|
+
);
|
|
566
|
+
} else if (error instanceof RunWaitingError) {
|
|
567
|
+
this.#logger.info({ ...fields, event: error.event }, "run waiting for an event");
|
|
568
|
+
} else if (error instanceof LeaseLostError && error.afterResend) {
|
|
569
|
+
this.#logger.info(
|
|
570
|
+
fields,
|
|
571
|
+
"lease lost after a resend; the first copy, sent before the connection dropped, may have been applied",
|
|
572
|
+
);
|
|
573
|
+
} else if (error instanceof StepFailedError) {
|
|
574
|
+
const cause = error.cause instanceof Error ? error.cause : undefined;
|
|
575
|
+
this.#logger.warn(
|
|
576
|
+
{ ...fields, step: error.step, retryable: error.retryable, err: cause },
|
|
577
|
+
error.message,
|
|
578
|
+
);
|
|
579
|
+
} else if (isRunStop(error)) {
|
|
580
|
+
this.#logger.warn({ ...fields, code: error.code }, "run stopped on this worker");
|
|
581
|
+
} else if (error instanceof StepMismatchError) {
|
|
582
|
+
this.#logger.error({ ...fields, err: error }, "run stopped: step does not match the journal");
|
|
583
|
+
} else {
|
|
584
|
+
// The failure could not be reported (the engine refused it): the lease expires and
|
|
585
|
+
// the run is tried again, bounded by the engine's lease-expiry cap.
|
|
586
|
+
this.#logger.error(
|
|
587
|
+
{ ...fields, err: error },
|
|
588
|
+
"run stopped: its failure could not be recorded",
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/** Sends a request for `run` until it is acknowledged, counting it as in flight meanwhile. */
|
|
594
|
+
async #deliver(
|
|
595
|
+
build: (requestId: bigint) => RequestKind,
|
|
596
|
+
signal: AbortSignal,
|
|
597
|
+
fields: Record<string, unknown>,
|
|
598
|
+
run: ActiveRun,
|
|
599
|
+
): Promise<Ack> {
|
|
600
|
+
run.inFlight += 1;
|
|
601
|
+
try {
|
|
602
|
+
return await this.#sendUntilAcked(build, signal, fields);
|
|
603
|
+
} finally {
|
|
604
|
+
run.inFlight -= 1;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Sends a request until it is acknowledged, resending with backoff across disconnects and
|
|
610
|
+
* retryable failures, and returns the ack. Throws on a non-retryable failure, or when the
|
|
611
|
+
* run's signal aborts.
|
|
612
|
+
*/
|
|
613
|
+
async #sendUntilAcked(
|
|
614
|
+
build: (requestId: bigint) => RequestKind,
|
|
615
|
+
signal: AbortSignal,
|
|
616
|
+
fields: Record<string, unknown>,
|
|
617
|
+
): Promise<Ack> {
|
|
618
|
+
let resent = false;
|
|
619
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
620
|
+
if (attempt > 0) await sleep(backoffDelay(attempt - 1, this.#backoff), signal);
|
|
621
|
+
const connection = await this.#awaitConnection(signal);
|
|
622
|
+
const requestId = this.#nextRequestId++;
|
|
623
|
+
let reply: Reply;
|
|
624
|
+
try {
|
|
625
|
+
reply = await abortable(connection.request(requestId, build(requestId)), signal);
|
|
626
|
+
} catch (error) {
|
|
627
|
+
if (!(error instanceof DisconnectedError)) throw error;
|
|
628
|
+
resent = true;
|
|
629
|
+
continue;
|
|
630
|
+
}
|
|
631
|
+
if (reply.case === "ack") return reply.value;
|
|
632
|
+
if (reply.case === "heartbeatAck") {
|
|
633
|
+
throw new Error("the engine answered a request with a heartbeat ack");
|
|
634
|
+
}
|
|
635
|
+
if (!reply.value.retryable) throw errorFor(reply.value, resent);
|
|
636
|
+
this.#logger.warn({ ...fields, code: reply.value.code }, "request failed; resending");
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
async #awaitConnection(signal: AbortSignal): Promise<Connection> {
|
|
641
|
+
for (;;) {
|
|
642
|
+
const connection = this.#connection;
|
|
643
|
+
if (connection !== undefined) return connection;
|
|
644
|
+
await abortable(this.#connectionChanged.promise, signal);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
function errorFor(failure: Failure, resent: boolean): Error {
|
|
650
|
+
switch (failure.code) {
|
|
651
|
+
case "LEASE_LOST":
|
|
652
|
+
return new LeaseLostError(resent);
|
|
653
|
+
case "STEP_MISMATCH":
|
|
654
|
+
return new StepMismatchError(failure.message);
|
|
655
|
+
default:
|
|
656
|
+
return new RequestFailedError(failure.code, failure.message, failure.retryable);
|
|
657
|
+
}
|
|
658
|
+
}
|
package/src/workflow.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { WorkflowContext } from "./context.js";
|
|
2
|
+
|
|
3
|
+
/** A named workflow function, registered with a Worker. */
|
|
4
|
+
export interface Workflow<Input = unknown, Output = unknown> {
|
|
5
|
+
readonly name: string;
|
|
6
|
+
readonly run: (ctx: WorkflowContext, input: Input) => Promise<Output>;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Defines a workflow. `name` is what runs are triggered with; it must not change while runs
|
|
11
|
+
* of it are in flight. The function runs from the top on every attempt, so everything with
|
|
12
|
+
* an effect or a cost belongs inside `ctx.step`. `Input` is not checked at runtime: it is
|
|
13
|
+
* whatever JSON the run was triggered with.
|
|
14
|
+
*/
|
|
15
|
+
export function workflow<Input = unknown, Output = unknown>(
|
|
16
|
+
name: string,
|
|
17
|
+
run: (ctx: WorkflowContext, input: Input) => Promise<Output>,
|
|
18
|
+
): Workflow<Input, Output> {
|
|
19
|
+
return { name, run };
|
|
20
|
+
}
|