@ship.zone/runner 0.2.1 → 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;
@@ -365,7 +382,11 @@ const decode = (value: Uint8Array): string => new TextDecoder().decode(value).tr
365
382
  export const scavengeHostTmpfsProbes = async (
366
383
  directory = '/dev/shm',
367
384
  dependencies: IHostTmpfsProbeScavengerDependencies = {},
385
+ runtimeProbeOwnerId?: string,
368
386
  ): Promise<void> => {
387
+ if (!runtimeProbeOwnerId || !runtimeProbeOwnerIdPattern.test(runtimeProbeOwnerId)) {
388
+ return;
389
+ }
369
390
  let uid: number | null | undefined;
370
391
  try {
371
392
  uid = dependencies.getUid
@@ -387,7 +408,7 @@ export const scavengeHostTmpfsProbes = async (
387
408
  now() - stat.mtime.getTime() > hostTmpfsProbeMaximumAgeMs;
388
409
 
389
410
  for await (const entry of readDir(directory)) {
390
- if (!hostTmpfsProbeNamePattern.test(entry.name)) continue;
411
+ if (hostTmpfsProbeNamePattern.exec(entry.name)?.[1] !== runtimeProbeOwnerId) continue;
391
412
  const path = join(directory, entry.name);
392
413
  let initial: IRuntimeFileInfo;
393
414
  try {
@@ -881,12 +902,118 @@ const mapArchitecture = (
881
902
  }
882
903
  };
883
904
 
884
- const sha256File = async (path: string): Promise<string> => {
885
- const bytes = await Deno.readFile(path);
905
+ const sha256Bytes = async (bytes: Uint8Array<ArrayBuffer>): Promise<string> => {
886
906
  const digest = await crypto.subtle.digest('SHA-256', bytes);
887
907
  return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
888
908
  };
889
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
+
890
1017
  const safeSelections = (selections: string[]): string[] => {
891
1018
  if (selections.length === 0 || selections.length > 32) {
892
1019
  throw new ProtocolError('Workspace export must select between 1 and 32 paths');
@@ -959,7 +1086,10 @@ export class OciExecutor implements IJobExecutor {
959
1086
  private readonly randomId: () => string;
960
1087
  private readonly now: () => number;
961
1088
  private readonly resolveHelperPathImplementation: (target: TOciHelperTarget) => Promise<string>;
962
- private readonly probeTmpfsImplementation: (helperPath: string) => Promise<number>;
1089
+ private readonly probeTmpfsImplementation: (
1090
+ helperPath: string,
1091
+ runtimeProbeOwnerId: string,
1092
+ ) => Promise<number>;
963
1093
  private readonly makeTempDir: (options: IRuntimeMakeTempOptions) => Promise<string>;
964
1094
  private readonly chmod: (path: string, mode: number) => Promise<void>;
965
1095
  private readonly remove: (path: string, options?: IRuntimeRemoveOptions) => Promise<void>;
@@ -978,8 +1108,9 @@ export class OciExecutor implements IJobExecutor {
978
1108
  this.now = dependencies.now ?? Date.now;
979
1109
  this.resolveHelperPathImplementation = dependencies.resolveHelperPath ??
980
1110
  ((target) => this.resolvePackagedHelper(target));
981
- this.probeTmpfsImplementation = dependencies.probeTmpfs ??
982
- ((path) => this.probeHostTmpfs(path));
1111
+ this.probeTmpfsImplementation = dependencies.probeTmpfs
1112
+ ? (path) => dependencies.probeTmpfs!(path)
1113
+ : (path, runtimeProbeOwnerId) => this.probeHostTmpfs(path, runtimeProbeOwnerId);
983
1114
  this.makeTempDir = dependencies.makeTempDir ?? ((options) => Deno.makeTempDir(options));
984
1115
  this.chmod = dependencies.chmod ?? ((path, mode) => Deno.chmod(path, mode));
985
1116
  this.remove = dependencies.remove ?? ((path, options) => Deno.remove(path, options));
@@ -1100,7 +1231,12 @@ export class OciExecutor implements IJobExecutor {
1100
1231
  throw new RunnerError('Runner policy requires a rootless OCI engine');
1101
1232
  }
1102
1233
  const architecture = mapArchitecture(architectureValue);
1103
- 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();
1104
1240
  const helperStat = await Deno.stat(helperPath).catch((error) => {
1105
1241
  throw new RunnerError('Workspace helper is unavailable', { cause: error });
1106
1242
  });
@@ -1120,9 +1256,9 @@ export class OciExecutor implements IJobExecutor {
1120
1256
  if (helperArchitecture.helperTarget !== architecture.helperTarget) {
1121
1257
  throw new RunnerError('Workspace helper architecture does not match the OCI engine');
1122
1258
  }
1123
- const workspaceBlockSize = await this.probeTmpfsImplementation(helperPath);
1124
- await this.reconcileRuntimeProbeVolumes();
1125
- await this.probeRuntimeVolume(workspaceBlockSize);
1259
+ const workspaceBlockSize = await this.probeTmpfsImplementation(helperPath, runtimeProbeOwnerId);
1260
+ await this.reconcileRuntimeProbeVolumes(runtimeProbeOwnerId);
1261
+ await this.probeRuntimeVolume(workspaceBlockSize, runtimeProbeOwnerId);
1126
1262
  const facts: IOciRuntimeFacts = {
1127
1263
  runtime,
1128
1264
  endpoint,
@@ -1696,13 +1832,466 @@ export class OciExecutor implements IJobExecutor {
1696
1832
  );
1697
1833
  }
1698
1834
 
1699
- 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> {
1700
2286
  let path: string | undefined;
1701
2287
  let blockSize: number | undefined;
1702
2288
  let operationError: unknown;
1703
2289
  try {
1704
- await scavengeHostTmpfsProbes();
1705
- 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
+ });
1706
2295
  const before = await this.readFilesystemProbe(helperPath, path);
1707
2296
  const first = join(path, 'first');
1708
2297
  const second = join(path, 'second');
@@ -1766,7 +2355,7 @@ export class OciExecutor implements IJobExecutor {
1766
2355
  return { blockSize, availableInodes };
1767
2356
  }
1768
2357
 
1769
- private async reconcileRuntimeProbeVolumes(): Promise<void> {
2358
+ private async reconcileRuntimeProbeVolumes(runtimeProbeOwnerId: string): Promise<void> {
1770
2359
  const listed = await this.runRuntime([
1771
2360
  'volume',
1772
2361
  'ls',
@@ -1774,6 +2363,8 @@ export class OciExecutor implements IJobExecutor {
1774
2363
  `label=${managedLabel}=true`,
1775
2364
  '--filter',
1776
2365
  `label=${runtimeProbeLabel}=true`,
2366
+ '--filter',
2367
+ `label=${runtimeProbeOwnerLabel}=${runtimeProbeOwnerId}`,
1777
2368
  '--format',
1778
2369
  '{{.Name}}',
1779
2370
  ]);
@@ -1794,6 +2385,7 @@ export class OciExecutor implements IJobExecutor {
1794
2385
  !isRecord(labelsValue) ||
1795
2386
  labelsValue[managedLabel] !== 'true' ||
1796
2387
  labelsValue[runtimeProbeLabel] !== 'true' ||
2388
+ labelsValue[runtimeProbeOwnerLabel] !== runtimeProbeOwnerId ||
1797
2389
  typeof createdAtValue !== 'string'
1798
2390
  ) {
1799
2391
  continue;
@@ -1809,7 +2401,10 @@ export class OciExecutor implements IJobExecutor {
1809
2401
  }
1810
2402
  }
1811
2403
 
1812
- private async probeRuntimeVolume(blockSize: number): Promise<void> {
2404
+ private async probeRuntimeVolume(
2405
+ blockSize: number,
2406
+ runtimeProbeOwnerId: string,
2407
+ ): Promise<void> {
1813
2408
  const limits = calculateWorkspaceVolumeLimits(probeVolumeBytes, probeVolumeEntries, blockSize);
1814
2409
  const name = this.createResourceName('volume');
1815
2410
  let possiblyExists = false;
@@ -1818,7 +2413,14 @@ export class OciExecutor implements IJobExecutor {
1818
2413
  try {
1819
2414
  possiblyExists = true;
1820
2415
  const result = await this.runRuntime(
1821
- this.volumeCreateArgs(name, limits, undefined, undefined, undefined, true),
2416
+ this.volumeCreateArgs(
2417
+ name,
2418
+ limits,
2419
+ undefined,
2420
+ undefined,
2421
+ undefined,
2422
+ runtimeProbeOwnerId,
2423
+ ),
1822
2424
  );
1823
2425
  requireSuccess(result, 'OCI runtime cannot create local tmpfs volumes');
1824
2426
  const inspected = await this.runRuntime(['volume', 'inspect', name]);
@@ -1873,7 +2475,7 @@ export class OciExecutor implements IJobExecutor {
1873
2475
  runnerId?: string,
1874
2476
  sessionId?: string,
1875
2477
  attemptId?: string,
1876
- runtimeProbe = false,
2478
+ runtimeProbeOwnerId?: string,
1877
2479
  ): string[] {
1878
2480
  validateGeneratedName(name, 'volume');
1879
2481
  const mountOptions = [
@@ -1899,8 +2501,18 @@ export class OciExecutor implements IJobExecutor {
1899
2501
  ];
1900
2502
  if (runnerId && sessionId && attemptId) {
1901
2503
  args.push(...labels(runnerId, sessionId, attemptId));
1902
- } else if (runtimeProbe) {
1903
- 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
+ );
1904
2516
  }
1905
2517
  if (this.config.oci.runtime === 'podman') args.push('--opt', 'nocopy');
1906
2518
  args.push(name);