@ship.zone/runner 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/.smartconfig.json +48 -0
- package/changelog.md +12 -0
- package/deno.json +41 -0
- package/deno.lock +1843 -0
- package/dist_npm/mod.d.ts +689 -0
- package/dist_npm/mod.js +8980 -0
- package/dist_rust/runnerworkspace_linux_amd64_musl +0 -0
- package/dist_rust/runnerworkspace_linux_arm64_musl +0 -0
- package/license.md +18 -0
- package/mod.ts +8 -0
- package/musl-copyright.md +81 -0
- package/package.json +58 -0
- package/readme.md +274 -0
- package/rust/.cargo/config.toml +5 -0
- package/rust/Cargo.lock +144 -0
- package/rust/Cargo.toml +17 -0
- package/rust/src/lib.rs +1784 -0
- package/rust/src/main.rs +6 -0
- package/third-party-licenses.md +95 -0
- package/ts/00_commitinfo_data.ts +8 -0
- package/ts/api-client.ts +1059 -0
- package/ts/artifact-manager.ts +218 -0
- package/ts/attempt-state.ts +190 -0
- package/ts/cache-manager.ts +431 -0
- package/ts/cli.ts +239 -0
- package/ts/config.ts +724 -0
- package/ts/errors.ts +68 -0
- package/ts/index.ts +13 -0
- package/ts/interfaces.ts +547 -0
- package/ts/log-sender.ts +134 -0
- package/ts/oci-executor.ts +2472 -0
- package/ts/plugins.ts +11 -0
- package/ts/protocol-validator.ts +535 -0
- package/ts/redactor.ts +41 -0
- package/ts/registration-state.ts +253 -0
- package/ts/runner.ts +1036 -0
- package/ts/source-workspace.ts +161 -0
- package/ts/staging-scavenger.ts +62 -0
- package/ts/transfer-archive.ts +1605 -0
- package/ts/validation.ts +77 -0
package/ts/runner.ts
ADDED
|
@@ -0,0 +1,1036 @@
|
|
|
1
|
+
import { AttemptStateStore } from './attempt-state.ts';
|
|
2
|
+
import {
|
|
3
|
+
AuthenticationError,
|
|
4
|
+
CoordinatorError,
|
|
5
|
+
LeaseLostError,
|
|
6
|
+
ProtocolError,
|
|
7
|
+
ResourceCleanupError,
|
|
8
|
+
RunnerError,
|
|
9
|
+
} from './errors.ts';
|
|
10
|
+
import type {
|
|
11
|
+
IAbandonJobRequest,
|
|
12
|
+
IAcceptJobRequest,
|
|
13
|
+
IArtifactManager,
|
|
14
|
+
ICacheManager,
|
|
15
|
+
IClaimJobRequest,
|
|
16
|
+
IClaimJobResponse,
|
|
17
|
+
ICompleteJobRequest,
|
|
18
|
+
ICompleteJobResponse,
|
|
19
|
+
IDiscoveryResponse,
|
|
20
|
+
IJobExecutor,
|
|
21
|
+
IJobHeartbeatRequest,
|
|
22
|
+
IJobHeartbeatResponse,
|
|
23
|
+
IJobIdentity,
|
|
24
|
+
IJobLease,
|
|
25
|
+
ILogAcknowledgement,
|
|
26
|
+
ILogChunk,
|
|
27
|
+
IPreparedOciLease,
|
|
28
|
+
IPreparedWorkspace,
|
|
29
|
+
IProtocolLimits,
|
|
30
|
+
IRecoverAttemptRequest,
|
|
31
|
+
IRunnerCapabilities,
|
|
32
|
+
IRunnerConfig,
|
|
33
|
+
IRunnerCredential,
|
|
34
|
+
IRunnerHeartbeatRequest,
|
|
35
|
+
IRunnerHeartbeatResponse,
|
|
36
|
+
IRunnerRunResult,
|
|
37
|
+
ISourcePrepareContext,
|
|
38
|
+
IStartSessionRequest,
|
|
39
|
+
IStartSessionResponse,
|
|
40
|
+
TExecutionStopReason,
|
|
41
|
+
TJobCompletionStatus,
|
|
42
|
+
} from './interfaces.ts';
|
|
43
|
+
import { runnerProtocolIdentifier, runnerVersion } from './interfaces.ts';
|
|
44
|
+
import { LogSender } from './log-sender.ts';
|
|
45
|
+
import { createRunnerCapabilitySnapshot, RunnerProtocolValidator } from './protocol-validator.ts';
|
|
46
|
+
import { scavengeRunnerStaging } from './staging-scavenger.ts';
|
|
47
|
+
|
|
48
|
+
export interface IRunnerCoordinatorClient {
|
|
49
|
+
discover(signal?: AbortSignal): Promise<IDiscoveryResponse>;
|
|
50
|
+
setRunnerToken(token: string): void;
|
|
51
|
+
startSession(request: IStartSessionRequest, signal?: AbortSignal): Promise<IStartSessionResponse>;
|
|
52
|
+
heartbeatRunner(
|
|
53
|
+
request: IRunnerHeartbeatRequest,
|
|
54
|
+
signal?: AbortSignal,
|
|
55
|
+
): Promise<IRunnerHeartbeatResponse>;
|
|
56
|
+
claimJob(request: IClaimJobRequest, signal?: AbortSignal): Promise<IClaimJobResponse>;
|
|
57
|
+
acceptJob(request: IAcceptJobRequest, signal?: AbortSignal): Promise<void>;
|
|
58
|
+
heartbeatJob(
|
|
59
|
+
request: IJobHeartbeatRequest,
|
|
60
|
+
signal?: AbortSignal,
|
|
61
|
+
): Promise<IJobHeartbeatResponse>;
|
|
62
|
+
appendLog(chunk: ILogChunk, signal?: AbortSignal): Promise<ILogAcknowledgement>;
|
|
63
|
+
completeJob(request: ICompleteJobRequest, signal?: AbortSignal): Promise<ICompleteJobResponse>;
|
|
64
|
+
abandonJob(request: IAbandonJobRequest, signal?: AbortSignal): Promise<void>;
|
|
65
|
+
recoverAttempt(request: IRecoverAttemptRequest, signal?: AbortSignal): Promise<void>;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface IRunnerWorkspaceManager {
|
|
69
|
+
prepare(context: ISourcePrepareContext): Promise<IPreparedWorkspace>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface IRunnerDependencies {
|
|
73
|
+
api: IRunnerCoordinatorClient;
|
|
74
|
+
executor: IJobExecutor;
|
|
75
|
+
workspaceManager: IRunnerWorkspaceManager;
|
|
76
|
+
artifactManager?: IArtifactManager;
|
|
77
|
+
cacheManager?: ICacheManager;
|
|
78
|
+
onCredential?: (credential: IRunnerCredential) => Promise<void>;
|
|
79
|
+
onMessage?: (message: string) => void;
|
|
80
|
+
now?: () => number;
|
|
81
|
+
sleep?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
interface IHeartbeatState {
|
|
85
|
+
cancellation?: NonNullable<IJobHeartbeatResponse['cancellation']>;
|
|
86
|
+
cancellationDeadline?: number;
|
|
87
|
+
systemFailure?: unknown;
|
|
88
|
+
terminalError?: unknown;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const identifierPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
92
|
+
const genericSystemError = 'Runner system error';
|
|
93
|
+
const containsControlCharacter = (value: string): boolean =>
|
|
94
|
+
[...value].some((character) => {
|
|
95
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
96
|
+
return codePoint < 0x20 || codePoint === 0x7f;
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
const defaultSleep = (milliseconds: number, signal?: AbortSignal): Promise<void> =>
|
|
100
|
+
new Promise((resolve, reject) => {
|
|
101
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
102
|
+
let settled = false;
|
|
103
|
+
const cleanup = (): void => signal?.removeEventListener('abort', onAbort);
|
|
104
|
+
const finish = (): void => {
|
|
105
|
+
if (settled) return;
|
|
106
|
+
settled = true;
|
|
107
|
+
cleanup();
|
|
108
|
+
resolve();
|
|
109
|
+
};
|
|
110
|
+
const onAbort = (): void => {
|
|
111
|
+
if (settled) return;
|
|
112
|
+
settled = true;
|
|
113
|
+
clearTimeout(timer);
|
|
114
|
+
cleanup();
|
|
115
|
+
reject(signal?.reason);
|
|
116
|
+
};
|
|
117
|
+
const timer = setTimeout(finish, milliseconds);
|
|
118
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
const identityFor = (runnerId: string, sessionId: string, lease: IJobLease): IJobIdentity => ({
|
|
122
|
+
runnerId,
|
|
123
|
+
sessionId,
|
|
124
|
+
jobId: lease.jobId,
|
|
125
|
+
attemptId: lease.attemptId,
|
|
126
|
+
leaseId: lease.leaseId,
|
|
127
|
+
fencingToken: lease.fencingToken,
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
const safeIdentityFromUnknown = (
|
|
131
|
+
runnerId: string,
|
|
132
|
+
sessionId: string,
|
|
133
|
+
lease: unknown,
|
|
134
|
+
): IJobIdentity | undefined => {
|
|
135
|
+
if (typeof lease !== 'object' || lease === null || Array.isArray(lease)) return undefined;
|
|
136
|
+
const record = lease as Record<string, unknown>;
|
|
137
|
+
const identifiers = ['jobId', 'attemptId', 'leaseId'] as const;
|
|
138
|
+
if (
|
|
139
|
+
identifiers.some((field) =>
|
|
140
|
+
typeof record[field] !== 'string' || !identifierPattern.test(record[field])
|
|
141
|
+
) ||
|
|
142
|
+
typeof record.fencingToken !== 'string' ||
|
|
143
|
+
record.fencingToken.length < 16 ||
|
|
144
|
+
record.fencingToken.length > 512 ||
|
|
145
|
+
containsControlCharacter(record.fencingToken)
|
|
146
|
+
) {
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
return {
|
|
150
|
+
runnerId,
|
|
151
|
+
sessionId,
|
|
152
|
+
jobId: record.jobId as string,
|
|
153
|
+
attemptId: record.attemptId as string,
|
|
154
|
+
leaseId: record.leaseId as string,
|
|
155
|
+
fencingToken: record.fencingToken,
|
|
156
|
+
};
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
const isDefinitiveConflict = (error: unknown): boolean =>
|
|
160
|
+
error instanceof LeaseLostError || error instanceof CoordinatorError && error.status === 409;
|
|
161
|
+
|
|
162
|
+
class LeaseGuard {
|
|
163
|
+
readonly controller = new AbortController();
|
|
164
|
+
definitive = false;
|
|
165
|
+
private timer?: ReturnType<typeof setTimeout>;
|
|
166
|
+
|
|
167
|
+
constructor(
|
|
168
|
+
private readonly limits: IProtocolLimits,
|
|
169
|
+
private readonly safetyMarginMs: number,
|
|
170
|
+
) {}
|
|
171
|
+
|
|
172
|
+
update(serverTime: string, leaseExpiresAt: string, requestElapsedMs = 0): void {
|
|
173
|
+
if (this.controller.signal.aborted) return;
|
|
174
|
+
const leaseDurationMs = Date.parse(leaseExpiresAt) - Date.parse(serverTime);
|
|
175
|
+
const minimumMs = this.limits.minimumLeaseSeconds * 1000;
|
|
176
|
+
const maximumMs = this.limits.maximumLeaseSeconds * 1000;
|
|
177
|
+
if (
|
|
178
|
+
!Number.isFinite(leaseDurationMs) || leaseDurationMs < minimumMs ||
|
|
179
|
+
leaseDurationMs > maximumMs
|
|
180
|
+
) {
|
|
181
|
+
throw new ProtocolError('Coordinator returned a lease duration outside discovery limits');
|
|
182
|
+
}
|
|
183
|
+
if (this.timer !== undefined) clearTimeout(this.timer);
|
|
184
|
+
const remaining = leaseDurationMs - Math.max(0, requestElapsedMs) - this.safetyMarginMs;
|
|
185
|
+
if (remaining <= 0) {
|
|
186
|
+
this.fence('lease_expired');
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
this.timer = setTimeout(() => this.fence('lease_expired'), remaining);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
fence(reason: 'lease_lost' | 'lease_expired' | 'runner_shutdown', definitive = false): void {
|
|
193
|
+
this.definitive ||= definitive;
|
|
194
|
+
if (!this.controller.signal.aborted) this.controller.abort(reason);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
close(): void {
|
|
198
|
+
if (this.timer !== undefined) clearTimeout(this.timer);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export const runnerCapabilities = (config: IRunnerConfig): IRunnerCapabilities => {
|
|
203
|
+
const artifactEnabled = config.maximumArtifacts > 0 && config.maximumArtifactBytes > 0 &&
|
|
204
|
+
config.maximumArtifactExtractedBytes > 0 && config.maximumArtifactEntries > 0;
|
|
205
|
+
const cacheEnabled = config.maximumCaches > 0 && config.maximumCacheArchiveBytes > 0 &&
|
|
206
|
+
config.maximumCacheExtractedBytes > 0 && config.maximumCacheEntries > 0;
|
|
207
|
+
return createRunnerCapabilitySnapshot({
|
|
208
|
+
executionProfiles: ['oci.v1'],
|
|
209
|
+
labels: [...config.labels],
|
|
210
|
+
features: [
|
|
211
|
+
'source.tar-gz',
|
|
212
|
+
...(artifactEnabled ? ['artifacts.v1' as const] : []),
|
|
213
|
+
...(cacheEnabled ? ['caches.v1' as const] : []),
|
|
214
|
+
],
|
|
215
|
+
networks: [...config.oci.allowedNetworks],
|
|
216
|
+
sourceFormats: ['tar.gz'],
|
|
217
|
+
limits: {
|
|
218
|
+
maximumSourceArchiveBytes: config.maximumSourceArchiveBytes,
|
|
219
|
+
maximumSourceExtractedBytes: config.maximumSourceExtractedBytes,
|
|
220
|
+
maximumSourceEntries: config.maximumSourceEntries,
|
|
221
|
+
maximumArtifactArchiveBytes: config.maximumArtifactBytes,
|
|
222
|
+
maximumArtifactExtractedBytes: config.maximumArtifactExtractedBytes,
|
|
223
|
+
maximumArtifactEntries: config.maximumArtifactEntries,
|
|
224
|
+
maximumArtifacts: config.maximumArtifacts,
|
|
225
|
+
maximumCacheArchiveBytes: config.maximumCacheArchiveBytes,
|
|
226
|
+
maximumCacheExtractedBytes: config.maximumCacheExtractedBytes,
|
|
227
|
+
maximumCacheEntries: config.maximumCacheEntries,
|
|
228
|
+
maximumCaches: config.maximumCaches,
|
|
229
|
+
maximumLogChunkBytes: config.maximumLogChunkBytes,
|
|
230
|
+
maximumTotalLogBytes: config.maximumLogBytes,
|
|
231
|
+
maximumWorkspaceBytes: config.oci.workspaceSizeBytes,
|
|
232
|
+
maximumWorkspaceEntries: config.maximumWorkspaceEntries,
|
|
233
|
+
},
|
|
234
|
+
});
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
export const reconcileProtocolLimits = (
|
|
238
|
+
config: IRunnerConfig,
|
|
239
|
+
discovery: IDiscoveryResponse,
|
|
240
|
+
capabilities: IRunnerCapabilities,
|
|
241
|
+
): void => {
|
|
242
|
+
if (discovery.protocol !== runnerProtocolIdentifier) {
|
|
243
|
+
throw new ProtocolError('Coordinator discovery protocol changed during startup');
|
|
244
|
+
}
|
|
245
|
+
if (config.maximumResponseBytes > discovery.limits.maximumJsonBytes) {
|
|
246
|
+
throw new ProtocolError('Configured JSON response limit exceeds coordinator discovery');
|
|
247
|
+
}
|
|
248
|
+
if (
|
|
249
|
+
capabilities.limits.maximumLogChunkBytes > discovery.limits.maximumLogChunkBytes ||
|
|
250
|
+
capabilities.limits.maximumTotalLogBytes > discovery.limits.maximumTotalLogBytes
|
|
251
|
+
) {
|
|
252
|
+
throw new ProtocolError('Advertised log limits exceed coordinator discovery');
|
|
253
|
+
}
|
|
254
|
+
if (
|
|
255
|
+
discovery.limits.minimumLeaseSeconds < 30 ||
|
|
256
|
+
discovery.limits.maximumLeaseSeconds > 600 ||
|
|
257
|
+
discovery.limits.minimumLeaseSeconds > discovery.limits.maximumLeaseSeconds
|
|
258
|
+
) {
|
|
259
|
+
throw new ProtocolError('Coordinator discovery lease limits are incompatible');
|
|
260
|
+
}
|
|
261
|
+
if (
|
|
262
|
+
config.jobHeartbeatIntervalMs + config.leaseSafetyMarginMs >=
|
|
263
|
+
discovery.limits.minimumLeaseSeconds * 1000
|
|
264
|
+
) {
|
|
265
|
+
throw new ProtocolError('Local heartbeat policy does not fit the minimum coordinator lease');
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
export class ShipRunner {
|
|
270
|
+
private drainRequested = false;
|
|
271
|
+
private sessionInvalid = false;
|
|
272
|
+
private readonly now: () => number;
|
|
273
|
+
private readonly sleep: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
|
|
274
|
+
|
|
275
|
+
constructor(
|
|
276
|
+
private readonly config: IRunnerConfig,
|
|
277
|
+
private readonly dependencies: IRunnerDependencies,
|
|
278
|
+
) {
|
|
279
|
+
this.now = dependencies.now ?? Date.now;
|
|
280
|
+
this.sleep = dependencies.sleep ?? defaultSleep;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async run(options: { once?: boolean; signal?: AbortSignal } = {}): Promise<IRunnerRunResult> {
|
|
284
|
+
const runnerId = this.config.runnerId;
|
|
285
|
+
if (
|
|
286
|
+
!runnerId || !this.config.runnerCredentialId || !this.config.runnerToken ||
|
|
287
|
+
!this.config.runnerTokenExpiresAt
|
|
288
|
+
) {
|
|
289
|
+
throw new RunnerError('Runner is not registered');
|
|
290
|
+
}
|
|
291
|
+
this.drainRequested = false;
|
|
292
|
+
this.sessionInvalid = false;
|
|
293
|
+
this.dependencies.api.setRunnerToken(this.config.runnerToken);
|
|
294
|
+
|
|
295
|
+
await this.dependencies.executor.verifyRuntime();
|
|
296
|
+
const discovery = await this.dependencies.api.discover(options.signal);
|
|
297
|
+
const capabilities = runnerCapabilities(this.config);
|
|
298
|
+
reconcileProtocolLimits(this.config, discovery, capabilities);
|
|
299
|
+
const validator = new RunnerProtocolValidator(capabilities);
|
|
300
|
+
const session = await this.dependencies.api.startSession({
|
|
301
|
+
sessionRequestId: crypto.randomUUID(),
|
|
302
|
+
runnerId,
|
|
303
|
+
protocol: runnerProtocolIdentifier,
|
|
304
|
+
runnerVersion,
|
|
305
|
+
capabilities,
|
|
306
|
+
}, options.signal);
|
|
307
|
+
if (session.credential) await this.applyCredential(session.credential);
|
|
308
|
+
|
|
309
|
+
const journal = new AttemptStateStore(this.config.stateDirectory);
|
|
310
|
+
const sessionLifecycle = new AbortController();
|
|
311
|
+
const externalAbort = (): void => sessionLifecycle.abort('runner_shutdown');
|
|
312
|
+
options.signal?.addEventListener('abort', externalAbort, { once: true });
|
|
313
|
+
if (options.signal?.aborted) externalAbort();
|
|
314
|
+
let heartbeatError: unknown;
|
|
315
|
+
const runnerHeartbeat = this.runnerHeartbeatLoop(
|
|
316
|
+
runnerId,
|
|
317
|
+
session.sessionId,
|
|
318
|
+
sessionLifecycle,
|
|
319
|
+
).catch((error) => {
|
|
320
|
+
heartbeatError = error;
|
|
321
|
+
if (!sessionLifecycle.signal.aborted) sessionLifecycle.abort('lease_lost');
|
|
322
|
+
});
|
|
323
|
+
let operationError: unknown;
|
|
324
|
+
let lastResult: IRunnerRunResult = { claimed: false };
|
|
325
|
+
try {
|
|
326
|
+
await this.dependencies.executor.reconcileOrphans(runnerId, session.sessionId);
|
|
327
|
+
await scavengeRunnerStaging(this.config.stateDirectory);
|
|
328
|
+
await this.recoverInterruptedAttempt(
|
|
329
|
+
journal,
|
|
330
|
+
runnerId,
|
|
331
|
+
session.sessionId,
|
|
332
|
+
sessionLifecycle.signal,
|
|
333
|
+
);
|
|
334
|
+
while (
|
|
335
|
+
!this.drainRequested && !this.sessionInvalid && !sessionLifecycle.signal.aborted
|
|
336
|
+
) {
|
|
337
|
+
lastResult = await this.runOnce(
|
|
338
|
+
runnerId,
|
|
339
|
+
session.sessionId,
|
|
340
|
+
capabilities,
|
|
341
|
+
validator,
|
|
342
|
+
discovery.limits,
|
|
343
|
+
journal,
|
|
344
|
+
sessionLifecycle.signal,
|
|
345
|
+
);
|
|
346
|
+
if (options.once) break;
|
|
347
|
+
if (!lastResult.claimed) {
|
|
348
|
+
await this.sleep(this.config.pollIntervalMs, sessionLifecycle.signal);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
} catch (error) {
|
|
352
|
+
if (error instanceof ResourceCleanupError) this.sessionInvalid = true;
|
|
353
|
+
operationError = error;
|
|
354
|
+
} finally {
|
|
355
|
+
if (!sessionLifecycle.signal.aborted) sessionLifecycle.abort('runner_shutdown');
|
|
356
|
+
options.signal?.removeEventListener('abort', externalAbort);
|
|
357
|
+
await runnerHeartbeat;
|
|
358
|
+
}
|
|
359
|
+
if (operationError instanceof ResourceCleanupError) throw operationError;
|
|
360
|
+
if (heartbeatError !== undefined) throw heartbeatError;
|
|
361
|
+
if (
|
|
362
|
+
operationError !== undefined &&
|
|
363
|
+
!(sessionLifecycle.signal.reason === 'runner_shutdown' &&
|
|
364
|
+
operationError === 'runner_shutdown')
|
|
365
|
+
) {
|
|
366
|
+
throw operationError;
|
|
367
|
+
}
|
|
368
|
+
return lastResult;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
private async recoverInterruptedAttempt(
|
|
372
|
+
journal: AttemptStateStore,
|
|
373
|
+
runnerId: string,
|
|
374
|
+
sessionId: string,
|
|
375
|
+
signal: AbortSignal,
|
|
376
|
+
): Promise<void> {
|
|
377
|
+
const interrupted = await journal.load();
|
|
378
|
+
if (!interrupted) return;
|
|
379
|
+
try {
|
|
380
|
+
await this.dependencies.api.recoverAttempt({
|
|
381
|
+
recoveryRequestId: crypto.randomUUID(),
|
|
382
|
+
runnerId,
|
|
383
|
+
currentSessionId: sessionId,
|
|
384
|
+
previousSessionId: interrupted.previousSessionId,
|
|
385
|
+
jobId: interrupted.jobId,
|
|
386
|
+
attemptId: interrupted.attemptId,
|
|
387
|
+
reason: 'runner_restarted',
|
|
388
|
+
}, signal);
|
|
389
|
+
} catch (error) {
|
|
390
|
+
if (!isDefinitiveConflict(error)) throw error;
|
|
391
|
+
}
|
|
392
|
+
await journal.clear();
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
private async runOnce(
|
|
396
|
+
runnerId: string,
|
|
397
|
+
sessionId: string,
|
|
398
|
+
capabilities: IRunnerCapabilities,
|
|
399
|
+
validator: RunnerProtocolValidator,
|
|
400
|
+
protocolLimits: IProtocolLimits,
|
|
401
|
+
journal: AttemptStateStore,
|
|
402
|
+
runnerSignal: AbortSignal,
|
|
403
|
+
): Promise<IRunnerRunResult> {
|
|
404
|
+
const claimStartedAt = this.now();
|
|
405
|
+
const claim = await this.dependencies.api.claimJob({
|
|
406
|
+
claimRequestId: crypto.randomUUID(),
|
|
407
|
+
runnerId,
|
|
408
|
+
sessionId,
|
|
409
|
+
capabilities,
|
|
410
|
+
}, runnerSignal);
|
|
411
|
+
const claimElapsedMs = Math.max(0, this.now() - claimStartedAt);
|
|
412
|
+
if (claim.lease === null) {
|
|
413
|
+
if (claim.retryAfterMs && claim.retryAfterMs > this.config.pollIntervalMs) {
|
|
414
|
+
await this.sleep(claim.retryAfterMs - this.config.pollIntervalMs, runnerSignal);
|
|
415
|
+
}
|
|
416
|
+
return { claimed: false };
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const unvalidatedIdentity = safeIdentityFromUnknown(runnerId, sessionId, claim.lease);
|
|
420
|
+
let lease: IJobLease;
|
|
421
|
+
try {
|
|
422
|
+
lease = await validator.validateJobLease(claim.lease);
|
|
423
|
+
} catch (error) {
|
|
424
|
+
if (!unvalidatedIdentity) throw error;
|
|
425
|
+
await this.abandon(unvalidatedIdentity, 'runner_error');
|
|
426
|
+
return { claimed: true, status: 'system_error' };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const identity = identityFor(runnerId, sessionId, lease);
|
|
430
|
+
const guard = new LeaseGuard(protocolLimits, this.config.leaseSafetyMarginMs);
|
|
431
|
+
const runnerAbort = (): void => {
|
|
432
|
+
const reason = runnerSignal.reason === 'runner_shutdown' ? 'runner_shutdown' : 'lease_lost';
|
|
433
|
+
guard.fence(reason);
|
|
434
|
+
};
|
|
435
|
+
runnerSignal.addEventListener('abort', runnerAbort, { once: true });
|
|
436
|
+
if (runnerSignal.aborted) runnerAbort();
|
|
437
|
+
let preparedLease: IPreparedOciLease | undefined;
|
|
438
|
+
const abandonAfterCleanupFailure = async (
|
|
439
|
+
error: ResourceCleanupError,
|
|
440
|
+
reason: IAbandonJobRequest['reason'],
|
|
441
|
+
): Promise<never> => {
|
|
442
|
+
this.sessionInvalid = true;
|
|
443
|
+
try {
|
|
444
|
+
await this.abandon(identity, reason);
|
|
445
|
+
} catch {
|
|
446
|
+
// The cleanup failure remains the terminal local invariant violation.
|
|
447
|
+
}
|
|
448
|
+
throw error;
|
|
449
|
+
};
|
|
450
|
+
const cleanupPreparedLease = async (
|
|
451
|
+
primaryError?: unknown,
|
|
452
|
+
message = 'OCI lease preparation cleanup failed',
|
|
453
|
+
): Promise<void> => {
|
|
454
|
+
const ownedPreparedLease = preparedLease;
|
|
455
|
+
preparedLease = undefined;
|
|
456
|
+
if (!ownedPreparedLease) return;
|
|
457
|
+
try {
|
|
458
|
+
await ownedPreparedLease.cleanup();
|
|
459
|
+
} catch (cleanupError) {
|
|
460
|
+
if (primaryError === undefined && cleanupError instanceof ResourceCleanupError) {
|
|
461
|
+
throw cleanupError;
|
|
462
|
+
}
|
|
463
|
+
throw new ResourceCleanupError(
|
|
464
|
+
message,
|
|
465
|
+
primaryError === undefined ? [cleanupError] : [primaryError, cleanupError],
|
|
466
|
+
);
|
|
467
|
+
}
|
|
468
|
+
};
|
|
469
|
+
let runResult: IRunnerRunResult | undefined;
|
|
470
|
+
let runError: unknown;
|
|
471
|
+
try {
|
|
472
|
+
runResult = await (async (): Promise<IRunnerRunResult> => {
|
|
473
|
+
try {
|
|
474
|
+
guard.update(claim.serverTime, lease.leaseExpiresAt, claimElapsedMs);
|
|
475
|
+
if (guard.controller.signal.aborted) throw guard.controller.signal.reason;
|
|
476
|
+
preparedLease = await this.dependencies.executor.prepareLease({
|
|
477
|
+
runnerId,
|
|
478
|
+
sessionId,
|
|
479
|
+
lease,
|
|
480
|
+
signal: guard.controller.signal,
|
|
481
|
+
});
|
|
482
|
+
} catch (error) {
|
|
483
|
+
if (error instanceof ResourceCleanupError) {
|
|
484
|
+
return await abandonAfterCleanupFailure(
|
|
485
|
+
error,
|
|
486
|
+
guard.controller.signal.reason === 'runner_shutdown'
|
|
487
|
+
? 'runner_shutdown'
|
|
488
|
+
: 'runner_error',
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
await cleanupPreparedLease(error, 'OCI lease preparation and cleanup both failed').catch(
|
|
492
|
+
(cleanupError) =>
|
|
493
|
+
abandonAfterCleanupFailure(
|
|
494
|
+
cleanupError as ResourceCleanupError,
|
|
495
|
+
guard.controller.signal.reason === 'runner_shutdown'
|
|
496
|
+
? 'runner_shutdown'
|
|
497
|
+
: 'runner_error',
|
|
498
|
+
),
|
|
499
|
+
);
|
|
500
|
+
const reason = guard.controller.signal.reason === 'runner_shutdown'
|
|
501
|
+
? 'runner_shutdown'
|
|
502
|
+
: 'runner_error';
|
|
503
|
+
await this.abandon(identity, reason);
|
|
504
|
+
return { claimed: true, status: 'system_error' };
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
try {
|
|
508
|
+
await journal.save({
|
|
509
|
+
previousSessionId: sessionId,
|
|
510
|
+
jobId: lease.jobId,
|
|
511
|
+
attemptId: lease.attemptId,
|
|
512
|
+
});
|
|
513
|
+
} catch (error) {
|
|
514
|
+
try {
|
|
515
|
+
await cleanupPreparedLease(
|
|
516
|
+
error,
|
|
517
|
+
'Attempt journal failure and OCI cleanup both failed',
|
|
518
|
+
);
|
|
519
|
+
} catch (cleanupError) {
|
|
520
|
+
return await abandonAfterCleanupFailure(
|
|
521
|
+
cleanupError as ResourceCleanupError,
|
|
522
|
+
guard.controller.signal.reason === 'runner_shutdown'
|
|
523
|
+
? 'runner_shutdown'
|
|
524
|
+
: 'runner_error',
|
|
525
|
+
);
|
|
526
|
+
}
|
|
527
|
+
const reason = guard.controller.signal.reason === 'runner_shutdown'
|
|
528
|
+
? 'runner_shutdown'
|
|
529
|
+
: 'runner_error';
|
|
530
|
+
await this.abandon(identity, reason, journal);
|
|
531
|
+
return { claimed: true, status: 'system_error' };
|
|
532
|
+
}
|
|
533
|
+
try {
|
|
534
|
+
await this.dependencies.api.acceptJob({
|
|
535
|
+
acceptRequestId: crypto.randomUUID(),
|
|
536
|
+
identity,
|
|
537
|
+
}, guard.controller.signal);
|
|
538
|
+
} catch (error) {
|
|
539
|
+
try {
|
|
540
|
+
await cleanupPreparedLease(error, 'Job acceptance and OCI cleanup both failed');
|
|
541
|
+
} catch (cleanupError) {
|
|
542
|
+
return await abandonAfterCleanupFailure(
|
|
543
|
+
cleanupError as ResourceCleanupError,
|
|
544
|
+
guard.controller.signal.reason === 'runner_shutdown'
|
|
545
|
+
? 'runner_shutdown'
|
|
546
|
+
: 'runner_error',
|
|
547
|
+
);
|
|
548
|
+
}
|
|
549
|
+
if (isDefinitiveConflict(error)) {
|
|
550
|
+
await journal.clear();
|
|
551
|
+
return { claimed: true, status: 'system_error' };
|
|
552
|
+
}
|
|
553
|
+
if (guard.controller.signal.reason === 'runner_shutdown') {
|
|
554
|
+
await this.abandon(identity, 'runner_shutdown', journal);
|
|
555
|
+
return { claimed: true, status: 'system_error' };
|
|
556
|
+
}
|
|
557
|
+
throw error;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
const acceptedPreparedLease = preparedLease;
|
|
561
|
+
preparedLease = undefined;
|
|
562
|
+
return await this.runAcceptedAttempt(
|
|
563
|
+
runnerId,
|
|
564
|
+
sessionId,
|
|
565
|
+
lease,
|
|
566
|
+
identity,
|
|
567
|
+
acceptedPreparedLease,
|
|
568
|
+
guard,
|
|
569
|
+
journal,
|
|
570
|
+
);
|
|
571
|
+
})();
|
|
572
|
+
} catch (error) {
|
|
573
|
+
runError = error;
|
|
574
|
+
}
|
|
575
|
+
let finalCleanupError: unknown;
|
|
576
|
+
if (preparedLease) {
|
|
577
|
+
try {
|
|
578
|
+
await cleanupPreparedLease();
|
|
579
|
+
} catch (error) {
|
|
580
|
+
this.sessionInvalid = true;
|
|
581
|
+
finalCleanupError = error;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
guard.close();
|
|
585
|
+
runnerSignal.removeEventListener('abort', runnerAbort);
|
|
586
|
+
if (finalCleanupError !== undefined) throw finalCleanupError;
|
|
587
|
+
if (runError !== undefined) throw runError;
|
|
588
|
+
if (!runResult) throw new RunnerError('Runner attempt produced no result');
|
|
589
|
+
return runResult;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
private async runAcceptedAttempt(
|
|
593
|
+
runnerId: string,
|
|
594
|
+
sessionId: string,
|
|
595
|
+
lease: IJobLease,
|
|
596
|
+
identity: IJobIdentity,
|
|
597
|
+
preparedLease: IPreparedOciLease,
|
|
598
|
+
guard: LeaseGuard,
|
|
599
|
+
journal: AttemptStateStore,
|
|
600
|
+
): Promise<IRunnerRunResult> {
|
|
601
|
+
const executionAbort = new AbortController();
|
|
602
|
+
const heartbeatLifecycle = new AbortController();
|
|
603
|
+
const heartbeatState: IHeartbeatState = {};
|
|
604
|
+
const heartbeat = this.jobHeartbeatLoop(
|
|
605
|
+
identity,
|
|
606
|
+
guard,
|
|
607
|
+
executionAbort,
|
|
608
|
+
heartbeatState,
|
|
609
|
+
heartbeatLifecycle.signal,
|
|
610
|
+
);
|
|
611
|
+
const startedAt = new Date(this.now()).toISOString();
|
|
612
|
+
const logs = new LogSender(
|
|
613
|
+
this.dependencies.api,
|
|
614
|
+
identity,
|
|
615
|
+
Object.values(lease.job.secrets),
|
|
616
|
+
this.config.maximumLogBytes,
|
|
617
|
+
this.config.maximumLogChunkBytes,
|
|
618
|
+
guard.controller.signal,
|
|
619
|
+
);
|
|
620
|
+
let stagingWorkspace: IPreparedWorkspace | undefined;
|
|
621
|
+
let runtimeWorkspace: Awaited<ReturnType<IJobExecutor['execute']>>['workspace'];
|
|
622
|
+
let status: TJobCompletionStatus = 'system_error';
|
|
623
|
+
let exitCode: number | null = null;
|
|
624
|
+
let systemFailure: unknown;
|
|
625
|
+
let cleanupFailure: ResourceCleanupError | undefined;
|
|
626
|
+
const executionSignal = AbortSignal.any([guard.controller.signal, executionAbort.signal]);
|
|
627
|
+
|
|
628
|
+
const recordFailure = (error: unknown): void => {
|
|
629
|
+
systemFailure ??= error;
|
|
630
|
+
status = 'system_error';
|
|
631
|
+
exitCode = null;
|
|
632
|
+
if (error instanceof LeaseLostError) {
|
|
633
|
+
guard.fence('lease_lost', true);
|
|
634
|
+
} else if (error instanceof AuthenticationError) {
|
|
635
|
+
heartbeatState.terminalError ??= error;
|
|
636
|
+
guard.fence('lease_lost');
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
|
|
640
|
+
const recordCleanupFailure = (error: unknown): void => {
|
|
641
|
+
const next = error instanceof ResourceCleanupError
|
|
642
|
+
? error
|
|
643
|
+
: new ResourceCleanupError('Accepted attempt cleanup failed', [error]);
|
|
644
|
+
cleanupFailure = cleanupFailure === undefined
|
|
645
|
+
? next
|
|
646
|
+
: new ResourceCleanupError('Accepted attempt cleanup failed', [cleanupFailure, next]);
|
|
647
|
+
this.sessionInvalid = true;
|
|
648
|
+
if (!executionAbort.signal.aborted) executionAbort.abort('runner_shutdown');
|
|
649
|
+
if (!heartbeatLifecycle.signal.aborted) heartbeatLifecycle.abort('job_finished');
|
|
650
|
+
};
|
|
651
|
+
|
|
652
|
+
const recordPostExecutionFailure = (error: unknown): void => {
|
|
653
|
+
if (
|
|
654
|
+
executionAbort.signal.reason === 'job_canceled' && heartbeatState.cancellation &&
|
|
655
|
+
!guard.controller.signal.aborted
|
|
656
|
+
) {
|
|
657
|
+
status = 'canceled';
|
|
658
|
+
exitCode = null;
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
recordFailure(error);
|
|
662
|
+
};
|
|
663
|
+
|
|
664
|
+
try {
|
|
665
|
+
if (lease.job.artifacts.length > 0 && !this.dependencies.artifactManager) {
|
|
666
|
+
throw new RunnerError('Artifact manager is not configured');
|
|
667
|
+
}
|
|
668
|
+
if (lease.job.caches.length > 0 && !this.dependencies.cacheManager) {
|
|
669
|
+
throw new RunnerError('Cache manager is not configured');
|
|
670
|
+
}
|
|
671
|
+
stagingWorkspace = await this.dependencies.workspaceManager.prepare({
|
|
672
|
+
identity,
|
|
673
|
+
job: lease.job,
|
|
674
|
+
signal: executionSignal,
|
|
675
|
+
});
|
|
676
|
+
if (lease.job.caches.length > 0) {
|
|
677
|
+
await this.dependencies.cacheManager!.restore({
|
|
678
|
+
workspacePath: stagingWorkspace.path,
|
|
679
|
+
job: lease.job,
|
|
680
|
+
identity,
|
|
681
|
+
signal: executionSignal,
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
const result = await this.dependencies.executor.execute({
|
|
685
|
+
runnerId,
|
|
686
|
+
sessionId,
|
|
687
|
+
lease,
|
|
688
|
+
preparedLease,
|
|
689
|
+
workspacePath: stagingWorkspace.path,
|
|
690
|
+
signal: executionSignal,
|
|
691
|
+
terminationDeadline: () => heartbeatState.cancellationDeadline,
|
|
692
|
+
onLog: (stream, data) => logs.write(stream, data),
|
|
693
|
+
});
|
|
694
|
+
runtimeWorkspace = result.workspace;
|
|
695
|
+
exitCode = result.exitCode;
|
|
696
|
+
status = this.completionStatus(result.stopReason, result.exitCode, heartbeatState);
|
|
697
|
+
if (status !== 'succeeded' && status !== 'failed') exitCode = null;
|
|
698
|
+
} catch (error) {
|
|
699
|
+
if (error instanceof ResourceCleanupError) recordCleanupFailure(error);
|
|
700
|
+
else if (
|
|
701
|
+
executionAbort.signal.reason === 'job_canceled' && heartbeatState.cancellation &&
|
|
702
|
+
!guard.controller.signal.aborted
|
|
703
|
+
) {
|
|
704
|
+
status = 'canceled';
|
|
705
|
+
exitCode = null;
|
|
706
|
+
} else if (!guard.controller.signal.aborted) recordFailure(error);
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
if (!cleanupFailure && !guard.controller.signal.aborted) {
|
|
710
|
+
try {
|
|
711
|
+
await logs.flush();
|
|
712
|
+
} catch (error) {
|
|
713
|
+
if (error instanceof ResourceCleanupError) recordCleanupFailure(error);
|
|
714
|
+
else recordFailure(error);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
if (
|
|
718
|
+
!cleanupFailure && heartbeatState.systemFailure !== undefined &&
|
|
719
|
+
!guard.controller.signal.aborted
|
|
720
|
+
) {
|
|
721
|
+
recordFailure(heartbeatState.systemFailure);
|
|
722
|
+
}
|
|
723
|
+
if (
|
|
724
|
+
heartbeatState.cancellation && status !== 'system_error' &&
|
|
725
|
+
!guard.controller.signal.aborted
|
|
726
|
+
) {
|
|
727
|
+
status = 'canceled';
|
|
728
|
+
exitCode = null;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
if (runtimeWorkspace && !cleanupFailure && !executionSignal.aborted) {
|
|
732
|
+
if (lease.job.caches.length > 0) {
|
|
733
|
+
try {
|
|
734
|
+
await this.dependencies.cacheManager!.save({
|
|
735
|
+
workspace: runtimeWorkspace,
|
|
736
|
+
job: lease.job,
|
|
737
|
+
status,
|
|
738
|
+
identity,
|
|
739
|
+
signal: executionSignal,
|
|
740
|
+
});
|
|
741
|
+
} catch (error) {
|
|
742
|
+
if (error instanceof ResourceCleanupError) recordCleanupFailure(error);
|
|
743
|
+
else recordPostExecutionFailure(error);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
if (
|
|
747
|
+
lease.job.artifacts.length > 0 && !cleanupFailure &&
|
|
748
|
+
!executionSignal.aborted
|
|
749
|
+
) {
|
|
750
|
+
try {
|
|
751
|
+
await this.dependencies.artifactManager!.upload({
|
|
752
|
+
workspace: runtimeWorkspace,
|
|
753
|
+
job: lease.job,
|
|
754
|
+
status,
|
|
755
|
+
identity,
|
|
756
|
+
signal: executionSignal,
|
|
757
|
+
});
|
|
758
|
+
} catch (error) {
|
|
759
|
+
if (error instanceof ResourceCleanupError) recordCleanupFailure(error);
|
|
760
|
+
else recordPostExecutionFailure(error);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
const cleanupErrors: unknown[] = [];
|
|
766
|
+
for (
|
|
767
|
+
const cleanup of [
|
|
768
|
+
...(runtimeWorkspace ? [() => runtimeWorkspace!.cleanup()] : []),
|
|
769
|
+
...(stagingWorkspace ? [() => stagingWorkspace!.cleanup()] : []),
|
|
770
|
+
() => preparedLease.cleanup(),
|
|
771
|
+
]
|
|
772
|
+
) {
|
|
773
|
+
try {
|
|
774
|
+
await cleanup();
|
|
775
|
+
} catch (error) {
|
|
776
|
+
this.sessionInvalid = true;
|
|
777
|
+
if (!executionAbort.signal.aborted) executionAbort.abort('runner_shutdown');
|
|
778
|
+
if (!heartbeatLifecycle.signal.aborted) heartbeatLifecycle.abort('job_finished');
|
|
779
|
+
cleanupErrors.push(error);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
heartbeatLifecycle.abort('job_finished');
|
|
783
|
+
try {
|
|
784
|
+
await heartbeat;
|
|
785
|
+
} catch (error) {
|
|
786
|
+
if (error instanceof ResourceCleanupError) recordCleanupFailure(error);
|
|
787
|
+
else if (!guard.controller.signal.aborted) recordFailure(error);
|
|
788
|
+
}
|
|
789
|
+
if (heartbeatState.systemFailure !== undefined && !guard.controller.signal.aborted) {
|
|
790
|
+
recordFailure(heartbeatState.systemFailure);
|
|
791
|
+
}
|
|
792
|
+
if (
|
|
793
|
+
heartbeatState.cancellation && status !== 'system_error' &&
|
|
794
|
+
!guard.controller.signal.aborted
|
|
795
|
+
) {
|
|
796
|
+
status = 'canceled';
|
|
797
|
+
exitCode = null;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
if (cleanupErrors.length > 0) {
|
|
801
|
+
recordCleanupFailure(
|
|
802
|
+
new ResourceCleanupError(
|
|
803
|
+
'Accepted attempt cleanup failed',
|
|
804
|
+
[
|
|
805
|
+
...(systemFailure === undefined ? [] : [systemFailure]),
|
|
806
|
+
...cleanupErrors,
|
|
807
|
+
],
|
|
808
|
+
),
|
|
809
|
+
);
|
|
810
|
+
}
|
|
811
|
+
if (cleanupFailure) throw cleanupFailure;
|
|
812
|
+
|
|
813
|
+
const fenceReason = guard.controller.signal.reason;
|
|
814
|
+
if (fenceReason === 'runner_shutdown') {
|
|
815
|
+
await this.abandon(identity, 'runner_shutdown', journal);
|
|
816
|
+
return { claimed: true, status: 'system_error' };
|
|
817
|
+
}
|
|
818
|
+
if (fenceReason === 'lease_lost' || fenceReason === 'lease_expired') {
|
|
819
|
+
if (guard.definitive) await journal.clear();
|
|
820
|
+
else this.sessionInvalid = true;
|
|
821
|
+
if (heartbeatState.terminalError !== undefined) throw heartbeatState.terminalError;
|
|
822
|
+
return { claimed: true, status };
|
|
823
|
+
}
|
|
824
|
+
if (heartbeatState.terminalError !== undefined) throw heartbeatState.terminalError;
|
|
825
|
+
|
|
826
|
+
if (status === 'canceled' && !heartbeatState.cancellation) {
|
|
827
|
+
status = 'system_error';
|
|
828
|
+
exitCode = null;
|
|
829
|
+
systemFailure ??= new ProtocolError('Executor reported cancellation without a directive');
|
|
830
|
+
}
|
|
831
|
+
if (status === 'succeeded' && exitCode !== 0) {
|
|
832
|
+
status = 'system_error';
|
|
833
|
+
exitCode = null;
|
|
834
|
+
}
|
|
835
|
+
if (status === 'failed' && (!Number.isInteger(exitCode) || exitCode! < 0 || exitCode! > 255)) {
|
|
836
|
+
status = 'system_error';
|
|
837
|
+
exitCode = null;
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
const completion: ICompleteJobRequest = {
|
|
841
|
+
completionRequestId: crypto.randomUUID(),
|
|
842
|
+
identity,
|
|
843
|
+
status,
|
|
844
|
+
exitCode,
|
|
845
|
+
startedAt,
|
|
846
|
+
completedAt: new Date(this.now()).toISOString(),
|
|
847
|
+
...(status === 'canceled'
|
|
848
|
+
? { cancellationRequestId: heartbeatState.cancellation!.requestId }
|
|
849
|
+
: {}),
|
|
850
|
+
...(status === 'system_error' || systemFailure !== undefined
|
|
851
|
+
? { error: genericSystemError }
|
|
852
|
+
: {}),
|
|
853
|
+
};
|
|
854
|
+
try {
|
|
855
|
+
await this.dependencies.api.completeJob(completion);
|
|
856
|
+
await journal.clear();
|
|
857
|
+
} catch (error) {
|
|
858
|
+
if (isDefinitiveConflict(error)) {
|
|
859
|
+
await journal.clear();
|
|
860
|
+
} else {
|
|
861
|
+
throw error;
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
return { claimed: true, status };
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
private completionStatus(
|
|
868
|
+
reason: TExecutionStopReason | undefined,
|
|
869
|
+
exitCode: number | null,
|
|
870
|
+
heartbeatState: IHeartbeatState,
|
|
871
|
+
): TJobCompletionStatus {
|
|
872
|
+
if (heartbeatState.systemFailure !== undefined) return 'system_error';
|
|
873
|
+
if (reason === 'job_canceled') {
|
|
874
|
+
return heartbeatState.cancellation ? 'canceled' : 'system_error';
|
|
875
|
+
}
|
|
876
|
+
if (reason === 'job_timeout') return 'timed_out';
|
|
877
|
+
if (reason) return 'system_error';
|
|
878
|
+
return exitCode === 0 ? 'succeeded' : 'failed';
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
private async jobHeartbeatLoop(
|
|
882
|
+
identity: IJobIdentity,
|
|
883
|
+
guard: LeaseGuard,
|
|
884
|
+
executionAbort: AbortController,
|
|
885
|
+
state: IHeartbeatState,
|
|
886
|
+
signal: AbortSignal,
|
|
887
|
+
): Promise<void> {
|
|
888
|
+
let immediate = true;
|
|
889
|
+
while (!signal.aborted && !guard.controller.signal.aborted) {
|
|
890
|
+
try {
|
|
891
|
+
if (!immediate) await this.sleep(this.config.jobHeartbeatIntervalMs, signal);
|
|
892
|
+
immediate = false;
|
|
893
|
+
const requestStartedAt = this.now();
|
|
894
|
+
const response = await this.dependencies.api.heartbeatJob({
|
|
895
|
+
identity,
|
|
896
|
+
...(state.cancellation
|
|
897
|
+
? { observedCancellationRequestId: state.cancellation.requestId }
|
|
898
|
+
: {}),
|
|
899
|
+
}, signal);
|
|
900
|
+
const requestElapsedMs = Math.max(0, this.now() - requestStartedAt);
|
|
901
|
+
guard.update(response.serverTime, response.leaseExpiresAt, requestElapsedMs);
|
|
902
|
+
if (response.cancellation) {
|
|
903
|
+
immediate = this.observeCancellation(
|
|
904
|
+
response,
|
|
905
|
+
requestElapsedMs,
|
|
906
|
+
executionAbort,
|
|
907
|
+
state,
|
|
908
|
+
);
|
|
909
|
+
}
|
|
910
|
+
} catch (error) {
|
|
911
|
+
if (signal.aborted) return;
|
|
912
|
+
if (error instanceof ResourceCleanupError) {
|
|
913
|
+
state.terminalError = error;
|
|
914
|
+
if (!executionAbort.signal.aborted) executionAbort.abort('runner_shutdown');
|
|
915
|
+
throw error;
|
|
916
|
+
}
|
|
917
|
+
if (error instanceof LeaseLostError) {
|
|
918
|
+
guard.fence('lease_lost', true);
|
|
919
|
+
return;
|
|
920
|
+
}
|
|
921
|
+
if (error instanceof AuthenticationError) {
|
|
922
|
+
state.terminalError = error;
|
|
923
|
+
guard.fence('lease_lost');
|
|
924
|
+
return;
|
|
925
|
+
}
|
|
926
|
+
if (error instanceof ProtocolError) {
|
|
927
|
+
state.systemFailure ??= error;
|
|
928
|
+
if (!executionAbort.signal.aborted) executionAbort.abort('runner_shutdown');
|
|
929
|
+
immediate = false;
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
this.dependencies.onMessage?.('Job heartbeat failed; lease expiry guard remains active');
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
private observeCancellation(
|
|
938
|
+
response: IJobHeartbeatResponse,
|
|
939
|
+
requestElapsedMs: number,
|
|
940
|
+
executionAbort: AbortController,
|
|
941
|
+
state: IHeartbeatState,
|
|
942
|
+
): boolean {
|
|
943
|
+
const directive = response.cancellation!;
|
|
944
|
+
const graceMs = Date.parse(directive.terminateBy) - Date.parse(response.serverTime);
|
|
945
|
+
const remainingGraceMs = graceMs - requestElapsedMs;
|
|
946
|
+
if (
|
|
947
|
+
!Number.isFinite(graceMs) || graceMs < 0 || graceMs > 30_000 ||
|
|
948
|
+
remainingGraceMs < 0
|
|
949
|
+
) {
|
|
950
|
+
state.systemFailure ??= new ProtocolError('Coordinator cancellation deadline is invalid');
|
|
951
|
+
if (!executionAbort.signal.aborted) executionAbort.abort('runner_shutdown');
|
|
952
|
+
return false;
|
|
953
|
+
}
|
|
954
|
+
if (state.cancellation) {
|
|
955
|
+
if (
|
|
956
|
+
state.cancellation.requestId !== directive.requestId ||
|
|
957
|
+
state.cancellation.requestedAt !== directive.requestedAt ||
|
|
958
|
+
state.cancellation.reason !== directive.reason ||
|
|
959
|
+
state.cancellation.terminateBy !== directive.terminateBy
|
|
960
|
+
) {
|
|
961
|
+
state.systemFailure ??= new ProtocolError('Coordinator changed a cancellation directive');
|
|
962
|
+
if (!executionAbort.signal.aborted) executionAbort.abort('runner_shutdown');
|
|
963
|
+
}
|
|
964
|
+
return false;
|
|
965
|
+
}
|
|
966
|
+
state.cancellation = directive;
|
|
967
|
+
state.cancellationDeadline = this.now() + remainingGraceMs;
|
|
968
|
+
executionAbort.abort('job_canceled');
|
|
969
|
+
return true;
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
private async runnerHeartbeatLoop(
|
|
973
|
+
runnerId: string,
|
|
974
|
+
sessionId: string,
|
|
975
|
+
lifecycle: AbortController,
|
|
976
|
+
): Promise<void> {
|
|
977
|
+
while (!lifecycle.signal.aborted) {
|
|
978
|
+
try {
|
|
979
|
+
const heartbeat = await this.dependencies.api.heartbeatRunner(
|
|
980
|
+
{ runnerId, sessionId },
|
|
981
|
+
lifecycle.signal,
|
|
982
|
+
);
|
|
983
|
+
this.drainRequested ||= heartbeat.drainRequested;
|
|
984
|
+
if (heartbeat.credential) await this.applyCredential(heartbeat.credential);
|
|
985
|
+
await this.sleep(this.config.runnerHeartbeatIntervalMs, lifecycle.signal);
|
|
986
|
+
} catch (error) {
|
|
987
|
+
if (lifecycle.signal.aborted) return;
|
|
988
|
+
if (error instanceof ResourceCleanupError) {
|
|
989
|
+
this.sessionInvalid = true;
|
|
990
|
+
lifecycle.abort('lease_lost');
|
|
991
|
+
throw error;
|
|
992
|
+
}
|
|
993
|
+
if (
|
|
994
|
+
error instanceof AuthenticationError || error instanceof LeaseLostError ||
|
|
995
|
+
error instanceof CoordinatorError && error.status === 409
|
|
996
|
+
) {
|
|
997
|
+
lifecycle.abort('lease_lost');
|
|
998
|
+
throw error;
|
|
999
|
+
}
|
|
1000
|
+
this.dependencies.onMessage?.('Runner heartbeat failed; retrying');
|
|
1001
|
+
await this.sleep(this.config.runnerHeartbeatIntervalMs, lifecycle.signal);
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
private async abandon(
|
|
1007
|
+
identity: IJobIdentity,
|
|
1008
|
+
reason: IAbandonJobRequest['reason'],
|
|
1009
|
+
journal?: AttemptStateStore,
|
|
1010
|
+
): Promise<void> {
|
|
1011
|
+
try {
|
|
1012
|
+
await this.dependencies.api.abandonJob({
|
|
1013
|
+
abandonRequestId: crypto.randomUUID(),
|
|
1014
|
+
identity,
|
|
1015
|
+
reason,
|
|
1016
|
+
});
|
|
1017
|
+
} catch (error) {
|
|
1018
|
+
if (!isDefinitiveConflict(error)) throw error;
|
|
1019
|
+
}
|
|
1020
|
+
await journal?.clear();
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
private async applyCredential(credential: IRunnerCredential): Promise<void> {
|
|
1024
|
+
if (credential.runnerId !== this.config.runnerId) {
|
|
1025
|
+
throw new RunnerError('Coordinator attempted to rotate credentials for another runner');
|
|
1026
|
+
}
|
|
1027
|
+
if (!this.dependencies.onCredential) {
|
|
1028
|
+
throw new RunnerError('Runner credential persistence is not configured');
|
|
1029
|
+
}
|
|
1030
|
+
await this.dependencies.onCredential(credential);
|
|
1031
|
+
this.dependencies.api.setRunnerToken(credential.token);
|
|
1032
|
+
this.config.runnerCredentialId = credential.credentialId;
|
|
1033
|
+
this.config.runnerToken = credential.token;
|
|
1034
|
+
this.config.runnerTokenExpiresAt = credential.expiresAt;
|
|
1035
|
+
}
|
|
1036
|
+
}
|