@ship.zone/runner 2.1.0 → 4.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 (200) hide show
  1. package/.smartconfig.json +118 -3
  2. package/changelog.md +101 -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 +47 -0
  14. package/dist_ts/api-client.js +600 -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 +18 -0
  23. package/dist_ts/cli.d.ts +14 -0
  24. package/dist_ts/cli.js +243 -0
  25. package/dist_ts/config.d.ts +8 -0
  26. package/dist_ts/config.js +495 -0
  27. package/dist_ts/egress-proxy.d.ts +99 -0
  28. package/dist_ts/egress-proxy.js +607 -0
  29. package/dist_ts/errors.d.ts +41 -0
  30. package/dist_ts/errors.js +90 -0
  31. package/dist_ts/filesystem.d.ts +73 -0
  32. package/dist_ts/filesystem.js +207 -0
  33. package/dist_ts/index.d.ts +20 -0
  34. package/dist_ts/index.js +21 -0
  35. package/dist_ts/interfaces.d.ts +685 -0
  36. package/dist_ts/interfaces.js +3 -0
  37. package/dist_ts/log-sender.d.ts +26 -0
  38. package/dist_ts/log-sender.js +124 -0
  39. package/dist_ts/microvm-executor.d.ts +90 -0
  40. package/dist_ts/microvm-executor.js +1045 -0
  41. package/dist_ts/node-version.d.ts +11 -0
  42. package/dist_ts/node-version.js +43 -0
  43. package/dist_ts/npm-grants.d.ts +9 -0
  44. package/dist_ts/npm-grants.js +44 -0
  45. package/dist_ts/oci-registry.d.ts +73 -0
  46. package/dist_ts/oci-registry.js +508 -0
  47. package/dist_ts/plugins.d.ts +23 -0
  48. package/dist_ts/plugins.js +27 -0
  49. package/dist_ts/protocol-validator.d.ts +39 -0
  50. package/dist_ts/protocol-validator.js +488 -0
  51. package/dist_ts/redactor.d.ts +78 -0
  52. package/dist_ts/redactor.js +235 -0
  53. package/dist_ts/registration-state.d.ts +16 -0
  54. package/dist_ts/registration-state.js +171 -0
  55. package/dist_ts/runner.d.ts +65 -0
  56. package/dist_ts/runner.js +912 -0
  57. package/dist_ts/source-workspace.d.ts +10 -0
  58. package/dist_ts/source-workspace.js +125 -0
  59. package/dist_ts/spec-version.d.ts +11 -0
  60. package/dist_ts/spec-version.js +41 -0
  61. package/dist_ts/staging-scavenger.d.ts +7 -0
  62. package/dist_ts/staging-scavenger.js +63 -0
  63. package/dist_ts/state-owner.d.ts +74 -0
  64. package/dist_ts/state-owner.js +291 -0
  65. package/dist_ts/transfer-archive.d.ts +78 -0
  66. package/dist_ts/transfer-archive.js +1619 -0
  67. package/dist_ts/validation.d.ts +11 -0
  68. package/dist_ts/validation.js +79 -0
  69. package/dist_ts/vsock-protocol.d.ts +130 -0
  70. package/dist_ts/vsock-protocol.js +336 -0
  71. package/dist_ts/wire-schema.d.ts +10 -0
  72. package/dist_ts/wire-schema.js +114 -0
  73. package/native-notices/crates/bitflags-2.13.1/license-apache +201 -0
  74. package/native-notices/crates/bitflags-2.13.1/license-mit +25 -0
  75. package/native-notices/crates/cc-1.8.0/license-apache +201 -0
  76. package/native-notices/crates/cc-1.8.0/license-mit +25 -0
  77. package/native-notices/crates/cfg-if-1.0.4/license-apache +201 -0
  78. package/native-notices/crates/cfg-if-1.0.4/license-mit +25 -0
  79. package/native-notices/crates/cfg_aliases-0.2.2/license +9 -0
  80. package/native-notices/crates/cfg_aliases-0.2.2/notices.md +26 -0
  81. package/native-notices/crates/find-msvc-tools-0.1.14/license-apache +201 -0
  82. package/native-notices/crates/find-msvc-tools-0.1.14/license-mit +25 -0
  83. package/native-notices/crates/itoa-1.0.18/license-apache +176 -0
  84. package/native-notices/crates/itoa-1.0.18/license-mit +23 -0
  85. package/native-notices/crates/libc-0.2.189/license-apache +176 -0
  86. package/native-notices/crates/libc-0.2.189/license-mit +25 -0
  87. package/native-notices/crates/memchr-2.8.3/copying +3 -0
  88. package/native-notices/crates/memchr-2.8.3/license-mit +21 -0
  89. package/native-notices/crates/memchr-2.8.3/unlicense +24 -0
  90. package/native-notices/crates/nix-0.30.1/license +21 -0
  91. package/native-notices/crates/proc-macro2-1.0.107/license-apache +176 -0
  92. package/native-notices/crates/proc-macro2-1.0.107/license-mit +23 -0
  93. package/native-notices/crates/quote-1.0.47/license-apache +176 -0
  94. package/native-notices/crates/quote-1.0.47/license-mit +23 -0
  95. package/native-notices/crates/serde-1.0.229/license-apache +176 -0
  96. package/native-notices/crates/serde-1.0.229/license-mit +23 -0
  97. package/native-notices/crates/serde_core-1.0.229/license-apache +176 -0
  98. package/native-notices/crates/serde_core-1.0.229/license-mit +23 -0
  99. package/native-notices/crates/serde_derive-1.0.229/license-apache +176 -0
  100. package/native-notices/crates/serde_derive-1.0.229/license-mit +23 -0
  101. package/native-notices/crates/serde_json-1.0.151/license-apache +176 -0
  102. package/native-notices/crates/serde_json-1.0.151/license-mit +23 -0
  103. package/native-notices/crates/shlex-2.0.1/license-apache +13 -0
  104. package/native-notices/crates/shlex-2.0.1/license-mit +21 -0
  105. package/native-notices/crates/syn-3.0.3/license-apache +176 -0
  106. package/native-notices/crates/syn-3.0.3/license-mit +23 -0
  107. package/native-notices/crates/tikv-jemalloc-sys-0.7.1+5.3.1-0-g81034ce1f1373e37dc865038e1bc8eeecf559ce8/license-apache +201 -0
  108. package/native-notices/crates/tikv-jemalloc-sys-0.7.1+5.3.1-0-g81034ce1f1373e37dc865038e1bc8eeecf559ce8/license-mit +25 -0
  109. package/native-notices/crates/tikv-jemallocator-0.7.0/license-apache +201 -0
  110. package/native-notices/crates/tikv-jemallocator-0.7.0/license-mit +25 -0
  111. package/native-notices/crates/unicode-ident-1.0.24/license-apache +176 -0
  112. package/native-notices/crates/unicode-ident-1.0.24/license-mit +23 -0
  113. package/native-notices/crates/unicode-ident-1.0.24/license-unicode +39 -0
  114. package/native-notices/crates/zmij-1.0.23/license-mit +23 -0
  115. package/native-notices/manifest.json +763 -0
  116. package/native-notices/native/tikv-jemalloc-sys-0.7.1+5.3.1-0-g81034ce1f1373e37dc865038e1bc8eeecf559ce8/jemalloc-5.3.1/jemalloc-copying +27 -0
  117. package/native-notices/readme.md +46 -0
  118. package/native-notices/runtime/gcc/gpl-3.0.txt +674 -0
  119. package/native-notices/runtime/gcc/runtime-library-exception-3.1.txt +73 -0
  120. package/native-notices/runtime/libunwind-22.1.2/license.txt +311 -0
  121. package/native-notices/runtime/musl-1.2.5/copyright +193 -0
  122. package/native-notices/rust/compiler-builtins-license.txt +275 -0
  123. package/native-notices/rust/copyright-library.html +8266 -0
  124. package/native-notices/rust/crates/addr2line-0.25.1/license-apache +201 -0
  125. package/native-notices/rust/crates/addr2line-0.25.1/license-mit +25 -0
  126. package/native-notices/rust/crates/adler2-2.0.1/license-0bsd +12 -0
  127. package/native-notices/rust/crates/adler2-2.0.1/license-apache +201 -0
  128. package/native-notices/rust/crates/adler2-2.0.1/license-mit +23 -0
  129. package/native-notices/rust/crates/memchr-2.7.6/copying +3 -0
  130. package/native-notices/rust/crates/memchr-2.7.6/license-mit +21 -0
  131. package/native-notices/rust/crates/memchr-2.7.6/unlicense +24 -0
  132. package/native-notices/rust/crates/miniz_oxide-0.8.9/license +25 -0
  133. package/native-notices/rust/crates/miniz_oxide-0.8.9/license-apache.md +177 -0
  134. package/native-notices/rust/crates/miniz_oxide-0.8.9/license-mit.md +24 -0
  135. package/native-notices/rust/crates/miniz_oxide-0.8.9/license-zlib.md +14 -0
  136. package/native-notices/rust/crates/object-0.37.3/license-apache +201 -0
  137. package/native-notices/rust/crates/object-0.37.3/license-mit +25 -0
  138. package/native-notices/rust/licenses/apache-2.0.txt +73 -0
  139. package/native-notices/rust/licenses/bsd-2-clause.txt +9 -0
  140. package/native-notices/rust/licenses/cc-by-sa-4.0.txt +427 -0
  141. package/native-notices/rust/licenses/gcc-exception-3.1.txt +30 -0
  142. package/native-notices/rust/licenses/gpl-2.0-only.txt +133 -0
  143. package/native-notices/rust/licenses/gpl-3.0-or-later.txt +202 -0
  144. package/native-notices/rust/licenses/isc.txt +7 -0
  145. package/native-notices/rust/licenses/llvm-exception.txt +15 -0
  146. package/native-notices/rust/licenses/mit.txt +9 -0
  147. package/native-notices/rust/licenses/ncsa.txt +29 -0
  148. package/native-notices/rust/licenses/ofl-1.1.txt +43 -0
  149. package/native-notices/rust/licenses/unicode-3.0.txt +39 -0
  150. package/package.json +31 -26
  151. package/readme.md +157 -95
  152. package/rust/.cargo/config.toml +1 -1
  153. package/rust/Cargo.lock +1 -0
  154. package/rust/Cargo.toml +3 -2
  155. package/rust/src/cpio.rs +147 -0
  156. package/rust/src/extfs.rs +747 -0
  157. package/rust/src/guest.rs +2411 -0
  158. package/rust/src/lib.rs +197 -1
  159. package/rust/src/main.rs +7 -2
  160. package/rust/src/oci_tar.rs +842 -0
  161. package/rust-toolchain.toml +4 -0
  162. package/ts/00_commitinfo_data.ts +2 -2
  163. package/ts/api-client.ts +29 -8
  164. package/ts/artifact-manager.ts +9 -7
  165. package/ts/attempt-state.ts +75 -84
  166. package/ts/cache-manager.ts +22 -28
  167. package/ts/cli-entry.ts +17 -0
  168. package/ts/cli.ts +86 -53
  169. package/ts/config.ts +146 -62
  170. package/ts/egress-proxy.ts +649 -0
  171. package/ts/errors.ts +19 -0
  172. package/ts/filesystem.ts +316 -0
  173. package/ts/index.ts +20 -15
  174. package/ts/interfaces.ts +105 -23
  175. package/ts/log-sender.ts +4 -4
  176. package/ts/microvm-executor.ts +1265 -0
  177. package/ts/node-version.ts +49 -0
  178. package/ts/npm-grants.ts +49 -0
  179. package/ts/oci-registry.ts +649 -0
  180. package/ts/plugins.ts +25 -3
  181. package/ts/protocol-validator.ts +34 -30
  182. package/ts/redactor.ts +2 -2
  183. package/ts/registration-state.ts +82 -90
  184. package/ts/runner.ts +81 -34
  185. package/ts/source-workspace.ts +11 -8
  186. package/ts/spec-version.ts +2 -2
  187. package/ts/staging-scavenger.ts +37 -26
  188. package/ts/state-owner.ts +353 -0
  189. package/ts/transfer-archive.ts +214 -243
  190. package/ts/validation.ts +1 -1
  191. package/ts/vsock-protocol.ts +437 -0
  192. package/ts/wire-schema.ts +3 -3
  193. package/deno.json +0 -56
  194. package/deno.lock +0 -1495
  195. package/dist_npm/mod.d.ts +0 -967
  196. package/dist_npm/mod.js +0 -10058
  197. package/mod.ts +0 -8
  198. package/musl-copyright.md +0 -81
  199. package/third-party-licenses.md +0 -187
  200. package/ts/oci-executor.ts +0 -3137
@@ -1,5 +1,6 @@
1
- import { join } from '@std/path';
2
- import { ProtocolError, ResourceCleanupError } from './errors.ts';
1
+ import * as plugins from './plugins.js';
2
+ import { makeTempDir } from './filesystem.js';
3
+ import { ProtocolError, ResourceCleanupError } from './errors.js';
3
4
  import type {
4
5
  IJobIdentity,
5
6
  IJobSource,
@@ -7,12 +8,14 @@ import type {
7
8
  ISourcePrepareContext,
8
9
  ITransferDownload,
9
10
  ITransferManagerConfig,
10
- } from './interfaces.ts';
11
+ } from './interfaces.js';
11
12
  import {
12
13
  extractTarGzipArchive,
13
14
  removePathIfPresent,
14
15
  stageTransferDownload,
15
- } from './transfer-archive.ts';
16
+ } from './transfer-archive.js';
17
+
18
+ const { join } = plugins.path;
16
19
 
17
20
  export interface ISourceApiClient {
18
21
  downloadSource(
@@ -96,8 +99,8 @@ export class SourceWorkspaceManager {
96
99
 
97
100
  const archiveRoot = join(this.config.stateDirectory, 'source-archives');
98
101
  const workspaceRoot = join(this.config.stateDirectory, 'workspaces');
99
- await Deno.mkdir(archiveRoot, { recursive: true, mode: 0o700 });
100
- await Deno.mkdir(workspaceRoot, { recursive: true, mode: 0o700 });
102
+ await plugins.fs.mkdir(archiveRoot, { recursive: true, mode: 0o700 });
103
+ await plugins.fs.mkdir(workspaceRoot, { recursive: true, mode: 0o700 });
101
104
  const download = await this.api.downloadSource(context.identity, source, context.signal);
102
105
  const staged = await stageTransferDownload(download, {
103
106
  directory: archiveRoot,
@@ -115,11 +118,11 @@ export class SourceWorkspaceManager {
115
118
  });
116
119
  let workspacePath: string | undefined;
117
120
  try {
118
- workspacePath = await Deno.makeTempDir({
121
+ workspacePath = await makeTempDir({
119
122
  dir: workspaceRoot,
120
123
  prefix: 'attempt-',
121
124
  });
122
- await Deno.chmod(workspacePath, 0o700);
125
+ await plugins.fs.chmod(workspacePath, 0o700);
123
126
  const metadata = await extractTarGzipArchive({
124
127
  archivePath: staged.path,
125
128
  destinationPath: workspacePath,
@@ -1,5 +1,5 @@
1
- import { ProtocolError } from './errors.ts';
2
- import * as plugins from './plugins.ts';
1
+ import { ProtocolError } from './errors.js';
2
+ import * as plugins from './plugins.js';
3
3
 
4
4
  /**
5
5
  * Outcome of the specification version acceptance rule of the runner protocol: a declared
@@ -1,5 +1,15 @@
1
- import { join, resolve } from '@std/path';
2
- import { RunnerError } from './errors.ts';
1
+ import * as plugins from './plugins.js';
2
+ import { RunnerError } from './errors.js';
3
+ import { isNotFound, lstatIfPresent, removePath } from './filesystem.js';
4
+ import {
5
+ ensurePrivateStateDirectory,
6
+ type RunnerStateOwner,
7
+ stateOwnerHelperTemporaryNamePattern,
8
+ } from './state-owner.js';
9
+
10
+ const { join } = plugins.path;
11
+
12
+ const stateOwnerHelperTemporaryMaximumAgeMs = 60 * 60 * 1000;
3
13
 
4
14
  const stagingDirectoryNames = [
5
15
  'source-archives',
@@ -14,48 +24,49 @@ const stagingDirectoryNames = [
14
24
  const journalTemporaryNamePattern =
15
25
  /^\.[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
26
 
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
27
  const removeIfPresent = async (path: string, recursive = false): Promise<void> => {
27
28
  try {
28
- await Deno.remove(path, { recursive });
29
+ await removePath(path, { recursive });
29
30
  } catch (error) {
30
- if (!(error instanceof Deno.errors.NotFound)) throw error;
31
+ if (!isNotFound(error)) throw error;
31
32
  }
32
33
  };
33
34
 
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
- }
35
+ /**
36
+ * Removes the runner's known host-staging directories, its journal temporary files and stale
37
+ * private copies of the state owner helper. It runs under state ownership, before anything else
38
+ * in the state directory is used.
39
+ */
40
+ export const scavengeRunnerStaging = async (
41
+ owner: RunnerStateOwner,
42
+ now: () => number = Date.now,
43
+ ): Promise<void> => {
44
+ owner.assertHeld();
45
+ const stateRoot = await ensurePrivateStateDirectory(owner.stateDirectory);
41
46
 
42
47
  for (const name of stagingDirectoryNames) {
43
48
  const path = join(stateRoot, name);
44
49
  const stat = await lstatIfPresent(path);
45
50
  if (!stat) continue;
46
- if (!stat.isDirectory || stat.isSymlink) {
51
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
47
52
  throw new RunnerError(`Runner staging path ${name} must be a real directory`);
48
53
  }
49
54
  await removeIfPresent(path, true);
50
55
  }
51
56
 
52
- for await (const entry of Deno.readDir(stateRoot)) {
53
- if (!journalTemporaryNamePattern.test(entry.name)) continue;
54
- const path = join(stateRoot, entry.name);
57
+ for (const entry of await plugins.fs.readdir(stateRoot)) {
58
+ const journalTemporary = journalTemporaryNamePattern.test(entry);
59
+ if (!journalTemporary && !stateOwnerHelperTemporaryNamePattern.test(entry)) continue;
60
+ const path = join(stateRoot, entry);
55
61
  const stat = await lstatIfPresent(path);
56
62
  if (!stat) continue;
57
- if (!stat.isFile || stat.isSymlink) {
58
- throw new RunnerError('Runner journal temporary path must be a regular file');
63
+ if (!stat.isFile() || stat.isSymbolicLink()) {
64
+ throw new RunnerError('Runner state temporary path must be a regular file');
65
+ }
66
+ // A state owner helper copy younger than the age limit may belong to a concurrent start
67
+ // that is about to fail on the lock; it removes its own copy.
68
+ if (!journalTemporary && now() - stat.mtime.getTime() < stateOwnerHelperTemporaryMaximumAgeMs) {
69
+ continue;
59
70
  }
60
71
  await removeIfPresent(path);
61
72
  }
@@ -0,0 +1,353 @@
1
+ import * as plugins from './plugins.js';
2
+ import {
3
+ ResourceCleanupError,
4
+ RunnerError,
5
+ RunnerStateOwnedElsewhereError,
6
+ RunnerStateOwnershipLostError,
7
+ } from './errors.js';
8
+ import {
9
+ isNotFound,
10
+ readBoundedRegularFile,
11
+ removePath,
12
+ withOpenFile,
13
+ writeAll,
14
+ } from './filesystem.js';
15
+ import type { TOciHelperTarget } from './interfaces.js';
16
+
17
+ /** Name of the lock file that the state owner helper holds an exclusive `flock` on. */
18
+ export const runnerStateOwnerLockName = '.runner-owner.lock';
19
+ /** Exit code of `runnerworkspace own-state` when another process holds the lock. */
20
+ export const stateOwnedElsewhereExitCode = 3;
21
+ /** Matches the private executable copy that starts the state owner helper. */
22
+ export const stateOwnerHelperTemporaryNamePattern =
23
+ /^\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.state-owner-helper\.tmp$/;
24
+
25
+ export const workspaceHelperMaximumBytes = 64 * 1024 * 1024;
26
+
27
+ const lockedLine = 'locked\n';
28
+ const startTimeoutMs = 30_000;
29
+ const releaseTimeoutMs = 5_000;
30
+ const maximumHelperErrorBytes = 512;
31
+
32
+ export interface IRunnerStateOwnerOptions {
33
+ stateDirectory: string;
34
+ /**
35
+ * Source file of the host workspace helper. The packaged helper of the host architecture is
36
+ * used when it is omitted.
37
+ */
38
+ helperSourcePath?: string;
39
+ }
40
+
41
+ /** Maps the Node.js host architecture to the workspace helper build target. */
42
+ export const hostHelperTarget = (): TOciHelperTarget => {
43
+ if (process.platform !== 'linux') {
44
+ throw new RunnerError('The runner requires a Linux host');
45
+ }
46
+ switch (process.arch) {
47
+ case 'x64':
48
+ return 'linux_amd64';
49
+ case 'arm64':
50
+ return 'linux_arm64';
51
+ default:
52
+ throw new RunnerError(`Unsupported runner host architecture: ${process.arch}`);
53
+ }
54
+ };
55
+
56
+ /** Name of the workspace helper sidecar that the runner's single executables embed. */
57
+ export const workspaceHelperSidecarName = 'runnerworkspace';
58
+
59
+ /**
60
+ * Path of the packaged static workspace helper for `target`, a real file the runner reads and
61
+ * copies. Inside a runner single executable it is the embedded helper of the host architecture,
62
+ * which smartsea extracts into its cache; elsewhere it is the helper in the package's `dist_rust/`.
63
+ */
64
+ export const resolvePackagedWorkspaceHelperPath = async (
65
+ target: TOciHelperTarget,
66
+ ): Promise<string> => {
67
+ if (plugins.smartsea.isSea()) {
68
+ const embeddedTarget = hostHelperTarget();
69
+ if (target !== embeddedTarget) {
70
+ throw new RunnerError(
71
+ `This executable embeds only the ${embeddedTarget} workspace helper, not ${target}`,
72
+ );
73
+ }
74
+ return await plugins.smartsea.getSidecarPath(workspaceHelperSidecarName).catch((error) => {
75
+ throw new RunnerError(
76
+ `The embedded ${embeddedTarget} workspace helper is unavailable: ${
77
+ error instanceof Error ? error.message : String(error)
78
+ }`,
79
+ { cause: error },
80
+ );
81
+ });
82
+ }
83
+ return plugins.url.fileURLToPath(
84
+ new URL(`../dist_rust/runnerworkspace_${target}_musl`, import.meta.url),
85
+ );
86
+ };
87
+
88
+ /** Creates the runner state directory if needed and checks that it is a private real directory. */
89
+ export const ensurePrivateStateDirectory = async (stateDirectory: string): Promise<string> => {
90
+ const stateRoot = plugins.path.resolve(stateDirectory);
91
+ await plugins.fs.mkdir(stateRoot, { recursive: true, mode: 0o700 });
92
+ const stat = await plugins.fs.lstat(stateRoot);
93
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
94
+ throw new RunnerError('Runner state directory must be a real directory');
95
+ }
96
+ if ((stat.mode & 0o077) !== 0) {
97
+ throw new RunnerError('Runner state directory permissions are not private');
98
+ }
99
+ return stateRoot;
100
+ };
101
+
102
+ const waitForExit = (child: plugins.childProcess.ChildProcess): Promise<void> =>
103
+ new Promise((resolvePromise) => {
104
+ if (child.exitCode !== null || child.signalCode !== null) {
105
+ resolvePromise();
106
+ return;
107
+ }
108
+ child.once('exit', () => resolvePromise());
109
+ });
110
+
111
+ const boundedWait = async (promise: Promise<void>, timeoutMs: number): Promise<boolean> => {
112
+ let timer: ReturnType<typeof setTimeout> | undefined;
113
+ const timedOut = new Promise<boolean>((resolvePromise) => {
114
+ timer = setTimeout(() => resolvePromise(false), timeoutMs);
115
+ });
116
+ try {
117
+ return await Promise.race([promise.then(() => true), timedOut]);
118
+ } finally {
119
+ clearTimeout(timer);
120
+ }
121
+ };
122
+
123
+ /**
124
+ * Exclusive ownership of one runner state directory.
125
+ *
126
+ * Ownership is a kernel `flock` held by a child process running the runner's own static helper
127
+ * (`runnerworkspace own-state`). The lock ends with that process, so a crashed runner never leaves
128
+ * a stale lock behind, and a second runner on the same state directory fails at once. Many
129
+ * runners per host remain supported, each with its own state directory.
130
+ *
131
+ * State stores, scavengers and the OCI executor take the owner, so state cannot be touched without
132
+ * it. Within the process, `serialize` runs state operations one after another on a single chain.
133
+ */
134
+ export class RunnerStateOwner {
135
+ private readonly lostController = new AbortController();
136
+ private chain: Promise<void> = Promise.resolve();
137
+ private runtimeProbeOwnerIdPromise?: Promise<string>;
138
+ private releasePromise?: Promise<void>;
139
+
140
+ private constructor(
141
+ readonly stateDirectory: string,
142
+ private readonly child: plugins.childProcess.ChildProcess,
143
+ ) {
144
+ const onExit = (): void => {
145
+ if (this.releasePromise) return;
146
+ this.lostController.abort(new RunnerStateOwnershipLostError());
147
+ };
148
+ if (child.exitCode !== null || child.signalCode !== null) onExit();
149
+ else child.once('exit', onExit);
150
+ }
151
+
152
+ /** Process ID of the helper that holds the lock, for diagnostics. */
153
+ get helperProcessId(): number | undefined {
154
+ return this.child.pid;
155
+ }
156
+
157
+ /** Aborted with a `RunnerStateOwnershipLostError` when the lock holder exits unexpectedly. */
158
+ get lost(): AbortSignal {
159
+ return this.lostController.signal;
160
+ }
161
+
162
+ /**
163
+ * Takes the exclusive lock of `stateDirectory`. Nothing else in the state directory is touched
164
+ * before the lock is held, apart from creating the directory and the private executable copy of
165
+ * the helper that takes the lock.
166
+ */
167
+ static async acquire(options: IRunnerStateOwnerOptions): Promise<RunnerStateOwner> {
168
+ const stateDirectory = await ensurePrivateStateDirectory(options.stateDirectory);
169
+ const helperSourcePath = options.helperSourcePath ??
170
+ await resolvePackagedWorkspaceHelperPath(hostHelperTarget());
171
+ const helperSource = await plugins.fs.realpath(helperSourcePath).catch((error) => {
172
+ throw new RunnerError('Workspace helper source is unavailable', { cause: error });
173
+ });
174
+ const { bytes } = await readBoundedRegularFile(
175
+ helperSource,
176
+ workspaceHelperMaximumBytes,
177
+ 'Workspace helper source',
178
+ );
179
+ const executablePath = plugins.path.join(
180
+ stateDirectory,
181
+ `.${plugins.crypto.randomUUID()}.state-owner-helper.tmp`,
182
+ );
183
+ let child: plugins.childProcess.ChildProcess | undefined;
184
+ let operationError: unknown;
185
+ let hasOperationError = false;
186
+ try {
187
+ await withOpenFile(
188
+ executablePath,
189
+ 'wx',
190
+ 0o700,
191
+ async (handle) => {
192
+ await writeAll(handle, bytes, 'State owner helper write made no progress');
193
+ await handle.sync();
194
+ },
195
+ 'State owner helper write and close failed',
196
+ );
197
+ child = plugins.childProcess.spawn(executablePath, ['own-state', stateDirectory], {
198
+ env: {},
199
+ stdio: ['pipe', 'pipe', 'pipe'],
200
+ });
201
+ await RunnerStateOwner.waitForLock(child, stateDirectory);
202
+ } catch (error) {
203
+ operationError = error;
204
+ hasOperationError = true;
205
+ }
206
+ const cleanupErrors: unknown[] = [];
207
+ try {
208
+ await removePath(executablePath);
209
+ } catch (error) {
210
+ if (!hasOperationError || !isNotFound(error)) {
211
+ cleanupErrors.push(error);
212
+ }
213
+ }
214
+ if (child && (hasOperationError || cleanupErrors.length > 0)) {
215
+ try {
216
+ await RunnerStateOwner.stopChild(child);
217
+ } catch (error) {
218
+ cleanupErrors.push(error);
219
+ }
220
+ }
221
+ if (cleanupErrors.length > 0) {
222
+ throw new ResourceCleanupError(
223
+ hasOperationError
224
+ ? 'Runner state lock and cleanup both failed'
225
+ : 'Unable to clean the runner state lock setup',
226
+ [...(hasOperationError ? [operationError] : []), ...cleanupErrors],
227
+ );
228
+ }
229
+ if (hasOperationError) throw operationError;
230
+ if (!child) throw new RunnerError('Runner state lock helper was not started');
231
+ return new RunnerStateOwner(stateDirectory, child);
232
+ }
233
+
234
+ private static async waitForLock(
235
+ child: plugins.childProcess.ChildProcess,
236
+ stateDirectory: string,
237
+ ): Promise<void> {
238
+ const { stdout, stderr } = child;
239
+ if (!stdout || !stderr) throw new RunnerError('Runner state lock helper has no output pipes');
240
+ await new Promise<void>((resolvePromise, rejectPromise) => {
241
+ let output = '';
242
+ const errorChunks: Buffer[] = [];
243
+ let errorBytes = 0;
244
+ let settled = false;
245
+ const finish = (error?: unknown): void => {
246
+ if (settled) return;
247
+ settled = true;
248
+ clearTimeout(timer);
249
+ stdout.off('data', onOutput);
250
+ stderr.off('data', onError);
251
+ child.off('exit', onExit);
252
+ child.off('error', onSpawnError);
253
+ if (error === undefined) resolvePromise();
254
+ else rejectPromise(error);
255
+ };
256
+ const onOutput = (chunk: Buffer): void => {
257
+ output += chunk.toString('utf8');
258
+ if (output === lockedLine) finish();
259
+ else if (!lockedLine.startsWith(output)) {
260
+ finish(new RunnerError('Runner state lock helper reported unexpected output'));
261
+ }
262
+ };
263
+ const onError = (chunk: Buffer): void => {
264
+ if (errorBytes >= maximumHelperErrorBytes) return;
265
+ const kept = chunk.subarray(0, maximumHelperErrorBytes - errorBytes);
266
+ errorChunks.push(kept);
267
+ errorBytes += kept.byteLength;
268
+ };
269
+ const onExit = (code: number | null): void => {
270
+ if (code === stateOwnedElsewhereExitCode) {
271
+ finish(new RunnerStateOwnedElsewhereError(stateDirectory));
272
+ return;
273
+ }
274
+ const detail = Buffer.concat(errorChunks).toString('utf8').trim();
275
+ finish(
276
+ new RunnerError(
277
+ `Runner state lock helper exited before taking the lock${detail ? `: ${detail}` : ''}`,
278
+ ),
279
+ );
280
+ };
281
+ const onSpawnError = (error: Error): void =>
282
+ finish(new RunnerError('Unable to start the runner state lock helper', { cause: error }));
283
+ const timer = setTimeout(
284
+ () => finish(new RunnerError('Runner state lock helper did not report the lock')),
285
+ startTimeoutMs,
286
+ );
287
+ stdout.on('data', onOutput);
288
+ stderr.on('data', onError);
289
+ child.once('exit', onExit);
290
+ child.once('error', onSpawnError);
291
+ });
292
+ // The helper prints nothing after `locked`; keep draining so a pipe never fills up.
293
+ stdout.resume();
294
+ stderr.resume();
295
+ }
296
+
297
+ private static async stopChild(child: plugins.childProcess.ChildProcess): Promise<void> {
298
+ // A helper that could not be started has no process to stop.
299
+ if (child.pid === undefined) return;
300
+ const exited = waitForExit(child);
301
+ child.stdin?.end();
302
+ if (await boundedWait(exited, releaseTimeoutMs)) return;
303
+ child.kill('SIGKILL');
304
+ if (!(await boundedWait(exited, releaseTimeoutMs))) {
305
+ throw new RunnerError('Runner state lock helper did not exit');
306
+ }
307
+ }
308
+
309
+ /** Throws unless this owner still holds the lock. */
310
+ assertHeld(): void {
311
+ if (this.lostController.signal.aborted) throw this.lostController.signal.reason;
312
+ if (this.releasePromise) throw new RunnerError('Runner state ownership was released');
313
+ }
314
+
315
+ /**
316
+ * Runs `operation` after every operation queued before it has settled, while the lock is held.
317
+ * There is one chain per owner, no timeout and no polling.
318
+ */
319
+ serialize<T>(operation: () => Promise<T>): Promise<T> {
320
+ try {
321
+ this.assertHeld();
322
+ } catch (error) {
323
+ return Promise.reject(error);
324
+ }
325
+ const result = this.chain.then(() => {
326
+ this.assertHeld();
327
+ return operation();
328
+ });
329
+ this.chain = result.then(
330
+ () => undefined,
331
+ () => undefined,
332
+ );
333
+ return result;
334
+ }
335
+
336
+ /**
337
+ * Returns the runtime probe owner ID of this state directory, creating it through `create` once
338
+ * per owner on the serialized chain. A failed creation is not memoized.
339
+ */
340
+ runtimeProbeOwnerId(create: () => Promise<string>): Promise<string> {
341
+ this.runtimeProbeOwnerIdPromise ??= this.serialize(create).catch((error) => {
342
+ this.runtimeProbeOwnerIdPromise = undefined;
343
+ throw error;
344
+ });
345
+ return this.runtimeProbeOwnerIdPromise;
346
+ }
347
+
348
+ /** Releases the lock by ending the helper's input and waits until the helper has exited. */
349
+ release(): Promise<void> {
350
+ this.releasePromise ??= RunnerStateOwner.stopChild(this.child);
351
+ return this.releasePromise;
352
+ }
353
+ }