@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
package/ts/plugins.ts CHANGED
@@ -1,3 +1,20 @@
1
+ // node native scope
2
+ import * as childProcess from 'node:child_process';
3
+ import * as crypto from 'node:crypto';
4
+ import * as fs from 'node:fs/promises';
5
+ import * as os from 'node:os';
6
+ import * as path from 'node:path';
7
+ import * as stream from 'node:stream';
8
+ import * as url from 'node:url';
9
+
10
+ export { childProcess, crypto, fs, os, path, stream, url };
11
+ export type { BigIntStatsFs, Stats } from 'node:fs';
12
+
13
+ // @push.rocks scope
14
+ import * as smartsea from '@push.rocks/smartsea';
15
+ export { smartsea };
16
+
17
+ // @ship.zone scope
1
18
  export {
2
19
  ciSpecStatus,
3
20
  ciSpecVersion,
@@ -9,11 +26,12 @@ export {
9
26
  export const loadCiSpecArchiveCases = async (): Promise<unknown> =>
10
27
  (await import('@ship.zone/ci-spec/archive-cases.json', { with: { type: 'json' } })).default;
11
28
 
12
- import { Ajv2020 } from 'ajv/dist/2020.js';
13
- export { Ajv2020 };
14
-
15
29
  import runnerJobSchema from '@ship.zone/ci-spec/runner-job.schema.json' with { type: 'json' };
16
30
  export { runnerJobSchema };
17
31
 
18
32
  import runnerOpenApi from '@ship.zone/ci-spec/runner.openapi.json' with { type: 'json' };
19
33
  export { runnerOpenApi };
34
+
35
+ // third party scope
36
+ import { Ajv2020 } from 'ajv/dist/2020.js';
37
+ export { Ajv2020 };
@@ -1,4 +1,4 @@
1
- import { ProtocolError } from './errors.ts';
1
+ import { ProtocolError } from './errors.js';
2
2
  import type {
3
3
  ICompiledStep,
4
4
  IJobLease,
@@ -11,10 +11,10 @@ import type {
11
11
  TJsonObject,
12
12
  TJsonValue,
13
13
  TLeaseFeature,
14
- } from './interfaces.ts';
15
- import { acceptSpecVersion, runnerSpecVersion } from './spec-version.ts';
16
- import { isRecord } from './validation.ts';
17
- import { validateCompiledJobSchema, validateWireMessage } from './wire-schema.ts';
14
+ } from './interfaces.js';
15
+ import { acceptSpecVersion, runnerSpecVersion } from './spec-version.js';
16
+ import { isRecord } from './validation.js';
17
+ import { validateCompiledJobSchema, validateWireMessage } from './wire-schema.js';
18
18
 
19
19
  const sha256Pattern = /^[a-f0-9]{64}$/;
20
20
  const reservedEnvironmentNames = ['SHIPZONE_CI_INPUTS_JSON', 'SHIPZONE_CI_MATRIX_JSON'] as const;
package/ts/redactor.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { ISecretContentMatcher, ISecretRedactionSet, TLogStream } from './interfaces.ts';
2
- import { utf8Length } from './validation.ts';
1
+ import type { ISecretContentMatcher, ISecretRedactionSet, TLogStream } from './interfaces.js';
2
+ import { utf8Length } from './validation.js';
3
3
 
4
4
  /** Redaction set members shorter than this many UTF-8 bytes are left out by the protocol. */
5
5
  export const minimumRedactionMemberBytes = 8;
@@ -1,8 +1,21 @@
1
- import { join } from '@std/path';
2
- import { ConfigurationError, RunnerError } from './errors.ts';
3
- import type { IRegisterRunnerRequest } from './interfaces.ts';
4
- import { canonicalizeJson, createRunnerCapabilitySnapshot } from './protocol-validator.ts';
5
- import { validateWireMessage } from './wire-schema.ts';
1
+ import * as plugins from './plugins.js';
2
+ import { ConfigurationError, RunnerError } from './errors.js';
3
+ import {
4
+ createNewWriteFlags,
5
+ isNotFound,
6
+ readInto,
7
+ removePath,
8
+ sameFileIdentity,
9
+ syncDirectory,
10
+ withOpenFile,
11
+ writeAll,
12
+ } from './filesystem.js';
13
+ import { ensurePrivateStateDirectory, type RunnerStateOwner } from './state-owner.js';
14
+ import type { IRegisterRunnerRequest } from './interfaces.js';
15
+ import { canonicalizeJson, createRunnerCapabilitySnapshot } from './protocol-validator.js';
16
+ import { validateWireMessage } from './wire-schema.js';
17
+
18
+ const { join } = plugins.path;
6
19
 
7
20
  const journalName = 'pending-registration.json';
8
21
  const maximumJournalBytes = 64 * 1024;
@@ -35,27 +48,18 @@ const withoutRequestId = (request: IRegisterRunnerRequest): TRegistrationRequest
35
48
  capabilities: request.capabilities,
36
49
  });
37
50
 
38
- const writeAll = async (file: Deno.FsFile, bytes: Uint8Array): Promise<void> => {
39
- let offset = 0;
40
- while (offset < bytes.byteLength) {
41
- const written = await file.write(bytes.subarray(offset));
42
- if (written <= 0) throw new RunnerError('Registration journal write made no progress');
43
- offset += written;
44
- }
45
- };
46
-
47
- const isNotFound = (error: unknown): boolean => error instanceof Deno.errors.NotFound;
48
-
49
51
  export class RegistrationStateStore {
50
52
  readonly path: string;
53
+ private readonly stateDirectory: string;
51
54
 
52
- constructor(private readonly stateDirectory: string) {
53
- this.path = join(stateDirectory, journalName);
55
+ constructor(private readonly owner: RunnerStateOwner) {
56
+ this.stateDirectory = owner.stateDirectory;
57
+ this.path = join(this.stateDirectory, journalName);
54
58
  }
55
59
 
56
60
  async loadOrCreate(
57
61
  template: TRegistrationRequestTemplate,
58
- createRequestId: () => string = () => crypto.randomUUID(),
62
+ createRequestId: () => string = () => plugins.crypto.randomUUID(),
59
63
  ): Promise<IRegisterRunnerRequest> {
60
64
  const candidate = validateRegistrationRequest({
61
65
  registrationRequestId: 'pending-validation',
@@ -83,9 +87,9 @@ export class RegistrationStateStore {
83
87
 
84
88
  async load(): Promise<IRegisterRunnerRequest | undefined> {
85
89
  await this.ensureDirectory();
86
- let pathStat: Deno.FileInfo;
90
+ let pathStat: plugins.Stats;
87
91
  try {
88
- pathStat = await Deno.lstat(this.path);
92
+ pathStat = await plugins.fs.lstat(this.path);
89
93
  } catch (error) {
90
94
  if (isNotFound(error)) return undefined;
91
95
  throw error;
@@ -94,75 +98,74 @@ export class RegistrationStateStore {
94
98
  if (pathStat.size > maximumJournalBytes) {
95
99
  throw new RunnerError('Registration journal exceeds its size limit');
96
100
  }
97
- const file = await Deno.open(this.path, { read: true });
98
- try {
99
- const openStat = await file.stat();
100
- this.assertSafeJournalFile(openStat);
101
- if (
102
- (pathStat.dev !== null && openStat.dev !== pathStat.dev) ||
103
- (pathStat.ino !== null && openStat.ino !== pathStat.ino)
104
- ) {
105
- throw new RunnerError('Registration journal changed while it was opened');
106
- }
107
- const bytes = new Uint8Array(pathStat.size + 1);
108
- let offset = 0;
109
- while (offset < bytes.byteLength) {
110
- const read = await file.read(bytes.subarray(offset));
111
- if (read === null) break;
112
- offset += read;
113
- }
114
- if (offset !== pathStat.size) {
115
- throw new RunnerError('Registration journal changed while it was read');
116
- }
117
- let parsed: unknown;
118
- try {
119
- parsed = JSON.parse(
120
- new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, offset)),
121
- );
122
- } catch (error) {
123
- throw new RunnerError('Registration journal is not valid UTF-8 JSON', { cause: error });
124
- }
125
- return validateRegistrationRequest(parsed);
126
- } finally {
127
- file.close();
128
- }
101
+ return await withOpenFile(
102
+ this.path,
103
+ 'r',
104
+ undefined,
105
+ async (file) => {
106
+ const openStat = await file.stat();
107
+ this.assertSafeJournalFile(openStat);
108
+ if (!sameFileIdentity(pathStat, openStat)) {
109
+ throw new RunnerError('Registration journal changed while it was opened');
110
+ }
111
+ const bytes = new Uint8Array(pathStat.size + 1);
112
+ let offset = 0;
113
+ while (offset < bytes.byteLength) {
114
+ const read = await readInto(file, bytes.subarray(offset));
115
+ if (read === null) break;
116
+ offset += read;
117
+ }
118
+ if (offset !== pathStat.size) {
119
+ throw new RunnerError('Registration journal changed while it was read');
120
+ }
121
+ let parsed: unknown;
122
+ try {
123
+ parsed = JSON.parse(
124
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, offset)),
125
+ );
126
+ } catch (error) {
127
+ throw new RunnerError('Registration journal is not valid UTF-8 JSON', { cause: error });
128
+ }
129
+ return validateRegistrationRequest(parsed);
130
+ },
131
+ 'Registration journal read and close failed',
132
+ );
129
133
  }
130
134
 
131
135
  async save(request: IRegisterRunnerRequest): Promise<void> {
132
136
  const validated = validateRegistrationRequest(request);
133
137
  await this.ensureDirectory();
134
138
  try {
135
- this.assertSafeJournalFile(await Deno.lstat(this.path));
139
+ this.assertSafeJournalFile(await plugins.fs.lstat(this.path));
136
140
  } catch (error) {
137
141
  if (!isNotFound(error)) throw error;
138
142
  }
139
143
  const temporaryPath = join(
140
144
  this.stateDirectory,
141
- `.${crypto.randomUUID()}.registration-journal.tmp`,
145
+ `.${plugins.crypto.randomUUID()}.registration-journal.tmp`,
142
146
  );
143
147
  const bytes = new TextEncoder().encode(`${JSON.stringify(validated)}\n`);
144
148
  if (bytes.byteLength > maximumJournalBytes) {
145
149
  throw new RunnerError('Registration journal exceeds its size limit');
146
150
  }
147
- let file: Deno.FsFile | undefined;
148
151
  try {
149
- file = await Deno.open(temporaryPath, {
150
- write: true,
151
- createNew: true,
152
- mode: 0o600,
153
- });
154
- await writeAll(file, bytes);
155
- await file.sync();
156
- file.close();
157
- file = undefined;
158
- await Deno.chmod(temporaryPath, 0o600);
159
- await Deno.rename(temporaryPath, this.path);
160
- await Deno.chmod(this.path, 0o600);
152
+ await withOpenFile(
153
+ temporaryPath,
154
+ createNewWriteFlags,
155
+ 0o600,
156
+ async (file) => {
157
+ await writeAll(file, bytes, 'Registration journal write made no progress');
158
+ await file.sync();
159
+ },
160
+ 'Registration journal write and close failed',
161
+ );
162
+ await plugins.fs.chmod(temporaryPath, 0o600);
163
+ await plugins.fs.rename(temporaryPath, this.path);
164
+ await plugins.fs.chmod(this.path, 0o600);
161
165
  await this.syncDirectory();
162
166
  } catch (error) {
163
- file?.close();
164
167
  try {
165
- await Deno.remove(temporaryPath);
168
+ await removePath(temporaryPath);
166
169
  } catch (cleanupError) {
167
170
  if (!isNotFound(cleanupError)) {
168
171
  throw new AggregateError(
@@ -177,44 +180,33 @@ export class RegistrationStateStore {
177
180
 
178
181
  async clear(): Promise<void> {
179
182
  await this.ensureDirectory();
180
- let stat: Deno.FileInfo;
183
+ let stat: plugins.Stats;
181
184
  try {
182
- stat = await Deno.lstat(this.path);
185
+ stat = await plugins.fs.lstat(this.path);
183
186
  } catch (error) {
184
187
  if (isNotFound(error)) return;
185
188
  throw error;
186
189
  }
187
190
  this.assertSafeJournalFile(stat);
188
- await Deno.remove(this.path);
191
+ await removePath(this.path);
189
192
  await this.syncDirectory();
190
193
  }
191
194
 
192
195
  private async ensureDirectory(): Promise<void> {
193
- await Deno.mkdir(this.stateDirectory, { recursive: true, mode: 0o700 });
194
- const stat = await Deno.lstat(this.stateDirectory);
195
- if (!stat.isDirectory || stat.isSymlink) {
196
- throw new RunnerError('Runner state directory must be a real directory');
197
- }
198
- if (Deno.build.os !== 'windows' && stat.mode !== null && (stat.mode & 0o077) !== 0) {
199
- throw new RunnerError('Runner state directory permissions are not private');
200
- }
196
+ this.owner.assertHeld();
197
+ await ensurePrivateStateDirectory(this.stateDirectory);
201
198
  }
202
199
 
203
- private assertSafeJournalFile(stat: Deno.FileInfo): void {
204
- if (!stat.isFile || stat.isSymlink) {
200
+ private assertSafeJournalFile(stat: plugins.Stats): void {
201
+ if (!stat.isFile() || stat.isSymbolicLink()) {
205
202
  throw new RunnerError('Registration journal must be a regular file');
206
203
  }
207
- if (Deno.build.os !== 'windows' && stat.mode !== null && (stat.mode & 0o777) !== 0o600) {
204
+ if ((stat.mode & 0o777) !== 0o600) {
208
205
  throw new RunnerError('Registration journal permissions must be 0600');
209
206
  }
210
207
  }
211
208
 
212
209
  private async syncDirectory(): Promise<void> {
213
- const directory = await Deno.open(this.stateDirectory, { read: true });
214
- try {
215
- await directory.sync();
216
- } finally {
217
- directory.close();
218
- }
210
+ await syncDirectory(this.stateDirectory, 'Runner state directory sync and close failed');
219
211
  }
220
212
  }
package/ts/runner.ts CHANGED
@@ -1,12 +1,14 @@
1
- import { AttemptStateStore } from './attempt-state.ts';
1
+ import * as plugins from './plugins.js';
2
+ import { AttemptStateStore } from './attempt-state.js';
2
3
  import {
3
4
  AuthenticationError,
5
+ ConfigurationError,
4
6
  CoordinatorError,
5
7
  LeaseLostError,
6
8
  ProtocolError,
7
9
  ResourceCleanupError,
8
10
  RunnerError,
9
- } from './errors.ts';
11
+ } from './errors.js';
10
12
  import type {
11
13
  IAbandonJobRequest,
12
14
  IAcceptJobRequest,
@@ -40,13 +42,14 @@ import type {
40
42
  IStartSessionResponse,
41
43
  TExecutionStopReason,
42
44
  TJobCompletionStatus,
43
- } from './interfaces.ts';
44
- import { runnerVersion } from './interfaces.ts';
45
- import { LogSender } from './log-sender.ts';
46
- import { createRunnerCapabilitySnapshot, RunnerProtocolValidator } from './protocol-validator.ts';
47
- import { SecretRedactionSet } from './redactor.ts';
48
- import { runnerSpecVersion, specMajorVersionsMatch } from './spec-version.ts';
49
- import { scavengeRunnerStaging } from './staging-scavenger.ts';
45
+ } from './interfaces.js';
46
+ import { runnerVersion } from './interfaces.js';
47
+ import { LogSender } from './log-sender.js';
48
+ import { createRunnerCapabilitySnapshot, RunnerProtocolValidator } from './protocol-validator.js';
49
+ import { SecretRedactionSet } from './redactor.js';
50
+ import { runnerSpecVersion, specMajorVersionsMatch } from './spec-version.js';
51
+ import { scavengeRunnerStaging } from './staging-scavenger.js';
52
+ import type { RunnerStateOwner } from './state-owner.js';
50
53
 
51
54
  export interface IRunnerCoordinatorClient {
52
55
  discover(signal?: AbortSignal): Promise<IDiscoveryResponse>;
@@ -73,6 +76,8 @@ export interface IRunnerWorkspaceManager {
73
76
  }
74
77
 
75
78
  export interface IRunnerDependencies {
79
+ /** Ownership of `config.stateDirectory`; the runner stops when it is lost. */
80
+ stateOwner: RunnerStateOwner;
76
81
  api: IRunnerCoordinatorClient;
77
82
  executor: IJobExecutor;
78
83
  workspaceManager: IRunnerWorkspaceManager;
@@ -318,15 +323,20 @@ export class ShipRunner {
318
323
  }
319
324
  this.drainRequested = false;
320
325
  this.sessionInvalid = false;
326
+ const stateOwner = this.dependencies.stateOwner;
327
+ if (plugins.path.resolve(this.config.stateDirectory) !== stateOwner.stateDirectory) {
328
+ throw new ConfigurationError('Runner state owner does not own the configured state');
329
+ }
321
330
  this.dependencies.api.setRunnerToken(this.config.runnerToken);
322
331
 
332
+ await scavengeRunnerStaging(stateOwner);
323
333
  const runtime = await this.dependencies.executor.verifyRuntime();
324
334
  const discovery = await this.dependencies.api.discover(options.signal);
325
335
  const capabilities = runnerCapabilities(this.config, runtime);
326
336
  reconcileProtocolLimits(this.config, discovery, capabilities);
327
337
  const validator = new RunnerProtocolValidator(capabilities);
328
338
  const session = await this.dependencies.api.startSession({
329
- sessionRequestId: crypto.randomUUID(),
339
+ sessionRequestId: plugins.crypto.randomUUID(),
330
340
  runnerId,
331
341
  spec: runnerSpecVersion,
332
342
  runnerVersion,
@@ -334,11 +344,13 @@ export class ShipRunner {
334
344
  }, options.signal);
335
345
  if (session.credential) await this.applyCredential(session.credential);
336
346
 
337
- const journal = new AttemptStateStore(this.config.stateDirectory);
347
+ const journal = new AttemptStateStore(stateOwner);
338
348
  const sessionLifecycle = new AbortController();
339
349
  const externalAbort = (): void => sessionLifecycle.abort('runner_shutdown');
340
350
  options.signal?.addEventListener('abort', externalAbort, { once: true });
341
351
  if (options.signal?.aborted) externalAbort();
352
+ stateOwner.lost.addEventListener('abort', externalAbort, { once: true });
353
+ if (stateOwner.lost.aborted) externalAbort();
342
354
  let heartbeatError: unknown;
343
355
  const runnerHeartbeat = this.runnerHeartbeatLoop(
344
356
  runnerId,
@@ -352,7 +364,6 @@ export class ShipRunner {
352
364
  let lastResult: IRunnerRunResult = { claimed: false };
353
365
  try {
354
366
  await this.dependencies.executor.reconcileOrphans(runnerId, session.sessionId);
355
- await scavengeRunnerStaging(this.config.stateDirectory);
356
367
  await this.recoverInterruptedAttempt(
357
368
  journal,
358
369
  runnerId,
@@ -382,8 +393,10 @@ export class ShipRunner {
382
393
  } finally {
383
394
  if (!sessionLifecycle.signal.aborted) sessionLifecycle.abort('runner_shutdown');
384
395
  options.signal?.removeEventListener('abort', externalAbort);
396
+ stateOwner.lost.removeEventListener('abort', externalAbort);
385
397
  await runnerHeartbeat;
386
398
  }
399
+ if (stateOwner.lost.aborted) throw stateOwner.lost.reason;
387
400
  if (operationError instanceof ResourceCleanupError) throw operationError;
388
401
  if (heartbeatError !== undefined) throw heartbeatError;
389
402
  if (
@@ -406,7 +419,7 @@ export class ShipRunner {
406
419
  if (!interrupted) return;
407
420
  try {
408
421
  await this.dependencies.api.recoverAttempt({
409
- recoveryRequestId: crypto.randomUUID(),
422
+ recoveryRequestId: plugins.crypto.randomUUID(),
410
423
  runnerId,
411
424
  currentSessionId: sessionId,
412
425
  previousSessionId: interrupted.previousSessionId,
@@ -431,7 +444,7 @@ export class ShipRunner {
431
444
  ): Promise<IRunnerRunResult> {
432
445
  const claimStartedAt = this.now();
433
446
  const claim = await this.dependencies.api.claimJob({
434
- claimRequestId: crypto.randomUUID(),
447
+ claimRequestId: plugins.crypto.randomUUID(),
435
448
  runnerId,
436
449
  sessionId,
437
450
  capabilities,
@@ -565,7 +578,7 @@ export class ShipRunner {
565
578
  }
566
579
  try {
567
580
  await this.dependencies.api.acceptJob({
568
- acceptRequestId: crypto.randomUUID(),
581
+ acceptRequestId: plugins.crypto.randomUUID(),
569
582
  identity,
570
583
  }, guard.controller.signal);
571
584
  } catch (error) {
@@ -896,7 +909,7 @@ export class ShipRunner {
896
909
  }
897
910
 
898
911
  const completion: ICompleteJobRequest = {
899
- completionRequestId: crypto.randomUUID(),
912
+ completionRequestId: plugins.crypto.randomUUID(),
900
913
  identity,
901
914
  status,
902
915
  exitCode,
@@ -1068,7 +1081,7 @@ export class ShipRunner {
1068
1081
  ): Promise<void> {
1069
1082
  try {
1070
1083
  await this.dependencies.api.abandonJob({
1071
- abandonRequestId: crypto.randomUUID(),
1084
+ abandonRequestId: plugins.crypto.randomUUID(),
1072
1085
  identity,
1073
1086
  reason,
1074
1087
  });
@@ -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
  }