@ship.zone/runner 2.0.0 → 3.0.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.
Files changed (180) hide show
  1. package/.smartconfig.json +101 -3
  2. package/changelog.md +69 -0
  3. package/dist_rust/runnerworkspace_linux_amd64_musl +0 -0
  4. package/dist_rust/runnerworkspace_linux_amd64_musl.third-party-notices.json +679 -0
  5. package/dist_rust/runnerworkspace_linux_amd64_musl.third-party-notices.txt +15719 -0
  6. package/dist_rust/runnerworkspace_linux_amd64_musl.tsrust-build.json +5 -5
  7. package/dist_rust/runnerworkspace_linux_arm64_musl +0 -0
  8. package/dist_rust/runnerworkspace_linux_arm64_musl.third-party-notices.json +679 -0
  9. package/dist_rust/runnerworkspace_linux_arm64_musl.third-party-notices.txt +15719 -0
  10. package/dist_rust/runnerworkspace_linux_arm64_musl.tsrust-build.json +5 -5
  11. package/dist_ts/00_commitinfo_data.d.ts +8 -0
  12. package/dist_ts/00_commitinfo_data.js +9 -0
  13. package/dist_ts/api-client.d.ts +46 -0
  14. package/dist_ts/api-client.js +592 -0
  15. package/dist_ts/artifact-manager.d.ts +11 -0
  16. package/dist_ts/artifact-manager.js +140 -0
  17. package/dist_ts/attempt-state.d.ts +18 -0
  18. package/dist_ts/attempt-state.js +151 -0
  19. package/dist_ts/cache-manager.d.ts +13 -0
  20. package/dist_ts/cache-manager.js +300 -0
  21. package/dist_ts/cli-entry.d.ts +2 -0
  22. package/dist_ts/cli-entry.js +4 -0
  23. package/dist_ts/cli.d.ts +14 -0
  24. package/dist_ts/cli.js +215 -0
  25. package/dist_ts/config.d.ts +8 -0
  26. package/dist_ts/config.js +445 -0
  27. package/dist_ts/errors.d.ts +41 -0
  28. package/dist_ts/errors.js +90 -0
  29. package/dist_ts/filesystem.d.ts +73 -0
  30. package/dist_ts/filesystem.js +207 -0
  31. package/dist_ts/index.d.ts +16 -0
  32. package/dist_ts/index.js +17 -0
  33. package/dist_ts/interfaces.d.ts +614 -0
  34. package/dist_ts/interfaces.js +3 -0
  35. package/dist_ts/log-sender.d.ts +26 -0
  36. package/dist_ts/log-sender.js +124 -0
  37. package/dist_ts/oci-executor.d.ts +155 -0
  38. package/dist_ts/oci-executor.js +2238 -0
  39. package/dist_ts/plugins.d.ts +19 -0
  40. package/dist_ts/plugins.js +23 -0
  41. package/dist_ts/protocol-validator.d.ts +39 -0
  42. package/dist_ts/protocol-validator.js +483 -0
  43. package/dist_ts/redactor.d.ts +78 -0
  44. package/dist_ts/redactor.js +235 -0
  45. package/dist_ts/registration-state.d.ts +16 -0
  46. package/dist_ts/registration-state.js +171 -0
  47. package/dist_ts/runner.d.ts +64 -0
  48. package/dist_ts/runner.js +882 -0
  49. package/dist_ts/source-workspace.d.ts +10 -0
  50. package/dist_ts/source-workspace.js +125 -0
  51. package/dist_ts/spec-version.d.ts +11 -0
  52. package/dist_ts/spec-version.js +41 -0
  53. package/dist_ts/staging-scavenger.d.ts +7 -0
  54. package/dist_ts/staging-scavenger.js +63 -0
  55. package/dist_ts/state-owner.d.ts +74 -0
  56. package/dist_ts/state-owner.js +289 -0
  57. package/dist_ts/transfer-archive.d.ts +78 -0
  58. package/dist_ts/transfer-archive.js +1619 -0
  59. package/dist_ts/validation.d.ts +11 -0
  60. package/dist_ts/validation.js +79 -0
  61. package/dist_ts/wire-schema.d.ts +10 -0
  62. package/dist_ts/wire-schema.js +114 -0
  63. package/native-notices/crates/bitflags-2.13.1/license-apache +201 -0
  64. package/native-notices/crates/bitflags-2.13.1/license-mit +25 -0
  65. package/native-notices/crates/cc-1.8.0/license-apache +201 -0
  66. package/native-notices/crates/cc-1.8.0/license-mit +25 -0
  67. package/native-notices/crates/cfg-if-1.0.4/license-apache +201 -0
  68. package/native-notices/crates/cfg-if-1.0.4/license-mit +25 -0
  69. package/native-notices/crates/cfg_aliases-0.2.2/license +9 -0
  70. package/native-notices/crates/cfg_aliases-0.2.2/notices.md +26 -0
  71. package/native-notices/crates/find-msvc-tools-0.1.14/license-apache +201 -0
  72. package/native-notices/crates/find-msvc-tools-0.1.14/license-mit +25 -0
  73. package/native-notices/crates/itoa-1.0.18/license-apache +176 -0
  74. package/native-notices/crates/itoa-1.0.18/license-mit +23 -0
  75. package/native-notices/crates/libc-0.2.189/license-apache +176 -0
  76. package/native-notices/crates/libc-0.2.189/license-mit +25 -0
  77. package/native-notices/crates/memchr-2.8.3/copying +3 -0
  78. package/native-notices/crates/memchr-2.8.3/license-mit +21 -0
  79. package/native-notices/crates/memchr-2.8.3/unlicense +24 -0
  80. package/native-notices/crates/nix-0.30.1/license +21 -0
  81. package/native-notices/crates/proc-macro2-1.0.107/license-apache +176 -0
  82. package/native-notices/crates/proc-macro2-1.0.107/license-mit +23 -0
  83. package/native-notices/crates/quote-1.0.47/license-apache +176 -0
  84. package/native-notices/crates/quote-1.0.47/license-mit +23 -0
  85. package/native-notices/crates/serde-1.0.229/license-apache +176 -0
  86. package/native-notices/crates/serde-1.0.229/license-mit +23 -0
  87. package/native-notices/crates/serde_core-1.0.229/license-apache +176 -0
  88. package/native-notices/crates/serde_core-1.0.229/license-mit +23 -0
  89. package/native-notices/crates/serde_derive-1.0.229/license-apache +176 -0
  90. package/native-notices/crates/serde_derive-1.0.229/license-mit +23 -0
  91. package/native-notices/crates/serde_json-1.0.151/license-apache +176 -0
  92. package/native-notices/crates/serde_json-1.0.151/license-mit +23 -0
  93. package/native-notices/crates/shlex-2.0.1/license-apache +13 -0
  94. package/native-notices/crates/shlex-2.0.1/license-mit +21 -0
  95. package/native-notices/crates/syn-3.0.3/license-apache +176 -0
  96. package/native-notices/crates/syn-3.0.3/license-mit +23 -0
  97. package/native-notices/crates/tikv-jemalloc-sys-0.7.1+5.3.1-0-g81034ce1f1373e37dc865038e1bc8eeecf559ce8/license-apache +201 -0
  98. package/native-notices/crates/tikv-jemalloc-sys-0.7.1+5.3.1-0-g81034ce1f1373e37dc865038e1bc8eeecf559ce8/license-mit +25 -0
  99. package/native-notices/crates/tikv-jemallocator-0.7.0/license-apache +201 -0
  100. package/native-notices/crates/tikv-jemallocator-0.7.0/license-mit +25 -0
  101. package/native-notices/crates/unicode-ident-1.0.24/license-apache +176 -0
  102. package/native-notices/crates/unicode-ident-1.0.24/license-mit +23 -0
  103. package/native-notices/crates/unicode-ident-1.0.24/license-unicode +39 -0
  104. package/native-notices/crates/zmij-1.0.23/license-mit +23 -0
  105. package/native-notices/manifest.json +763 -0
  106. package/native-notices/native/tikv-jemalloc-sys-0.7.1+5.3.1-0-g81034ce1f1373e37dc865038e1bc8eeecf559ce8/jemalloc-5.3.1/jemalloc-copying +27 -0
  107. package/native-notices/readme.md +46 -0
  108. package/native-notices/runtime/gcc/gpl-3.0.txt +674 -0
  109. package/native-notices/runtime/gcc/runtime-library-exception-3.1.txt +73 -0
  110. package/native-notices/runtime/libunwind-22.1.2/license.txt +311 -0
  111. package/native-notices/runtime/musl-1.2.5/copyright +193 -0
  112. package/native-notices/rust/compiler-builtins-license.txt +275 -0
  113. package/native-notices/rust/copyright-library.html +8266 -0
  114. package/native-notices/rust/crates/addr2line-0.25.1/license-apache +201 -0
  115. package/native-notices/rust/crates/addr2line-0.25.1/license-mit +25 -0
  116. package/native-notices/rust/crates/adler2-2.0.1/license-0bsd +12 -0
  117. package/native-notices/rust/crates/adler2-2.0.1/license-apache +201 -0
  118. package/native-notices/rust/crates/adler2-2.0.1/license-mit +23 -0
  119. package/native-notices/rust/crates/memchr-2.7.6/copying +3 -0
  120. package/native-notices/rust/crates/memchr-2.7.6/license-mit +21 -0
  121. package/native-notices/rust/crates/memchr-2.7.6/unlicense +24 -0
  122. package/native-notices/rust/crates/miniz_oxide-0.8.9/license +25 -0
  123. package/native-notices/rust/crates/miniz_oxide-0.8.9/license-apache.md +177 -0
  124. package/native-notices/rust/crates/miniz_oxide-0.8.9/license-mit.md +24 -0
  125. package/native-notices/rust/crates/miniz_oxide-0.8.9/license-zlib.md +14 -0
  126. package/native-notices/rust/crates/object-0.37.3/license-apache +201 -0
  127. package/native-notices/rust/crates/object-0.37.3/license-mit +25 -0
  128. package/native-notices/rust/licenses/apache-2.0.txt +73 -0
  129. package/native-notices/rust/licenses/bsd-2-clause.txt +9 -0
  130. package/native-notices/rust/licenses/cc-by-sa-4.0.txt +427 -0
  131. package/native-notices/rust/licenses/gcc-exception-3.1.txt +30 -0
  132. package/native-notices/rust/licenses/gpl-2.0-only.txt +133 -0
  133. package/native-notices/rust/licenses/gpl-3.0-or-later.txt +202 -0
  134. package/native-notices/rust/licenses/isc.txt +7 -0
  135. package/native-notices/rust/licenses/llvm-exception.txt +15 -0
  136. package/native-notices/rust/licenses/mit.txt +9 -0
  137. package/native-notices/rust/licenses/ncsa.txt +29 -0
  138. package/native-notices/rust/licenses/ofl-1.1.txt +43 -0
  139. package/native-notices/rust/licenses/unicode-3.0.txt +39 -0
  140. package/package.json +24 -21
  141. package/readme.md +91 -40
  142. package/rust/.cargo/config.toml +1 -1
  143. package/rust/Cargo.lock +43 -0
  144. package/rust/Cargo.toml +4 -1
  145. package/rust/src/lib.rs +156 -1
  146. package/rust/src/main.rs +5 -1
  147. package/rust-toolchain.toml +4 -0
  148. package/ts/00_commitinfo_data.ts +1 -1
  149. package/ts/api-client.ts +10 -7
  150. package/ts/artifact-manager.ts +9 -7
  151. package/ts/attempt-state.ts +75 -84
  152. package/ts/cache-manager.ts +22 -28
  153. package/ts/cli-entry.ts +4 -0
  154. package/ts/cli.ts +56 -45
  155. package/ts/config.ts +50 -39
  156. package/ts/errors.ts +19 -0
  157. package/ts/filesystem.ts +316 -0
  158. package/ts/index.ts +16 -15
  159. package/ts/interfaces.ts +2 -2
  160. package/ts/log-sender.ts +4 -4
  161. package/ts/oci-executor.ts +235 -383
  162. package/ts/plugins.ts +21 -3
  163. package/ts/protocol-validator.ts +5 -5
  164. package/ts/redactor.ts +2 -2
  165. package/ts/registration-state.ts +82 -90
  166. package/ts/runner.ts +30 -17
  167. package/ts/source-workspace.ts +11 -8
  168. package/ts/spec-version.ts +2 -2
  169. package/ts/staging-scavenger.ts +37 -26
  170. package/ts/state-owner.ts +346 -0
  171. package/ts/transfer-archive.ts +214 -243
  172. package/ts/validation.ts +1 -1
  173. package/ts/wire-schema.ts +3 -3
  174. package/deno.json +0 -56
  175. package/deno.lock +0 -1762
  176. package/dist_npm/mod.d.ts +0 -967
  177. package/dist_npm/mod.js +0 -10058
  178. package/mod.ts +0 -8
  179. package/musl-copyright.md +0 -81
  180. package/third-party-licenses.md +0 -95
@@ -1,5 +1,25 @@
1
- import { join, resolve } from '@std/path';
2
- import { ProtocolError, ResourceCleanupError, RunnerError } from './errors.ts';
1
+ import * as plugins from './plugins.js';
2
+ import { ConfigurationError, ProtocolError, ResourceCleanupError, RunnerError } from './errors.js';
3
+ import {
4
+ createNewWriteFlags,
5
+ isAlreadyExists,
6
+ isNotFound,
7
+ lstatIfPresent,
8
+ makeTempDir,
9
+ readBoundedRegularFile,
10
+ removePath,
11
+ sameFileIdentity,
12
+ sha256Hex,
13
+ syncDirectory,
14
+ withOpenFile,
15
+ writeAll,
16
+ } from './filesystem.js';
17
+ import {
18
+ ensurePrivateStateDirectory,
19
+ resolvePackagedWorkspaceHelperPath,
20
+ type RunnerStateOwner,
21
+ workspaceHelperMaximumBytes,
22
+ } from './state-owner.js';
3
23
  import type {
4
24
  ICompiledStep,
5
25
  IExecutionContext,
@@ -17,8 +37,10 @@ import type {
17
37
  TExecutionStopReason,
18
38
  TOciArchitecture,
19
39
  TOciHelperTarget,
20
- } from './interfaces.ts';
21
- import { utf8Length, validateEnvironmentName, validateIdentifier } from './validation.ts';
40
+ } from './interfaces.js';
41
+ import { utf8Length, validateEnvironmentName, validateIdentifier } from './validation.js';
42
+
43
+ const { join, resolve } = plugins.path;
22
44
 
23
45
  const runtimeEnvironmentNames = [
24
46
  'CONTAINER_CONNECTION',
@@ -59,17 +81,15 @@ const runtimeProbeOwnerIdPattern = /^[a-f0-9]{32}$/;
59
81
  const hostTmpfsProbeNamePattern = /^shipzone-ci-probe-([a-f0-9]{32})-[a-f0-9]{16}$/;
60
82
  const runtimeProbeVolumeNamePattern = /^shipzone-ci-volume-[a-f0-9]{32}$/;
61
83
  const workspaceHelperDirectoryName = 'workspace-helpers';
62
- const workspaceHelperLockName = '.workspace-helper.lock';
84
+ /** The advisory lock file of runner 2.x, replaced by the state owner lock and removed on sight. */
85
+ const legacyWorkspaceHelperLockName = '.workspace-helper.lock';
63
86
  const runtimeProbeOwnerMarkerPrefix = '.runtime-probe-owner_';
64
87
  const runtimeProbeOwnerMarkerPattern = /^\.runtime-probe-owner_([a-f0-9]{32})$/;
65
88
  const workspaceHelperExecutableMode = 0o755;
66
- const workspaceHelperMaximumBytes = 64 * 1024 * 1024;
67
89
  const workspaceHelperRetainedFinalCount = 8;
68
90
  const workspaceHelperTemporaryMaximumBytes = 8 * workspaceHelperMaximumBytes;
69
91
  const workspaceHelperTemporaryMaximumCount = 8;
70
92
  const workspaceHelperTemporaryMaximumAgeMs = 60 * 60 * 1000;
71
- const workspaceHelperLockTimeoutMs = 30 * 1000;
72
- const workspaceHelperLockRetryMs = 25;
73
93
  const workspaceHelperFinalNamePattern = /^runnerworkspace_linux_(?:amd64|arm64)_musl_[a-f0-9]{64}$/;
74
94
  const workspaceHelperTemporaryNamePattern =
75
95
  /^\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.workspace-helper\.tmp$/;
@@ -223,7 +243,7 @@ const field = (record: Record<string, unknown>, ...names: string[]): unknown =>
223
243
  const readRuntimeEnvironment = (): Record<string, string> => {
224
244
  const environment: Record<string, string> = {};
225
245
  for (const name of runtimeEnvironmentNames) {
226
- const value = Deno.env.get(name);
246
+ const value = process.env[name];
227
247
  if (value !== undefined) environment[name] = value;
228
248
  }
229
249
  return environment;
@@ -240,39 +260,25 @@ const concatChunks = (chunks: Uint8Array[], total: number): Uint8Array => {
240
260
  };
241
261
 
242
262
  const consumeCommandStream = async (
243
- stream: ReadableStream<Uint8Array>,
263
+ stream: plugins.stream.Readable,
244
264
  streamName: 'stdout' | 'stderr',
245
265
  maximumBytes: number,
246
266
  onOutput?: IOciRuntimeCommandRequest['onOutput'],
247
267
  ): Promise<Uint8Array> => {
248
- const reader = stream.getReader();
249
268
  const chunks: Uint8Array[] = [];
250
269
  let total = 0;
251
- try {
252
- while (true) {
253
- const { done, value } = await reader.read();
254
- if (done) break;
255
- if (onOutput) {
256
- await onOutput(streamName, value);
257
- continue;
258
- }
259
- total += value.byteLength;
260
- if (total > maximumBytes) {
261
- const error = new RunnerError('OCI runtime output exceeded the configured limit');
262
- try {
263
- await reader.cancel(error);
264
- } catch (cleanupError) {
265
- throw new ResourceCleanupError('OCI runtime output stream cleanup failed', [
266
- error,
267
- cleanupError,
268
- ]);
269
- }
270
- throw error;
271
- }
272
- chunks.push(value);
270
+ for await (const value of stream as AsyncIterable<Buffer>) {
271
+ const chunk = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
272
+ if (onOutput) {
273
+ await onOutput(streamName, chunk);
274
+ continue;
273
275
  }
274
- } finally {
275
- reader.releaseLock();
276
+ total += chunk.byteLength;
277
+ if (total > maximumBytes) {
278
+ // Leaving the loop destroys the stream, which closes the pipe.
279
+ throw new RunnerError('OCI runtime output exceeded the configured limit');
280
+ }
281
+ chunks.push(chunk);
276
282
  }
277
283
  return onOutput ? new Uint8Array() : concatChunks(chunks, total);
278
284
  };
@@ -293,40 +299,51 @@ const withTimeout = async <T>(
293
299
  }
294
300
  };
295
301
 
296
- const terminateChild = async (child: Deno.ChildProcess): Promise<void> => {
297
- const status = child.status;
298
- try {
299
- child.kill('SIGTERM');
300
- } catch {
301
- // The child may already have exited.
302
- }
302
+ interface IChildExit {
303
+ code: number;
304
+ success: boolean;
305
+ }
306
+
307
+ /** Resolves when the child has exited, or when it could not be started at all. */
308
+ const childExit = (child: plugins.childProcess.ChildProcess): Promise<IChildExit> =>
309
+ new Promise((resolvePromise, rejectPromise) => {
310
+ child.once('exit', (code, signal) => {
311
+ const signalNumber = signal ? plugins.os.constants.signals[signal] : undefined;
312
+ const exitCode = code ?? (signalNumber === undefined ? 1 : 128 + signalNumber);
313
+ resolvePromise({ code: exitCode, success: code === 0 });
314
+ });
315
+ child.once('error', (error) => {
316
+ if (child.pid === undefined) rejectPromise(error);
317
+ });
318
+ });
319
+
320
+ const terminateChild = async (
321
+ child: plugins.childProcess.ChildProcess,
322
+ exited: Promise<unknown>,
323
+ ): Promise<void> => {
324
+ const status = exited.then(() => undefined, () => undefined);
325
+ child.kill('SIGTERM');
303
326
  try {
304
327
  await withTimeout(status, runtimeTerminationGraceMs, 'OCI runtime process ignored SIGTERM');
305
328
  return;
306
329
  } catch {
307
330
  // Escalate below.
308
331
  }
309
- try {
310
- child.kill('SIGKILL');
311
- } catch {
312
- // The child may have exited between waits.
313
- }
332
+ child.kill('SIGKILL');
314
333
  await withTimeout(status, runtimeTerminationGraceMs, 'OCI runtime process ignored SIGKILL');
315
334
  };
316
335
 
317
336
  const defaultCommandRunner: TOciRuntimeCommandRunner = async (request) => {
318
- const child = new Deno.Command(request.executable, {
319
- args: request.args,
320
- clearEnv: true,
337
+ // An explicit `env` replaces the runner's environment: the command sees only the given names.
338
+ const child = plugins.childProcess.spawn(request.executable, request.args, {
321
339
  env: request.environment,
322
- stdin: 'null',
323
- stdout: 'piped',
324
- stderr: 'piped',
325
- }).spawn();
340
+ stdio: ['ignore', 'pipe', 'pipe'],
341
+ });
342
+ const exited = childExit(child);
326
343
  const maximumBytes = request.maximumOutputBytes ?? maximumRuntimeOutputBytes;
327
- const stdout = consumeCommandStream(child.stdout, 'stdout', maximumBytes, request.onOutput);
328
- const stderr = consumeCommandStream(child.stderr, 'stderr', maximumBytes, request.onOutput);
329
- const output = Promise.all([child.status, stdout, stderr]);
344
+ const stdout = consumeCommandStream(child.stdout!, 'stdout', maximumBytes, request.onOutput);
345
+ const stderr = consumeCommandStream(child.stderr!, 'stderr', maximumBytes, request.onOutput);
346
+ const output = Promise.all([exited, stdout, stderr]);
330
347
  let abortListener: (() => void) | undefined;
331
348
  const aborted = new Promise<never>((_resolve, reject) => {
332
349
  abortListener = () => reject(request.signal?.reason ?? new RunnerError('Command aborted'));
@@ -348,13 +365,13 @@ const defaultCommandRunner: TOciRuntimeCommandRunner = async (request) => {
348
365
  } catch (error) {
349
366
  const cleanupErrors: unknown[] = [];
350
367
  try {
351
- await terminateChild(child);
368
+ await terminateChild(child, exited);
352
369
  } catch (cleanupError) {
353
370
  cleanupErrors.push(cleanupError);
354
371
  }
355
372
  try {
356
373
  await withTimeout(
357
- Promise.allSettled([child.status, stdout, stderr]),
374
+ Promise.allSettled([exited, stdout, stderr]),
358
375
  runtimeTerminationGraceMs,
359
376
  'OCI runtime resources did not close after termination',
360
377
  );
@@ -379,6 +396,29 @@ const requireSuccess = (result: IOciRuntimeCommandResult, message: string): void
379
396
 
380
397
  const decode = (value: Uint8Array): string => new TextDecoder().decode(value).trim();
381
398
 
399
+ async function* readRuntimeDirectory(path: string): AsyncIterable<IRuntimeDirectoryEntry> {
400
+ for (const entry of await plugins.fs.readdir(path, { withFileTypes: true })) {
401
+ yield {
402
+ name: entry.name,
403
+ isFile: entry.isFile(),
404
+ isDirectory: entry.isDirectory(),
405
+ isSymlink: entry.isSymbolicLink(),
406
+ };
407
+ }
408
+ }
409
+
410
+ const lstatRuntimeFile = async (path: string): Promise<IRuntimeFileInfo> => {
411
+ const stat = await plugins.fs.lstat(path);
412
+ return {
413
+ isDirectory: stat.isDirectory(),
414
+ isSymlink: stat.isSymbolicLink(),
415
+ uid: stat.uid,
416
+ mtime: stat.mtime,
417
+ dev: stat.dev,
418
+ ino: stat.ino,
419
+ };
420
+ };
421
+
382
422
  export const scavengeHostTmpfsProbes = async (
383
423
  directory = '/dev/shm',
384
424
  dependencies: IHostTmpfsProbeScavengerDependencies = {},
@@ -389,20 +429,16 @@ export const scavengeHostTmpfsProbes = async (
389
429
  }
390
430
  let uid: number | null | undefined;
391
431
  try {
392
- uid = dependencies.getUid
393
- ? dependencies.getUid()
394
- : typeof Deno.uid === 'function'
395
- ? Deno.uid()
396
- : undefined;
432
+ uid = dependencies.getUid ? dependencies.getUid() : process.getuid?.();
397
433
  } catch {
398
434
  return;
399
435
  }
400
436
  if (uid === undefined || uid === null || !Number.isSafeInteger(uid) || uid < 0) return;
401
437
 
402
438
  const now = dependencies.now ?? Date.now;
403
- const readDir = dependencies.readDir ?? ((path: string) => Deno.readDir(path));
404
- const lstat = dependencies.lstat ?? ((path: string) => Deno.lstat(path));
405
- const remove = dependencies.remove ?? ((path, options) => Deno.remove(path, options));
439
+ const readDir = dependencies.readDir ?? readRuntimeDirectory;
440
+ const lstat = dependencies.lstat ?? lstatRuntimeFile;
441
+ const remove = dependencies.remove ?? ((path, options) => removePath(path, options));
406
442
  const isEligible = (stat: IRuntimeFileInfo): boolean =>
407
443
  stat.isDirectory && !stat.isSymlink && stat.uid === uid && stat.mtime !== null &&
408
444
  now() - stat.mtime.getTime() > hostTmpfsProbeMaximumAgeMs;
@@ -414,7 +450,7 @@ export const scavengeHostTmpfsProbes = async (
414
450
  try {
415
451
  initial = await lstat(path);
416
452
  } catch (error) {
417
- if (error instanceof Deno.errors.NotFound) continue;
453
+ if (isNotFound(error)) continue;
418
454
  throw error;
419
455
  }
420
456
  if (!isEligible(initial) || initial.dev === null || initial.ino === null) continue;
@@ -422,7 +458,7 @@ export const scavengeHostTmpfsProbes = async (
422
458
  try {
423
459
  current = await lstat(path);
424
460
  } catch (error) {
425
- if (error instanceof Deno.errors.NotFound) continue;
461
+ if (isNotFound(error)) continue;
426
462
  throw error;
427
463
  }
428
464
  if (
@@ -431,7 +467,7 @@ export const scavengeHostTmpfsProbes = async (
431
467
  try {
432
468
  await remove(path, { recursive: true });
433
469
  } catch (error) {
434
- if (!(error instanceof Deno.errors.NotFound)) {
470
+ if (!isNotFound(error)) {
435
471
  throw new ResourceCleanupError(`Unable to remove stale host tmpfs probe ${path}`, [error]);
436
472
  }
437
473
  }
@@ -924,118 +960,11 @@ const mapArchitecture = (
924
960
  }
925
961
  };
926
962
 
927
- const sha256Bytes = async (bytes: Uint8Array<ArrayBuffer>): Promise<string> => {
928
- const digest = await crypto.subtle.digest('SHA-256', bytes);
929
- return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
930
- };
931
-
932
- const sameFileIdentity = (first: Deno.FileInfo, second: Deno.FileInfo): boolean =>
933
- (first.dev === null || second.dev === first.dev) &&
934
- (first.ino === null || second.ino === first.ino);
935
-
936
- const withFsFile = async <T>(
937
- file: Deno.FsFile,
938
- operation: (file: Deno.FsFile) => Promise<T>,
939
- closeFailureMessage: string,
940
- ): Promise<T> => {
941
- let result: T | undefined;
942
- let operationError: unknown;
943
- let hasOperationError = false;
944
- try {
945
- result = await operation(file);
946
- } catch (error) {
947
- operationError = error;
948
- hasOperationError = true;
949
- }
950
- let closeError: unknown;
951
- let hasCloseError = false;
952
- try {
953
- file.close();
954
- } catch (error) {
955
- closeError = error;
956
- hasCloseError = true;
957
- }
958
- if (hasCloseError) {
959
- throw new ResourceCleanupError(closeFailureMessage, [
960
- ...(hasOperationError ? [operationError] : []),
961
- closeError,
962
- ]);
963
- }
964
- if (hasOperationError) throw operationError;
965
- return result as T;
966
- };
967
-
968
- const readBoundedRegularFile = async (
969
- path: string,
970
- maximumBytes: number,
971
- label: string,
972
- ): Promise<{ bytes: Uint8Array<ArrayBuffer>; stat: Deno.FileInfo }> => {
973
- const pathStat = await Deno.lstat(path);
974
- if (
975
- !pathStat.isFile || pathStat.isSymlink || pathStat.size < 1 || pathStat.size > maximumBytes
976
- ) {
977
- throw new RunnerError(`${label} must be a bounded regular file`);
978
- }
979
- const file = await Deno.open(path, { read: true });
980
- return await withFsFile(
981
- file,
982
- async (openedFile) => {
983
- const before = await openedFile.stat();
984
- if (
985
- !before.isFile || before.size < 1 || before.size > maximumBytes ||
986
- before.size !== pathStat.size || !sameFileIdentity(pathStat, before)
987
- ) {
988
- throw new RunnerError(`${label} changed while it was opened`);
989
- }
990
- const bytes = new Uint8Array(before.size);
991
- let offset = 0;
992
- while (offset < bytes.byteLength) {
993
- const read = await openedFile.read(bytes.subarray(offset));
994
- if (read === null || read <= 0) {
995
- throw new RunnerError(`${label} changed while it was read`);
996
- }
997
- offset += read;
998
- }
999
- const overflow = await openedFile.read(new Uint8Array(1));
1000
- const after = await openedFile.stat();
1001
- const currentPathStat = await Deno.lstat(path);
1002
- if (
1003
- overflow !== null || !after.isFile || after.size !== before.size ||
1004
- !currentPathStat.isFile || currentPathStat.isSymlink ||
1005
- currentPathStat.size !== before.size || !sameFileIdentity(before, after) ||
1006
- !sameFileIdentity(after, currentPathStat)
1007
- ) {
1008
- throw new RunnerError(`${label} changed while it was read`);
1009
- }
1010
- return { bytes, stat: after };
1011
- },
1012
- `${label} read and close failed`,
1013
- );
1014
- };
1015
-
1016
963
  const sha256File = async (path: string): Promise<string> =>
1017
- await sha256Bytes(
964
+ sha256Hex(
1018
965
  (await readBoundedRegularFile(path, workspaceHelperMaximumBytes, 'Workspace helper')).bytes,
1019
966
  );
1020
967
 
1021
- const writeAll = async (file: Deno.FsFile, bytes: Uint8Array): Promise<void> => {
1022
- let offset = 0;
1023
- while (offset < bytes.byteLength) {
1024
- const written = await file.write(bytes.subarray(offset));
1025
- if (written <= 0) throw new RunnerError('Workspace helper write made no progress');
1026
- offset += written;
1027
- }
1028
- };
1029
-
1030
- const lstatIfPresent = async (path: string): Promise<Deno.FileInfo | undefined> => {
1031
- try {
1032
- return await Deno.lstat(path);
1033
- } catch (error) {
1034
- if (error instanceof Deno.errors.NotFound) return undefined;
1035
- throw error;
1036
- }
1037
- };
1038
-
1039
968
  const safeSelections = (selections: string[]): string[] => {
1040
969
  if (selections.length === 0 || selections.length > 32) {
1041
970
  throw new ProtocolError('Workspace export must select between 1 and 32 paths');
@@ -1118,24 +1047,33 @@ export class OciExecutor implements IJobExecutor {
1118
1047
  private runtimeFacts?: IOciRuntimeFacts;
1119
1048
  private readonly preparedLeases = new Map<string, PreparedOciLease>();
1120
1049
 
1050
+ /**
1051
+ * @param stateOwner Ownership of `config.stateDirectory`, where the executor keeps its workspace
1052
+ * helpers, runtime probe owner marker and workspace exports.
1053
+ */
1121
1054
  constructor(
1122
1055
  private readonly config: IRunnerConfig,
1056
+ private readonly stateOwner: RunnerStateOwner,
1123
1057
  dependencies: IOciExecutorDependencies = {},
1124
1058
  ) {
1059
+ if (plugins.path.resolve(config.stateDirectory) !== stateOwner.stateDirectory) {
1060
+ throw new ConfigurationError('OCI executor state owner does not own the configured state');
1061
+ }
1125
1062
  this.commandRunner = dependencies.commandRunner ?? defaultCommandRunner;
1126
1063
  this.runtimeEnvironment = dependencies.runtimeEnvironment
1127
1064
  ? { ...dependencies.runtimeEnvironment }
1128
1065
  : readRuntimeEnvironment();
1129
- this.randomId = dependencies.randomId ?? (() => crypto.randomUUID().replaceAll('-', ''));
1066
+ this.randomId = dependencies.randomId ??
1067
+ (() => plugins.crypto.randomUUID().replaceAll('-', ''));
1130
1068
  this.now = dependencies.now ?? Date.now;
1131
1069
  this.resolveHelperPathImplementation = dependencies.resolveHelperPath ??
1132
1070
  ((target) => this.resolvePackagedHelper(target));
1133
1071
  this.probeTmpfsImplementation = dependencies.probeTmpfs
1134
1072
  ? (path) => dependencies.probeTmpfs!(path)
1135
1073
  : (path, runtimeProbeOwnerId) => this.probeHostTmpfs(path, runtimeProbeOwnerId);
1136
- this.makeTempDir = dependencies.makeTempDir ?? ((options) => Deno.makeTempDir(options));
1137
- this.chmod = dependencies.chmod ?? ((path, mode) => Deno.chmod(path, mode));
1138
- this.remove = dependencies.remove ?? ((path, options) => Deno.remove(path, options));
1074
+ this.makeTempDir = dependencies.makeTempDir ?? ((options) => makeTempDir(options));
1075
+ this.chmod = dependencies.chmod ?? ((path, mode) => plugins.fs.chmod(path, mode));
1076
+ this.remove = dependencies.remove ?? ((path, options) => removePath(path, options));
1139
1077
  parseContainerUser(config.oci.containerUser);
1140
1078
  }
1141
1079
 
@@ -1259,10 +1197,10 @@ export class OciExecutor implements IJobExecutor {
1259
1197
  architecture.helperTarget,
1260
1198
  );
1261
1199
  const runtimeProbeOwnerId = await this.ensureRuntimeProbeOwner();
1262
- const helperStat = await Deno.stat(helperPath).catch((error) => {
1200
+ const helperStat = await plugins.fs.stat(helperPath).catch((error) => {
1263
1201
  throw new RunnerError('Workspace helper is unavailable', { cause: error });
1264
1202
  });
1265
- if (!helperStat.isFile || (helperStat.mode !== null && (helperStat.mode & 0o111) === 0)) {
1203
+ if (!helperStat.isFile() || (helperStat.mode & 0o111) === 0) {
1266
1204
  throw new RunnerError('Workspace helper is not an executable regular file');
1267
1205
  }
1268
1206
  const hostProbe = await this.runHostHelper(helperPath, ['probe']);
@@ -1532,8 +1470,9 @@ export class OciExecutor implements IJobExecutor {
1532
1470
  throw new ProtocolError('Workspace export limits exceed the accepted workspace limits');
1533
1471
  }
1534
1472
  if (request.signal?.aborted) throw request.signal.reason;
1535
- const root = join(this.config.stateDirectory, 'workspace-exports');
1536
- await Deno.mkdir(root, { recursive: true, mode: 0o700 });
1473
+ this.stateOwner.assertHeld();
1474
+ const root = join(this.stateOwner.stateDirectory, 'workspace-exports');
1475
+ await plugins.fs.mkdir(root, { recursive: true, mode: 0o700 });
1537
1476
  const path = await this.makeTempDir({ dir: root, prefix: `${context.lease.attemptId}-` });
1538
1477
  exportPaths.add(path);
1539
1478
  let exportCleaned = false;
@@ -1850,11 +1789,8 @@ export class OciExecutor implements IJobExecutor {
1850
1789
  }
1851
1790
 
1852
1791
  private async resolvePackagedHelper(target: TOciHelperTarget): Promise<string> {
1853
- if (this.config.oci.workspaceHelperPath) {
1854
- return await Deno.realPath(this.config.oci.workspaceHelperPath);
1855
- }
1856
- return await Deno.realPath(
1857
- new URL(`../dist_rust/runnerworkspace_${target}_musl`, import.meta.url),
1792
+ return await plugins.fs.realpath(
1793
+ this.config.oci.workspaceHelperPath ?? await resolvePackagedWorkspaceHelperPath(target),
1858
1794
  );
1859
1795
  }
1860
1796
 
@@ -1862,7 +1798,7 @@ export class OciExecutor implements IJobExecutor {
1862
1798
  sourcePathArg: string,
1863
1799
  targetArg: TOciHelperTarget,
1864
1800
  ): Promise<string> {
1865
- const sourcePath = await Deno.realPath(sourcePathArg).catch((error) => {
1801
+ const sourcePath = await plugins.fs.realpath(sourcePathArg).catch((error) => {
1866
1802
  throw new RunnerError('Workspace helper source is unavailable', { cause: error });
1867
1803
  });
1868
1804
  const sourceBytes = (
@@ -1872,11 +1808,11 @@ export class OciExecutor implements IJobExecutor {
1872
1808
  'Workspace helper source',
1873
1809
  )
1874
1810
  ).bytes;
1875
- const sourceDigest = await sha256Bytes(sourceBytes);
1876
- const helperDirectory = await this.ensureWorkspaceHelperDirectory();
1811
+ const sourceDigest = sha256Hex(sourceBytes);
1877
1812
  const destinationName = `runnerworkspace_${targetArg}_musl_${sourceDigest}`;
1878
- const destinationPath = join(helperDirectory, destinationName);
1879
- return await this.withWorkspaceHelperLock(helperDirectory, async () => {
1813
+ return await this.stateOwner.serialize(async () => {
1814
+ const helperDirectory = await this.ensureWorkspaceHelperDirectory();
1815
+ const destinationPath = join(helperDirectory, destinationName);
1880
1816
  const temporaryUsage = await this.scavengeWorkspaceHelpers(
1881
1817
  helperDirectory,
1882
1818
  destinationName,
@@ -1884,7 +1820,7 @@ export class OciExecutor implements IJobExecutor {
1884
1820
  );
1885
1821
  if (await lstatIfPresent(destinationPath)) {
1886
1822
  await this.validateMaterializedWorkspaceHelper(destinationPath, sourceDigest);
1887
- return await Deno.realPath(destinationPath);
1823
+ return await plugins.fs.realpath(destinationPath);
1888
1824
  }
1889
1825
  if (
1890
1826
  temporaryUsage.count >= workspaceHelperTemporaryMaximumCount ||
@@ -1895,38 +1831,35 @@ export class OciExecutor implements IJobExecutor {
1895
1831
 
1896
1832
  const temporaryPath = join(
1897
1833
  helperDirectory,
1898
- `.${crypto.randomUUID()}.workspace-helper.tmp`,
1834
+ `.${plugins.crypto.randomUUID()}.workspace-helper.tmp`,
1899
1835
  );
1900
1836
  try {
1901
- const temporaryFile = await Deno.open(temporaryPath, {
1902
- write: true,
1903
- createNew: true,
1904
- mode: 0o600,
1905
- });
1906
- await withFsFile(
1907
- temporaryFile,
1837
+ await withOpenFile(
1838
+ temporaryPath,
1839
+ createNewWriteFlags,
1840
+ 0o600,
1908
1841
  async (openedFile) => {
1909
- await writeAll(openedFile, sourceBytes);
1842
+ await writeAll(openedFile, sourceBytes, 'Workspace helper write made no progress');
1910
1843
  await openedFile.sync();
1911
1844
  },
1912
1845
  'Workspace helper write and close failed',
1913
1846
  );
1914
1847
  await this.validateMaterializedWorkspaceHelper(temporaryPath, sourceDigest, true);
1915
1848
  try {
1916
- await Deno.link(temporaryPath, destinationPath);
1849
+ await plugins.fs.link(temporaryPath, destinationPath);
1917
1850
  } catch (error) {
1918
- if (!(error instanceof Deno.errors.AlreadyExists)) throw error;
1851
+ if (!isAlreadyExists(error)) throw error;
1919
1852
  await this.validateMaterializedWorkspaceHelper(destinationPath, sourceDigest);
1920
1853
  }
1921
- await Deno.remove(temporaryPath);
1854
+ await removePath(temporaryPath);
1922
1855
  await this.validateMaterializedWorkspaceHelper(destinationPath, sourceDigest);
1923
1856
  await this.syncDirectory(helperDirectory);
1924
- return await Deno.realPath(destinationPath);
1857
+ return await plugins.fs.realpath(destinationPath);
1925
1858
  } catch (error) {
1926
1859
  try {
1927
- await Deno.remove(temporaryPath);
1860
+ await removePath(temporaryPath);
1928
1861
  } catch (cleanupError) {
1929
- if (!(cleanupError instanceof Deno.errors.NotFound)) {
1862
+ if (!isNotFound(cleanupError)) {
1930
1863
  throw new ResourceCleanupError('Workspace helper setup and cleanup failed', [
1931
1864
  error,
1932
1865
  cleanupError,
@@ -1939,48 +1872,40 @@ export class OciExecutor implements IJobExecutor {
1939
1872
  }
1940
1873
 
1941
1874
  private async ensureWorkspaceHelperDirectory(): Promise<string> {
1942
- const stateRoot = resolve(this.config.stateDirectory);
1943
- await Deno.mkdir(stateRoot, { recursive: true, mode: 0o700 });
1944
- const stateStat = await Deno.lstat(stateRoot);
1945
- if (!stateStat.isDirectory || stateStat.isSymlink) {
1946
- throw new RunnerError('Runner state directory must be a real directory');
1947
- }
1948
- if (Deno.build.os !== 'windows' && stateStat.mode !== null && (stateStat.mode & 0o077) !== 0) {
1949
- throw new RunnerError('Runner state directory permissions are not private');
1950
- }
1875
+ this.stateOwner.assertHeld();
1876
+ const stateRoot = await ensurePrivateStateDirectory(this.stateOwner.stateDirectory);
1951
1877
 
1952
1878
  const helperDirectory = join(stateRoot, workspaceHelperDirectoryName);
1953
1879
  try {
1954
- await Deno.mkdir(helperDirectory, { mode: 0o700 });
1880
+ await plugins.fs.mkdir(helperDirectory, { mode: 0o700 });
1955
1881
  } catch (error) {
1956
- if (!(error instanceof Deno.errors.AlreadyExists)) throw error;
1882
+ if (!isAlreadyExists(error)) throw error;
1957
1883
  }
1958
- const helperStat = await Deno.lstat(helperDirectory);
1959
- if (!helperStat.isDirectory || helperStat.isSymlink) {
1884
+ const helperStat = await plugins.fs.lstat(helperDirectory);
1885
+ if (!helperStat.isDirectory() || helperStat.isSymbolicLink()) {
1960
1886
  throw new RunnerError('Workspace helper directory must be a real directory');
1961
1887
  }
1962
- await Deno.chmod(helperDirectory, 0o700);
1963
- const privateStat = await Deno.lstat(helperDirectory);
1888
+ await plugins.fs.chmod(helperDirectory, 0o700);
1889
+ const privateStat = await plugins.fs.lstat(helperDirectory);
1964
1890
  if (
1965
- !privateStat.isDirectory || privateStat.isSymlink ||
1966
- (Deno.build.os !== 'windows' && privateStat.mode !== null &&
1967
- (privateStat.mode & 0o777) !== 0o700)
1891
+ !privateStat.isDirectory() || privateStat.isSymbolicLink() ||
1892
+ (privateStat.mode & 0o777) !== 0o700
1968
1893
  ) {
1969
1894
  throw new RunnerError('Workspace helper directory permissions are not private');
1970
1895
  }
1971
1896
  await this.syncDirectory(stateRoot);
1972
- return await Deno.realPath(helperDirectory);
1897
+ return await plugins.fs.realpath(helperDirectory);
1973
1898
  }
1974
1899
 
1975
- private async ensureRuntimeProbeOwner(): Promise<string> {
1976
- const helperDirectory = await this.ensureWorkspaceHelperDirectory();
1977
- return await this.withWorkspaceHelperLock(helperDirectory, async () => {
1900
+ private ensureRuntimeProbeOwner(): Promise<string> {
1901
+ return this.stateOwner.runtimeProbeOwnerId(async () => {
1902
+ const helperDirectory = await this.ensureWorkspaceHelperDirectory();
1978
1903
  const markers: Array<{ name: string; ownerId: string }> = [];
1979
- for await (const entry of Deno.readDir(helperDirectory)) {
1980
- if (!entry.name.startsWith(runtimeProbeOwnerMarkerPrefix)) continue;
1981
- const match = runtimeProbeOwnerMarkerPattern.exec(entry.name);
1904
+ for (const name of await plugins.fs.readdir(helperDirectory)) {
1905
+ if (!name.startsWith(runtimeProbeOwnerMarkerPrefix)) continue;
1906
+ const match = runtimeProbeOwnerMarkerPattern.exec(name);
1982
1907
  if (!match) throw new RunnerError('Runtime probe owner marker name is invalid');
1983
- markers.push({ name: entry.name, ownerId: match[1] });
1908
+ markers.push({ name, ownerId: match[1] });
1984
1909
  }
1985
1910
  if (markers.length > 1) {
1986
1911
  throw new RunnerError('Runner state contains multiple runtime probe owner markers');
@@ -1996,14 +1921,10 @@ export class OciExecutor implements IJobExecutor {
1996
1921
  helperDirectory,
1997
1922
  `${runtimeProbeOwnerMarkerPrefix}${ownerId}`,
1998
1923
  );
1999
- const markerFile = await Deno.open(markerPath, {
2000
- read: true,
2001
- write: true,
2002
- createNew: true,
2003
- mode: 0o600,
2004
- });
2005
- await withFsFile(
2006
- markerFile,
1924
+ await withOpenFile(
1925
+ markerPath,
1926
+ 'wx+',
1927
+ 0o600,
2007
1928
  async (openedMarkerFile) => await openedMarkerFile.sync(),
2008
1929
  'Runtime probe owner marker sync and close failed',
2009
1930
  );
@@ -2014,29 +1935,25 @@ export class OciExecutor implements IJobExecutor {
2014
1935
  }
2015
1936
 
2016
1937
  private async validateRuntimeProbeOwnerMarker(pathArg: string): Promise<void> {
2017
- const before = await Deno.lstat(pathArg);
1938
+ const before = await plugins.fs.lstat(pathArg);
2018
1939
  if (
2019
- !before.isFile || before.isSymlink || before.size !== 0 ||
2020
- (Deno.build.os !== 'windows' && before.nlink !== null && before.nlink !== 1) ||
2021
- (Deno.build.os !== 'windows' && before.mode !== null &&
2022
- (before.mode & 0o7777) !== 0o600)
1940
+ !before.isFile() || before.isSymbolicLink() || before.size !== 0 || before.nlink !== 1 ||
1941
+ (before.mode & 0o7777) !== 0o600
2023
1942
  ) {
2024
1943
  throw new RunnerError('Runtime probe owner marker must be a private single-link file');
2025
1944
  }
2026
- const markerFile = await Deno.open(pathArg, { read: true });
2027
- await withFsFile(
2028
- markerFile,
1945
+ await withOpenFile(
1946
+ pathArg,
1947
+ 'r',
1948
+ undefined,
2029
1949
  async (openedMarkerFile) => {
2030
1950
  const descriptorStat = await openedMarkerFile.stat();
2031
- const current = await Deno.lstat(pathArg);
1951
+ const current = await plugins.fs.lstat(pathArg);
2032
1952
  if (
2033
- !descriptorStat.isFile || !current.isFile || current.isSymlink ||
1953
+ !descriptorStat.isFile() || !current.isFile() || current.isSymbolicLink() ||
2034
1954
  !sameFileIdentity(before, descriptorStat) || !sameFileIdentity(before, current) ||
2035
- (Deno.build.os !== 'windows' && descriptorStat.nlink !== null &&
2036
- descriptorStat.nlink !== 1) ||
2037
- (Deno.build.os !== 'windows' && current.nlink !== null && current.nlink !== 1) ||
2038
- (Deno.build.os !== 'windows' && current.mode !== null &&
2039
- (current.mode & 0o7777) !== 0o600)
1955
+ descriptorStat.nlink !== 1 || current.nlink !== 1 ||
1956
+ (current.mode & 0o7777) !== 0o600
2040
1957
  ) {
2041
1958
  throw new RunnerError('Runtime probe owner marker changed during validation');
2042
1959
  }
@@ -2045,96 +1962,36 @@ export class OciExecutor implements IJobExecutor {
2045
1962
  );
2046
1963
  }
2047
1964
 
2048
- private async withWorkspaceHelperLock<T>(
2049
- helperDirectoryArg: string,
2050
- operation: () => Promise<T>,
2051
- ): Promise<T> {
2052
- const lockPath = join(helperDirectoryArg, workspaceHelperLockName);
2053
- const lockFile = await Deno.open(lockPath, {
2054
- read: true,
2055
- write: true,
2056
- create: true,
2057
- mode: 0o600,
2058
- });
2059
- return await withFsFile(
2060
- lockFile,
2061
- async (openedLockFile) => {
2062
- const initialStat = await Deno.lstat(lockPath);
2063
- if (
2064
- !initialStat.isFile || initialStat.isSymlink ||
2065
- (Deno.build.os !== 'windows' && initialStat.nlink !== null && initialStat.nlink !== 1)
2066
- ) {
2067
- throw new RunnerError('Workspace helper lock must be a regular file');
2068
- }
2069
- await Deno.chmod(lockPath, 0o600);
2070
- const pathStat = await Deno.lstat(lockPath);
2071
- const descriptorStat = await openedLockFile.stat();
2072
- if (
2073
- !pathStat.isFile || pathStat.isSymlink || !descriptorStat.isFile ||
2074
- !sameFileIdentity(pathStat, descriptorStat) ||
2075
- (Deno.build.os !== 'windows' && pathStat.mode !== null &&
2076
- (pathStat.mode & 0o777) !== 0o600)
2077
- ) {
2078
- throw new RunnerError('Workspace helper lock changed while it was opened');
2079
- }
2080
-
2081
- const lockDeadline = performance.now() + workspaceHelperLockTimeoutMs;
2082
- while (!(await openedLockFile.tryLock(true))) {
2083
- if (performance.now() >= lockDeadline) {
2084
- throw new RunnerError('Timed out waiting for the workspace helper lock');
2085
- }
2086
- await new Promise((resolvePromise) =>
2087
- setTimeout(resolvePromise, workspaceHelperLockRetryMs)
2088
- );
2089
- }
2090
-
2091
- let result: T | undefined;
2092
- let operationError: unknown;
2093
- let hasOperationError = false;
2094
- try {
2095
- result = await operation();
2096
- } catch (error) {
2097
- operationError = error;
2098
- hasOperationError = true;
2099
- }
2100
- let unlockError: unknown;
2101
- try {
2102
- await openedLockFile.unlock();
2103
- } catch (error) {
2104
- unlockError = error;
2105
- }
2106
- if (unlockError !== undefined) {
2107
- throw new ResourceCleanupError(
2108
- hasOperationError
2109
- ? 'Workspace helper operation and lock release failed'
2110
- : 'Unable to release workspace helper lock',
2111
- [...(hasOperationError ? [operationError] : []), unlockError],
2112
- );
2113
- }
2114
- if (hasOperationError) throw operationError;
2115
- return result as T;
2116
- },
2117
- 'Workspace helper lock operation and close failed',
2118
- );
2119
- }
2120
-
2121
1965
  private async scavengeWorkspaceHelpers(
2122
1966
  helperDirectoryArg: string,
2123
1967
  currentDestinationNameArg: string,
2124
1968
  currentDigestArg: string,
2125
1969
  ): Promise<{ count: number; bytes: number }> {
2126
- const finalFiles: Array<{ name: string; path: string; stat: Deno.FileInfo }> = [];
1970
+ const finalFiles: Array<{ name: string; path: string; stat: plugins.Stats }> = [];
2127
1971
  let recentTemporaryCount = 0;
2128
1972
  let recentTemporaryBytes = 0;
2129
1973
  let removed = false;
2130
- for await (const entry of Deno.readDir(helperDirectoryArg)) {
2131
- const path = join(helperDirectoryArg, entry.name);
2132
- if (workspaceHelperTemporaryNamePattern.test(entry.name)) {
1974
+ for (const name of await plugins.fs.readdir(helperDirectoryArg)) {
1975
+ const path = join(helperDirectoryArg, name);
1976
+ if (name === legacyWorkspaceHelperLockName) {
1977
+ const stat = await lstatIfPresent(path);
1978
+ if (!stat) continue;
1979
+ if (!stat.isFile() || stat.isSymbolicLink()) {
1980
+ throw new RunnerError('Legacy workspace helper lock must be a regular file');
1981
+ }
1982
+ try {
1983
+ await removePath(path);
1984
+ removed = true;
1985
+ } catch (error) {
1986
+ if (!isNotFound(error)) throw error;
1987
+ }
1988
+ continue;
1989
+ }
1990
+ if (workspaceHelperTemporaryNamePattern.test(name)) {
2133
1991
  const stat = await lstatIfPresent(path);
2134
1992
  if (!stat) continue;
2135
1993
  if (
2136
- !stat.isFile || stat.isSymlink || stat.size > workspaceHelperMaximumBytes ||
2137
- stat.mtime === null
1994
+ !stat.isFile() || stat.isSymbolicLink() || stat.size > workspaceHelperMaximumBytes
2138
1995
  ) {
2139
1996
  throw new RunnerError('Workspace helper temporary path must be a bounded regular file');
2140
1997
  }
@@ -2156,10 +2013,10 @@ export class OciExecutor implements IJobExecutor {
2156
2013
  throw new RunnerError('Workspace helper temporary path changed during cleanup');
2157
2014
  }
2158
2015
  try {
2159
- await Deno.remove(path);
2016
+ await removePath(path);
2160
2017
  removed = true;
2161
2018
  } catch (error) {
2162
- if (!(error instanceof Deno.errors.NotFound)) throw error;
2019
+ if (!isNotFound(error)) throw error;
2163
2020
  }
2164
2021
  continue;
2165
2022
  }
@@ -2167,23 +2024,23 @@ export class OciExecutor implements IJobExecutor {
2167
2024
  recentTemporaryBytes += stat.size;
2168
2025
  continue;
2169
2026
  }
2170
- if (workspaceHelperFinalNamePattern.test(entry.name)) {
2027
+ if (workspaceHelperFinalNamePattern.test(name)) {
2171
2028
  const stat = await lstatIfPresent(path);
2172
2029
  if (!stat) continue;
2173
2030
  if (
2174
- !stat.isFile || stat.isSymlink || stat.size < 1 ||
2175
- stat.size > workspaceHelperMaximumBytes || stat.mtime === null
2031
+ !stat.isFile() || stat.isSymbolicLink() || stat.size < 1 ||
2032
+ stat.size > workspaceHelperMaximumBytes
2176
2033
  ) {
2177
2034
  throw new RunnerError('Retained workspace helper must be a bounded regular file');
2178
2035
  }
2179
- finalFiles.push({ name: entry.name, path, stat });
2036
+ finalFiles.push({ name, path, stat });
2180
2037
  }
2181
2038
  }
2182
2039
 
2183
2040
  finalFiles.sort((first, second) => {
2184
2041
  if (first.name === currentDestinationNameArg) return -1;
2185
2042
  if (second.name === currentDestinationNameArg) return 1;
2186
- return (second.stat.mtime?.getTime() ?? 0) - (first.stat.mtime?.getTime() ?? 0) ||
2043
+ return second.stat.mtime.getTime() - first.stat.mtime.getTime() ||
2187
2044
  first.name.localeCompare(second.name);
2188
2045
  });
2189
2046
  const retainedFinalCount = finalFiles.some((entry) => entry.name === currentDestinationNameArg)
@@ -2196,10 +2053,10 @@ export class OciExecutor implements IJobExecutor {
2196
2053
  throw new RunnerError('Retained workspace helper changed during cleanup');
2197
2054
  }
2198
2055
  try {
2199
- await Deno.remove(stale.path);
2056
+ await removePath(stale.path);
2200
2057
  removed = true;
2201
2058
  } catch (error) {
2202
- if (!(error instanceof Deno.errors.NotFound)) throw error;
2059
+ if (!isNotFound(error)) throw error;
2203
2060
  }
2204
2061
  }
2205
2062
  if (removed) await this.syncDirectory(helperDirectoryArg);
@@ -2208,12 +2065,11 @@ export class OciExecutor implements IJobExecutor {
2208
2065
 
2209
2066
  private async recoverInterruptedWorkspaceHelperPublication(
2210
2067
  temporaryPathArg: string,
2211
- temporaryStatArg: Deno.FileInfo,
2068
+ temporaryStatArg: plugins.Stats,
2212
2069
  destinationPathArg: string,
2213
2070
  expectedDigestArg: string,
2214
2071
  ): Promise<boolean> {
2215
2072
  if (
2216
- Deno.build.os === 'windows' || temporaryStatArg.nlink === null ||
2217
2073
  temporaryStatArg.nlink !== 2
2218
2074
  ) {
2219
2075
  return false;
@@ -2221,9 +2077,8 @@ export class OciExecutor implements IJobExecutor {
2221
2077
  const destinationStat = await lstatIfPresent(destinationPathArg);
2222
2078
  if (!destinationStat || !sameFileIdentity(temporaryStatArg, destinationStat)) return false;
2223
2079
  if (
2224
- !destinationStat.isFile || destinationStat.isSymlink || destinationStat.size < 1 ||
2080
+ !destinationStat.isFile() || destinationStat.isSymbolicLink() || destinationStat.size < 1 ||
2225
2081
  destinationStat.size > workspaceHelperMaximumBytes || destinationStat.nlink !== 2 ||
2226
- destinationStat.mode === null ||
2227
2082
  (destinationStat.mode & 0o7777) !== workspaceHelperExecutableMode
2228
2083
  ) {
2229
2084
  throw new RunnerError('Interrupted workspace helper publication is invalid');
@@ -2235,14 +2090,13 @@ export class OciExecutor implements IJobExecutor {
2235
2090
  );
2236
2091
  if (
2237
2092
  !sameFileIdentity(temporaryStatArg, validated.stat) || validated.stat.nlink !== 2 ||
2238
- validated.stat.mode === null ||
2239
2093
  (validated.stat.mode & 0o7777) !== workspaceHelperExecutableMode ||
2240
- await sha256Bytes(validated.bytes) !== expectedDigestArg
2094
+ sha256Hex(validated.bytes) !== expectedDigestArg
2241
2095
  ) {
2242
2096
  throw new RunnerError('Interrupted workspace helper publication changed during validation');
2243
2097
  }
2244
- const currentTemporary = await Deno.lstat(temporaryPathArg);
2245
- const currentDestination = await Deno.lstat(destinationPathArg);
2098
+ const currentTemporary = await plugins.fs.lstat(temporaryPathArg);
2099
+ const currentDestination = await plugins.fs.lstat(destinationPathArg);
2246
2100
  if (
2247
2101
  !sameFileIdentity(temporaryStatArg, currentTemporary) ||
2248
2102
  !sameFileIdentity(temporaryStatArg, currentDestination) ||
@@ -2250,11 +2104,11 @@ export class OciExecutor implements IJobExecutor {
2250
2104
  ) {
2251
2105
  throw new RunnerError('Interrupted workspace helper publication changed before recovery');
2252
2106
  }
2253
- await Deno.remove(temporaryPathArg);
2254
- const recoveredDestination = await Deno.lstat(destinationPathArg);
2107
+ await removePath(temporaryPathArg);
2108
+ const recoveredDestination = await plugins.fs.lstat(destinationPathArg);
2255
2109
  if (
2256
2110
  !sameFileIdentity(destinationStat, recoveredDestination) ||
2257
- recoveredDestination.nlink !== 1 || recoveredDestination.mode === null ||
2111
+ recoveredDestination.nlink !== 1 ||
2258
2112
  (recoveredDestination.mode & 0o7777) !== workspaceHelperExecutableMode
2259
2113
  ) {
2260
2114
  throw new RunnerError('Interrupted workspace helper publication did not recover safely');
@@ -2267,15 +2121,15 @@ export class OciExecutor implements IJobExecutor {
2267
2121
  expectedDigestArg: string,
2268
2122
  setExecutableModeArg = false,
2269
2123
  ): Promise<void> {
2270
- const before = await Deno.lstat(pathArg);
2124
+ const before = await plugins.fs.lstat(pathArg);
2271
2125
  if (
2272
- !before.isFile || before.isSymlink || before.size < 1 ||
2126
+ !before.isFile() || before.isSymbolicLink() || before.size < 1 ||
2273
2127
  before.size > workspaceHelperMaximumBytes ||
2274
- (Deno.build.os !== 'windows' && before.nlink !== null && before.nlink !== 1)
2128
+ before.nlink !== 1
2275
2129
  ) {
2276
2130
  throw new RunnerError('Materialized workspace helper must be a bounded regular file');
2277
2131
  }
2278
- if (setExecutableModeArg) await Deno.chmod(pathArg, workspaceHelperExecutableMode);
2132
+ if (setExecutableModeArg) await plugins.fs.chmod(pathArg, workspaceHelperExecutableMode);
2279
2133
  const validated = await readBoundedRegularFile(
2280
2134
  pathArg,
2281
2135
  workspaceHelperMaximumBytes,
@@ -2283,26 +2137,19 @@ export class OciExecutor implements IJobExecutor {
2283
2137
  );
2284
2138
  if (
2285
2139
  !sameFileIdentity(before, validated.stat) ||
2286
- (Deno.build.os !== 'windows' && validated.stat.nlink !== null &&
2287
- validated.stat.nlink !== 1) ||
2288
- (Deno.build.os !== 'windows' && validated.stat.mode !== null &&
2289
- (validated.stat.mode & 0o7777) !== workspaceHelperExecutableMode)
2140
+ (validated.stat.nlink !== 1) ||
2141
+ ((validated.stat.mode & 0o7777) !== workspaceHelperExecutableMode)
2290
2142
  ) {
2291
2143
  throw new RunnerError('Materialized workspace helper changed during validation');
2292
2144
  }
2293
- const digest = await sha256Bytes(validated.bytes);
2145
+ const digest = sha256Hex(validated.bytes);
2294
2146
  if (digest !== expectedDigestArg) {
2295
2147
  throw new RunnerError('Materialized workspace helper digest does not match its source');
2296
2148
  }
2297
2149
  }
2298
2150
 
2299
2151
  private async syncDirectory(pathArg: string): Promise<void> {
2300
- const directory = await Deno.open(pathArg, { read: true });
2301
- await withFsFile(
2302
- directory,
2303
- async (openedDirectory) => await openedDirectory.sync(),
2304
- 'Workspace helper directory sync and close failed',
2305
- );
2152
+ await syncDirectory(pathArg, 'Workspace helper directory sync and close failed');
2306
2153
  }
2307
2154
 
2308
2155
  private async probeHostTmpfs(
@@ -2314,25 +2161,30 @@ export class OciExecutor implements IJobExecutor {
2314
2161
  let operationError: unknown;
2315
2162
  try {
2316
2163
  await scavengeHostTmpfsProbes('/dev/shm', {}, runtimeProbeOwnerId);
2317
- path = await Deno.makeTempDir({
2164
+ path = await makeTempDir({
2318
2165
  dir: '/dev/shm',
2319
2166
  prefix: `shipzone-ci-probe-${runtimeProbeOwnerId}-`,
2320
2167
  });
2321
2168
  const before = await this.readFilesystemProbe(helperPath, path);
2322
2169
  const first = join(path, 'first');
2323
2170
  const second = join(path, 'second');
2324
- await Deno.writeFile(first, new Uint8Array([1]), { createNew: true, mode: 0o600 });
2171
+ await withOpenFile(
2172
+ first,
2173
+ createNewWriteFlags,
2174
+ 0o600,
2175
+ async (file) =>
2176
+ await writeAll(file, new Uint8Array([1]), 'Host tmpfs probe write made no progress'),
2177
+ 'Host tmpfs probe file close failed',
2178
+ );
2325
2179
  const afterFile = await this.readFilesystemProbe(helperPath, path);
2326
- await Deno.link(first, second);
2180
+ await plugins.fs.link(first, second);
2327
2181
  const afterLink = await this.readFilesystemProbe(helperPath, path);
2328
- const firstStat = await Deno.lstat(first);
2329
- const secondStat = await Deno.lstat(second);
2182
+ const firstStat = await plugins.fs.lstat(first);
2183
+ const secondStat = await plugins.fs.lstat(second);
2330
2184
  if (
2331
2185
  before.availableInodes - afterFile.availableInodes !== 1 ||
2332
2186
  afterFile.availableInodes - afterLink.availableInodes !== 1 ||
2333
- firstStat.ino === null ||
2334
2187
  firstStat.ino !== secondStat.ino ||
2335
- firstStat.nlink === null ||
2336
2188
  firstStat.nlink < 2
2337
2189
  ) {
2338
2190
  throw new RunnerError('Host tmpfs does not provide required hardlink inode accounting');
@@ -3111,7 +2963,7 @@ export class OciExecutor implements IJobExecutor {
3111
2963
  try {
3112
2964
  await this.remove(path, { recursive: true });
3113
2965
  } catch (error) {
3114
- if (!(error instanceof Deno.errors.NotFound)) {
2966
+ if (!isNotFound(error)) {
3115
2967
  throw new ResourceCleanupError(`Unable to remove owned path ${path}`, [error]);
3116
2968
  }
3117
2969
  }