@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
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
import { dirname, join, resolve } from '@std/path';
|
|
2
|
+
import { ProtocolError, ResourceCleanupError, RunnerError } from './errors.ts';
|
|
3
|
+
import type {
|
|
4
|
+
ICacheDeclaration,
|
|
5
|
+
ICacheManager,
|
|
6
|
+
ICacheRestoreContext,
|
|
7
|
+
ICacheSaveContext,
|
|
8
|
+
IJobIdentity,
|
|
9
|
+
ITransferManagerConfig,
|
|
10
|
+
ITransferMetadata,
|
|
11
|
+
ITransferRecord,
|
|
12
|
+
TCacheDownload,
|
|
13
|
+
TOpenTransferBody,
|
|
14
|
+
} from './interfaces.ts';
|
|
15
|
+
import {
|
|
16
|
+
createTarGzipArchive,
|
|
17
|
+
ensureStagingCapacity,
|
|
18
|
+
extractTarGzipArchive,
|
|
19
|
+
removePathIfPresent,
|
|
20
|
+
stageTransferDownload,
|
|
21
|
+
validateRelativeSelections,
|
|
22
|
+
validateTransferRecord,
|
|
23
|
+
} from './transfer-archive.ts';
|
|
24
|
+
|
|
25
|
+
export interface ICacheApiClient {
|
|
26
|
+
downloadCache(
|
|
27
|
+
identity: IJobIdentity,
|
|
28
|
+
name: string,
|
|
29
|
+
signal?: AbortSignal,
|
|
30
|
+
): Promise<TCacheDownload>;
|
|
31
|
+
uploadCache(
|
|
32
|
+
identity: IJobIdentity,
|
|
33
|
+
name: string,
|
|
34
|
+
transferRequestId: string,
|
|
35
|
+
metadata: ITransferMetadata,
|
|
36
|
+
openBody: TOpenTransferBody,
|
|
37
|
+
signal?: AbortSignal,
|
|
38
|
+
): Promise<ITransferRecord>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface IEffectiveCacheLimits {
|
|
42
|
+
archiveBytes: number;
|
|
43
|
+
extractedBytes: number;
|
|
44
|
+
entries: number;
|
|
45
|
+
count: number;
|
|
46
|
+
workspaceBytes: number;
|
|
47
|
+
workspaceEntries: number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const safePositive = (value: number, field: string): number => {
|
|
51
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
52
|
+
throw new ProtocolError(`${field} must be a positive integer`);
|
|
53
|
+
}
|
|
54
|
+
return value;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const checkedAdd = (left: number, right: number, message: string): number => {
|
|
58
|
+
const result = left + right;
|
|
59
|
+
if (!Number.isSafeInteger(result)) throw new ProtocolError(message);
|
|
60
|
+
return result;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const effectiveLimits = (
|
|
64
|
+
config: ITransferManagerConfig,
|
|
65
|
+
job: ICacheRestoreContext['job'] | ICacheSaveContext['job'],
|
|
66
|
+
): IEffectiveCacheLimits => ({
|
|
67
|
+
archiveBytes: Math.min(
|
|
68
|
+
config.maximumCacheArchiveBytes,
|
|
69
|
+
job.requirements.limits.maximumCacheArchiveBytes,
|
|
70
|
+
),
|
|
71
|
+
extractedBytes: Math.min(
|
|
72
|
+
config.maximumCacheExtractedBytes,
|
|
73
|
+
config.oci.workspaceSizeBytes,
|
|
74
|
+
job.requirements.limits.maximumCacheExtractedBytes,
|
|
75
|
+
job.requirements.limits.maximumWorkspaceBytes,
|
|
76
|
+
),
|
|
77
|
+
entries: Math.min(
|
|
78
|
+
config.maximumCacheEntries,
|
|
79
|
+
config.maximumWorkspaceEntries,
|
|
80
|
+
job.requirements.limits.maximumCacheEntries,
|
|
81
|
+
job.requirements.limits.maximumWorkspaceEntries,
|
|
82
|
+
),
|
|
83
|
+
count: Math.min(config.maximumCaches, job.requirements.limits.maximumCaches),
|
|
84
|
+
workspaceBytes: Math.min(
|
|
85
|
+
config.oci.workspaceSizeBytes,
|
|
86
|
+
job.requirements.limits.maximumWorkspaceBytes,
|
|
87
|
+
),
|
|
88
|
+
workspaceEntries: Math.min(
|
|
89
|
+
config.maximumWorkspaceEntries,
|
|
90
|
+
job.requirements.limits.maximumWorkspaceEntries,
|
|
91
|
+
),
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
const validateCaches = (
|
|
95
|
+
config: ITransferManagerConfig,
|
|
96
|
+
job: ICacheRestoreContext['job'] | ICacheSaveContext['job'],
|
|
97
|
+
): IEffectiveCacheLimits => {
|
|
98
|
+
const caches = job.caches;
|
|
99
|
+
const limits = effectiveLimits(config, job);
|
|
100
|
+
if (caches.length === 0) return limits;
|
|
101
|
+
if (job.permissions.caches === 'none') {
|
|
102
|
+
throw new ProtocolError('Job does not permit cache transfers');
|
|
103
|
+
}
|
|
104
|
+
if (!job.requirements.features.includes('caches.v1')) {
|
|
105
|
+
throw new ProtocolError('Job does not declare the caches.v1 feature');
|
|
106
|
+
}
|
|
107
|
+
if (caches.length > limits.count) throw new ProtocolError('Job declares too many caches');
|
|
108
|
+
const allPaths: Array<{ cache: string; path: string }> = [];
|
|
109
|
+
for (const cache of caches) {
|
|
110
|
+
if (cache.access !== 'read' && cache.access !== 'read-write') {
|
|
111
|
+
throw new ProtocolError(`Cache ${cache.name} has invalid access`);
|
|
112
|
+
}
|
|
113
|
+
if (cache.access === 'read-write' && job.permissions.caches !== 'read-write') {
|
|
114
|
+
throw new ProtocolError(`Cache ${cache.name} exceeds the job cache permission`);
|
|
115
|
+
}
|
|
116
|
+
safePositive(cache.maximumBytes, `Cache ${cache.name} maximumBytes`);
|
|
117
|
+
safePositive(cache.maximumExtractedBytes, `Cache ${cache.name} maximumExtractedBytes`);
|
|
118
|
+
safePositive(cache.maximumEntries, `Cache ${cache.name} maximumEntries`);
|
|
119
|
+
if (
|
|
120
|
+
cache.maximumBytes > limits.archiveBytes ||
|
|
121
|
+
cache.maximumExtractedBytes > limits.extractedBytes ||
|
|
122
|
+
cache.maximumEntries > limits.entries
|
|
123
|
+
) {
|
|
124
|
+
throw new ProtocolError(`Cache ${cache.name} exceeds its effective runner limits`);
|
|
125
|
+
}
|
|
126
|
+
for (const path of validateRelativeSelections(cache.paths, `Cache ${cache.name}`)) {
|
|
127
|
+
allPaths.push({ cache: cache.name, path });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const sorted = [...allPaths].sort((left, right) => left.path.localeCompare(right.path));
|
|
131
|
+
for (let left = 0; left < sorted.length; left++) {
|
|
132
|
+
for (let right = left + 1; right < sorted.length; right++) {
|
|
133
|
+
if (
|
|
134
|
+
sorted[left].path === sorted[right].path ||
|
|
135
|
+
sorted[right].path.startsWith(`${sorted[left].path}/`)
|
|
136
|
+
) {
|
|
137
|
+
throw new ProtocolError(
|
|
138
|
+
`Cache paths overlap between ${sorted[left].cache} and ${sorted[right].cache}`,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return limits;
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const lstatIfPresent = async (path: string): Promise<Deno.FileInfo | undefined> => {
|
|
147
|
+
try {
|
|
148
|
+
return await Deno.lstat(path);
|
|
149
|
+
} catch (error) {
|
|
150
|
+
if (error instanceof Deno.errors.NotFound) return undefined;
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
const assertSafeDestinationParents = async (workspacePath: string, path: string): Promise<void> => {
|
|
156
|
+
let current = resolve(workspacePath);
|
|
157
|
+
const segments = path.split('/');
|
|
158
|
+
for (let index = 0; index < segments.length - 1; index++) {
|
|
159
|
+
current = join(current, segments[index]);
|
|
160
|
+
const stat = await lstatIfPresent(current);
|
|
161
|
+
if (!stat) return;
|
|
162
|
+
if (!stat.isDirectory || stat.isSymlink) {
|
|
163
|
+
throw new RunnerError('Cache destination has an unsafe ancestor');
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const restoreSelectedPaths = async (
|
|
169
|
+
stagingPath: string,
|
|
170
|
+
workspacePath: string,
|
|
171
|
+
cache: ICacheDeclaration,
|
|
172
|
+
): Promise<void> => {
|
|
173
|
+
const candidates: Array<{
|
|
174
|
+
source: string;
|
|
175
|
+
destination: string;
|
|
176
|
+
existed: boolean;
|
|
177
|
+
}> = [];
|
|
178
|
+
for (const path of cache.paths) {
|
|
179
|
+
const source = join(resolve(stagingPath), ...path.split('/'));
|
|
180
|
+
const sourceStat = await lstatIfPresent(source);
|
|
181
|
+
if (!sourceStat) throw new ProtocolError(`Cache ${cache.name} omitted a declared path`);
|
|
182
|
+
await assertSafeDestinationParents(workspacePath, path);
|
|
183
|
+
const destination = join(resolve(workspacePath), ...path.split('/'));
|
|
184
|
+
const destinationStat = await lstatIfPresent(destination);
|
|
185
|
+
if (destinationStat?.isSymlink) {
|
|
186
|
+
throw new RunnerError('Cache destination is a symbolic link');
|
|
187
|
+
}
|
|
188
|
+
candidates.push({ source, destination, existed: destinationStat !== undefined });
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const workspaceRoot = resolve(workspacePath);
|
|
192
|
+
const backupRoot = await Deno.makeTempDir({
|
|
193
|
+
dir: dirname(workspaceRoot),
|
|
194
|
+
prefix: '.cache-restore-',
|
|
195
|
+
});
|
|
196
|
+
const backedUp: Array<{ backup: string; destination: string }> = [];
|
|
197
|
+
const installed: string[] = [];
|
|
198
|
+
try {
|
|
199
|
+
for (let index = 0; index < candidates.length; index++) {
|
|
200
|
+
const candidate = candidates[index];
|
|
201
|
+
if (!candidate.existed) continue;
|
|
202
|
+
const backup = join(backupRoot, String(index));
|
|
203
|
+
await Deno.rename(candidate.destination, backup);
|
|
204
|
+
backedUp.push({ backup, destination: candidate.destination });
|
|
205
|
+
}
|
|
206
|
+
for (const candidate of candidates) {
|
|
207
|
+
await Deno.mkdir(dirname(candidate.destination), { recursive: true, mode: 0o700 });
|
|
208
|
+
await Deno.rename(candidate.source, candidate.destination);
|
|
209
|
+
installed.push(candidate.destination);
|
|
210
|
+
}
|
|
211
|
+
await Deno.remove(backupRoot, { recursive: true });
|
|
212
|
+
} catch (error) {
|
|
213
|
+
const errors = [error];
|
|
214
|
+
for (const destination of installed.reverse()) {
|
|
215
|
+
try {
|
|
216
|
+
await removePathIfPresent(destination, true);
|
|
217
|
+
} catch (rollbackError) {
|
|
218
|
+
errors.push(rollbackError);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
for (const entry of backedUp.reverse()) {
|
|
222
|
+
try {
|
|
223
|
+
await Deno.mkdir(dirname(entry.destination), { recursive: true, mode: 0o700 });
|
|
224
|
+
await Deno.rename(entry.backup, entry.destination);
|
|
225
|
+
} catch (rollbackError) {
|
|
226
|
+
errors.push(rollbackError);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
try {
|
|
230
|
+
await removePathIfPresent(backupRoot, true);
|
|
231
|
+
} catch (rollbackError) {
|
|
232
|
+
errors.push(rollbackError);
|
|
233
|
+
}
|
|
234
|
+
if (errors.length > 1) {
|
|
235
|
+
throw new ResourceCleanupError(
|
|
236
|
+
`Cache ${cache.name} restore and rollback failed`,
|
|
237
|
+
errors,
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
throw error;
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
const cleanupResources = async (
|
|
245
|
+
primaryError: unknown | undefined,
|
|
246
|
+
cleanups: Array<() => Promise<void>>,
|
|
247
|
+
message: string,
|
|
248
|
+
): Promise<void> => {
|
|
249
|
+
const cleanupErrors: unknown[] = [];
|
|
250
|
+
for (const cleanup of cleanups) {
|
|
251
|
+
try {
|
|
252
|
+
await cleanup();
|
|
253
|
+
} catch (error) {
|
|
254
|
+
cleanupErrors.push(error);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if (cleanupErrors.length > 0) {
|
|
258
|
+
throw new ResourceCleanupError(
|
|
259
|
+
message,
|
|
260
|
+
primaryError === undefined ? cleanupErrors : [primaryError, ...cleanupErrors],
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
if (primaryError !== undefined) throw primaryError;
|
|
264
|
+
};
|
|
265
|
+
|
|
266
|
+
export class CacheManager implements ICacheManager {
|
|
267
|
+
constructor(
|
|
268
|
+
private readonly config: ITransferManagerConfig,
|
|
269
|
+
private readonly api: ICacheApiClient,
|
|
270
|
+
private readonly onMessage?: (message: string) => void,
|
|
271
|
+
) {}
|
|
272
|
+
|
|
273
|
+
public async restore(context: ICacheRestoreContext): Promise<void> {
|
|
274
|
+
const limits = validateCaches(this.config, context.job);
|
|
275
|
+
let workspaceBytes = context.job.source.extractedSizeBytes;
|
|
276
|
+
let workspaceEntries = context.job.source.entryCount;
|
|
277
|
+
for (const cache of context.job.caches) {
|
|
278
|
+
if (context.signal.aborted) throw context.signal.reason;
|
|
279
|
+
const download = await this.api.downloadCache(context.identity, cache.name, context.signal);
|
|
280
|
+
if (!download.hit) {
|
|
281
|
+
this.onMessage?.(`Cache ${cache.name} missed`);
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
const remainingWorkspaceBytes = Math.max(0, limits.workspaceBytes - workspaceBytes);
|
|
285
|
+
const remainingWorkspaceEntries = Math.max(0, limits.workspaceEntries - workspaceEntries);
|
|
286
|
+
const archiveRoot = join(this.config.stateDirectory, 'cache-downloads');
|
|
287
|
+
const restoreRoot = join(this.config.stateDirectory, 'cache-restores');
|
|
288
|
+
const staged = await stageTransferDownload(download, {
|
|
289
|
+
directory: archiveRoot,
|
|
290
|
+
prefix: 'cache-',
|
|
291
|
+
limits: {
|
|
292
|
+
maximumArchiveBytes: Math.min(limits.archiveBytes, cache.maximumBytes),
|
|
293
|
+
maximumExtractedBytes: Math.min(
|
|
294
|
+
limits.extractedBytes,
|
|
295
|
+
cache.maximumExtractedBytes,
|
|
296
|
+
remainingWorkspaceBytes,
|
|
297
|
+
),
|
|
298
|
+
maximumEntries: Math.min(
|
|
299
|
+
limits.entries,
|
|
300
|
+
cache.maximumEntries,
|
|
301
|
+
remainingWorkspaceEntries,
|
|
302
|
+
),
|
|
303
|
+
},
|
|
304
|
+
reserveBytes: this.config.transferStagingReserveBytes,
|
|
305
|
+
reserveInodes: this.config.transferStagingReserveInodes,
|
|
306
|
+
signal: context.signal,
|
|
307
|
+
label: `Cache ${cache.name}`,
|
|
308
|
+
});
|
|
309
|
+
let restorePath: string | undefined;
|
|
310
|
+
let primaryError: unknown;
|
|
311
|
+
try {
|
|
312
|
+
await Deno.mkdir(restoreRoot, { recursive: true, mode: 0o700 });
|
|
313
|
+
await ensureStagingCapacity(
|
|
314
|
+
restoreRoot,
|
|
315
|
+
staged.metadata.extractedSizeBytes,
|
|
316
|
+
staged.metadata.entryCount + 1,
|
|
317
|
+
this.config.transferStagingReserveBytes,
|
|
318
|
+
this.config.transferStagingReserveInodes,
|
|
319
|
+
);
|
|
320
|
+
restorePath = await Deno.makeTempDir({
|
|
321
|
+
dir: restoreRoot,
|
|
322
|
+
prefix: 'cache-',
|
|
323
|
+
});
|
|
324
|
+
await Deno.chmod(restorePath, 0o700);
|
|
325
|
+
await extractTarGzipArchive({
|
|
326
|
+
archivePath: staged.path,
|
|
327
|
+
destinationPath: restorePath,
|
|
328
|
+
expectedMetadata: staged.metadata,
|
|
329
|
+
maximumExtractedBytes: Math.min(cache.maximumExtractedBytes, remainingWorkspaceBytes),
|
|
330
|
+
maximumEntries: Math.min(cache.maximumEntries, remainingWorkspaceEntries),
|
|
331
|
+
allowSymlinks: false,
|
|
332
|
+
allowedPaths: cache.paths,
|
|
333
|
+
requireAllowedPaths: true,
|
|
334
|
+
signal: context.signal,
|
|
335
|
+
});
|
|
336
|
+
await restoreSelectedPaths(restorePath, context.workspacePath, cache);
|
|
337
|
+
workspaceBytes = checkedAdd(
|
|
338
|
+
workspaceBytes,
|
|
339
|
+
staged.metadata.extractedSizeBytes,
|
|
340
|
+
'Restored workspace byte count overflow',
|
|
341
|
+
);
|
|
342
|
+
workspaceEntries = checkedAdd(
|
|
343
|
+
workspaceEntries,
|
|
344
|
+
staged.metadata.entryCount,
|
|
345
|
+
'Restored workspace entry count overflow',
|
|
346
|
+
);
|
|
347
|
+
} catch (error) {
|
|
348
|
+
primaryError = error;
|
|
349
|
+
}
|
|
350
|
+
await cleanupResources(
|
|
351
|
+
primaryError,
|
|
352
|
+
[
|
|
353
|
+
...(restorePath ? [() => removePathIfPresent(restorePath!, true)] : []),
|
|
354
|
+
() => staged.cleanup(),
|
|
355
|
+
],
|
|
356
|
+
`Cache ${cache.name} restore and cleanup failed`,
|
|
357
|
+
);
|
|
358
|
+
this.onMessage?.(`Cache ${cache.name} restored`);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
public async save(context: ICacheSaveContext): Promise<void> {
|
|
363
|
+
validateCaches(this.config, context.job);
|
|
364
|
+
if (context.status !== 'succeeded') return;
|
|
365
|
+
for (const cache of context.job.caches) {
|
|
366
|
+
if (cache.access !== 'read-write') continue;
|
|
367
|
+
if (context.signal.aborted) throw context.signal.reason;
|
|
368
|
+
await Deno.mkdir(this.config.stateDirectory, { recursive: true, mode: 0o700 });
|
|
369
|
+
await ensureStagingCapacity(
|
|
370
|
+
this.config.stateDirectory,
|
|
371
|
+
cache.maximumExtractedBytes,
|
|
372
|
+
cache.maximumEntries + 1,
|
|
373
|
+
this.config.transferStagingReserveBytes,
|
|
374
|
+
this.config.transferStagingReserveInodes,
|
|
375
|
+
);
|
|
376
|
+
let exported: Awaited<ReturnType<typeof context.workspace.exportSelected>> | undefined;
|
|
377
|
+
let archive: Awaited<ReturnType<typeof createTarGzipArchive>> | undefined;
|
|
378
|
+
let primaryError: unknown;
|
|
379
|
+
try {
|
|
380
|
+
exported = await context.workspace.exportSelected({
|
|
381
|
+
selections: cache.paths,
|
|
382
|
+
maximumBytes: cache.maximumExtractedBytes,
|
|
383
|
+
maximumEntries: cache.maximumEntries,
|
|
384
|
+
signal: context.signal,
|
|
385
|
+
});
|
|
386
|
+
const archiveRoot = join(this.config.stateDirectory, 'cache-uploads');
|
|
387
|
+
await Deno.mkdir(archiveRoot, { recursive: true, mode: 0o700 });
|
|
388
|
+
await ensureStagingCapacity(
|
|
389
|
+
archiveRoot,
|
|
390
|
+
cache.maximumBytes,
|
|
391
|
+
1,
|
|
392
|
+
this.config.transferStagingReserveBytes,
|
|
393
|
+
this.config.transferStagingReserveInodes,
|
|
394
|
+
);
|
|
395
|
+
archive = await createTarGzipArchive({
|
|
396
|
+
sourcePath: exported.path,
|
|
397
|
+
selections: cache.paths,
|
|
398
|
+
expectedMetadata: exported.metadata,
|
|
399
|
+
archiveDirectory: archiveRoot,
|
|
400
|
+
archivePrefix: 'cache-',
|
|
401
|
+
maximumArchiveBytes: cache.maximumBytes,
|
|
402
|
+
maximumExtractedBytes: cache.maximumExtractedBytes,
|
|
403
|
+
maximumEntries: cache.maximumEntries,
|
|
404
|
+
allowSymlinks: false,
|
|
405
|
+
signal: context.signal,
|
|
406
|
+
});
|
|
407
|
+
const transferRequestId = crypto.randomUUID();
|
|
408
|
+
const record = await this.api.uploadCache(
|
|
409
|
+
context.identity,
|
|
410
|
+
cache.name,
|
|
411
|
+
transferRequestId,
|
|
412
|
+
archive.metadata,
|
|
413
|
+
archive.openBody,
|
|
414
|
+
context.signal,
|
|
415
|
+
);
|
|
416
|
+
validateTransferRecord(record, cache.name, archive.metadata);
|
|
417
|
+
} catch (error) {
|
|
418
|
+
primaryError = error;
|
|
419
|
+
}
|
|
420
|
+
await cleanupResources(
|
|
421
|
+
primaryError,
|
|
422
|
+
[
|
|
423
|
+
...(archive ? [() => archive!.cleanup()] : []),
|
|
424
|
+
...(exported ? [() => exported!.cleanup()] : []),
|
|
425
|
+
],
|
|
426
|
+
`Cache ${cache.name} save and cleanup failed`,
|
|
427
|
+
);
|
|
428
|
+
this.onMessage?.(`Cache ${cache.name} saved`);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
package/ts/cli.ts
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { RunnerApiClient } from './api-client.ts';
|
|
2
|
+
import { ArtifactManager } from './artifact-manager.ts';
|
|
3
|
+
import { CacheManager } from './cache-manager.ts';
|
|
4
|
+
import {
|
|
5
|
+
defaultRunnerConfig,
|
|
6
|
+
loadRunnerConfig,
|
|
7
|
+
maskRunnerConfig,
|
|
8
|
+
saveRunnerConfig,
|
|
9
|
+
validateRunnerConfig,
|
|
10
|
+
withRunnerCredential,
|
|
11
|
+
} from './config.ts';
|
|
12
|
+
import { ConfigurationError } from './errors.ts';
|
|
13
|
+
import type {
|
|
14
|
+
IRegisterRunnerRequest,
|
|
15
|
+
IRegisterRunnerResponse,
|
|
16
|
+
IRunnerCapabilities,
|
|
17
|
+
IRunnerConfig,
|
|
18
|
+
} from './interfaces.ts';
|
|
19
|
+
import { runnerProtocolIdentifier, runnerVersion } from './interfaces.ts';
|
|
20
|
+
import { OciExecutor } from './oci-executor.ts';
|
|
21
|
+
import { RegistrationStateStore } from './registration-state.ts';
|
|
22
|
+
import { reconcileProtocolLimits, runnerCapabilities, ShipRunner } from './runner.ts';
|
|
23
|
+
import { SourceWorkspaceManager } from './source-workspace.ts';
|
|
24
|
+
|
|
25
|
+
interface IParsedArguments {
|
|
26
|
+
command: string;
|
|
27
|
+
options: Map<string, string | true>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const cliInvocation =
|
|
31
|
+
'deno run --allow-env --allow-net --allow-read --allow-write --allow-run npm:@ship.zone/runner';
|
|
32
|
+
|
|
33
|
+
const usage = `ship.zone runner ${runnerVersion}
|
|
34
|
+
|
|
35
|
+
Usage:
|
|
36
|
+
${cliInvocation} init --control-plane <url> [--config <path>] [--name <name>]
|
|
37
|
+
${cliInvocation} register [--config <path>]
|
|
38
|
+
${cliInvocation} run [--config <path>]
|
|
39
|
+
${cliInvocation} once [--config <path>]
|
|
40
|
+
${cliInvocation} config [--config <path>]
|
|
41
|
+
${cliInvocation} version
|
|
42
|
+
|
|
43
|
+
Bootstrap credentials must be supplied through SHIP_RUNNER_BOOTSTRAP_TOKEN or the
|
|
44
|
+
0600 config file. Secret values are intentionally not accepted as command arguments.
|
|
45
|
+
`;
|
|
46
|
+
|
|
47
|
+
const parseArguments = (arguments_: string[]): IParsedArguments => {
|
|
48
|
+
const normalizedArguments = arguments_[0] === '--' ? arguments_.slice(1) : arguments_;
|
|
49
|
+
const [command = 'help', ...rest] = normalizedArguments;
|
|
50
|
+
const options = new Map<string, string | true>();
|
|
51
|
+
for (let index = 0; index < rest.length; index++) {
|
|
52
|
+
const entry = rest[index];
|
|
53
|
+
if (!entry.startsWith('--')) throw new ConfigurationError(`Unexpected argument: ${entry}`);
|
|
54
|
+
const name = entry.slice(2);
|
|
55
|
+
const next = rest[index + 1];
|
|
56
|
+
if (!next || next.startsWith('--')) options.set(name, true);
|
|
57
|
+
else {
|
|
58
|
+
options.set(name, next);
|
|
59
|
+
index++;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return { command, options };
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const stringOption = (
|
|
66
|
+
options: Map<string, string | true>,
|
|
67
|
+
name: string,
|
|
68
|
+
): string | undefined => {
|
|
69
|
+
const value = options.get(name);
|
|
70
|
+
if (value === undefined) return undefined;
|
|
71
|
+
if (value === true) throw new ConfigurationError(`--${name} requires a value`);
|
|
72
|
+
return value;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const configPath = (options: Map<string, string | true>): string =>
|
|
76
|
+
stringOption(options, 'config') ?? Deno.env.get('SHIP_RUNNER_CONFIG') ?? './runner.config.json';
|
|
77
|
+
|
|
78
|
+
const apiFor = (config: IRunnerConfig): RunnerApiClient =>
|
|
79
|
+
new RunnerApiClient({
|
|
80
|
+
controlPlaneUrl: config.controlPlaneUrl,
|
|
81
|
+
allowInsecureLoopback: config.allowInsecureLoopback,
|
|
82
|
+
requestTimeoutMs: config.requestTimeoutMs,
|
|
83
|
+
sourceTransferTimeoutMs: config.sourceTransferTimeoutMs,
|
|
84
|
+
artifactUploadTimeoutMs: config.artifactUploadTimeoutMs,
|
|
85
|
+
cacheTransferTimeoutMs: config.cacheTransferTimeoutMs,
|
|
86
|
+
maximumResponseBytes: config.maximumResponseBytes,
|
|
87
|
+
runnerToken: config.runnerToken,
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
export const registerRunnerDurably = async (options: {
|
|
91
|
+
configPath: string;
|
|
92
|
+
config: IRunnerConfig;
|
|
93
|
+
capabilities: IRunnerCapabilities;
|
|
94
|
+
api: {
|
|
95
|
+
register(
|
|
96
|
+
request: IRegisterRunnerRequest,
|
|
97
|
+
bootstrapToken: string,
|
|
98
|
+
): Promise<IRegisterRunnerResponse>;
|
|
99
|
+
};
|
|
100
|
+
stateStore?: RegistrationStateStore;
|
|
101
|
+
createRequestId?: () => string;
|
|
102
|
+
persistConfig?: (path: string, config: IRunnerConfig) => Promise<void>;
|
|
103
|
+
}): Promise<IRunnerConfig> => {
|
|
104
|
+
if (!options.config.bootstrapToken) {
|
|
105
|
+
throw new ConfigurationError('SHIP_RUNNER_BOOTSTRAP_TOKEN is required for registration');
|
|
106
|
+
}
|
|
107
|
+
const stateStore = options.stateStore ??
|
|
108
|
+
new RegistrationStateStore(options.config.stateDirectory);
|
|
109
|
+
const request = await stateStore.loadOrCreate({
|
|
110
|
+
protocol: runnerProtocolIdentifier,
|
|
111
|
+
runnerVersion,
|
|
112
|
+
name: options.config.name,
|
|
113
|
+
capabilities: options.capabilities,
|
|
114
|
+
}, options.createRequestId);
|
|
115
|
+
const response = await options.api.register(request, options.config.bootstrapToken);
|
|
116
|
+
const registered = withRunnerCredential(options.config, response.credential);
|
|
117
|
+
await (options.persistConfig ?? saveRunnerConfig)(options.configPath, registered);
|
|
118
|
+
await stateStore.clear();
|
|
119
|
+
return registered;
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const runInit = async (options: Map<string, string | true>): Promise<void> => {
|
|
123
|
+
const config = defaultRunnerConfig();
|
|
124
|
+
config.controlPlaneUrl = stringOption(options, 'control-plane') ?? '';
|
|
125
|
+
config.name = stringOption(options, 'name') ?? config.name;
|
|
126
|
+
const labels = stringOption(options, 'labels');
|
|
127
|
+
if (labels) config.labels = labels.split(',').map((entry) => entry.trim()).filter(Boolean);
|
|
128
|
+
const runtimePath = stringOption(options, 'runtime-path');
|
|
129
|
+
if (runtimePath) config.oci.runtimePath = runtimePath;
|
|
130
|
+
const helperPath = stringOption(options, 'workspace-helper-path');
|
|
131
|
+
if (helperPath) config.oci.workspaceHelperPath = helperPath;
|
|
132
|
+
if (options.has('allow-insecure-loopback')) config.allowInsecureLoopback = true;
|
|
133
|
+
if (options.has('allow-network')) config.oci.allowedNetworks = ['none', 'bridge'];
|
|
134
|
+
validateRunnerConfig(config);
|
|
135
|
+
const path = configPath(options);
|
|
136
|
+
await saveRunnerConfig(path, config);
|
|
137
|
+
console.log(`Created ${path}`);
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const runRegister = async (options: Map<string, string | true>): Promise<void> => {
|
|
141
|
+
const path = configPath(options);
|
|
142
|
+
const config = await loadRunnerConfig(path);
|
|
143
|
+
if (!config.bootstrapToken) {
|
|
144
|
+
throw new ConfigurationError('SHIP_RUNNER_BOOTSTRAP_TOKEN is required for registration');
|
|
145
|
+
}
|
|
146
|
+
const api = apiFor(config);
|
|
147
|
+
const executor = new OciExecutor(config);
|
|
148
|
+
await executor.verifyRuntime();
|
|
149
|
+
const discovery = await api.discover();
|
|
150
|
+
const capabilities = runnerCapabilities(config);
|
|
151
|
+
reconcileProtocolLimits(config, discovery, capabilities);
|
|
152
|
+
const registered = await registerRunnerDurably({
|
|
153
|
+
configPath: path,
|
|
154
|
+
config,
|
|
155
|
+
capabilities,
|
|
156
|
+
api,
|
|
157
|
+
});
|
|
158
|
+
console.log(`Registered runner ${registered.runnerId}`);
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
const runDaemon = async (
|
|
162
|
+
options: Map<string, string | true>,
|
|
163
|
+
once: boolean,
|
|
164
|
+
): Promise<void> => {
|
|
165
|
+
const path = configPath(options);
|
|
166
|
+
let config = await loadRunnerConfig(path);
|
|
167
|
+
const api = apiFor(config);
|
|
168
|
+
const executor = new OciExecutor(config);
|
|
169
|
+
await executor.verifyRuntime();
|
|
170
|
+
const shutdown = new AbortController();
|
|
171
|
+
const shutdownListener = (): void => shutdown.abort('runner_shutdown');
|
|
172
|
+
const installedSignals: Array<'SIGINT' | 'SIGTERM'> = [];
|
|
173
|
+
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
|
174
|
+
try {
|
|
175
|
+
Deno.addSignalListener(signal, shutdownListener);
|
|
176
|
+
installedSignals.push(signal);
|
|
177
|
+
} catch {
|
|
178
|
+
// Signal listeners are unavailable on some supported hosts.
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
const reportMessage = (message: string): void => console.error(message);
|
|
183
|
+
const runner = new ShipRunner(config, {
|
|
184
|
+
api,
|
|
185
|
+
executor,
|
|
186
|
+
workspaceManager: new SourceWorkspaceManager(config, api),
|
|
187
|
+
artifactManager: new ArtifactManager(config, api, reportMessage),
|
|
188
|
+
cacheManager: new CacheManager(config, api, reportMessage),
|
|
189
|
+
onCredential: async (credential) => {
|
|
190
|
+
const updatedConfig = withRunnerCredential(config, credential);
|
|
191
|
+
await saveRunnerConfig(path, updatedConfig);
|
|
192
|
+
config = updatedConfig;
|
|
193
|
+
},
|
|
194
|
+
onMessage: reportMessage,
|
|
195
|
+
});
|
|
196
|
+
const result = await runner.run({ once, signal: shutdown.signal });
|
|
197
|
+
if (once) console.log(result.claimed ? `Job ${result.status}` : 'No job available');
|
|
198
|
+
} finally {
|
|
199
|
+
for (const signal of installedSignals) Deno.removeSignalListener(signal, shutdownListener);
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
export const runCli = async (arguments_: string[]): Promise<void> => {
|
|
204
|
+
try {
|
|
205
|
+
const { command, options } = parseArguments(arguments_);
|
|
206
|
+
switch (command) {
|
|
207
|
+
case 'init':
|
|
208
|
+
await runInit(options);
|
|
209
|
+
break;
|
|
210
|
+
case 'register':
|
|
211
|
+
await runRegister(options);
|
|
212
|
+
break;
|
|
213
|
+
case 'run':
|
|
214
|
+
await runDaemon(options, false);
|
|
215
|
+
break;
|
|
216
|
+
case 'once':
|
|
217
|
+
await runDaemon(options, true);
|
|
218
|
+
break;
|
|
219
|
+
case 'config': {
|
|
220
|
+
const config = await loadRunnerConfig(configPath(options));
|
|
221
|
+
console.log(JSON.stringify(maskRunnerConfig(config), null, 2));
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
case 'version':
|
|
225
|
+
console.log(runnerVersion);
|
|
226
|
+
break;
|
|
227
|
+
case 'help':
|
|
228
|
+
case '--help':
|
|
229
|
+
case '-h':
|
|
230
|
+
console.log(usage);
|
|
231
|
+
break;
|
|
232
|
+
default:
|
|
233
|
+
throw new ConfigurationError(`Unknown command: ${command}\n\n${usage}`);
|
|
234
|
+
}
|
|
235
|
+
} catch (error) {
|
|
236
|
+
console.error(error instanceof Error ? error.message : 'Runner failed');
|
|
237
|
+
Deno.exitCode = 1;
|
|
238
|
+
}
|
|
239
|
+
};
|