@ship.zone/runner 0.2.0 → 0.2.2

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.
@@ -1,4 +1,4 @@
1
- import { join } from '@std/path';
1
+ import { join, resolve } from '@std/path';
2
2
  import { ProtocolError, ResourceCleanupError, RunnerError } from './errors.ts';
3
3
  import type {
4
4
  ICompiledStep,
@@ -39,6 +39,7 @@ const runnerLabel = 'ship.zone.runner.id';
39
39
  const sessionLabel = 'ship.zone.runner.session';
40
40
  const attemptLabel = 'ship.zone.runner.attempt';
41
41
  const runtimeProbeLabel = 'ship.zone.runner.runtime-probe';
42
+ const runtimeProbeOwnerLabel = 'ship.zone.runner.runtime-probe-owner';
42
43
  const helperContainerPath = '/runnerworkspace';
43
44
  const maximumRuntimeOutputBytes = 1024 * 1024;
44
45
  const runtimeCommandTimeoutMs = 30_000;
@@ -54,8 +55,24 @@ const maximumCommandBytes = 128 * 1024;
54
55
  const maximumWorkspaceHelperErrorBytes = 512;
55
56
  const hostTmpfsProbeMaximumAgeMs = 60 * 60 * 1000;
56
57
  const runtimeProbeVolumeMaximumAgeMs = 60 * 60 * 1000;
57
- const hostTmpfsProbeNamePattern = /^foss-ci-probe-[a-f0-9]{16}$/;
58
+ const runtimeProbeOwnerIdPattern = /^[a-f0-9]{32}$/;
59
+ const hostTmpfsProbeNamePattern = /^foss-ci-probe-([a-f0-9]{32})-[a-f0-9]{16}$/;
58
60
  const runtimeProbeVolumeNamePattern = /^foss-ci-volume-[a-f0-9]{32}$/;
61
+ const workspaceHelperDirectoryName = 'workspace-helpers';
62
+ const workspaceHelperLockName = '.workspace-helper.lock';
63
+ const runtimeProbeOwnerMarkerPrefix = '.runtime-probe-owner_';
64
+ const runtimeProbeOwnerMarkerPattern = /^\.runtime-probe-owner_([a-f0-9]{32})$/;
65
+ const workspaceHelperExecutableMode = 0o755;
66
+ const workspaceHelperMaximumBytes = 64 * 1024 * 1024;
67
+ const workspaceHelperRetainedFinalCount = 8;
68
+ const workspaceHelperTemporaryMaximumBytes = 8 * workspaceHelperMaximumBytes;
69
+ const workspaceHelperTemporaryMaximumCount = 8;
70
+ const workspaceHelperTemporaryMaximumAgeMs = 60 * 60 * 1000;
71
+ const workspaceHelperLockTimeoutMs = 30 * 1000;
72
+ const workspaceHelperLockRetryMs = 25;
73
+ const workspaceHelperFinalNamePattern = /^runnerworkspace_linux_(?:amd64|arm64)_musl_[a-f0-9]{64}$/;
74
+ const workspaceHelperTemporaryNamePattern =
75
+ /^\.[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$/;
59
76
 
60
77
  export const workspaceHelperReserveBytes = 1024 * 1024;
61
78
  export const workspaceFixedInodes = 3;
@@ -81,6 +98,32 @@ export type TOciRuntimeCommandRunner = (
81
98
  request: IOciRuntimeCommandRequest,
82
99
  ) => Promise<IOciRuntimeCommandResult>;
83
100
 
101
+ export interface IRuntimeMakeTempOptions {
102
+ dir?: string;
103
+ prefix?: string;
104
+ suffix?: string;
105
+ }
106
+
107
+ export interface IRuntimeRemoveOptions {
108
+ recursive?: boolean;
109
+ }
110
+
111
+ export interface IRuntimeDirectoryEntry {
112
+ name: string;
113
+ isFile: boolean;
114
+ isDirectory: boolean;
115
+ isSymlink: boolean;
116
+ }
117
+
118
+ export interface IRuntimeFileInfo {
119
+ isDirectory: boolean;
120
+ isSymlink: boolean;
121
+ uid: number | null;
122
+ mtime: Date | null;
123
+ dev: number | null;
124
+ ino: number | null;
125
+ }
126
+
84
127
  export interface IOciExecutorDependencies {
85
128
  commandRunner?: TOciRuntimeCommandRunner;
86
129
  runtimeEnvironment?: Record<string, string>;
@@ -88,17 +131,17 @@ export interface IOciExecutorDependencies {
88
131
  probeTmpfs?: (helperPath: string) => Promise<number>;
89
132
  randomId?: () => string;
90
133
  now?: () => number;
91
- makeTempDir?: (options: Deno.MakeTempOptions) => Promise<string>;
134
+ makeTempDir?: (options: IRuntimeMakeTempOptions) => Promise<string>;
92
135
  chmod?: (path: string, mode: number) => Promise<void>;
93
- remove?: (path: string, options?: Deno.RemoveOptions) => Promise<void>;
136
+ remove?: (path: string, options?: IRuntimeRemoveOptions) => Promise<void>;
94
137
  }
95
138
 
96
139
  export interface IHostTmpfsProbeScavengerDependencies {
97
140
  getUid?: () => number | undefined;
98
141
  now?: () => number;
99
- readDir?: (path: string) => AsyncIterable<Deno.DirEntry>;
100
- lstat?: (path: string) => Promise<Deno.FileInfo>;
101
- remove?: (path: string, options?: Deno.RemoveOptions) => Promise<void>;
142
+ readDir?: (path: string) => AsyncIterable<IRuntimeDirectoryEntry>;
143
+ lstat?: (path: string) => Promise<IRuntimeFileInfo>;
144
+ remove?: (path: string, options?: IRuntimeRemoveOptions) => Promise<void>;
102
145
  }
103
146
 
104
147
  export interface IWorkspaceVolumeLimits {
@@ -339,7 +382,11 @@ const decode = (value: Uint8Array): string => new TextDecoder().decode(value).tr
339
382
  export const scavengeHostTmpfsProbes = async (
340
383
  directory = '/dev/shm',
341
384
  dependencies: IHostTmpfsProbeScavengerDependencies = {},
385
+ runtimeProbeOwnerId?: string,
342
386
  ): Promise<void> => {
387
+ if (!runtimeProbeOwnerId || !runtimeProbeOwnerIdPattern.test(runtimeProbeOwnerId)) {
388
+ return;
389
+ }
343
390
  let uid: number | null | undefined;
344
391
  try {
345
392
  uid = dependencies.getUid
@@ -356,14 +403,14 @@ export const scavengeHostTmpfsProbes = async (
356
403
  const readDir = dependencies.readDir ?? ((path: string) => Deno.readDir(path));
357
404
  const lstat = dependencies.lstat ?? ((path: string) => Deno.lstat(path));
358
405
  const remove = dependencies.remove ?? ((path, options) => Deno.remove(path, options));
359
- const isEligible = (stat: Deno.FileInfo): boolean =>
406
+ const isEligible = (stat: IRuntimeFileInfo): boolean =>
360
407
  stat.isDirectory && !stat.isSymlink && stat.uid === uid && stat.mtime !== null &&
361
408
  now() - stat.mtime.getTime() > hostTmpfsProbeMaximumAgeMs;
362
409
 
363
410
  for await (const entry of readDir(directory)) {
364
- if (!hostTmpfsProbeNamePattern.test(entry.name)) continue;
411
+ if (hostTmpfsProbeNamePattern.exec(entry.name)?.[1] !== runtimeProbeOwnerId) continue;
365
412
  const path = join(directory, entry.name);
366
- let initial: Deno.FileInfo;
413
+ let initial: IRuntimeFileInfo;
367
414
  try {
368
415
  initial = await lstat(path);
369
416
  } catch (error) {
@@ -371,7 +418,7 @@ export const scavengeHostTmpfsProbes = async (
371
418
  throw error;
372
419
  }
373
420
  if (!isEligible(initial) || initial.dev === null || initial.ino === null) continue;
374
- let current: Deno.FileInfo;
421
+ let current: IRuntimeFileInfo;
375
422
  try {
376
423
  current = await lstat(path);
377
424
  } catch (error) {
@@ -855,12 +902,118 @@ const mapArchitecture = (
855
902
  }
856
903
  };
857
904
 
858
- const sha256File = async (path: string): Promise<string> => {
859
- const bytes = await Deno.readFile(path);
905
+ const sha256Bytes = async (bytes: Uint8Array<ArrayBuffer>): Promise<string> => {
860
906
  const digest = await crypto.subtle.digest('SHA-256', bytes);
861
907
  return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
862
908
  };
863
909
 
910
+ const sameFileIdentity = (first: Deno.FileInfo, second: Deno.FileInfo): boolean =>
911
+ (first.dev === null || second.dev === first.dev) &&
912
+ (first.ino === null || second.ino === first.ino);
913
+
914
+ const withFsFile = async <T>(
915
+ file: Deno.FsFile,
916
+ operation: (file: Deno.FsFile) => Promise<T>,
917
+ closeFailureMessage: string,
918
+ ): Promise<T> => {
919
+ let result: T | undefined;
920
+ let operationError: unknown;
921
+ let hasOperationError = false;
922
+ try {
923
+ result = await operation(file);
924
+ } catch (error) {
925
+ operationError = error;
926
+ hasOperationError = true;
927
+ }
928
+ let closeError: unknown;
929
+ let hasCloseError = false;
930
+ try {
931
+ file.close();
932
+ } catch (error) {
933
+ closeError = error;
934
+ hasCloseError = true;
935
+ }
936
+ if (hasCloseError) {
937
+ throw new ResourceCleanupError(closeFailureMessage, [
938
+ ...(hasOperationError ? [operationError] : []),
939
+ closeError,
940
+ ]);
941
+ }
942
+ if (hasOperationError) throw operationError;
943
+ return result as T;
944
+ };
945
+
946
+ const readBoundedRegularFile = async (
947
+ path: string,
948
+ maximumBytes: number,
949
+ label: string,
950
+ ): Promise<{ bytes: Uint8Array<ArrayBuffer>; stat: Deno.FileInfo }> => {
951
+ const pathStat = await Deno.lstat(path);
952
+ if (
953
+ !pathStat.isFile || pathStat.isSymlink || pathStat.size < 1 || pathStat.size > maximumBytes
954
+ ) {
955
+ throw new RunnerError(`${label} must be a bounded regular file`);
956
+ }
957
+ const file = await Deno.open(path, { read: true });
958
+ return await withFsFile(
959
+ file,
960
+ async (openedFile) => {
961
+ const before = await openedFile.stat();
962
+ if (
963
+ !before.isFile || before.size < 1 || before.size > maximumBytes ||
964
+ before.size !== pathStat.size || !sameFileIdentity(pathStat, before)
965
+ ) {
966
+ throw new RunnerError(`${label} changed while it was opened`);
967
+ }
968
+ const bytes = new Uint8Array(before.size);
969
+ let offset = 0;
970
+ while (offset < bytes.byteLength) {
971
+ const read = await openedFile.read(bytes.subarray(offset));
972
+ if (read === null || read <= 0) {
973
+ throw new RunnerError(`${label} changed while it was read`);
974
+ }
975
+ offset += read;
976
+ }
977
+ const overflow = await openedFile.read(new Uint8Array(1));
978
+ const after = await openedFile.stat();
979
+ const currentPathStat = await Deno.lstat(path);
980
+ if (
981
+ overflow !== null || !after.isFile || after.size !== before.size ||
982
+ !currentPathStat.isFile || currentPathStat.isSymlink ||
983
+ currentPathStat.size !== before.size || !sameFileIdentity(before, after) ||
984
+ !sameFileIdentity(after, currentPathStat)
985
+ ) {
986
+ throw new RunnerError(`${label} changed while it was read`);
987
+ }
988
+ return { bytes, stat: after };
989
+ },
990
+ `${label} read and close failed`,
991
+ );
992
+ };
993
+
994
+ const sha256File = async (path: string): Promise<string> =>
995
+ await sha256Bytes(
996
+ (await readBoundedRegularFile(path, workspaceHelperMaximumBytes, 'Workspace helper')).bytes,
997
+ );
998
+
999
+ const writeAll = async (file: Deno.FsFile, bytes: Uint8Array): Promise<void> => {
1000
+ let offset = 0;
1001
+ while (offset < bytes.byteLength) {
1002
+ const written = await file.write(bytes.subarray(offset));
1003
+ if (written <= 0) throw new RunnerError('Workspace helper write made no progress');
1004
+ offset += written;
1005
+ }
1006
+ };
1007
+
1008
+ const lstatIfPresent = async (path: string): Promise<Deno.FileInfo | undefined> => {
1009
+ try {
1010
+ return await Deno.lstat(path);
1011
+ } catch (error) {
1012
+ if (error instanceof Deno.errors.NotFound) return undefined;
1013
+ throw error;
1014
+ }
1015
+ };
1016
+
864
1017
  const safeSelections = (selections: string[]): string[] => {
865
1018
  if (selections.length === 0 || selections.length > 32) {
866
1019
  throw new ProtocolError('Workspace export must select between 1 and 32 paths');
@@ -933,10 +1086,13 @@ export class OciExecutor implements IJobExecutor {
933
1086
  private readonly randomId: () => string;
934
1087
  private readonly now: () => number;
935
1088
  private readonly resolveHelperPathImplementation: (target: TOciHelperTarget) => Promise<string>;
936
- private readonly probeTmpfsImplementation: (helperPath: string) => Promise<number>;
937
- private readonly makeTempDir: (options: Deno.MakeTempOptions) => Promise<string>;
1089
+ private readonly probeTmpfsImplementation: (
1090
+ helperPath: string,
1091
+ runtimeProbeOwnerId: string,
1092
+ ) => Promise<number>;
1093
+ private readonly makeTempDir: (options: IRuntimeMakeTempOptions) => Promise<string>;
938
1094
  private readonly chmod: (path: string, mode: number) => Promise<void>;
939
- private readonly remove: (path: string, options?: Deno.RemoveOptions) => Promise<void>;
1095
+ private readonly remove: (path: string, options?: IRuntimeRemoveOptions) => Promise<void>;
940
1096
  private runtimeFacts?: IOciRuntimeFacts;
941
1097
  private readonly preparedLeases = new Map<string, PreparedOciLease>();
942
1098
 
@@ -952,8 +1108,9 @@ export class OciExecutor implements IJobExecutor {
952
1108
  this.now = dependencies.now ?? Date.now;
953
1109
  this.resolveHelperPathImplementation = dependencies.resolveHelperPath ??
954
1110
  ((target) => this.resolvePackagedHelper(target));
955
- this.probeTmpfsImplementation = dependencies.probeTmpfs ??
956
- ((path) => this.probeHostTmpfs(path));
1111
+ this.probeTmpfsImplementation = dependencies.probeTmpfs
1112
+ ? (path) => dependencies.probeTmpfs!(path)
1113
+ : (path, runtimeProbeOwnerId) => this.probeHostTmpfs(path, runtimeProbeOwnerId);
957
1114
  this.makeTempDir = dependencies.makeTempDir ?? ((options) => Deno.makeTempDir(options));
958
1115
  this.chmod = dependencies.chmod ?? ((path, mode) => Deno.chmod(path, mode));
959
1116
  this.remove = dependencies.remove ?? ((path, options) => Deno.remove(path, options));
@@ -1074,7 +1231,12 @@ export class OciExecutor implements IJobExecutor {
1074
1231
  throw new RunnerError('Runner policy requires a rootless OCI engine');
1075
1232
  }
1076
1233
  const architecture = mapArchitecture(architectureValue);
1077
- const helperPath = await this.resolveHelperPathImplementation(architecture.helperTarget);
1234
+ const helperSourcePath = await this.resolveHelperPathImplementation(architecture.helperTarget);
1235
+ const helperPath = await this.materializeWorkspaceHelper(
1236
+ helperSourcePath,
1237
+ architecture.helperTarget,
1238
+ );
1239
+ const runtimeProbeOwnerId = await this.ensureRuntimeProbeOwner();
1078
1240
  const helperStat = await Deno.stat(helperPath).catch((error) => {
1079
1241
  throw new RunnerError('Workspace helper is unavailable', { cause: error });
1080
1242
  });
@@ -1094,9 +1256,9 @@ export class OciExecutor implements IJobExecutor {
1094
1256
  if (helperArchitecture.helperTarget !== architecture.helperTarget) {
1095
1257
  throw new RunnerError('Workspace helper architecture does not match the OCI engine');
1096
1258
  }
1097
- const workspaceBlockSize = await this.probeTmpfsImplementation(helperPath);
1098
- await this.reconcileRuntimeProbeVolumes();
1099
- await this.probeRuntimeVolume(workspaceBlockSize);
1259
+ const workspaceBlockSize = await this.probeTmpfsImplementation(helperPath, runtimeProbeOwnerId);
1260
+ await this.reconcileRuntimeProbeVolumes(runtimeProbeOwnerId);
1261
+ await this.probeRuntimeVolume(workspaceBlockSize, runtimeProbeOwnerId);
1100
1262
  const facts: IOciRuntimeFacts = {
1101
1263
  runtime,
1102
1264
  endpoint,
@@ -1670,13 +1832,466 @@ export class OciExecutor implements IJobExecutor {
1670
1832
  );
1671
1833
  }
1672
1834
 
1673
- private async probeHostTmpfs(helperPath: string): Promise<number> {
1835
+ private async materializeWorkspaceHelper(
1836
+ sourcePathArg: string,
1837
+ targetArg: TOciHelperTarget,
1838
+ ): Promise<string> {
1839
+ const sourcePath = await Deno.realPath(sourcePathArg).catch((error) => {
1840
+ throw new RunnerError('Workspace helper source is unavailable', { cause: error });
1841
+ });
1842
+ const sourceBytes = (
1843
+ await readBoundedRegularFile(
1844
+ sourcePath,
1845
+ workspaceHelperMaximumBytes,
1846
+ 'Workspace helper source',
1847
+ )
1848
+ ).bytes;
1849
+ const sourceDigest = await sha256Bytes(sourceBytes);
1850
+ const helperDirectory = await this.ensureWorkspaceHelperDirectory();
1851
+ const destinationName = `runnerworkspace_${targetArg}_musl_${sourceDigest}`;
1852
+ const destinationPath = join(helperDirectory, destinationName);
1853
+ return await this.withWorkspaceHelperLock(helperDirectory, async () => {
1854
+ const temporaryUsage = await this.scavengeWorkspaceHelpers(
1855
+ helperDirectory,
1856
+ destinationName,
1857
+ sourceDigest,
1858
+ );
1859
+ if (await lstatIfPresent(destinationPath)) {
1860
+ await this.validateMaterializedWorkspaceHelper(destinationPath, sourceDigest);
1861
+ return await Deno.realPath(destinationPath);
1862
+ }
1863
+ if (
1864
+ temporaryUsage.count >= workspaceHelperTemporaryMaximumCount ||
1865
+ temporaryUsage.bytes > workspaceHelperTemporaryMaximumBytes - sourceBytes.byteLength
1866
+ ) {
1867
+ throw new RunnerError('Workspace helper temporary storage limit is exhausted');
1868
+ }
1869
+
1870
+ const temporaryPath = join(
1871
+ helperDirectory,
1872
+ `.${crypto.randomUUID()}.workspace-helper.tmp`,
1873
+ );
1874
+ try {
1875
+ const temporaryFile = await Deno.open(temporaryPath, {
1876
+ write: true,
1877
+ createNew: true,
1878
+ mode: 0o600,
1879
+ });
1880
+ await withFsFile(
1881
+ temporaryFile,
1882
+ async (openedFile) => {
1883
+ await writeAll(openedFile, sourceBytes);
1884
+ await openedFile.sync();
1885
+ },
1886
+ 'Workspace helper write and close failed',
1887
+ );
1888
+ await this.validateMaterializedWorkspaceHelper(temporaryPath, sourceDigest, true);
1889
+ try {
1890
+ await Deno.link(temporaryPath, destinationPath);
1891
+ } catch (error) {
1892
+ if (!(error instanceof Deno.errors.AlreadyExists)) throw error;
1893
+ await this.validateMaterializedWorkspaceHelper(destinationPath, sourceDigest);
1894
+ }
1895
+ await Deno.remove(temporaryPath);
1896
+ await this.validateMaterializedWorkspaceHelper(destinationPath, sourceDigest);
1897
+ await this.syncDirectory(helperDirectory);
1898
+ return await Deno.realPath(destinationPath);
1899
+ } catch (error) {
1900
+ try {
1901
+ await Deno.remove(temporaryPath);
1902
+ } catch (cleanupError) {
1903
+ if (!(cleanupError instanceof Deno.errors.NotFound)) {
1904
+ throw new ResourceCleanupError('Workspace helper setup and cleanup failed', [
1905
+ error,
1906
+ cleanupError,
1907
+ ]);
1908
+ }
1909
+ }
1910
+ throw error;
1911
+ }
1912
+ });
1913
+ }
1914
+
1915
+ private async ensureWorkspaceHelperDirectory(): Promise<string> {
1916
+ const stateRoot = resolve(this.config.stateDirectory);
1917
+ await Deno.mkdir(stateRoot, { recursive: true, mode: 0o700 });
1918
+ const stateStat = await Deno.lstat(stateRoot);
1919
+ if (!stateStat.isDirectory || stateStat.isSymlink) {
1920
+ throw new RunnerError('Runner state directory must be a real directory');
1921
+ }
1922
+ if (Deno.build.os !== 'windows' && stateStat.mode !== null && (stateStat.mode & 0o077) !== 0) {
1923
+ throw new RunnerError('Runner state directory permissions are not private');
1924
+ }
1925
+
1926
+ const helperDirectory = join(stateRoot, workspaceHelperDirectoryName);
1927
+ try {
1928
+ await Deno.mkdir(helperDirectory, { mode: 0o700 });
1929
+ } catch (error) {
1930
+ if (!(error instanceof Deno.errors.AlreadyExists)) throw error;
1931
+ }
1932
+ const helperStat = await Deno.lstat(helperDirectory);
1933
+ if (!helperStat.isDirectory || helperStat.isSymlink) {
1934
+ throw new RunnerError('Workspace helper directory must be a real directory');
1935
+ }
1936
+ await Deno.chmod(helperDirectory, 0o700);
1937
+ const privateStat = await Deno.lstat(helperDirectory);
1938
+ if (
1939
+ !privateStat.isDirectory || privateStat.isSymlink ||
1940
+ (Deno.build.os !== 'windows' && privateStat.mode !== null &&
1941
+ (privateStat.mode & 0o777) !== 0o700)
1942
+ ) {
1943
+ throw new RunnerError('Workspace helper directory permissions are not private');
1944
+ }
1945
+ await this.syncDirectory(stateRoot);
1946
+ return await Deno.realPath(helperDirectory);
1947
+ }
1948
+
1949
+ private async ensureRuntimeProbeOwner(): Promise<string> {
1950
+ const helperDirectory = await this.ensureWorkspaceHelperDirectory();
1951
+ return await this.withWorkspaceHelperLock(helperDirectory, async () => {
1952
+ const markers: Array<{ name: string; ownerId: string }> = [];
1953
+ for await (const entry of Deno.readDir(helperDirectory)) {
1954
+ if (!entry.name.startsWith(runtimeProbeOwnerMarkerPrefix)) continue;
1955
+ const match = runtimeProbeOwnerMarkerPattern.exec(entry.name);
1956
+ if (!match) throw new RunnerError('Runtime probe owner marker name is invalid');
1957
+ markers.push({ name: entry.name, ownerId: match[1] });
1958
+ }
1959
+ if (markers.length > 1) {
1960
+ throw new RunnerError('Runner state contains multiple runtime probe owner markers');
1961
+ }
1962
+ if (markers.length === 1) {
1963
+ const marker = markers[0];
1964
+ await this.validateRuntimeProbeOwnerMarker(join(helperDirectory, marker.name));
1965
+ return marker.ownerId;
1966
+ }
1967
+
1968
+ const ownerId = this.randomHex();
1969
+ const markerPath = join(
1970
+ helperDirectory,
1971
+ `${runtimeProbeOwnerMarkerPrefix}${ownerId}`,
1972
+ );
1973
+ const markerFile = await Deno.open(markerPath, {
1974
+ read: true,
1975
+ write: true,
1976
+ createNew: true,
1977
+ mode: 0o600,
1978
+ });
1979
+ await withFsFile(
1980
+ markerFile,
1981
+ async (openedMarkerFile) => await openedMarkerFile.sync(),
1982
+ 'Runtime probe owner marker sync and close failed',
1983
+ );
1984
+ await this.validateRuntimeProbeOwnerMarker(markerPath);
1985
+ await this.syncDirectory(helperDirectory);
1986
+ return ownerId;
1987
+ });
1988
+ }
1989
+
1990
+ private async validateRuntimeProbeOwnerMarker(pathArg: string): Promise<void> {
1991
+ const before = await Deno.lstat(pathArg);
1992
+ if (
1993
+ !before.isFile || before.isSymlink || before.size !== 0 ||
1994
+ (Deno.build.os !== 'windows' && before.nlink !== null && before.nlink !== 1) ||
1995
+ (Deno.build.os !== 'windows' && before.mode !== null &&
1996
+ (before.mode & 0o7777) !== 0o600)
1997
+ ) {
1998
+ throw new RunnerError('Runtime probe owner marker must be a private single-link file');
1999
+ }
2000
+ const markerFile = await Deno.open(pathArg, { read: true });
2001
+ await withFsFile(
2002
+ markerFile,
2003
+ async (openedMarkerFile) => {
2004
+ const descriptorStat = await openedMarkerFile.stat();
2005
+ const current = await Deno.lstat(pathArg);
2006
+ if (
2007
+ !descriptorStat.isFile || !current.isFile || current.isSymlink ||
2008
+ !sameFileIdentity(before, descriptorStat) || !sameFileIdentity(before, current) ||
2009
+ (Deno.build.os !== 'windows' && descriptorStat.nlink !== null &&
2010
+ descriptorStat.nlink !== 1) ||
2011
+ (Deno.build.os !== 'windows' && current.nlink !== null && current.nlink !== 1) ||
2012
+ (Deno.build.os !== 'windows' && current.mode !== null &&
2013
+ (current.mode & 0o7777) !== 0o600)
2014
+ ) {
2015
+ throw new RunnerError('Runtime probe owner marker changed during validation');
2016
+ }
2017
+ },
2018
+ 'Runtime probe owner marker validation and close failed',
2019
+ );
2020
+ }
2021
+
2022
+ private async withWorkspaceHelperLock<T>(
2023
+ helperDirectoryArg: string,
2024
+ operation: () => Promise<T>,
2025
+ ): Promise<T> {
2026
+ const lockPath = join(helperDirectoryArg, workspaceHelperLockName);
2027
+ const lockFile = await Deno.open(lockPath, {
2028
+ read: true,
2029
+ write: true,
2030
+ create: true,
2031
+ mode: 0o600,
2032
+ });
2033
+ return await withFsFile(
2034
+ lockFile,
2035
+ async (openedLockFile) => {
2036
+ const initialStat = await Deno.lstat(lockPath);
2037
+ if (
2038
+ !initialStat.isFile || initialStat.isSymlink ||
2039
+ (Deno.build.os !== 'windows' && initialStat.nlink !== null && initialStat.nlink !== 1)
2040
+ ) {
2041
+ throw new RunnerError('Workspace helper lock must be a regular file');
2042
+ }
2043
+ await Deno.chmod(lockPath, 0o600);
2044
+ const pathStat = await Deno.lstat(lockPath);
2045
+ const descriptorStat = await openedLockFile.stat();
2046
+ if (
2047
+ !pathStat.isFile || pathStat.isSymlink || !descriptorStat.isFile ||
2048
+ !sameFileIdentity(pathStat, descriptorStat) ||
2049
+ (Deno.build.os !== 'windows' && pathStat.mode !== null &&
2050
+ (pathStat.mode & 0o777) !== 0o600)
2051
+ ) {
2052
+ throw new RunnerError('Workspace helper lock changed while it was opened');
2053
+ }
2054
+
2055
+ const lockDeadline = performance.now() + workspaceHelperLockTimeoutMs;
2056
+ while (!(await openedLockFile.tryLock(true))) {
2057
+ if (performance.now() >= lockDeadline) {
2058
+ throw new RunnerError('Timed out waiting for the workspace helper lock');
2059
+ }
2060
+ await new Promise((resolvePromise) =>
2061
+ setTimeout(resolvePromise, workspaceHelperLockRetryMs)
2062
+ );
2063
+ }
2064
+
2065
+ let result: T | undefined;
2066
+ let operationError: unknown;
2067
+ let hasOperationError = false;
2068
+ try {
2069
+ result = await operation();
2070
+ } catch (error) {
2071
+ operationError = error;
2072
+ hasOperationError = true;
2073
+ }
2074
+ let unlockError: unknown;
2075
+ try {
2076
+ await openedLockFile.unlock();
2077
+ } catch (error) {
2078
+ unlockError = error;
2079
+ }
2080
+ if (unlockError !== undefined) {
2081
+ throw new ResourceCleanupError(
2082
+ hasOperationError
2083
+ ? 'Workspace helper operation and lock release failed'
2084
+ : 'Unable to release workspace helper lock',
2085
+ [...(hasOperationError ? [operationError] : []), unlockError],
2086
+ );
2087
+ }
2088
+ if (hasOperationError) throw operationError;
2089
+ return result as T;
2090
+ },
2091
+ 'Workspace helper lock operation and close failed',
2092
+ );
2093
+ }
2094
+
2095
+ private async scavengeWorkspaceHelpers(
2096
+ helperDirectoryArg: string,
2097
+ currentDestinationNameArg: string,
2098
+ currentDigestArg: string,
2099
+ ): Promise<{ count: number; bytes: number }> {
2100
+ const finalFiles: Array<{ name: string; path: string; stat: Deno.FileInfo }> = [];
2101
+ let recentTemporaryCount = 0;
2102
+ let recentTemporaryBytes = 0;
2103
+ let removed = false;
2104
+ for await (const entry of Deno.readDir(helperDirectoryArg)) {
2105
+ const path = join(helperDirectoryArg, entry.name);
2106
+ if (workspaceHelperTemporaryNamePattern.test(entry.name)) {
2107
+ const stat = await lstatIfPresent(path);
2108
+ if (!stat) continue;
2109
+ if (
2110
+ !stat.isFile || stat.isSymlink || stat.size > workspaceHelperMaximumBytes ||
2111
+ stat.mtime === null
2112
+ ) {
2113
+ throw new RunnerError('Workspace helper temporary path must be a bounded regular file');
2114
+ }
2115
+ if (
2116
+ await this.recoverInterruptedWorkspaceHelperPublication(
2117
+ path,
2118
+ stat,
2119
+ join(helperDirectoryArg, currentDestinationNameArg),
2120
+ currentDigestArg,
2121
+ )
2122
+ ) {
2123
+ removed = true;
2124
+ continue;
2125
+ }
2126
+ if (this.now() - stat.mtime.getTime() >= workspaceHelperTemporaryMaximumAgeMs) {
2127
+ const currentStat = await lstatIfPresent(path);
2128
+ if (!currentStat) continue;
2129
+ if (!sameFileIdentity(stat, currentStat)) {
2130
+ throw new RunnerError('Workspace helper temporary path changed during cleanup');
2131
+ }
2132
+ try {
2133
+ await Deno.remove(path);
2134
+ removed = true;
2135
+ } catch (error) {
2136
+ if (!(error instanceof Deno.errors.NotFound)) throw error;
2137
+ }
2138
+ continue;
2139
+ }
2140
+ recentTemporaryCount++;
2141
+ recentTemporaryBytes += stat.size;
2142
+ continue;
2143
+ }
2144
+ if (workspaceHelperFinalNamePattern.test(entry.name)) {
2145
+ const stat = await lstatIfPresent(path);
2146
+ if (!stat) continue;
2147
+ if (
2148
+ !stat.isFile || stat.isSymlink || stat.size < 1 ||
2149
+ stat.size > workspaceHelperMaximumBytes || stat.mtime === null
2150
+ ) {
2151
+ throw new RunnerError('Retained workspace helper must be a bounded regular file');
2152
+ }
2153
+ finalFiles.push({ name: entry.name, path, stat });
2154
+ }
2155
+ }
2156
+
2157
+ finalFiles.sort((first, second) => {
2158
+ if (first.name === currentDestinationNameArg) return -1;
2159
+ if (second.name === currentDestinationNameArg) return 1;
2160
+ return (second.stat.mtime?.getTime() ?? 0) - (first.stat.mtime?.getTime() ?? 0) ||
2161
+ first.name.localeCompare(second.name);
2162
+ });
2163
+ const retainedFinalCount = finalFiles.some((entry) => entry.name === currentDestinationNameArg)
2164
+ ? workspaceHelperRetainedFinalCount
2165
+ : workspaceHelperRetainedFinalCount - 1;
2166
+ for (const stale of finalFiles.slice(retainedFinalCount)) {
2167
+ const currentStat = await lstatIfPresent(stale.path);
2168
+ if (!currentStat) continue;
2169
+ if (!sameFileIdentity(stale.stat, currentStat)) {
2170
+ throw new RunnerError('Retained workspace helper changed during cleanup');
2171
+ }
2172
+ try {
2173
+ await Deno.remove(stale.path);
2174
+ removed = true;
2175
+ } catch (error) {
2176
+ if (!(error instanceof Deno.errors.NotFound)) throw error;
2177
+ }
2178
+ }
2179
+ if (removed) await this.syncDirectory(helperDirectoryArg);
2180
+ return { count: recentTemporaryCount, bytes: recentTemporaryBytes };
2181
+ }
2182
+
2183
+ private async recoverInterruptedWorkspaceHelperPublication(
2184
+ temporaryPathArg: string,
2185
+ temporaryStatArg: Deno.FileInfo,
2186
+ destinationPathArg: string,
2187
+ expectedDigestArg: string,
2188
+ ): Promise<boolean> {
2189
+ if (
2190
+ Deno.build.os === 'windows' || temporaryStatArg.nlink === null ||
2191
+ temporaryStatArg.nlink !== 2
2192
+ ) {
2193
+ return false;
2194
+ }
2195
+ const destinationStat = await lstatIfPresent(destinationPathArg);
2196
+ if (!destinationStat || !sameFileIdentity(temporaryStatArg, destinationStat)) return false;
2197
+ if (
2198
+ !destinationStat.isFile || destinationStat.isSymlink || destinationStat.size < 1 ||
2199
+ destinationStat.size > workspaceHelperMaximumBytes || destinationStat.nlink !== 2 ||
2200
+ destinationStat.mode === null ||
2201
+ (destinationStat.mode & 0o7777) !== workspaceHelperExecutableMode
2202
+ ) {
2203
+ throw new RunnerError('Interrupted workspace helper publication is invalid');
2204
+ }
2205
+ const validated = await readBoundedRegularFile(
2206
+ temporaryPathArg,
2207
+ workspaceHelperMaximumBytes,
2208
+ 'Interrupted workspace helper publication',
2209
+ );
2210
+ if (
2211
+ !sameFileIdentity(temporaryStatArg, validated.stat) || validated.stat.nlink !== 2 ||
2212
+ validated.stat.mode === null ||
2213
+ (validated.stat.mode & 0o7777) !== workspaceHelperExecutableMode ||
2214
+ await sha256Bytes(validated.bytes) !== expectedDigestArg
2215
+ ) {
2216
+ throw new RunnerError('Interrupted workspace helper publication changed during validation');
2217
+ }
2218
+ const currentTemporary = await Deno.lstat(temporaryPathArg);
2219
+ const currentDestination = await Deno.lstat(destinationPathArg);
2220
+ if (
2221
+ !sameFileIdentity(temporaryStatArg, currentTemporary) ||
2222
+ !sameFileIdentity(temporaryStatArg, currentDestination) ||
2223
+ currentTemporary.nlink !== 2 || currentDestination.nlink !== 2
2224
+ ) {
2225
+ throw new RunnerError('Interrupted workspace helper publication changed before recovery');
2226
+ }
2227
+ await Deno.remove(temporaryPathArg);
2228
+ const recoveredDestination = await Deno.lstat(destinationPathArg);
2229
+ if (
2230
+ !sameFileIdentity(destinationStat, recoveredDestination) ||
2231
+ recoveredDestination.nlink !== 1 || recoveredDestination.mode === null ||
2232
+ (recoveredDestination.mode & 0o7777) !== workspaceHelperExecutableMode
2233
+ ) {
2234
+ throw new RunnerError('Interrupted workspace helper publication did not recover safely');
2235
+ }
2236
+ return true;
2237
+ }
2238
+
2239
+ private async validateMaterializedWorkspaceHelper(
2240
+ pathArg: string,
2241
+ expectedDigestArg: string,
2242
+ setExecutableModeArg = false,
2243
+ ): Promise<void> {
2244
+ const before = await Deno.lstat(pathArg);
2245
+ if (
2246
+ !before.isFile || before.isSymlink || before.size < 1 ||
2247
+ before.size > workspaceHelperMaximumBytes ||
2248
+ (Deno.build.os !== 'windows' && before.nlink !== null && before.nlink !== 1)
2249
+ ) {
2250
+ throw new RunnerError('Materialized workspace helper must be a bounded regular file');
2251
+ }
2252
+ if (setExecutableModeArg) await Deno.chmod(pathArg, workspaceHelperExecutableMode);
2253
+ const validated = await readBoundedRegularFile(
2254
+ pathArg,
2255
+ workspaceHelperMaximumBytes,
2256
+ 'Materialized workspace helper',
2257
+ );
2258
+ if (
2259
+ !sameFileIdentity(before, validated.stat) ||
2260
+ (Deno.build.os !== 'windows' && validated.stat.nlink !== null &&
2261
+ validated.stat.nlink !== 1) ||
2262
+ (Deno.build.os !== 'windows' && validated.stat.mode !== null &&
2263
+ (validated.stat.mode & 0o7777) !== workspaceHelperExecutableMode)
2264
+ ) {
2265
+ throw new RunnerError('Materialized workspace helper changed during validation');
2266
+ }
2267
+ const digest = await sha256Bytes(validated.bytes);
2268
+ if (digest !== expectedDigestArg) {
2269
+ throw new RunnerError('Materialized workspace helper digest does not match its source');
2270
+ }
2271
+ }
2272
+
2273
+ private async syncDirectory(pathArg: string): Promise<void> {
2274
+ const directory = await Deno.open(pathArg, { read: true });
2275
+ await withFsFile(
2276
+ directory,
2277
+ async (openedDirectory) => await openedDirectory.sync(),
2278
+ 'Workspace helper directory sync and close failed',
2279
+ );
2280
+ }
2281
+
2282
+ private async probeHostTmpfs(
2283
+ helperPath: string,
2284
+ runtimeProbeOwnerId: string,
2285
+ ): Promise<number> {
1674
2286
  let path: string | undefined;
1675
2287
  let blockSize: number | undefined;
1676
2288
  let operationError: unknown;
1677
2289
  try {
1678
- await scavengeHostTmpfsProbes();
1679
- path = await Deno.makeTempDir({ dir: '/dev/shm', prefix: 'foss-ci-probe-' });
2290
+ await scavengeHostTmpfsProbes('/dev/shm', {}, runtimeProbeOwnerId);
2291
+ path = await Deno.makeTempDir({
2292
+ dir: '/dev/shm',
2293
+ prefix: `foss-ci-probe-${runtimeProbeOwnerId}-`,
2294
+ });
1680
2295
  const before = await this.readFilesystemProbe(helperPath, path);
1681
2296
  const first = join(path, 'first');
1682
2297
  const second = join(path, 'second');
@@ -1740,7 +2355,7 @@ export class OciExecutor implements IJobExecutor {
1740
2355
  return { blockSize, availableInodes };
1741
2356
  }
1742
2357
 
1743
- private async reconcileRuntimeProbeVolumes(): Promise<void> {
2358
+ private async reconcileRuntimeProbeVolumes(runtimeProbeOwnerId: string): Promise<void> {
1744
2359
  const listed = await this.runRuntime([
1745
2360
  'volume',
1746
2361
  'ls',
@@ -1748,6 +2363,8 @@ export class OciExecutor implements IJobExecutor {
1748
2363
  `label=${managedLabel}=true`,
1749
2364
  '--filter',
1750
2365
  `label=${runtimeProbeLabel}=true`,
2366
+ '--filter',
2367
+ `label=${runtimeProbeOwnerLabel}=${runtimeProbeOwnerId}`,
1751
2368
  '--format',
1752
2369
  '{{.Name}}',
1753
2370
  ]);
@@ -1768,6 +2385,7 @@ export class OciExecutor implements IJobExecutor {
1768
2385
  !isRecord(labelsValue) ||
1769
2386
  labelsValue[managedLabel] !== 'true' ||
1770
2387
  labelsValue[runtimeProbeLabel] !== 'true' ||
2388
+ labelsValue[runtimeProbeOwnerLabel] !== runtimeProbeOwnerId ||
1771
2389
  typeof createdAtValue !== 'string'
1772
2390
  ) {
1773
2391
  continue;
@@ -1783,7 +2401,10 @@ export class OciExecutor implements IJobExecutor {
1783
2401
  }
1784
2402
  }
1785
2403
 
1786
- private async probeRuntimeVolume(blockSize: number): Promise<void> {
2404
+ private async probeRuntimeVolume(
2405
+ blockSize: number,
2406
+ runtimeProbeOwnerId: string,
2407
+ ): Promise<void> {
1787
2408
  const limits = calculateWorkspaceVolumeLimits(probeVolumeBytes, probeVolumeEntries, blockSize);
1788
2409
  const name = this.createResourceName('volume');
1789
2410
  let possiblyExists = false;
@@ -1792,7 +2413,14 @@ export class OciExecutor implements IJobExecutor {
1792
2413
  try {
1793
2414
  possiblyExists = true;
1794
2415
  const result = await this.runRuntime(
1795
- this.volumeCreateArgs(name, limits, undefined, undefined, undefined, true),
2416
+ this.volumeCreateArgs(
2417
+ name,
2418
+ limits,
2419
+ undefined,
2420
+ undefined,
2421
+ undefined,
2422
+ runtimeProbeOwnerId,
2423
+ ),
1796
2424
  );
1797
2425
  requireSuccess(result, 'OCI runtime cannot create local tmpfs volumes');
1798
2426
  const inspected = await this.runRuntime(['volume', 'inspect', name]);
@@ -1847,7 +2475,7 @@ export class OciExecutor implements IJobExecutor {
1847
2475
  runnerId?: string,
1848
2476
  sessionId?: string,
1849
2477
  attemptId?: string,
1850
- runtimeProbe = false,
2478
+ runtimeProbeOwnerId?: string,
1851
2479
  ): string[] {
1852
2480
  validateGeneratedName(name, 'volume');
1853
2481
  const mountOptions = [
@@ -1873,8 +2501,18 @@ export class OciExecutor implements IJobExecutor {
1873
2501
  ];
1874
2502
  if (runnerId && sessionId && attemptId) {
1875
2503
  args.push(...labels(runnerId, sessionId, attemptId));
1876
- } else if (runtimeProbe) {
1877
- args.push('--label', `${managedLabel}=true`, '--label', `${runtimeProbeLabel}=true`);
2504
+ } else if (runtimeProbeOwnerId) {
2505
+ if (!/^[a-f0-9]{32}$/.test(runtimeProbeOwnerId)) {
2506
+ throw new RunnerError('Runtime probe owner ID is invalid');
2507
+ }
2508
+ args.push(
2509
+ '--label',
2510
+ `${managedLabel}=true`,
2511
+ '--label',
2512
+ `${runtimeProbeLabel}=true`,
2513
+ '--label',
2514
+ `${runtimeProbeOwnerLabel}=${runtimeProbeOwnerId}`,
2515
+ );
1878
2516
  }
1879
2517
  if (this.config.oci.runtime === 'podman') args.push('--opt', 'nocopy');
1880
2518
  args.push(name);