@defrex/autobuild 1.15.0 → 1.16.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.
@@ -884,32 +884,40 @@ async function runSystemProvisioning(
884
884
  ): Promise<string[]> {
885
885
  const completed: string[] = []
886
886
  for (const step of steps) {
887
- const result = (await sandbox.runCommand({
888
- cmd: 'sh',
889
- args: ['-c', step.command],
890
- cwd: VERCEL_WORKSPACE_PATH,
891
- sudo: true,
892
- ...(signal === undefined ? {} : { signal }),
893
- })) as VercelCommand
894
- if (result.exitCode !== 0) {
895
- const [stdout, stderr] = await Promise.all([
896
- result.stdout?.() ?? Promise.resolve(''),
897
- result.stderr?.() ?? Promise.resolve(''),
898
- ])
899
- throw new Error(
900
- `system provisioning step ${JSON.stringify(step.name)} failed\n` +
901
- `command: ${step.command}\n` +
902
- `exit status: ${result.exitCode ?? '(missing)'}\n` +
903
- `stdout:\n${stdout.trim() === '' ? '(empty)' : stdout}\n` +
904
- `stderr:\n${stderr.trim() === '' ? '(empty)' : stderr}\n` +
905
- 'remediation: fix [workspace.config].provisioning and rerun ab init --validate',
906
- )
907
- }
887
+ await runSystemProvisioningStep(sandbox, step, signal)
908
888
  completed.push(step.name)
909
889
  }
910
890
  return completed
911
891
  }
912
892
 
893
+ async function runSystemProvisioningStep(
894
+ sandbox: VercelSandboxHandle,
895
+ step: VercelProvisioningStep,
896
+ signal?: AbortSignal,
897
+ ): Promise<void> {
898
+ const result = (await sandbox.runCommand({
899
+ cmd: 'sh',
900
+ args: ['-c', step.command],
901
+ cwd: VERCEL_WORKSPACE_PATH,
902
+ sudo: true,
903
+ ...(signal === undefined ? {} : { signal }),
904
+ })) as VercelCommand
905
+ if (result.exitCode !== 0) {
906
+ const [stdout, stderr] = await Promise.all([
907
+ result.stdout?.() ?? Promise.resolve(''),
908
+ result.stderr?.() ?? Promise.resolve(''),
909
+ ])
910
+ throw new Error(
911
+ `system provisioning step ${JSON.stringify(step.name)} failed\n` +
912
+ `command: ${step.command}\n` +
913
+ `exit status: ${result.exitCode ?? '(missing)'}\n` +
914
+ `stdout:\n${stdout.trim() === '' ? '(empty)' : stdout}\n` +
915
+ `stderr:\n${stderr.trim() === '' ? '(empty)' : stderr}\n` +
916
+ 'remediation: fix [workspace.config].provisioning and rerun ab init --validate',
917
+ )
918
+ }
919
+ }
920
+
913
921
  /** Bring a reused sandbox's Bun to exactly the pin before any guest command
914
922
  * runs with it. A matching `bun --version` costs one command; any other
915
923
  * report (a stale pin, a missing or unrunnable executable) is reinstalled at
@@ -1016,6 +1024,114 @@ async function checkedOutBranchHead(
1016
1024
  return head
1017
1025
  }
1018
1026
 
1027
+ /** The commit the guest clone's HEAD resolves to, whether detached at the
1028
+ * cloned revision or already on the build branch. */
1029
+ async function guestHeadCommit(
1030
+ sandbox: VercelSandboxHandle,
1031
+ signal?: AbortSignal,
1032
+ ): Promise<string> {
1033
+ const stdout = await readableCommand(sandbox, {
1034
+ cmd: 'git',
1035
+ args: ['rev-parse', '--verify', 'HEAD^{commit}'],
1036
+ cwd: VERCEL_WORKSPACE_PATH,
1037
+ ...(signal ? { signal } : {}),
1038
+ })
1039
+ const head = stdout.trim()
1040
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(head))
1041
+ throw new Error(`unreadable clone head: ${JSON.stringify(head)}`)
1042
+ return head
1043
+ }
1044
+
1045
+ /** Per-stage provisioning checkpoints: one file per completed stage holding a
1046
+ * sha256 fingerprint of that stage's inputs chained onto the previous stage's
1047
+ * fingerprint. Consulted only when finishing a teardown-abandoned attempt, so
1048
+ * a resumed provision skips stages already completed with unchanged inputs.
1049
+ * Fingerprints cover non-secret inputs only; no env value or token is ever
1050
+ * written here. */
1051
+ export const VERCEL_PROVISION_CHECKPOINT_DIR = `${VERCEL_AUTOBUILD_PATH}/.provision-checkpoints`
1052
+
1053
+ const PROVISION_CHECKPOINT_KEY = /^\d{2}-[a-z]+(?:-\d+)?$/
1054
+ const PROVISION_CHECKPOINT_FINGERPRINT = /^[0-9a-f]{64}$/
1055
+
1056
+ function provisionFingerprint(previous: string, stage: string, inputs: unknown): string {
1057
+ return createHash('sha256')
1058
+ .update(JSON.stringify([previous, stage, inputs]))
1059
+ .digest('hex')
1060
+ }
1061
+
1062
+ async function writeProvisionCheckpoint(
1063
+ sandbox: VercelSandboxHandle,
1064
+ key: string,
1065
+ fingerprint: string,
1066
+ signal?: AbortSignal,
1067
+ ): Promise<void> {
1068
+ await commandOrThrow(sandbox, {
1069
+ cmd: 'sh',
1070
+ args: [
1071
+ '-c',
1072
+ 'mkdir -p "$1" && printf %s "$3" > "$1/$2"',
1073
+ 'provision-checkpoint',
1074
+ VERCEL_PROVISION_CHECKPOINT_DIR,
1075
+ key,
1076
+ fingerprint,
1077
+ ],
1078
+ ...(signal === undefined ? {} : { signal }),
1079
+ })
1080
+ }
1081
+
1082
+ /** Every well-formed checkpoint in the guest; malformed entries are absent. */
1083
+ async function readProvisionCheckpoints(
1084
+ sandbox: VercelSandboxHandle,
1085
+ signal?: AbortSignal,
1086
+ ): Promise<Map<string, string>> {
1087
+ const stdout = await readableCommand(sandbox, {
1088
+ cmd: 'sh',
1089
+ args: [
1090
+ '-c',
1091
+ '[ -d "$1" ] || exit 0; for f in "$1"/*; do [ -f "$f" ] || continue; printf "%s %s\\n" "$(basename "$f")" "$(cat "$f")"; done',
1092
+ 'provision-checkpoints',
1093
+ VERCEL_PROVISION_CHECKPOINT_DIR,
1094
+ ],
1095
+ ...(signal === undefined ? {} : { signal }),
1096
+ })
1097
+ const checkpoints = new Map<string, string>()
1098
+ for (const line of stdout.split('\n')) {
1099
+ const [key, fingerprint, ...rest] = line.trim().split(' ')
1100
+ if (
1101
+ rest.length === 0 &&
1102
+ key !== undefined &&
1103
+ fingerprint !== undefined &&
1104
+ PROVISION_CHECKPOINT_KEY.test(key) &&
1105
+ PROVISION_CHECKPOINT_FINGERPRINT.test(fingerprint)
1106
+ )
1107
+ checkpoints.set(key, fingerprint)
1108
+ }
1109
+ return checkpoints
1110
+ }
1111
+
1112
+ async function clearProvisionCheckpoints(
1113
+ sandbox: VercelSandboxHandle,
1114
+ keys: readonly string[],
1115
+ signal?: AbortSignal,
1116
+ ): Promise<void> {
1117
+ if (keys.length === 0) return
1118
+ for (const key of keys) {
1119
+ if (!PROVISION_CHECKPOINT_KEY.test(key))
1120
+ throw new Error(`invalid provisioning checkpoint key ${JSON.stringify(key)}`)
1121
+ }
1122
+ await commandOrThrow(sandbox, {
1123
+ cmd: 'sh',
1124
+ args: [
1125
+ '-c',
1126
+ 'cd "$1" || exit 0; shift; rm -f -- "$@"',
1127
+ 'provision-checkpoints-clear',
1128
+ VERCEL_PROVISION_CHECKPOINT_DIR,
1129
+ ...keys,
1130
+ ],
1131
+ ...(signal === undefined ? {} : { signal }),
1132
+ })
1133
+ }
1134
+
1019
1135
  /** Create, inspect, and always delete one remote readiness environment. Unlike
1020
1136
  * build provisioning this never uses a stable name, branch, or marker. */
1021
1137
  export async function validateVercelSandbox(
@@ -1729,20 +1845,25 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1729
1845
  release: (input) => this.sandboxRelease(input),
1730
1846
  }
1731
1847
  this.recovery = {
1732
- fence: async (handle) => {
1848
+ fence: async (handle, fenceOpts) => {
1733
1849
  if (handle.provider !== this.name) throw new Error('workspace fence provider mismatch')
1850
+ // In teardown the work deadline has passed: the cleanup scope bounds
1851
+ // the transport, and each call keeps only its own cap.
1852
+ const signal = () =>
1853
+ fenceOpts?.teardown === true
1854
+ ? AbortSignal.timeout(this.operationTimeoutMs())
1855
+ : this.recoveryMetadataSignal()
1734
1856
  try {
1735
1857
  return await this.deadlineAware('fence', async () => {
1736
1858
  // Never trust the in-process handle after restart or another resume.
1737
- const sandbox = await this.facade.get(handle.ref, this.recoveryMetadataSignal())
1859
+ const sandbox = await this.facade.get(handle.ref, signal())
1738
1860
  if (sandbox === null) {
1739
1861
  this.forget(handle.ref)
1740
1862
  return { outcome: 'absent' as const }
1741
1863
  }
1742
1864
  // A session the provider already reports stopped needs no second
1743
1865
  // stop; asking would only spend the acknowledgement budget.
1744
- if (sandbox.sessionStatus !== 'stopped')
1745
- await sandbox.stop({ signal: this.recoveryMetadataSignal() })
1866
+ if (sandbox.sessionStatus !== 'stopped') await sandbox.stop({ signal: signal() })
1746
1867
  this.active.delete(handle.ref)
1747
1868
  this.uncertain.delete(handle.ref)
1748
1869
  this.sessions.set(handle.ref, sandbox)
@@ -1996,7 +2117,8 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1996
2117
  } else {
1997
2118
  // The dispatcher recorded this generation's attempt as abandoned at
1998
2119
  // its own teardown, and its lease is gone. Finish the same sandbox in
1999
- // place, but only after verification; any doubt still reaps it.
2120
+ // place at the commit it cloned, resuming after its last completed
2121
+ // stage, but only after verification; any doubt still reaps it.
2000
2122
  try {
2001
2123
  // Quiesce first: stopping ends any command the dead invocation left
2002
2124
  // running, and the persistent guest resumes on the next command.
@@ -2013,7 +2135,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2013
2135
  base,
2014
2136
  distributionIdentity,
2015
2137
  scopedToken,
2016
- verifyClean: true,
2138
+ resume: true,
2017
2139
  })
2018
2140
  } catch (error) {
2019
2141
  throw new WorkspaceCleanupRequired(
@@ -2134,11 +2256,16 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2134
2256
  }
2135
2257
  }
2136
2258
 
2137
- /** The idempotent post-create sequence: branch checkout at the selected
2138
- * base, credential scrub, toolchain, distribution, dependencies, runtimes,
2139
- * then the completion marker and a snapshot stop. Shared by a fresh create
2140
- * and by finishing a teardown-abandoned attempt in place. Returns the
2141
- * verified checked-out head. */
2259
+ /** The checkpointed post-create sequence: branch checkout and credential
2260
+ * scrub, pinned Bun, each named system provisioning step, distribution,
2261
+ * lockfile dependencies, runtimes, then the completion marker and a
2262
+ * snapshot stop. Each stage records an input fingerprint chained onto the
2263
+ * previous stage's once it succeeds. Shared by a fresh create and by
2264
+ * finishing a teardown-abandoned attempt in place; with `resume`, the
2265
+ * sequence stays on the commit the clone holds, skips the leading run of
2266
+ * stages whose checkpoints match the current inputs, and executes every
2267
+ * stage from the first mismatch onward. Returns the verified checked-out
2268
+ * head. */
2142
2269
  private async completeProvisioning(
2143
2270
  sandbox: VercelSandboxHandle,
2144
2271
  input: {
@@ -2147,20 +2274,86 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2147
2274
  base: string
2148
2275
  distributionIdentity: string
2149
2276
  scopedToken: string
2150
- /** Require no tracked modifications before the marker is written. */
2151
- verifyClean?: boolean
2277
+ /** Finish an abandoned attempt: keep the cloned commit, skip completed
2278
+ * stages, and require no tracked modifications. */
2279
+ resume?: boolean
2152
2280
  },
2153
2281
  ): Promise<string> {
2154
- const { origin, branch, base, distributionIdentity, scopedToken } = input
2155
- await commandOrThrow(sandbox, {
2156
- cmd: 'git',
2157
- args: ['checkout', '-B', branch, base],
2158
- cwd: VERCEL_WORKSPACE_PATH,
2159
- })
2160
- const head = await checkedOutBranchHead(sandbox, branch, this.operationSignal())
2161
- if (head !== base)
2162
- throw new Error(`checked out ${branch} at ${head}, expected selected base ${base}`)
2163
- if (input.verifyClean) {
2282
+ const { origin, branch, distributionIdentity, scopedToken } = input
2283
+ const resume = input.resume === true
2284
+ const head = resume ? await guestHeadCommit(sandbox, this.operationSignal()) : input.base
2285
+ const checkpoints = resume
2286
+ ? await readProvisionCheckpoints(sandbox, this.operationSignal())
2287
+ : new Map<string, string>()
2288
+ let previous = ''
2289
+ let executing = !resume
2290
+ const kept = new Set<string>()
2291
+ const stage = async (
2292
+ key: string,
2293
+ inputs: unknown,
2294
+ run: () => Promise<void>,
2295
+ skipped?: () => Promise<void>,
2296
+ ): Promise<void> => {
2297
+ const fingerprint = provisionFingerprint(previous, key, inputs)
2298
+ if (!executing && checkpoints.get(key) === fingerprint) {
2299
+ kept.add(key)
2300
+ await skipped?.()
2301
+ } else {
2302
+ if (!executing) {
2303
+ // Durably drop every checkpoint outside the kept prefix before this
2304
+ // stage mutates the guest, so an interrupted rerun can never leave
2305
+ // a downstream checkpoint a later adoption would skip.
2306
+ await clearProvisionCheckpoints(
2307
+ sandbox,
2308
+ [...checkpoints.keys()].filter((existing) => !kept.has(existing)),
2309
+ this.operationSignal(),
2310
+ )
2311
+ executing = true
2312
+ }
2313
+ await run()
2314
+ await writeProvisionCheckpoint(sandbox, key, fingerprint, this.operationSignal())
2315
+ }
2316
+ previous = fingerprint
2317
+ }
2318
+
2319
+ await stage(
2320
+ '01-checkout',
2321
+ { branch, origin: origin.url, head },
2322
+ async () => {
2323
+ await commandOrThrow(sandbox, {
2324
+ cmd: 'git',
2325
+ args: ['checkout', '-B', branch, head],
2326
+ cwd: VERCEL_WORKSPACE_PATH,
2327
+ })
2328
+ const checked = await checkedOutBranchHead(sandbox, branch, this.operationSignal())
2329
+ if (checked !== head)
2330
+ throw new Error(`checked out ${branch} at ${checked}, expected selected base ${head}`)
2331
+ await commandOrThrow(sandbox, {
2332
+ cmd: 'git',
2333
+ args: ['remote', 'set-url', 'origin', origin.url],
2334
+ cwd: VERCEL_WORKSPACE_PATH,
2335
+ })
2336
+ for (const key of [
2337
+ 'credential.helper',
2338
+ 'http.extraheader',
2339
+ `http.${origin.url}.extraheader`,
2340
+ ]) {
2341
+ const result = await sandbox.runCommand({
2342
+ cmd: 'git',
2343
+ args: ['config', '--local', '--unset-all', key],
2344
+ cwd: VERCEL_WORKSPACE_PATH,
2345
+ })
2346
+ if (result.exitCode !== 0 && result.exitCode !== 5)
2347
+ throw new Error(`failed to scrub git config ${key}`)
2348
+ }
2349
+ },
2350
+ async () => {
2351
+ const checked = await checkedOutBranchHead(sandbox, branch, this.operationSignal())
2352
+ if (checked !== head)
2353
+ throw new Error(`checked out ${branch} at ${checked}, expected cloned head ${head}`)
2354
+ },
2355
+ )
2356
+ if (resume) {
2164
2357
  // A finished abandoned attempt must not expose tracked edits the dead
2165
2358
  // invocation may have left behind.
2166
2359
  const diff = await sandbox.runCommand({
@@ -2170,41 +2363,54 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2170
2363
  })
2171
2364
  if (diff.exitCode !== 0) throw new Error('abandoned provisioning left tracked modifications')
2172
2365
  }
2173
- await commandOrThrow(sandbox, {
2174
- cmd: 'git',
2175
- args: ['remote', 'set-url', 'origin', origin.url],
2176
- cwd: VERCEL_WORKSPACE_PATH,
2177
- })
2178
- for (const key of ['credential.helper', 'http.extraheader', `http.${origin.url}.extraheader`]) {
2179
- const result = await sandbox.runCommand({
2180
- cmd: 'git',
2181
- args: ['config', '--local', '--unset-all', key],
2182
- cwd: VERCEL_WORKSPACE_PATH,
2183
- })
2184
- if (result.exitCode !== 0 && result.exitCode !== 5)
2185
- throw new Error(`failed to scrub git config ${key}`)
2366
+ const image = this.options.config.image
2367
+ await stage('02-bun', { version: VERCEL_BUN_VERSION, image }, () =>
2368
+ provisionBun(sandbox, image),
2369
+ )
2370
+ const steps = this.options.config.provisioning ?? []
2371
+ for (const [index, step] of steps.entries()) {
2372
+ await stage(`03-step-${index}`, { name: step.name, command: step.command }, () =>
2373
+ runSystemProvisioningStep(sandbox, step),
2374
+ )
2186
2375
  }
2187
- await provisionBun(sandbox, this.options.config.image)
2188
- await runSystemProvisioning(sandbox, this.options.config.provisioning ?? [])
2189
- const archive = await this.archiveBytes()
2190
- await installDistribution(sandbox, archive, distributionIdentity, this.operationSignal())
2376
+ await stage('04-distribution', { identity: distributionIdentity }, async () => {
2377
+ const archive = await this.archiveBytes()
2378
+ await installDistribution(sandbox, archive, distributionIdentity, this.operationSignal())
2379
+ })
2191
2380
  // Repository dependencies precede branch-owned package plugin loading.
2192
2381
  // The fixed bootstrap supports the consuming repository's lockfile; its
2193
2382
  // configured setup command still runs at every runner attachment.
2194
- await commandOrThrow(sandbox, {
2195
- cmd: 'sh',
2196
- args: [
2197
- '-c',
2198
- `if [ -f bun.lock ] || [ -f bun.lockb ]; then ${VERCEL_BUN_EXECUTABLE} install --frozen-lockfile; elif [ -f package-lock.json ]; then npm ci; elif [ -f pnpm-lock.yaml ]; then corepack pnpm install --frozen-lockfile; elif [ -f yarn.lock ]; then corepack yarn install --immutable; fi`,
2199
- ],
2200
- cwd: VERCEL_WORKSPACE_PATH,
2201
- })
2202
- await bootstrapRuntimes(
2203
- sandbox,
2204
- this.options.config,
2205
- { ...this.guestEnvironment(), AB_TOKEN: scopedToken },
2206
- currentRuntimeReferences(this.options.runtimeReferences),
2207
- true,
2383
+ await stage('05-dependencies', { command: DEPENDENCY_INSTALL_COMMAND }, () =>
2384
+ commandOrThrow(sandbox, {
2385
+ cmd: 'sh',
2386
+ args: ['-c', DEPENDENCY_INSTALL_COMMAND],
2387
+ cwd: VERCEL_WORKSPACE_PATH,
2388
+ }),
2389
+ )
2390
+ const references = currentRuntimeReferences(this.options.runtimeReferences)
2391
+ await stage(
2392
+ '06-runtimes',
2393
+ [...references]
2394
+ .sort((left, right) =>
2395
+ left.runtime < right.runtime ? -1 : left.runtime > right.runtime ? 1 : 0,
2396
+ )
2397
+ .map((group) => {
2398
+ const provisioning = this.options.config.runtimeProvisioning?.[group.runtime]
2399
+ return {
2400
+ runtime: group.runtime,
2401
+ references: group.references,
2402
+ install: provisioning?.install ?? null,
2403
+ preflight: provisioning?.preflight ?? null,
2404
+ }
2405
+ }),
2406
+ () =>
2407
+ bootstrapRuntimes(
2408
+ sandbox,
2409
+ this.options.config,
2410
+ { ...this.guestEnvironment(), AB_TOKEN: scopedToken },
2411
+ references,
2412
+ true,
2413
+ ),
2208
2414
  )
2209
2415
  await commandOrThrow(sandbox, {
2210
2416
  cmd: 'touch',