@artieeez/cf-worker-runtime 0.0.0-stage → 0.1.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/README.md +12 -2
- package/dist/agents.d.ts +64 -0
- package/dist/agents.d.ts.map +1 -0
- package/dist/agents.js +324 -0
- package/dist/agents.js.map +1 -0
- package/dist/exec.d.ts +36 -0
- package/dist/exec.d.ts.map +1 -0
- package/dist/exec.js +186 -0
- package/dist/exec.js.map +1 -0
- package/dist/fatal.d.ts +5 -0
- package/dist/fatal.d.ts.map +1 -0
- package/dist/fatal.js +5 -0
- package/dist/fatal.js.map +1 -0
- package/dist/health.d.ts +49 -0
- package/dist/health.d.ts.map +1 -0
- package/dist/health.js +97 -0
- package/dist/health.js.map +1 -0
- package/dist/index.d.ts +80 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1058 -0
- package/dist/index.js.map +1 -0
- package/dist/provenance.d.ts +11 -0
- package/dist/provenance.d.ts.map +1 -0
- package/dist/provenance.js +74 -0
- package/dist/provenance.js.map +1 -0
- package/dist/run.d.ts +17 -0
- package/dist/run.d.ts.map +1 -0
- package/dist/run.js +37 -0
- package/dist/run.js.map +1 -0
- package/dist/sessions.d.ts +14 -0
- package/dist/sessions.d.ts.map +1 -0
- package/dist/sessions.js +98 -0
- package/dist/sessions.js.map +1 -0
- package/dist/steps.d.ts +25 -0
- package/dist/steps.d.ts.map +1 -0
- package/dist/steps.js +62 -0
- package/dist/steps.js.map +1 -0
- package/dist/workspaces.d.ts +37 -0
- package/dist/workspaces.d.ts.map +1 -0
- package/dist/workspaces.js +68 -0
- package/dist/workspaces.js.map +1 -0
- package/package.json +78 -3
- package/src/agents.ts +387 -0
- package/src/exec.ts +184 -0
- package/src/fatal.ts +4 -0
- package/src/health.ts +119 -0
- package/src/index.ts +1142 -0
- package/src/provenance.ts +74 -0
- package/src/run.ts +40 -0
- package/src/sessions.ts +98 -0
- package/src/steps.ts +85 -0
- package/src/workspaces.ts +81 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,1142 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { rm } from 'node:fs/promises';
|
|
4
|
+
import { dirname, join, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
|
+
import {
|
|
7
|
+
ApiError,
|
|
8
|
+
ConnectionError,
|
|
9
|
+
createClient,
|
|
10
|
+
DEFAULT_SERVER_URL,
|
|
11
|
+
type CompleteBody,
|
|
12
|
+
type LeasedUnit,
|
|
13
|
+
type WorkerEvent,
|
|
14
|
+
type WorkspaceFolder,
|
|
15
|
+
type WorkspaceStatus,
|
|
16
|
+
} from '@artieeez/cf-client';
|
|
17
|
+
import {
|
|
18
|
+
AGENT_TEXT_MAX,
|
|
19
|
+
ARTIFACT_MAX_BYTES,
|
|
20
|
+
artifactPathProblems,
|
|
21
|
+
cut,
|
|
22
|
+
EFFECT_NAME,
|
|
23
|
+
effectId,
|
|
24
|
+
MEDIA_TYPE,
|
|
25
|
+
OUTPUT_MAX_BYTES,
|
|
26
|
+
outputBytes,
|
|
27
|
+
outputProblem,
|
|
28
|
+
PAUSE_REASON_MAX,
|
|
29
|
+
PLUGIN_ERROR_MAX,
|
|
30
|
+
RUN_TITLE_KEY,
|
|
31
|
+
stepAt,
|
|
32
|
+
WORKER_EVENT_TYPES,
|
|
33
|
+
workerEventProblems,
|
|
34
|
+
type ArtifactRef,
|
|
35
|
+
type Manifest,
|
|
36
|
+
type UnitHook,
|
|
37
|
+
type WorkerEventType,
|
|
38
|
+
type WorkerMode,
|
|
39
|
+
WORKER_MODES,
|
|
40
|
+
WORKER_SLOTS_MAX,
|
|
41
|
+
} from '@artieeez/cf-core';
|
|
42
|
+
import {
|
|
43
|
+
AccountUnavailableError,
|
|
44
|
+
toManifest,
|
|
45
|
+
type AgentAccounts,
|
|
46
|
+
type AgentRunner,
|
|
47
|
+
type AnyStep,
|
|
48
|
+
type Artifact,
|
|
49
|
+
type Artifacts,
|
|
50
|
+
type Effects,
|
|
51
|
+
type EmitType,
|
|
52
|
+
type FinishContext,
|
|
53
|
+
type PluginActions,
|
|
54
|
+
type RunContext,
|
|
55
|
+
type TaskContext,
|
|
56
|
+
type WorkflowDefinition,
|
|
57
|
+
} from '@artieeez/cf-sdk';
|
|
58
|
+
import { actionNames } from '@artieeez/cf-plugin-host';
|
|
59
|
+
import { confined, createExec, inside } from './exec.ts';
|
|
60
|
+
import { WorkerFatalError } from './fatal.ts';
|
|
61
|
+
import { bounded, listenProbes, sameReadiness, Vitals, type CheckOutcome, type WorkflowReadiness } from './health.ts';
|
|
62
|
+
import { provenance } from './provenance.ts';
|
|
63
|
+
import { cleanupRunSessions, createRunSessions } from './sessions.ts';
|
|
64
|
+
import { outputOf, stepIndex, visitsOf } from './steps.ts';
|
|
65
|
+
import { decide, folderSize, isRunId } from './workspaces.ts';
|
|
66
|
+
|
|
67
|
+
export { scrubbedEnv } from './exec.ts';
|
|
68
|
+
export { provenance } from './provenance.ts';
|
|
69
|
+
export { WorkerFatalError } from './fatal.ts';
|
|
70
|
+
export {
|
|
71
|
+
balanceAgents,
|
|
72
|
+
DEFAULT_HARNESS_BINS,
|
|
73
|
+
isCooldownError,
|
|
74
|
+
isExecutableOnPath,
|
|
75
|
+
pickAgent,
|
|
76
|
+
type BalanceOptions,
|
|
77
|
+
type BalanceStrategy,
|
|
78
|
+
type BalanceTarget,
|
|
79
|
+
type ModelMapper,
|
|
80
|
+
} from './agents.ts';
|
|
81
|
+
export { runWorker, type RunWorkerOptions } from './run.ts';
|
|
82
|
+
|
|
83
|
+
export interface WorkerOptions {
|
|
84
|
+
/** used for the credential file and shown in `worker.registered` */
|
|
85
|
+
name: string;
|
|
86
|
+
workflows: WorkflowDefinition[];
|
|
87
|
+
serverUrl?: string;
|
|
88
|
+
/** default `CF_DATA_DIR` or `.cf`; a self-created token goes to `<dataDir>/workers/<name>.json` */
|
|
89
|
+
dataDir?: string;
|
|
90
|
+
/** where run folders live; default `CF_WORKSPACE_ROOT` or `<dataDir>/workspace` (door 4) */
|
|
91
|
+
workspaceRoot?: string;
|
|
92
|
+
/**
|
|
93
|
+
* The worker token (AD-063); default `CF_WORKER_TOKEN`, then the token saved in
|
|
94
|
+
* `<dataDir>/workers/<name>.json`. With none, the worker creates its own worker on the server,
|
|
95
|
+
* limited to its workflows, and saves it there (AD-064): this works only while auth is off.
|
|
96
|
+
*/
|
|
97
|
+
token?: string;
|
|
98
|
+
retryMs?: number;
|
|
99
|
+
heartbeatMs?: number;
|
|
100
|
+
/** largest artifact `ctx.artifacts.put` uploads; default `CF_ARTIFACT_MAX_BYTES` or 100 MiB */
|
|
101
|
+
artifactMaxBytes?: number;
|
|
102
|
+
/**
|
|
103
|
+
* The stop (SIGTERM, SIGINT): the worker stops leasing and its check rounds, and lets the units in
|
|
104
|
+
* flight finish and report for up to `drainTimeoutMs`, asking the server to pause their runs
|
|
105
|
+
* (`POST /w/drain`, AD-090). With none in flight it returns at once.
|
|
106
|
+
*/
|
|
107
|
+
signal?: AbortSignal;
|
|
108
|
+
/** A hard stop (a second SIGTERM): the units in flight are dropped at once, as at the drain's deadline. */
|
|
109
|
+
kill?: AbortSignal;
|
|
110
|
+
/**
|
|
111
|
+
* How long a stop lets the units in flight finish; then they are dropped and retried as lost.
|
|
112
|
+
* Default `CF_DRAIN_TIMEOUT_MS` or 25 s; 0 drops them at once (AD-090).
|
|
113
|
+
*/
|
|
114
|
+
drainTimeoutMs?: number;
|
|
115
|
+
/** the runner `ctx.agent` calls; without one `ctx.agent` rejects (AD-029) */
|
|
116
|
+
agent?: AgentRunner;
|
|
117
|
+
fetch?: typeof fetch;
|
|
118
|
+
sleep?: (ms: number) => Promise<void>;
|
|
119
|
+
log?: (msg: string) => void;
|
|
120
|
+
/** where `GET /health` and `GET /ready` listen; default `CF_HEALTH_PORT`, unset: no listener (health-ready door 4) */
|
|
121
|
+
healthPort?: number;
|
|
122
|
+
/** default `CF_HEALTH_HOST` or `0.0.0.0` */
|
|
123
|
+
healthHost?: string;
|
|
124
|
+
/** `/health` answers stuck when no server call settled for longer; default `CF_HEALTH_STALE_MS` or 90 s */
|
|
125
|
+
healthStaleMs?: number;
|
|
126
|
+
/** how often each workflow's `workerReady` runs again; default `CF_CHECK_INTERVAL_MS` or 60 s */
|
|
127
|
+
checkIntervalMs?: number;
|
|
128
|
+
/** how long one `workerReady` may take; default `CF_CHECK_TIMEOUT_MS` or 10 s */
|
|
129
|
+
checkTimeoutMs?: number;
|
|
130
|
+
/**
|
|
131
|
+
* Units this process runs at once, `1..64`; default `CF_WORKER_SLOTS` or 1 (multi-slot-workers
|
|
132
|
+
* door 1). Units of one run share its run folder; its `preInit` runs once.
|
|
133
|
+
*/
|
|
134
|
+
slots?: number;
|
|
135
|
+
/**
|
|
136
|
+
* `single`: units of one run at a time, up to `slots` of them; `multi` (default): any run's.
|
|
137
|
+
* Default `CF_WORKER_MODE` or `multi` (multi-slot-workers door 4).
|
|
138
|
+
*/
|
|
139
|
+
mode?: WorkerMode;
|
|
140
|
+
/**
|
|
141
|
+
* Hours a kept folder of a `failed` or `aborted` run stays after the run ended, under
|
|
142
|
+
* `keepWorkspace: onFailure`; 0 keeps it forever. Default `CF_WORKSPACE_RETAIN_HOURS` or 72 (ART-226).
|
|
143
|
+
*/
|
|
144
|
+
workspaceRetainHours?: number;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Most run ids one `POST /w/workspaces/check` takes (run-affinity door 5). */
|
|
148
|
+
export const WORKSPACE_CHECK_MAX = 500;
|
|
149
|
+
/** Most folders one `POST /w/workspaces/report` carries: the largest (ART-226). */
|
|
150
|
+
export const WORKSPACE_REPORT_MAX = 500;
|
|
151
|
+
|
|
152
|
+
/** Longest problem a health report carries; the server refuses over 2000 chars. */
|
|
153
|
+
export const PROBLEM_MAX = 1000;
|
|
154
|
+
|
|
155
|
+
/** Media types by extension (artifact-store door 3). */
|
|
156
|
+
const MEDIA_TYPES: Record<string, string> = {
|
|
157
|
+
md: 'text/markdown',
|
|
158
|
+
txt: 'text/plain',
|
|
159
|
+
json: 'application/json',
|
|
160
|
+
jsonl: 'application/x-ndjson',
|
|
161
|
+
html: 'text/html',
|
|
162
|
+
png: 'image/png',
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
/** The option, else the extension's type, else by the content's kind (door 3). */
|
|
166
|
+
export function mediaTypeOf(path: string, content: string | Uint8Array, given?: string): string {
|
|
167
|
+
if (given !== undefined) return given;
|
|
168
|
+
const name = path.split('/').pop() ?? '';
|
|
169
|
+
const dot = name.lastIndexOf('.');
|
|
170
|
+
const ext = dot > 0 ? name.slice(dot + 1).toLowerCase() : '';
|
|
171
|
+
// own keys only: `x.constructor` must not find Object.prototype's members
|
|
172
|
+
const byExt = Object.hasOwn(MEDIA_TYPES, ext) ? MEDIA_TYPES[ext] : undefined;
|
|
173
|
+
return byExt ?? (typeof content === 'string' ? 'text/plain; charset=utf-8' : 'application/octet-stream');
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
interface SavedCredential {
|
|
177
|
+
workerId: string;
|
|
178
|
+
credential: string;
|
|
179
|
+
server: string;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export async function startWorker(opts: WorkerOptions): Promise<void> {
|
|
183
|
+
const env = process.env;
|
|
184
|
+
const serverUrl = opts.serverUrl ?? env['CF_SERVER'] ?? DEFAULT_SERVER_URL;
|
|
185
|
+
const dataDir = resolve(opts.dataDir ?? env['CF_DATA_DIR'] ?? '.cf');
|
|
186
|
+
const credentialFile = join(dataDir, 'workers', `${opts.name}.json`);
|
|
187
|
+
const root = resolve(opts.workspaceRoot ?? env['CF_WORKSPACE_ROOT'] ?? join(dataDir, 'workspace'));
|
|
188
|
+
mkdirSync(root, { recursive: true });
|
|
189
|
+
const retryMs = opts.retryMs ?? 1000;
|
|
190
|
+
const heartbeatMs = opts.heartbeatMs ?? Number(env['CF_HEARTBEAT_MS'] ?? 5000);
|
|
191
|
+
const artifactMaxBytes = opts.artifactMaxBytes ?? Number(env['CF_ARTIFACT_MAX_BYTES'] ?? ARTIFACT_MAX_BYTES);
|
|
192
|
+
const sleep = opts.sleep ?? ((ms: number) => delay(ms));
|
|
193
|
+
const log = opts.log ?? ((msg: string) => console.log(`[${opts.name}] ${msg}`));
|
|
194
|
+
const signal = opts.signal ?? new AbortController().signal;
|
|
195
|
+
/** A whole number of ms (or a port) from the env; anything else stops the worker naming it. */
|
|
196
|
+
const envNumber = (name: string, fallback: number | undefined, min = 0): number | undefined => {
|
|
197
|
+
const raw = env[name];
|
|
198
|
+
if (raw === undefined || raw === '') return fallback;
|
|
199
|
+
const n = Number(raw);
|
|
200
|
+
if (!Number.isInteger(n) || n < min) {
|
|
201
|
+
throw new WorkerFatalError(`${name} must be a whole number${min > 0 ? ` of at least ${min}` : ''}, got "${raw}"`);
|
|
202
|
+
}
|
|
203
|
+
return n;
|
|
204
|
+
};
|
|
205
|
+
const drainTimeoutMs = opts.drainTimeoutMs ?? envNumber('CF_DRAIN_TIMEOUT_MS', 25_000)!;
|
|
206
|
+
const healthPort = opts.healthPort ?? envNumber('CF_HEALTH_PORT', undefined);
|
|
207
|
+
const healthHost = opts.healthHost ?? (env['CF_HEALTH_HOST'] || '0.0.0.0');
|
|
208
|
+
const checkIntervalMs = opts.checkIntervalMs ?? envNumber('CF_CHECK_INTERVAL_MS', 60_000)!;
|
|
209
|
+
const checkTimeoutMs = opts.checkTimeoutMs ?? envNumber('CF_CHECK_TIMEOUT_MS', 10_000, 1)!;
|
|
210
|
+
const slots = slotsOf(opts.slots, env['CF_WORKER_SLOTS']);
|
|
211
|
+
const mode = modeOf(opts.mode, env['CF_WORKER_MODE']);
|
|
212
|
+
const retainMs = retainHoursOf(opts.workspaceRetainHours, () => envNumber('CF_WORKSPACE_RETAIN_HOURS', 72)!) * 3_600_000;
|
|
213
|
+
const vitals = new Vitals(opts.healthStaleMs ?? envNumber('CF_HEALTH_STALE_MS', 90_000, 1)!);
|
|
214
|
+
// every server call that settles, answered or not, is progress for `/health` (AC 9)
|
|
215
|
+
const serverFetch = opts.fetch ?? ((input: Parameters<typeof fetch>[0], init?: RequestInit) => fetch(input, init));
|
|
216
|
+
const tracked = ((input: Parameters<typeof fetch>[0], init?: RequestInit) =>
|
|
217
|
+
serverFetch(input, init).finally(() => vitals.progress())) as typeof fetch;
|
|
218
|
+
const client = createClient({ baseUrl: serverUrl, fetch: tracked });
|
|
219
|
+
const byId = new Map(opts.workflows.map((w) => [w.id, w]));
|
|
220
|
+
const manifests = opts.workflows.map(toManifest);
|
|
221
|
+
// where each step object sits, for ctx.output (door 4)
|
|
222
|
+
const indexes = new Map(opts.workflows.map((w) => [w.id, stepIndex(w)]));
|
|
223
|
+
|
|
224
|
+
// plugins need no secret on a worker: their actions run on the server (AD-048). What the
|
|
225
|
+
// workflows' own code reads is hidden from ctx.exec children (AD-049)
|
|
226
|
+
const secretNames = [...new Set(opts.workflows.flatMap((w) => [...(w.secrets ?? [])]))];
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* The hard stop (AD-090): `kill`, the drain's deadline, or a stop with no unit in flight. What
|
|
230
|
+
* the units follow: it aborts `ctx.signal`, kills `ctx.exec` children and ends the retries.
|
|
231
|
+
*/
|
|
232
|
+
const hard = new AbortController();
|
|
233
|
+
/** units leased and not settled yet */
|
|
234
|
+
let inFlight = 0;
|
|
235
|
+
let deadline: NodeJS.Timeout | undefined;
|
|
236
|
+
const onStop = () => {
|
|
237
|
+
if (inFlight === 0 || drainTimeoutMs === 0) hard.abort();
|
|
238
|
+
else deadline = setTimeout(() => hard.abort(), drainTimeoutMs);
|
|
239
|
+
};
|
|
240
|
+
const onKill = () => hard.abort();
|
|
241
|
+
|
|
242
|
+
let warned = false;
|
|
243
|
+
/** Calls `fn`, again every `retryMs` while the server is unreachable, until `until` aborts. */
|
|
244
|
+
async function retrying<T>(fn: () => Promise<T>, until: AbortSignal = hard.signal): Promise<T> {
|
|
245
|
+
for (;;) {
|
|
246
|
+
try {
|
|
247
|
+
const value = await fn();
|
|
248
|
+
if (warned) log('server reachable again');
|
|
249
|
+
warned = false;
|
|
250
|
+
return value;
|
|
251
|
+
} catch (err) {
|
|
252
|
+
if (!(err instanceof ConnectionError) || until.aborted) throw err;
|
|
253
|
+
if (!warned) log(`${err.message}; retrying every ${retryMs / 1000} s`);
|
|
254
|
+
warned = true;
|
|
255
|
+
await sleep(retryMs);
|
|
256
|
+
vitals.progress();
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** The worker token (door 3): `opts.token`, `CF_WORKER_TOKEN`, the saved file, else a new one. */
|
|
262
|
+
async function credential(): Promise<string> {
|
|
263
|
+
// an empty token is no token, given or in the env
|
|
264
|
+
const given = opts.token || env['CF_WORKER_TOKEN'] || undefined;
|
|
265
|
+
if (given !== undefined) return given;
|
|
266
|
+
try {
|
|
267
|
+
const saved = (JSON.parse(readFileSync(credentialFile, 'utf8')) as Partial<SavedCredential>).credential;
|
|
268
|
+
if (typeof saved === 'string' && saved !== '') return saved;
|
|
269
|
+
} catch {
|
|
270
|
+
/* first start */
|
|
271
|
+
}
|
|
272
|
+
let created;
|
|
273
|
+
try {
|
|
274
|
+
created = await retrying(() => client.createWorker({ name: opts.name, workflows: [...byId.keys()] }));
|
|
275
|
+
} catch (err) {
|
|
276
|
+
if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {
|
|
277
|
+
throw new WorkerFatalError(
|
|
278
|
+
'set CF_WORKER_TOKEN: this server needs a worker token (create one on the Workers page or with cf worker create)',
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
if (err instanceof ApiError) throw new WorkerFatalError(err.message);
|
|
282
|
+
throw err;
|
|
283
|
+
}
|
|
284
|
+
const saved: SavedCredential = { workerId: created.id, credential: created.token, server: serverUrl };
|
|
285
|
+
mkdirSync(dirname(credentialFile), { recursive: true });
|
|
286
|
+
writeFileSync(credentialFile, JSON.stringify(saved, null, 2) + '\n', { mode: 0o600 });
|
|
287
|
+
log(`created worker ${saved.workerId}; its token is saved in ${credentialFile}`);
|
|
288
|
+
return saved.credential;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async function register(token: string): Promise<string> {
|
|
292
|
+
try {
|
|
293
|
+
const r = await retrying(() => client.register(token, manifests, provenance(opts.name, env), { slots, mode }));
|
|
294
|
+
log(`registered ${manifests.map((m) => `${m.id}@${m.version}`).join(', ')}`);
|
|
295
|
+
return r.sessionToken;
|
|
296
|
+
} catch (err) {
|
|
297
|
+
if (err instanceof ApiError && err.status === 401) throw new WorkerFatalError(`worker token refused: ${err.message}`);
|
|
298
|
+
if (err instanceof ApiError) throw new WorkerFatalError(err.message);
|
|
299
|
+
throw err;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Runs `fn` as hook `hook`, reporting `hook.*` into `push`; resolves with the error message on a throw. */
|
|
304
|
+
async function hooked(
|
|
305
|
+
hook: UnitHook,
|
|
306
|
+
push: (type: EmitType, data: Record<string, unknown>) => void,
|
|
307
|
+
fn: () => Promise<void> | void,
|
|
308
|
+
): Promise<string | undefined> {
|
|
309
|
+
const started = Date.now();
|
|
310
|
+
push('hook.started', { hook });
|
|
311
|
+
try {
|
|
312
|
+
await fn();
|
|
313
|
+
push('hook.completed', { hook, durationMs: Date.now() - started });
|
|
314
|
+
return undefined;
|
|
315
|
+
} catch (err) {
|
|
316
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
317
|
+
push('hook.failed', { hook, durationMs: Date.now() - started, error: cut(error, AGENT_TEXT_MAX) });
|
|
318
|
+
return error;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Run ids whose units this process is running, with how many: their folders are never collected
|
|
324
|
+
* (door 5), also while a second slot still runs one of them (multi-slot-workers).
|
|
325
|
+
*/
|
|
326
|
+
const working = new Map<string, number>();
|
|
327
|
+
/** Run ids whose `preInit` a slot is running now: another unit of the run waits for it. */
|
|
328
|
+
const preparing = new Map<string, Promise<void>>();
|
|
329
|
+
|
|
330
|
+
async function runUnit(session: string, unit: LeasedUnit): Promise<void> {
|
|
331
|
+
working.set(unit.runId, (working.get(unit.runId) ?? 0) + 1);
|
|
332
|
+
inFlight += 1;
|
|
333
|
+
try {
|
|
334
|
+
await runLeased(session, unit);
|
|
335
|
+
} finally {
|
|
336
|
+
inFlight -= 1;
|
|
337
|
+
const left = (working.get(unit.runId) ?? 1) - 1;
|
|
338
|
+
if (left === 0) working.delete(unit.runId);
|
|
339
|
+
else working.set(unit.runId, left);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async function runLeased(session: string, unit: LeasedUnit): Promise<void> {
|
|
344
|
+
const def = byId.get(unit.workflow);
|
|
345
|
+
const finishing = unit.kind === 'finish';
|
|
346
|
+
// a step inside a map or parallel is found by its path, `units[U2].build` (map-steps AC 27)
|
|
347
|
+
const found =
|
|
348
|
+
def === undefined || finishing ? undefined : (stepAt(def as unknown as Pick<Manifest, 'steps'>, unit.step) as unknown as AnyStep | undefined);
|
|
349
|
+
// a human step never becomes a unit; a unit for one would be a server bug
|
|
350
|
+
const step = found?.kind === 'task' ? found : undefined;
|
|
351
|
+
const buffer: WorkerEvent[] = [];
|
|
352
|
+
const drain = () => buffer.splice(0, buffer.length);
|
|
353
|
+
const push = (type: EmitType, data: Record<string, unknown>) =>
|
|
354
|
+
buffer.push({ type, time: new Date().toISOString(), data });
|
|
355
|
+
const abort = new AbortController();
|
|
356
|
+
// a stop lets the unit finish; only a hard stop drops it (AD-090)
|
|
357
|
+
const unitSignal = AbortSignal.any([abort.signal, hard.signal]);
|
|
358
|
+
let lost = false;
|
|
359
|
+
|
|
360
|
+
const beat = setInterval(() => {
|
|
361
|
+
client.heartbeat(session, unit.unitId, unit.leaseToken, drain()).catch((err: unknown) => {
|
|
362
|
+
if (err instanceof ApiError) {
|
|
363
|
+
lost = true;
|
|
364
|
+
abort.abort();
|
|
365
|
+
log(`${unit.unitId}: ${err.message}`);
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
}, heartbeatMs);
|
|
369
|
+
|
|
370
|
+
const runDir = join(root, unit.runId);
|
|
371
|
+
const shown = (abs: string) => `/${unit.runId}${abs === runDir ? '' : '/' + relative(runDir, abs).split(sep).join('/')}`;
|
|
372
|
+
const ensureRunDir = () => {
|
|
373
|
+
if (existsSync(runDir)) return;
|
|
374
|
+
mkdirSync(runDir, { recursive: true });
|
|
375
|
+
push('workspace.created', { path: shown(runDir) });
|
|
376
|
+
};
|
|
377
|
+
const logFn = (msg: string, level: 'debug' | 'info' | 'warn' | 'error' = 'info') => push('log', { level, msg });
|
|
378
|
+
const execs: { killAll(): void }[] = [];
|
|
379
|
+
const execIn = (base: string) => {
|
|
380
|
+
const e = createExec({
|
|
381
|
+
base,
|
|
382
|
+
root: runDir,
|
|
383
|
+
signal: unitSignal,
|
|
384
|
+
secrets: secretNames,
|
|
385
|
+
line: (msg, stream) =>
|
|
386
|
+
push('log', stream === 'note' ? { level: 'info', msg } : { level: stream === 'stderr' ? 'warn' : 'info', msg, stream }),
|
|
387
|
+
});
|
|
388
|
+
execs.push(e);
|
|
389
|
+
return e.exec;
|
|
390
|
+
};
|
|
391
|
+
const emit = (type: EmitType, data: Record<string, unknown>) => {
|
|
392
|
+
if ((WORKER_EVENT_TYPES as readonly string[]).includes(type)) {
|
|
393
|
+
push(type as WorkerEventType, data);
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
// a domain event: declared by this workflow, its data parsed by the declared schema (door 5)
|
|
397
|
+
const schema = def?.events?.[type];
|
|
398
|
+
if (schema === undefined) {
|
|
399
|
+
throw new Error(`ctx.emit: "${type}" is not a worker event type`);
|
|
400
|
+
}
|
|
401
|
+
const parsed = schema.safeParse(data);
|
|
402
|
+
if (!parsed.success) {
|
|
403
|
+
const issues = parsed.error.issues.map((i) => `${i.path.join('.') || '(data)'}: ${i.message}`).join('; ');
|
|
404
|
+
throw new Error(`ctx.emit: ${type}: ${issues}`);
|
|
405
|
+
}
|
|
406
|
+
push(type, data);
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
// ctx.artifacts (door 3): the lease's list, plus what this unit put itself
|
|
410
|
+
const leased = unit.artifacts ?? [];
|
|
411
|
+
const ownByPath = new Map<string, ArtifactRef>();
|
|
412
|
+
const ownBySha = new Map<string, ArtifactRef>();
|
|
413
|
+
const read = (ref: ArtifactRef, bytes: Uint8Array): Artifact => ({
|
|
414
|
+
...ref,
|
|
415
|
+
bytes,
|
|
416
|
+
text: () => new TextDecoder().decode(bytes),
|
|
417
|
+
});
|
|
418
|
+
const notFound = (err: unknown) => err instanceof ApiError && err.status === 404;
|
|
419
|
+
const artifacts: Artifacts = {
|
|
420
|
+
async put(path, content, putOpts) {
|
|
421
|
+
const problems = artifactPathProblems(path);
|
|
422
|
+
if (problems.length > 0) throw new Error(`ctx.artifacts.put: path "${path}" ${problems.join('; ')}`);
|
|
423
|
+
if (putOpts?.mediaType !== undefined && !MEDIA_TYPE.test(putOpts.mediaType)) {
|
|
424
|
+
throw new Error(`ctx.artifacts.put: media type ${JSON.stringify(putOpts.mediaType)} is not printable ASCII of 1 to 200 chars`);
|
|
425
|
+
}
|
|
426
|
+
const bytes = typeof content === 'string' ? new TextEncoder().encode(content) : content;
|
|
427
|
+
if (bytes.byteLength > artifactMaxBytes) {
|
|
428
|
+
throw new Error(`ctx.artifacts.put: ${path} is ${bytes.byteLength} bytes, more than ${artifactMaxBytes}`);
|
|
429
|
+
}
|
|
430
|
+
const sha256 = createHash('sha256').update(bytes).digest('hex');
|
|
431
|
+
await retrying(() => client.worker.artifacts.put(session, unit.leaseToken, sha256, bytes));
|
|
432
|
+
const ref: ArtifactRef = { path, sha256, size: bytes.byteLength, mediaType: mediaTypeOf(path, content, putOpts?.mediaType) };
|
|
433
|
+
push('artifact.created', { ...ref });
|
|
434
|
+
ownByPath.set(path, ref);
|
|
435
|
+
ownBySha.set(sha256, ref);
|
|
436
|
+
return ref;
|
|
437
|
+
},
|
|
438
|
+
async get(ref) {
|
|
439
|
+
const known =
|
|
440
|
+
typeof ref === 'string'
|
|
441
|
+
? (ownByPath.get(ref) ?? leased.find((a) => a.path === ref))
|
|
442
|
+
: (ownBySha.get(ref.sha256) ?? [...leased].reverse().find((a) => a.sha256 === ref.sha256));
|
|
443
|
+
if (known === undefined && typeof ref === 'string') return null;
|
|
444
|
+
const sha256 = known?.sha256 ?? (ref as { sha256: string }).sha256;
|
|
445
|
+
try {
|
|
446
|
+
const r = await retrying(() => client.worker.artifacts.read(session, unit.leaseToken, sha256));
|
|
447
|
+
if (known !== undefined) return read(known, r.bytes);
|
|
448
|
+
// an older version: the server names the path the run last recorded it under (door 8)
|
|
449
|
+
if (r.path === null) return null;
|
|
450
|
+
return read({ path: r.path, sha256, size: r.bytes.byteLength, mediaType: r.mediaType ?? 'application/octet-stream' }, r.bytes);
|
|
451
|
+
} catch (err) {
|
|
452
|
+
if (notFound(err)) return null;
|
|
453
|
+
throw err;
|
|
454
|
+
}
|
|
455
|
+
},
|
|
456
|
+
};
|
|
457
|
+
|
|
458
|
+
const progress = (p: { label: string; pct?: number }) => {
|
|
459
|
+
const problems = workerEventProblems('progress', p);
|
|
460
|
+
if (problems.length > 0) throw new Error(`ctx.progress: ${problems.join('; ')}`);
|
|
461
|
+
// only the last unsent progress goes out (door 4)
|
|
462
|
+
for (let i = buffer.length - 1; i >= 0; i--) if (buffer[i]!.type === 'progress') buffer.splice(i, 1);
|
|
463
|
+
push('progress', { ...p });
|
|
464
|
+
};
|
|
465
|
+
|
|
466
|
+
// ctx.plugins: each slot bound by the lease; a call is one request to the server, which runs
|
|
467
|
+
// the action with its own key and appends plugin.action.* (AD-048). Never retried
|
|
468
|
+
const apis: Record<string, PluginActions> = {};
|
|
469
|
+
for (const [slotName, binding] of Object.entries(unit.plugins ?? {})) {
|
|
470
|
+
const plugin = def?.plugins?.[slotName]?.plugin;
|
|
471
|
+
if (plugin === undefined || plugin.id !== binding.plugin) continue;
|
|
472
|
+
apis[slotName] = Object.fromEntries(
|
|
473
|
+
actionNames(plugin, binding.config).map((action) => [
|
|
474
|
+
action,
|
|
475
|
+
(...args: unknown[]) => client.worker.units.action(session, unit.unitId, unit.leaseToken, { slot: slotName, action, args }),
|
|
476
|
+
]),
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
const settings = unit.settings ?? {};
|
|
480
|
+
|
|
481
|
+
// ctx.effects (boss-sdd-gaps door 2): the lease's pending effects, plus what this unit defers
|
|
482
|
+
type Pending = { effectId: string; name: string; args: unknown[] };
|
|
483
|
+
const pending: Pending[] = [...(unit.effects ?? [])];
|
|
484
|
+
let deferred = 0;
|
|
485
|
+
const effects: Effects = {
|
|
486
|
+
defer(name: string, ...args: unknown[]) {
|
|
487
|
+
const fail = (why: string): never => {
|
|
488
|
+
throw new Error(`ctx.effects.defer: ${why}`);
|
|
489
|
+
};
|
|
490
|
+
if (typeof name !== 'string' || !EFFECT_NAME.test(name)) fail(`"${String(name)}" is not <slot>.<action>`);
|
|
491
|
+
const [slotName, action] = [name.slice(0, name.indexOf('.')), name.slice(name.indexOf('.') + 1)];
|
|
492
|
+
if (!Object.hasOwn(def?.plugins ?? {}, slotName)) fail(`slot "${slotName}" is not declared by ${unit.workflow}`);
|
|
493
|
+
const actions = Object.hasOwn(apis, slotName) ? apis[slotName]! : undefined;
|
|
494
|
+
if (actions === undefined) fail(`slot "${slotName}" is not bound to an instance`);
|
|
495
|
+
if (!Object.hasOwn(actions!, action)) fail(`plugin ${def!.plugins![slotName]!.plugin.id} has no action "${action}"`);
|
|
496
|
+
let json: string | undefined;
|
|
497
|
+
try {
|
|
498
|
+
json = JSON.stringify(args);
|
|
499
|
+
} catch (err) {
|
|
500
|
+
fail(`args of ${name} are not JSON: ${err instanceof Error ? err.message : String(err)}`);
|
|
501
|
+
}
|
|
502
|
+
const bytes = outputBytes(args);
|
|
503
|
+
if (bytes > OUTPUT_MAX_BYTES) fail(`args of ${name} are ${bytes} bytes, more than ${OUTPUT_MAX_BYTES}`);
|
|
504
|
+
const e: Pending = { effectId: effectId(unit.unitId, ++deferred), name, args: JSON.parse(json!) as unknown[] };
|
|
505
|
+
pending.push(e);
|
|
506
|
+
push('effect.deferred', { ...e });
|
|
507
|
+
return e.effectId;
|
|
508
|
+
},
|
|
509
|
+
async release(opts = {}) {
|
|
510
|
+
const out: { effectId: string; name: string; result: unknown }[] = [];
|
|
511
|
+
for (const e of pending.filter((x) => opts.name === undefined || x.name === opts.name)) {
|
|
512
|
+
const at = e.name.indexOf('.');
|
|
513
|
+
const fn = apis[e.name.slice(0, at)]?.[e.name.slice(at + 1)];
|
|
514
|
+
// done either way: an applied or failed effect is never applied again (door 1)
|
|
515
|
+
pending.splice(pending.indexOf(e), 1);
|
|
516
|
+
const started = Date.now();
|
|
517
|
+
try {
|
|
518
|
+
if (fn === undefined) throw new Error(`${e.name} is not an action of this worker's slots`);
|
|
519
|
+
const result = await fn(...e.args);
|
|
520
|
+
push('effect.applied', { effectId: e.effectId, name: e.name, durationMs: Date.now() - started });
|
|
521
|
+
out.push({ effectId: e.effectId, name: e.name, result });
|
|
522
|
+
} catch (err) {
|
|
523
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
524
|
+
push('effect.failed', { effectId: e.effectId, name: e.name, error: cut(error, PLUGIN_ERROR_MAX) });
|
|
525
|
+
throw err;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
return out;
|
|
529
|
+
},
|
|
530
|
+
} as Effects;
|
|
531
|
+
|
|
532
|
+
// ctx.pause (door 7): after the outcome from run, instead of the unit from beforeUnit
|
|
533
|
+
let pauseReason: string | undefined;
|
|
534
|
+
const pause = (reason: string) => {
|
|
535
|
+
if (typeof reason !== 'string' || reason.length === 0 || reason.length > PAUSE_REASON_MAX) {
|
|
536
|
+
throw new Error(`ctx.pause: the reason must be 1 to ${PAUSE_REASON_MAX} chars`);
|
|
537
|
+
}
|
|
538
|
+
pauseReason = reason;
|
|
539
|
+
};
|
|
540
|
+
|
|
541
|
+
const runCtx = (): RunContext<unknown> => ({
|
|
542
|
+
runId: unit.runId,
|
|
543
|
+
input: unit.input,
|
|
544
|
+
runDir,
|
|
545
|
+
wd: runDir,
|
|
546
|
+
exec: execIn(runDir),
|
|
547
|
+
log: logFn,
|
|
548
|
+
emit,
|
|
549
|
+
signal: unitSignal,
|
|
550
|
+
artifacts,
|
|
551
|
+
plugins: apis,
|
|
552
|
+
settings,
|
|
553
|
+
});
|
|
554
|
+
|
|
555
|
+
/** The task unit: run folder, preInit, beforeUnit, task (run-workspace path 3). */
|
|
556
|
+
async function task(): Promise<CompleteBody> {
|
|
557
|
+
if (step === undefined) throw new Error(`this worker has no step ${unit.workflow}/${unit.step}`);
|
|
558
|
+
const marker = join(root, '.ready', unit.runId);
|
|
559
|
+
// another slot runs this run's preInit: wait for it, then look at the marker again. From
|
|
560
|
+
// here to `preparing.set` nothing awaits, so two units never both start it
|
|
561
|
+
for (let pending = preparing.get(unit.runId); pending !== undefined; pending = preparing.get(unit.runId)) await pending;
|
|
562
|
+
const ready = existsSync(marker) && existsSync(runDir);
|
|
563
|
+
ensureRunDir();
|
|
564
|
+
let wd: string;
|
|
565
|
+
try {
|
|
566
|
+
const sub = unit.wd ?? step.wd;
|
|
567
|
+
wd = sub === undefined ? runDir : confined(runDir, runDir, sub);
|
|
568
|
+
mkdirSync(wd, { recursive: true });
|
|
569
|
+
if (!inside(realpathSync(runDir), realpathSync(wd))) throw new Error('escapes');
|
|
570
|
+
} catch {
|
|
571
|
+
return { error: { message: 'wd escapes the run folder' }, events: [] };
|
|
572
|
+
}
|
|
573
|
+
const hooks = def?.hooks;
|
|
574
|
+
if (!ready) {
|
|
575
|
+
let settled!: () => void;
|
|
576
|
+
preparing.set(unit.runId, new Promise<void>((resolve) => (settled = resolve)));
|
|
577
|
+
try {
|
|
578
|
+
if (hooks?.preInit !== undefined) {
|
|
579
|
+
const preInit = hooks.preInit;
|
|
580
|
+
const failed = await hooked('preInit', push, () => preInit(runCtx()));
|
|
581
|
+
// no marker: a unit that waited runs preInit itself (multi-slot-workers AC 9)
|
|
582
|
+
if (failed !== undefined) return { error: { message: failed, kind: 'hook', hook: 'preInit' }, events: [] };
|
|
583
|
+
}
|
|
584
|
+
mkdirSync(dirname(marker), { recursive: true });
|
|
585
|
+
writeFileSync(marker, '');
|
|
586
|
+
} finally {
|
|
587
|
+
preparing.delete(unit.runId);
|
|
588
|
+
settled();
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
const outputs = unit.outputs ?? {};
|
|
592
|
+
const visits = unit.visits ?? {};
|
|
593
|
+
const index = indexes.get(unit.workflow)!;
|
|
594
|
+
const agent = opts.agent;
|
|
595
|
+
// ctx.agent's accounts (agent-accounts door 5): one grant per session, under the unit's lease
|
|
596
|
+
const accounts: AgentAccounts = {
|
|
597
|
+
async acquire(harness, acquireOpts = {}) {
|
|
598
|
+
let got;
|
|
599
|
+
try {
|
|
600
|
+
got = await retrying(() =>
|
|
601
|
+
client.worker.units.acquireAccount(session, unit.unitId, unit.leaseToken, { harness: harness as 'claude-code', ...acquireOpts }),
|
|
602
|
+
);
|
|
603
|
+
} catch (err) {
|
|
604
|
+
if (err instanceof ApiError && err.code === 'code_factory/agent_account_unavailable') {
|
|
605
|
+
throw new AccountUnavailableError(err.retryAt ?? null, err.message);
|
|
606
|
+
}
|
|
607
|
+
throw err;
|
|
608
|
+
}
|
|
609
|
+
if (got === null) return null;
|
|
610
|
+
const { grant, account, env: grantEnv } = got;
|
|
611
|
+
let released = false;
|
|
612
|
+
return {
|
|
613
|
+
account,
|
|
614
|
+
env: grantEnv,
|
|
615
|
+
// under the worker's own data folder, beside its credential (agent-accounts AC 17)
|
|
616
|
+
home: join(dataDir, 'agent-accounts', account),
|
|
617
|
+
async release(report) {
|
|
618
|
+
if (released) return;
|
|
619
|
+
released = true;
|
|
620
|
+
await retrying(() => client.worker.units.releaseAccount(session, unit.unitId, unit.leaseToken, grant, report));
|
|
621
|
+
},
|
|
622
|
+
};
|
|
623
|
+
},
|
|
624
|
+
};
|
|
625
|
+
const sessions = createRunSessions(root, unit.runId);
|
|
626
|
+
const setTitle = async (title: string): Promise<void> => {
|
|
627
|
+
await client.worker.units.setRunMeta(session, unit.unitId, unit.leaseToken, { title });
|
|
628
|
+
};
|
|
629
|
+
const ctx: TaskContext<unknown> = {
|
|
630
|
+
runId: unit.runId,
|
|
631
|
+
unitId: unit.unitId,
|
|
632
|
+
step: unit.step,
|
|
633
|
+
visit: unit.visit,
|
|
634
|
+
attempt: unit.attempt,
|
|
635
|
+
input: unit.input,
|
|
636
|
+
outputs,
|
|
637
|
+
...(unit.item !== undefined ? { item: unit.item } : {}),
|
|
638
|
+
runDir,
|
|
639
|
+
wd,
|
|
640
|
+
exec: execIn(wd),
|
|
641
|
+
signal: unitSignal,
|
|
642
|
+
log: logFn,
|
|
643
|
+
emit,
|
|
644
|
+
artifacts,
|
|
645
|
+
progress,
|
|
646
|
+
plugins: apis,
|
|
647
|
+
settings,
|
|
648
|
+
effects,
|
|
649
|
+
visits,
|
|
650
|
+
pause,
|
|
651
|
+
claimKey: async (key: string) => ({ claimed: (await client.worker.units.claimKey(session, unit.unitId, unit.leaseToken, key)).claimed }),
|
|
652
|
+
setTitle,
|
|
653
|
+
addLink: async (link) => {
|
|
654
|
+
const r = await client.worker.units.setRunMeta(session, unit.unitId, unit.leaseToken, { links: [link] });
|
|
655
|
+
return { added: r.added.some((l) => l.url === link.url) };
|
|
656
|
+
},
|
|
657
|
+
agent: async (request) => {
|
|
658
|
+
if (agent === undefined) throw new Error(`no agent runner on worker ${opts.name}`);
|
|
659
|
+
const result = await agent({ ...ctx, accounts, sessions }, request);
|
|
660
|
+
// a completed output's `_title` names the run (AD-085); the output goes back unchanged
|
|
661
|
+
const out: unknown = result.status === 'completed' ? result.output : undefined;
|
|
662
|
+
if (out !== null && typeof out === 'object' && !Array.isArray(out)) {
|
|
663
|
+
const title = (out as Record<string, unknown>)[RUN_TITLE_KEY];
|
|
664
|
+
// a title the server refuses is logged: it does not undo the agent's work
|
|
665
|
+
if (typeof title === 'string') {
|
|
666
|
+
await setTitle(title).catch((err: unknown) => logFn(`${RUN_TITLE_KEY} not set: ${err instanceof Error ? err.message : String(err)}`, 'warn'));
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
return result;
|
|
670
|
+
},
|
|
671
|
+
output: ((s: object) => outputOf(index, unit.workflow, s, unit.step, outputs)) as TaskContext<unknown>['output'],
|
|
672
|
+
visitsOf: ((s: object) => visitsOf(index, unit.workflow, s, unit.step, visits)) as TaskContext<unknown>['visitsOf'],
|
|
673
|
+
};
|
|
674
|
+
if (hooks?.beforeUnit !== undefined) {
|
|
675
|
+
const beforeUnit = hooks.beforeUnit;
|
|
676
|
+
const failed = await hooked('beforeUnit', push, () => beforeUnit(ctx));
|
|
677
|
+
if (failed !== undefined) return { error: { message: failed, kind: 'hook', hook: 'beforeUnit' }, events: [] };
|
|
678
|
+
// the quota guard: the unit goes back to the queue unrun (door 7)
|
|
679
|
+
if (pauseReason !== undefined) return { yield: { reason: pauseReason }, events: [] };
|
|
680
|
+
}
|
|
681
|
+
// a hook may have changed the folder: check the wd again before the task runs in it
|
|
682
|
+
if (!existsSync(wd) || !inside(realpathSync(runDir), realpathSync(wd))) {
|
|
683
|
+
return { error: { message: 'wd escapes the run folder' }, events: [] };
|
|
684
|
+
}
|
|
685
|
+
const result = await step.run(ctx);
|
|
686
|
+
// the step's output schema (door 5, AD-031): what it parses is sent; a refusal is a crash
|
|
687
|
+
if (step.output !== undefined && result.output !== undefined) {
|
|
688
|
+
const parsed = step.output.safeParse(result.output);
|
|
689
|
+
if (!parsed.success) {
|
|
690
|
+
const issue = parsed.error.issues[0]!;
|
|
691
|
+
return { error: { message: `output of ${unit.step}: ${issue.path.join('.') || '(output)'}: ${issue.message}` }, events: [] };
|
|
692
|
+
}
|
|
693
|
+
result.output = parsed.data;
|
|
694
|
+
}
|
|
695
|
+
// the output cap (door 6, AD-012): fail the unit here rather than send what the server refuses
|
|
696
|
+
const tooLarge = result.output === undefined ? undefined : outputProblem(result.output);
|
|
697
|
+
if (tooLarge !== undefined) return { error: { message: tooLarge }, events: [] };
|
|
698
|
+
return {
|
|
699
|
+
outcome: result.outcome,
|
|
700
|
+
...(result.output !== undefined ? { output: result.output } : {}),
|
|
701
|
+
...(pauseReason !== undefined ? { pause: { reason: pauseReason } } : {}),
|
|
702
|
+
events: [],
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/** The finish unit: onFinish, then keepWorkspace (run-workspace path 6). */
|
|
707
|
+
async function finish(): Promise<CompleteBody> {
|
|
708
|
+
ensureRunDir();
|
|
709
|
+
// a server that sends no status gets the cautious reading: kept under onFailure
|
|
710
|
+
const status = unit.runStatus ?? 'failed';
|
|
711
|
+
let failed = false;
|
|
712
|
+
const onFinish = def?.hooks?.onFinish;
|
|
713
|
+
if (onFinish !== undefined) {
|
|
714
|
+
const ctx: FinishContext<unknown> = { ...runCtx(), status, outputs: unit.outputs ?? {} };
|
|
715
|
+
failed = (await hooked('onFinish', push, () => onFinish(ctx))) !== undefined;
|
|
716
|
+
}
|
|
717
|
+
const policy = toManifest(def!).policy?.keepWorkspace ?? 'onFailure';
|
|
718
|
+
const keep = policy === 'always' || (policy === 'onFailure' && (status !== 'succeeded' || failed));
|
|
719
|
+
for (const e of execs) e.killAll();
|
|
720
|
+
if (keep) {
|
|
721
|
+
push('workspace.kept', { path: shown(runDir), reason: policy === 'always' ? 'always' : 'failure' });
|
|
722
|
+
} else {
|
|
723
|
+
discard(runDir);
|
|
724
|
+
rmSync(join(root, '.ready', unit.runId), { force: true });
|
|
725
|
+
cleanupRunSessions(root, unit.runId);
|
|
726
|
+
push('workspace.deleted', { path: shown(runDir) });
|
|
727
|
+
}
|
|
728
|
+
return { outcome: 'finished', events: [] };
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
// A lost or cancelled unit (door 4) is dropped at once: a task that ignores ctx.signal is
|
|
732
|
+
// abandoned, and whatever it settles to later is ignored. So is the unit of a worker's hard
|
|
733
|
+
// stop (a second SIGTERM, or the drain's deadline, AD-090): what it settles to is the stop's
|
|
734
|
+
// doing (a killed `pnpm install` fails its hook), so it is not reported; its lease expires and
|
|
735
|
+
// the server retries it as lost. A first stop lets it finish and report.
|
|
736
|
+
const dropped = new Promise<'dropped'>((resolve) => {
|
|
737
|
+
if (unitSignal.aborted) resolve('dropped');
|
|
738
|
+
else unitSignal.addEventListener('abort', () => resolve('dropped'), { once: true });
|
|
739
|
+
});
|
|
740
|
+
let body: CompleteBody;
|
|
741
|
+
try {
|
|
742
|
+
if (def === undefined) throw new Error(`this worker has no workflow ${unit.workflow}`);
|
|
743
|
+
const work = Promise.resolve().then(() => (finishing ? finish() : task()));
|
|
744
|
+
work.catch(() => {});
|
|
745
|
+
const result = await Promise.race([work, dropped]);
|
|
746
|
+
if (result === 'dropped') return;
|
|
747
|
+
body = result;
|
|
748
|
+
} catch (err) {
|
|
749
|
+
body = { error: { message: err instanceof Error ? err.message : String(err) }, events: [] };
|
|
750
|
+
} finally {
|
|
751
|
+
clearInterval(beat);
|
|
752
|
+
// a process the unit started and left running dies with the unit (AC 28)
|
|
753
|
+
for (const e of execs) e.killAll();
|
|
754
|
+
}
|
|
755
|
+
if (lost) return;
|
|
756
|
+
body.events = drain();
|
|
757
|
+
try {
|
|
758
|
+
await retrying(() => client.complete(session, unit.unitId, unit.leaseToken, body));
|
|
759
|
+
} catch (err) {
|
|
760
|
+
if (!(err instanceof ApiError)) throw err;
|
|
761
|
+
log(`${unit.unitId}: result discarded: ${err.message}`);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* One check round (health-ready AC 13-15): each workflow's `workerReady` once, with
|
|
767
|
+
* `workerSetup`'s context, bounded by `checkTimeoutMs`. A workflow without one is ready.
|
|
768
|
+
*/
|
|
769
|
+
async function checkRound(): Promise<CheckOutcome[]> {
|
|
770
|
+
return Promise.all(
|
|
771
|
+
opts.workflows.map(async (w): Promise<CheckOutcome> => {
|
|
772
|
+
const base = { workflow: w.id, version: w.version };
|
|
773
|
+
const ready = w.hooks?.workerReady;
|
|
774
|
+
if (ready === undefined) return { ...base, ready: true, problems: [], fatal: false };
|
|
775
|
+
const dir = join(root, '.setup', w.id);
|
|
776
|
+
mkdirSync(dir, { recursive: true });
|
|
777
|
+
const kills: (() => void)[] = [];
|
|
778
|
+
try {
|
|
779
|
+
const r = await bounded(
|
|
780
|
+
(checkSignal) => {
|
|
781
|
+
const { exec, killAll } = createExec({
|
|
782
|
+
base: dir,
|
|
783
|
+
root: dir,
|
|
784
|
+
signal: checkSignal,
|
|
785
|
+
line: (msg, stream) => log(`${w.id} workerReady${stream === 'note' ? '' : ` ${stream}`}: ${msg}`),
|
|
786
|
+
});
|
|
787
|
+
kills.push(killAll);
|
|
788
|
+
return ready({ workflow: { id: w.id, version: w.version }, dir, exec, log: (msg) => log(`${w.id} workerReady: ${msg}`), signal: checkSignal });
|
|
789
|
+
},
|
|
790
|
+
checkTimeoutMs,
|
|
791
|
+
signal,
|
|
792
|
+
);
|
|
793
|
+
if (r.ok) return { ...base, ready: true, problems: [], fatal: false };
|
|
794
|
+
// the server takes problems of at most 2000 chars: a longer reason is cut, never refused
|
|
795
|
+
return { ...base, ready: false, problems: [cut(`workflow ${w.id}: ${r.reason}`, PROBLEM_MAX)], fatal: r.fatal === true };
|
|
796
|
+
} finally {
|
|
797
|
+
for (const kill of kills) kill();
|
|
798
|
+
}
|
|
799
|
+
}),
|
|
800
|
+
);
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/**
|
|
804
|
+
* The carried workflow a run folder belongs to (door 5): a run id is `<id>-<n>`, and with `n`
|
|
805
|
+
* all digits at most one workflow id matches it.
|
|
806
|
+
*/
|
|
807
|
+
function workflowOfRun(runId: string): WorkflowDefinition | undefined {
|
|
808
|
+
return [...byId.values()].find((w) => runId.startsWith(`${w.id}-`) && /^\d+$/.test(runId.slice(w.id.length + 1)));
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
/** Where run folders wait for their background delete; a dot folder, so no run id. */
|
|
812
|
+
const trash = join(root, '.trash');
|
|
813
|
+
let discarded = 0;
|
|
814
|
+
|
|
815
|
+
/**
|
|
816
|
+
* Takes a folder out of the workspace root at once and deletes it in the background. A run
|
|
817
|
+
* folder holds ~50k entries, and on NFS a synchronous `rmSync` blocked the event loop for
|
|
818
|
+
* seconds per folder (heartbeats, probes, keep-alive sockets; see `folderSize`). The rename is
|
|
819
|
+
* one call on the same filesystem, so the run's path is free before this returns and nothing
|
|
820
|
+
* can start writing into the folder being deleted; a failed rename throws. A failed delete is
|
|
821
|
+
* logged and left in `.trash`, which `emptyTrash` clears at the next start.
|
|
822
|
+
*/
|
|
823
|
+
function discard(path: string): void {
|
|
824
|
+
if (!existsSync(path)) return;
|
|
825
|
+
mkdirSync(trash, { recursive: true });
|
|
826
|
+
const to = join(trash, `${process.pid}-${Date.now()}-${discarded++}`);
|
|
827
|
+
renameSync(path, to);
|
|
828
|
+
void rm(to, { recursive: true, force: true }).catch((err: unknown) =>
|
|
829
|
+
log(`could not delete ${to}: ${err instanceof Error ? err.message : String(err)}`),
|
|
830
|
+
);
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/** At start: deletes in the background what a previous process left in `.trash`. */
|
|
834
|
+
function emptyTrash(): void {
|
|
835
|
+
let left: string[];
|
|
836
|
+
try {
|
|
837
|
+
left = readdirSync(trash);
|
|
838
|
+
} catch {
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
for (const name of left) {
|
|
842
|
+
void rm(join(trash, name), { recursive: true, force: true }).catch((err: unknown) =>
|
|
843
|
+
log(`could not delete ${join(trash, name)}: ${err instanceof Error ? err.message : String(err)}`),
|
|
844
|
+
);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* Deletes a run's folder, its ready marker and its session ledger, logging `why`; a folder that
|
|
850
|
+
* cannot be removed is logged and left (verification F2). Whether it is gone.
|
|
851
|
+
*/
|
|
852
|
+
function removeRun(runId: string, why: string): boolean {
|
|
853
|
+
try {
|
|
854
|
+
discard(join(root, runId));
|
|
855
|
+
rmSync(join(root, '.ready', runId), { force: true });
|
|
856
|
+
cleanupRunSessions(root, runId);
|
|
857
|
+
log(`deleted run folder ${runId} (${why})`);
|
|
858
|
+
return true;
|
|
859
|
+
} catch (err) {
|
|
860
|
+
log(`could not delete run folder ${runId}: ${err instanceof Error ? err.message : String(err)}`);
|
|
861
|
+
return false;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* Orphan run folders (run-affinity door 5, AD-070, ART-226): asks the server about each run
|
|
867
|
+
* folder this process is not working in, and deletes those `decide` says, by their workflow's
|
|
868
|
+
* `keepWorkspace` and the retention; a folder of a workflow it no longer carries counts as
|
|
869
|
+
* `onFailure`. Dot folders and names that are no run id are left alone. A failed check deletes
|
|
870
|
+
* nothing. Then reports what is left, and deletes the folders an admin asked for.
|
|
871
|
+
*/
|
|
872
|
+
async function collectWorkspaces(): Promise<void> {
|
|
873
|
+
let names: string[];
|
|
874
|
+
try {
|
|
875
|
+
names = readdirSync(root, { withFileTypes: true })
|
|
876
|
+
.filter((d) => d.isDirectory() && !d.name.startsWith('.') && isRunId(d.name))
|
|
877
|
+
.map((d) => d.name);
|
|
878
|
+
} catch {
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
/** each folder still on disk with its status: the server's answer, `running` while worked on */
|
|
882
|
+
const statuses = new Map<string, WorkspaceStatus>(names.filter((name) => working.has(name)).map((name) => [name, 'running']));
|
|
883
|
+
const candidates = names.filter((name) => !working.has(name));
|
|
884
|
+
const now = Date.now();
|
|
885
|
+
for (let i = 0; i < candidates.length; i += WORKSPACE_CHECK_MAX) {
|
|
886
|
+
const chunk = candidates.slice(i, i + WORKSPACE_CHECK_MAX);
|
|
887
|
+
let answer: { statuses: Record<string, WorkspaceStatus>; endedAt?: Record<string, string | null> };
|
|
888
|
+
try {
|
|
889
|
+
answer = await client.worker.workspaces.check(session, chunk);
|
|
890
|
+
} catch (err) {
|
|
891
|
+
log(`workspace check failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
for (const runId of chunk) {
|
|
895
|
+
const status = answer.statuses[runId];
|
|
896
|
+
if (status === undefined) continue;
|
|
897
|
+
// a slot may have leased a unit of the run while the check was out
|
|
898
|
+
if (working.has(runId)) {
|
|
899
|
+
statuses.set(runId, 'running');
|
|
900
|
+
continue;
|
|
901
|
+
}
|
|
902
|
+
statuses.set(runId, status);
|
|
903
|
+
const carried = workflowOfRun(runId);
|
|
904
|
+
const policy = carried === undefined ? 'onFailure' : (toManifest(carried).policy?.keepWorkspace ?? 'onFailure');
|
|
905
|
+
if (decide({ policy, status, endedAt: answer.endedAt?.[runId] ?? null, now, retainMs }) === 'keep') continue;
|
|
906
|
+
const why = policy === 'onFailure' && (status === 'failed' || status === 'aborted') ? `${status}, past retention` : status;
|
|
907
|
+
if (removeRun(runId, why)) statuses.delete(runId);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
await reportWorkspaces(statuses);
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/**
|
|
914
|
+
* `POST /w/workspaces/report` (ART-226): the folders left, largest first, then each deletion the
|
|
915
|
+
* answer names, unless a slot works on the run, the server answered `running`, or it is not here.
|
|
916
|
+
*/
|
|
917
|
+
async function reportWorkspaces(statuses: Map<string, WorkspaceStatus>): Promise<void> {
|
|
918
|
+
// one folder at a time: the walk yields to the event loop, and is concurrent inside a folder
|
|
919
|
+
const folders: WorkspaceFolder[] = [];
|
|
920
|
+
for (const [runId, status] of statuses) {
|
|
921
|
+
const { bytes, modifiedMs } = await folderSize(join(root, runId));
|
|
922
|
+
folders.push({ runId, bytes, modifiedAt: new Date(modifiedMs).toISOString(), status });
|
|
923
|
+
}
|
|
924
|
+
folders.sort((a, b) => b.bytes - a.bytes || a.runId.localeCompare(b.runId));
|
|
925
|
+
let asked: string[];
|
|
926
|
+
try {
|
|
927
|
+
asked = (await client.worker.workspaces.report(session, folders.slice(0, WORKSPACE_REPORT_MAX))).delete;
|
|
928
|
+
} catch (err) {
|
|
929
|
+
log(`workspace report failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
for (const runId of asked) {
|
|
933
|
+
const status = statuses.get(runId);
|
|
934
|
+
if (status === undefined || !existsSync(join(root, runId))) log(`kept run folder ${runId} (requested): not in the workspace root`);
|
|
935
|
+
else if (status === 'running' || working.has(runId)) log(`kept run folder ${runId} (requested): the run is running`);
|
|
936
|
+
else removeRun(runId, 'requested');
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
let session = '';
|
|
941
|
+
let current: WorkflowReadiness[] = [];
|
|
942
|
+
|
|
943
|
+
/** `POST /w/health` (AC 18): after each register, else only when the round changed. */
|
|
944
|
+
async function report(force: boolean): Promise<void> {
|
|
945
|
+
if (!force && sameReadiness(vitals.reported, current)) return;
|
|
946
|
+
const sent = current;
|
|
947
|
+
try {
|
|
948
|
+
await retrying(() => client.reportHealth(session, sent));
|
|
949
|
+
vitals.reported = sent;
|
|
950
|
+
} catch (err) {
|
|
951
|
+
// a lapsed session re-registers in the lease loop, which reports again
|
|
952
|
+
if (!(err instanceof ApiError)) throw err;
|
|
953
|
+
log(`health report refused: ${err.message}`);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
const strip = (round: CheckOutcome[]): WorkflowReadiness[] => round.map(({ fatal: _fatal, ...r }) => r);
|
|
958
|
+
|
|
959
|
+
const probes = healthPort === undefined ? undefined : await listenProbes(vitals, healthPort, healthHost);
|
|
960
|
+
if (probes !== undefined) log(`probes on http://${healthHost}:${healthPort} (/health, /ready)`);
|
|
961
|
+
let rounds: NodeJS.Timeout | undefined;
|
|
962
|
+
if (signal.aborted) onStop();
|
|
963
|
+
else signal.addEventListener('abort', onStop, { once: true });
|
|
964
|
+
if (opts.kill?.aborted) onKill();
|
|
965
|
+
else opts.kill?.addEventListener('abort', onKill, { once: true });
|
|
966
|
+
try {
|
|
967
|
+
// a kit secret the workflow's code reads must be in the env before anything starts (door 2)
|
|
968
|
+
for (const w of opts.workflows) {
|
|
969
|
+
for (const name of w.secrets ?? []) {
|
|
970
|
+
if ((env[name] ?? '') === '') throw new WorkerFatalError(`workflow ${w.id} needs ${name} in the worker's env`);
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
await serve();
|
|
974
|
+
} finally {
|
|
975
|
+
clearInterval(rounds);
|
|
976
|
+
clearTimeout(deadline);
|
|
977
|
+
signal.removeEventListener('abort', onStop);
|
|
978
|
+
opts.kill?.removeEventListener('abort', onKill);
|
|
979
|
+
if (probes !== undefined) await new Promise<void>((resolve) => probes.close(() => resolve()));
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
async function serve(): Promise<void> {
|
|
983
|
+
/** Each workflow's `workerSetup`, before the worker gets its token or registers (AC 7, 8). */
|
|
984
|
+
for (const w of opts.workflows) {
|
|
985
|
+
const setup = w.hooks?.workerSetup;
|
|
986
|
+
if (setup === undefined) continue;
|
|
987
|
+
const dir = join(root, '.setup', w.id);
|
|
988
|
+
mkdirSync(dir, { recursive: true });
|
|
989
|
+
const { exec, killAll } = createExec({
|
|
990
|
+
base: dir,
|
|
991
|
+
root: dir,
|
|
992
|
+
signal,
|
|
993
|
+
line: (msg, stream) => log(`${w.id} workerSetup${stream === 'note' ? '' : ` ${stream}`}: ${msg}`),
|
|
994
|
+
});
|
|
995
|
+
try {
|
|
996
|
+
await setup({ workflow: { id: w.id, version: w.version }, dir, exec, log: (msg) => log(`${w.id} workerSetup: ${msg}`), signal });
|
|
997
|
+
} catch (err) {
|
|
998
|
+
throw new WorkerFatalError(`workerSetup of ${w.id} failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
999
|
+
} finally {
|
|
1000
|
+
killAll();
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
const cred = await credential();
|
|
1005
|
+
session = await register(cred);
|
|
1006
|
+
// the first round decides before any lease: a fatal answer stops the worker (AD-050)
|
|
1007
|
+
const first = await checkRound();
|
|
1008
|
+
const fatal = first.find((o) => o.fatal);
|
|
1009
|
+
if (fatal !== undefined) throw new WorkerFatalError(fatal.problems[0] ?? `workflow ${fatal.workflow}: fatal`);
|
|
1010
|
+
current = strip(first);
|
|
1011
|
+
await report(true);
|
|
1012
|
+
emptyTrash();
|
|
1013
|
+
await collectWorkspaces();
|
|
1014
|
+
let checking = false;
|
|
1015
|
+
if (checkIntervalMs > 0) {
|
|
1016
|
+
rounds = setInterval(() => {
|
|
1017
|
+
if (checking || signal.aborted) return;
|
|
1018
|
+
checking = true;
|
|
1019
|
+
// a later fatal answer only makes its workflow unready (AC 17)
|
|
1020
|
+
void checkRound()
|
|
1021
|
+
.then(async (round) => {
|
|
1022
|
+
current = strip(round);
|
|
1023
|
+
await report(false);
|
|
1024
|
+
await collectWorkspaces();
|
|
1025
|
+
})
|
|
1026
|
+
.catch((err: unknown) => log(`check round failed: ${err instanceof Error ? err.message : String(err)}`))
|
|
1027
|
+
.finally(() => (checking = false));
|
|
1028
|
+
}, checkIntervalMs);
|
|
1029
|
+
}
|
|
1030
|
+
vitals.startLoop();
|
|
1031
|
+
// multi-slot-workers door 3: one lease request open at most, and only while a slot is free;
|
|
1032
|
+
// each leased unit runs beside the others
|
|
1033
|
+
const running = new Set<Promise<void>>();
|
|
1034
|
+
let failure: { err: unknown } | undefined;
|
|
1035
|
+
const stopped = new Promise<void>((resolve) => {
|
|
1036
|
+
if (signal.aborted) resolve();
|
|
1037
|
+
else signal.addEventListener('abort', () => resolve(), { once: true });
|
|
1038
|
+
});
|
|
1039
|
+
try {
|
|
1040
|
+
while (!signal.aborted && failure === undefined) {
|
|
1041
|
+
if (running.size >= slots) {
|
|
1042
|
+
await Promise.race([...running, stopped]);
|
|
1043
|
+
continue;
|
|
1044
|
+
}
|
|
1045
|
+
let unit: LeasedUnit | null;
|
|
1046
|
+
try {
|
|
1047
|
+
unit = await retrying(() => client.lease(session, signal), signal);
|
|
1048
|
+
} catch (err) {
|
|
1049
|
+
if (signal.aborted) break;
|
|
1050
|
+
if (err instanceof ApiError && err.status === 401) {
|
|
1051
|
+
session = await register(cred);
|
|
1052
|
+
await report(true);
|
|
1053
|
+
continue;
|
|
1054
|
+
}
|
|
1055
|
+
throw err;
|
|
1056
|
+
}
|
|
1057
|
+
if (unit === null) continue;
|
|
1058
|
+
const run: Promise<void> = runUnit(session, unit)
|
|
1059
|
+
.catch((err: unknown) => {
|
|
1060
|
+
failure ??= { err };
|
|
1061
|
+
})
|
|
1062
|
+
.finally(() => running.delete(run));
|
|
1063
|
+
running.add(run);
|
|
1064
|
+
}
|
|
1065
|
+
} finally {
|
|
1066
|
+
// a stop lets the units in flight finish (AD-090); a hard stop drops them at once (door 4)
|
|
1067
|
+
if (signal.aborted && !hard.signal.aborted && running.size > 0 && failure === undefined) await drain(running);
|
|
1068
|
+
await Promise.all(running);
|
|
1069
|
+
}
|
|
1070
|
+
if (failure !== undefined) throw failure.err;
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
/**
|
|
1074
|
+
* A stop with units in flight (AD-090): asks the server once to pause their runs, waits for the
|
|
1075
|
+
* units to settle, then asks again every `retryMs` until no run is `pausing`, so the replica's
|
|
1076
|
+
* next process finds them paused. A hard stop ends it; a refused call is logged.
|
|
1077
|
+
*/
|
|
1078
|
+
async function drain(running: Set<Promise<void>>): Promise<void> {
|
|
1079
|
+
const runs = [...working.keys()];
|
|
1080
|
+
log(`draining ${running.size} unit(s), up to ${drainTimeoutMs / 1000} s`);
|
|
1081
|
+
const killed = new Promise<'killed'>((resolve) => {
|
|
1082
|
+
if (hard.signal.aborted) resolve('killed');
|
|
1083
|
+
else hard.signal.addEventListener('abort', () => resolve('killed'), { once: true });
|
|
1084
|
+
});
|
|
1085
|
+
/** `p`, unless the hard stop comes first; a later rejection of `p` is then ignored */
|
|
1086
|
+
const unlessKilled = <T>(p: Promise<T>): Promise<T | 'killed'> => {
|
|
1087
|
+
p.catch(() => {});
|
|
1088
|
+
return Promise.race([p, killed]);
|
|
1089
|
+
};
|
|
1090
|
+
const ask = () => unlessKilled(retrying(() => client.worker.drain(session, runs)));
|
|
1091
|
+
try {
|
|
1092
|
+
if ((await ask()) === 'killed') return;
|
|
1093
|
+
if ((await unlessKilled(Promise.all(running))) === 'killed') return;
|
|
1094
|
+
for (;;) {
|
|
1095
|
+
const answer = await ask();
|
|
1096
|
+
if (answer === 'killed') return;
|
|
1097
|
+
if (!answer.some((r) => r.pause === 'pausing')) {
|
|
1098
|
+
log('drained');
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
if ((await unlessKilled(sleep(retryMs))) === 'killed') return;
|
|
1102
|
+
}
|
|
1103
|
+
} catch (err) {
|
|
1104
|
+
if (!hard.signal.aborted) log(`drain refused: ${err instanceof Error ? err.message : String(err)}`);
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
/** `slots`, else `CF_WORKER_SLOTS`, else 1; anything but a whole number in `1..64` is fatal (door 1). */
|
|
1110
|
+
function slotsOf(given: number | undefined, raw: string | undefined): number {
|
|
1111
|
+
if (given !== undefined) {
|
|
1112
|
+
if (!Number.isInteger(given) || given < 1 || given > WORKER_SLOTS_MAX) {
|
|
1113
|
+
throw new WorkerFatalError(`slots must be a whole number from 1 to ${WORKER_SLOTS_MAX}, got ${String(given)}`);
|
|
1114
|
+
}
|
|
1115
|
+
return given;
|
|
1116
|
+
}
|
|
1117
|
+
if (raw === undefined || raw === '') return 1;
|
|
1118
|
+
const n = Number(raw);
|
|
1119
|
+
if (!/^\d+$/.test(raw) || n < 1 || n > WORKER_SLOTS_MAX) {
|
|
1120
|
+
throw new WorkerFatalError(`CF_WORKER_SLOTS must be a whole number from 1 to ${WORKER_SLOTS_MAX}, got "${raw}"`);
|
|
1121
|
+
}
|
|
1122
|
+
return n;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
/** `workspaceRetainHours`, else what `fromEnv` reads; anything but a whole number ≥ 0 is fatal (ART-226). */
|
|
1126
|
+
function retainHoursOf(given: number | undefined, fromEnv: () => number): number {
|
|
1127
|
+
if (given === undefined) return fromEnv();
|
|
1128
|
+
if (!Number.isInteger(given) || given < 0) {
|
|
1129
|
+
throw new WorkerFatalError(`workspaceRetainHours must be a whole number, got ${String(given)}`);
|
|
1130
|
+
}
|
|
1131
|
+
return given;
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
/** `mode`, else `CF_WORKER_MODE`, else `multi`; any other value is fatal (door 4). */
|
|
1135
|
+
function modeOf(given: WorkerMode | undefined, raw: string | undefined): WorkerMode {
|
|
1136
|
+
const value: string | undefined = given ?? (raw === '' ? undefined : raw);
|
|
1137
|
+
if (value === undefined) return 'multi';
|
|
1138
|
+
if (!(WORKER_MODES as readonly string[]).includes(value)) {
|
|
1139
|
+
throw new WorkerFatalError(`${given !== undefined ? 'mode' : 'CF_WORKER_MODE'} must be single or multi, got "${value}"`);
|
|
1140
|
+
}
|
|
1141
|
+
return value as WorkerMode;
|
|
1142
|
+
}
|