@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.
@@ -0,0 +1,161 @@
1
+ import { join } from '@std/path';
2
+ import { ProtocolError, ResourceCleanupError } from './errors.ts';
3
+ import type {
4
+ IJobIdentity,
5
+ IJobSource,
6
+ IPreparedWorkspace,
7
+ ISourcePrepareContext,
8
+ ITransferDownload,
9
+ ITransferManagerConfig,
10
+ } from './interfaces.ts';
11
+ import {
12
+ ensureStagingCapacity,
13
+ extractTarGzipArchive,
14
+ removePathIfPresent,
15
+ stageTransferDownload,
16
+ } from './transfer-archive.ts';
17
+
18
+ export interface ISourceApiClient {
19
+ downloadSource(
20
+ identity: IJobIdentity,
21
+ source: IJobSource,
22
+ signal?: AbortSignal,
23
+ ): Promise<ITransferDownload>;
24
+ }
25
+
26
+ const effectiveSourceLimits = (
27
+ config: ITransferManagerConfig,
28
+ context: ISourcePrepareContext,
29
+ ): { archiveBytes: number; extractedBytes: number; entries: number } => ({
30
+ archiveBytes: Math.min(
31
+ config.maximumSourceArchiveBytes,
32
+ context.job.requirements.limits.maximumSourceArchiveBytes,
33
+ ),
34
+ extractedBytes: Math.min(
35
+ config.maximumSourceExtractedBytes,
36
+ config.oci.workspaceSizeBytes,
37
+ context.job.requirements.limits.maximumSourceExtractedBytes,
38
+ context.job.requirements.limits.maximumWorkspaceBytes,
39
+ ),
40
+ entries: Math.min(
41
+ config.maximumSourceEntries,
42
+ config.maximumWorkspaceEntries,
43
+ context.job.requirements.limits.maximumSourceEntries,
44
+ context.job.requirements.limits.maximumWorkspaceEntries,
45
+ ),
46
+ });
47
+
48
+ const cleanupFailure = async (
49
+ error: unknown,
50
+ cleanups: Array<() => Promise<void>>,
51
+ message: string,
52
+ ): Promise<never> => {
53
+ const cleanupErrors: unknown[] = [];
54
+ for (const cleanup of cleanups) {
55
+ try {
56
+ await cleanup();
57
+ } catch (cleanupError) {
58
+ cleanupErrors.push(cleanupError);
59
+ }
60
+ }
61
+ if (cleanupErrors.length > 0) {
62
+ throw new ResourceCleanupError(message, [error, ...cleanupErrors]);
63
+ }
64
+ throw error;
65
+ };
66
+
67
+ export class SourceWorkspaceManager {
68
+ constructor(
69
+ private readonly config: ITransferManagerConfig,
70
+ private readonly api: ISourceApiClient,
71
+ ) {}
72
+
73
+ async prepare(context: ISourcePrepareContext): Promise<IPreparedWorkspace> {
74
+ if (context.job.permissions.source !== 'read') {
75
+ throw new ProtocolError('Job does not permit source download');
76
+ }
77
+ if (!context.job.requirements.features.includes('source.tar-gz')) {
78
+ throw new ProtocolError('Job does not declare the source.tar-gz feature');
79
+ }
80
+ const source = context.job.source;
81
+ if (source.format !== 'tar.gz') throw new ProtocolError('Job source format is unsupported');
82
+ const limits = effectiveSourceLimits(this.config, context);
83
+ if (
84
+ source.sizeBytes > limits.archiveBytes ||
85
+ source.extractedSizeBytes > limits.extractedBytes ||
86
+ source.entryCount > limits.entries
87
+ ) {
88
+ throw new ProtocolError('Job source exceeds its effective runner limits');
89
+ }
90
+ if (context.signal.aborted) throw context.signal.reason;
91
+
92
+ const archiveRoot = join(this.config.stateDirectory, 'source-archives');
93
+ const workspaceRoot = join(this.config.stateDirectory, 'workspaces');
94
+ await Deno.mkdir(archiveRoot, { recursive: true, mode: 0o700 });
95
+ await Deno.mkdir(workspaceRoot, { recursive: true, mode: 0o700 });
96
+ const download = await this.api.downloadSource(context.identity, source, context.signal);
97
+ const staged = await stageTransferDownload(download, {
98
+ directory: archiveRoot,
99
+ prefix: 'source-',
100
+ limits: {
101
+ maximumArchiveBytes: limits.archiveBytes,
102
+ maximumExtractedBytes: limits.extractedBytes,
103
+ maximumEntries: limits.entries,
104
+ },
105
+ reserveBytes: this.config.transferStagingReserveBytes,
106
+ reserveInodes: this.config.transferStagingReserveInodes,
107
+ expectedMetadata: source,
108
+ signal: context.signal,
109
+ label: 'Source transfer',
110
+ });
111
+ let workspacePath: string | undefined;
112
+ try {
113
+ await ensureStagingCapacity(
114
+ workspaceRoot,
115
+ source.extractedSizeBytes,
116
+ source.entryCount + 1,
117
+ this.config.transferStagingReserveBytes,
118
+ this.config.transferStagingReserveInodes,
119
+ );
120
+ workspacePath = await Deno.makeTempDir({
121
+ dir: workspaceRoot,
122
+ prefix: 'attempt-',
123
+ });
124
+ await Deno.chmod(workspacePath, 0o700);
125
+ const metadata = await extractTarGzipArchive({
126
+ archivePath: staged.path,
127
+ destinationPath: workspacePath,
128
+ expectedMetadata: staged.metadata,
129
+ maximumExtractedBytes: limits.extractedBytes,
130
+ maximumEntries: limits.entries,
131
+ allowSymlinks: true,
132
+ signal: context.signal,
133
+ });
134
+ await staged.cleanup();
135
+ let cleaned = false;
136
+ let cleanupPromise: Promise<void> | undefined;
137
+ const ownedWorkspacePath = workspacePath;
138
+ return {
139
+ path: ownedWorkspacePath,
140
+ metadata,
141
+ cleanup: () => {
142
+ if (cleaned) return Promise.resolve();
143
+ cleanupPromise ??= removePathIfPresent(ownedWorkspacePath, true).then(
144
+ () => {
145
+ cleaned = true;
146
+ },
147
+ (error) => {
148
+ cleanupPromise = undefined;
149
+ throw error;
150
+ },
151
+ );
152
+ return cleanupPromise;
153
+ },
154
+ };
155
+ } catch (error) {
156
+ const cleanups: Array<() => Promise<void>> = [() => staged.cleanup()];
157
+ if (workspacePath) cleanups.push(() => removePathIfPresent(workspacePath!, true));
158
+ return await cleanupFailure(error, cleanups, 'Source preparation and cleanup failed');
159
+ }
160
+ }
161
+ }
@@ -0,0 +1,62 @@
1
+ import { join, resolve } from '@std/path';
2
+ import { RunnerError } from './errors.ts';
3
+
4
+ const stagingDirectoryNames = [
5
+ 'source-archives',
6
+ 'workspaces',
7
+ 'cache-downloads',
8
+ 'cache-restores',
9
+ 'cache-uploads',
10
+ 'artifact-uploads',
11
+ 'workspace-exports',
12
+ ] as const;
13
+
14
+ const journalTemporaryNamePattern =
15
+ /^\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.(?:attempt|registration)-journal\.tmp$/;
16
+
17
+ const lstatIfPresent = async (path: string): Promise<Deno.FileInfo | undefined> => {
18
+ try {
19
+ return await Deno.lstat(path);
20
+ } catch (error) {
21
+ if (error instanceof Deno.errors.NotFound) return undefined;
22
+ throw error;
23
+ }
24
+ };
25
+
26
+ const removeIfPresent = async (path: string, recursive = false): Promise<void> => {
27
+ try {
28
+ await Deno.remove(path, { recursive });
29
+ } catch (error) {
30
+ if (!(error instanceof Deno.errors.NotFound)) throw error;
31
+ }
32
+ };
33
+
34
+ export const scavengeRunnerStaging = async (stateDirectory: string): Promise<void> => {
35
+ const stateRoot = resolve(stateDirectory);
36
+ await Deno.mkdir(stateRoot, { recursive: true, mode: 0o700 });
37
+ const rootStat = await Deno.lstat(stateRoot);
38
+ if (!rootStat.isDirectory || rootStat.isSymlink) {
39
+ throw new RunnerError('Runner state directory must be a real directory');
40
+ }
41
+
42
+ for (const name of stagingDirectoryNames) {
43
+ const path = join(stateRoot, name);
44
+ const stat = await lstatIfPresent(path);
45
+ if (!stat) continue;
46
+ if (!stat.isDirectory || stat.isSymlink) {
47
+ throw new RunnerError(`Runner staging path ${name} must be a real directory`);
48
+ }
49
+ await removeIfPresent(path, true);
50
+ }
51
+
52
+ for await (const entry of Deno.readDir(stateRoot)) {
53
+ if (!journalTemporaryNamePattern.test(entry.name)) continue;
54
+ const path = join(stateRoot, entry.name);
55
+ const stat = await lstatIfPresent(path);
56
+ if (!stat) continue;
57
+ if (!stat.isFile || stat.isSymlink) {
58
+ throw new RunnerError('Runner journal temporary path must be a regular file');
59
+ }
60
+ await removeIfPresent(path);
61
+ }
62
+ };