From e0c2842823981d9dc85f94ea81da326ea1bb7d52 Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Tue, 24 Nov 2026 10:18:13 +0000 Subject: [PATCH 1/5] fix(release): wait for the new version on npm before syncing the template The template sync ran npm install right after publish, before the registry served the new version, so every attempt failed with ETARGET (npm also reused its stale cached packument between retries). The script now polls `npm view @ --prefer-online` for each package it pins, with backoff for up to 10 minutes, and fails naming the package and version if it never appears. npm install also runs with --prefer-online. The longer wait widens the window for main to move, so the sync commit is rebased onto the latest branch before tagging, and the commit and tag are pushed in one atomic push (with the tag named explicitly; --follow-tags silently skipped a tag that already existed on the remote). Co-authored-by: Isaac Signed-off-by: mario.cadenas --- tools/publish-template-tag.ts | 41 +++++++--- tools/wait-for-npm-version.test.ts | 119 +++++++++++++++++++++++++++++ tools/wait-for-npm-version.ts | 51 +++++++++++++ 3 files changed, 202 insertions(+), 9 deletions(-) create mode 100644 tools/wait-for-npm-version.test.ts create mode 100644 tools/wait-for-npm-version.ts diff --git a/tools/publish-template-tag.ts b/tools/publish-template-tag.ts index 469f1db63..d13d34e38 100644 --- a/tools/publish-template-tag.ts +++ b/tools/publish-template-tag.ts @@ -1,7 +1,7 @@ #!/usr/bin/env tsx /** - * Syncs the template to the given version (with retry), then commits, tags - * template-vX.X.X, and pushes. + * Waits until npm serves the given version, syncs the template to it (with + * retry), then commits, tags template-vX.X.X, and pushes. * * Used by the private secure release repo during the template-sync step. * Changes here affect the release pipeline. @@ -11,6 +11,8 @@ import { spawnSync } from "node:child_process"; import { readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import { waitForNpmVersion } from "./wait-for-npm-version"; + const ROOT = process.cwd(); const version = process.argv[2]; if (!version) { @@ -34,12 +36,13 @@ function run( // 1. Update template package.json const templatePath = join(ROOT, "template", "package.json"); const templateJson = JSON.parse(readFileSync(templatePath, "utf-8")); +// The packages this release just published. +const pinned = ["@databricks/appkit", "@databricks/appkit-ui"].filter( + (name) => name in (templateJson.dependencies ?? {}), +); if (templateJson.dependencies) { - if ("@databricks/appkit" in templateJson.dependencies) { - templateJson.dependencies["@databricks/appkit"] = version; - } - if ("@databricks/appkit-ui" in templateJson.dependencies) { - templateJson.dependencies["@databricks/appkit-ui"] = version; + for (const name of pinned) { + templateJson.dependencies[name] = version; } writeFileSync(templatePath, `${JSON.stringify(templateJson, null, 2)}\n`); console.log(`✓ template/package.json → ${version}`); @@ -97,9 +100,20 @@ if (npmConfig.status !== 0 || npmConfig.stdout.trim() === "undefined") { process.exit(1); } -// 2a. npm → package-lock.json +// Install only once the registry serves the new version; the retries below +// are too short to outlast registry propagation. +await waitForNpmVersion(pinned, version, { cwd: templateDir }).catch( + (error: Error) => { + console.error(error.message); + process.exit(1); + }, +); + +// 2a. npm → package-lock.json (--prefer-online: a stale cached packument +// would otherwise fail every attempt with ETARGET) const npmExit = await runInstallWithRetry("npm install", "npm", [ "install", + "--prefer-online", `--min-release-age=${RELEASE_AGE_DAYS}`, `--min-release-age-exclude=${RELEASE_AGE_EXCLUDE}`, ]); @@ -144,6 +158,9 @@ if (pnpmExit !== 0) { console.log("✓ template/pnpm-lock.yaml updated (pnpm install)"); // 3. Git add, commit, tag, push +const branch = spawnSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { + encoding: "utf-8", +}).stdout.trim(); const commands: [string, string[]][] = [ [ "git", @@ -158,8 +175,14 @@ const commands: [string, string[]][] = [ "git", ["commit", "-s", "-m", `chore: sync template to v${version} [skip ci]`], ], + // The branch may have moved while we waited for the registry. + ["git", ["pull", "--rebase", "origin", branch]], ["git", ["tag", "-a", `template-v${version}`, "-m", `Template v${version}`]], - ["git", ["push", "origin", "HEAD", "--follow-tags"]], + // --atomic: never leave the tag pushed without the commit (or the reverse). + [ + "git", + ["push", "--atomic", "origin", "HEAD", `refs/tags/template-v${version}`], + ], ]; for (const [command, args] of commands) { diff --git a/tools/wait-for-npm-version.test.ts b/tools/wait-for-npm-version.test.ts new file mode 100644 index 000000000..0a54dfed7 --- /dev/null +++ b/tools/wait-for-npm-version.test.ts @@ -0,0 +1,119 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, beforeEach, expect, test, vi } from "vitest"; + +import { waitForNpmVersion } from "./wait-for-npm-version"; + +const VERSION = "0.104.0"; +const fast = { delayMs: 10, maxDelayMs: 20 }; +let directory: string; +let server: Server; +const requests = new Map(); + +/** + * A registry that serves `name@VERSION` only from request `servedFrom[name]` + * on; before that it returns the pre-publish packument, cacheable like npm's. + */ +async function fakeRegistry(servedFrom: Record) { + server = createServer((req, res) => { + const name = decodeURIComponent(req.url?.slice(1) ?? ""); + const count = (requests.get(name) ?? 0) + 1; + requests.set(name, count); + if (!(name in servedFrom)) { + res.writeHead(404).end(); + return; + } + const versions = + count >= servedFrom[name] ? ["0.103.0", VERSION] : ["0.103.0"]; + res.writeHead(200, { + "content-type": "application/json", + "cache-control": "public, max-age=300", + }); + res.end( + JSON.stringify({ + name, + "dist-tags": { latest: versions.at(-1) }, + versions: Object.fromEntries( + versions.map((version) => [ + version, + { + name, + version, + dist: { tarball: `http://unused/${version}.tgz` }, + }, + ]), + ), + }), + ); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const registry = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; + // Both spellings: npm reads either, and the developer's env may set one. + vi.stubEnv("npm_config_registry", registry); + vi.stubEnv("NPM_CONFIG_REGISTRY", registry); +} + +beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), "appkit-wait-npm-test-")); + vi.stubEnv("npm_config_cache", join(directory, "cache")); + vi.stubEnv("npm_config_userconfig", join(directory, "npmrc")); + vi.stubEnv("npm_config_update_notifier", "false"); +}); + +afterEach(() => { + server?.close(); + requests.clear(); + vi.unstubAllEnvs(); + rmSync(directory, { recursive: true, force: true }); +}); + +test( + "waits until the registry serves every package", + { timeout: 60_000 }, + async () => { + await fakeRegistry({ "@databricks/appkit": 3, "@databricks/appkit-ui": 2 }); + + await waitForNpmVersion( + ["@databricks/appkit", "@databricks/appkit-ui"], + VERSION, + { + cwd: directory, + timeoutMs: 50_000, + ...fast, + }, + ); + + // One request per try: the cached stale packument is never trusted. + expect(requests.get("@databricks/appkit")).toBe(3); + expect(requests.get("@databricks/appkit-ui")).toBe(2); + }, +); + +test( + "names the package and version when the wait times out", + { timeout: 60_000 }, + async () => { + await fakeRegistry({ + "@databricks/appkit": 1, + "@databricks/appkit-ui": Infinity, + }); + + await expect( + waitForNpmVersion( + ["@databricks/appkit", "@databricks/appkit-ui"], + VERSION, + { + cwd: directory, + timeoutMs: 1_000, + ...fast, + }, + ), + ).rejects.toThrow( + `@databricks/appkit-ui@${VERSION} is still not on the npm registry`, + ); + }, +); diff --git a/tools/wait-for-npm-version.ts b/tools/wait-for-npm-version.ts new file mode 100644 index 000000000..2a05f1c23 --- /dev/null +++ b/tools/wait-for-npm-version.ts @@ -0,0 +1,51 @@ +import { execFile } from "node:child_process"; +import { setTimeout as sleep } from "node:timers/promises"; +import { promisify } from "node:util"; + +const execFileAsync = promisify(execFile); + +/** + * Waits until the npm registry serves `name@version` for every name. A + * just-published version takes minutes to reach the registry's packument and + * CDN cache, so installing it right away fails with ETARGET. + */ +export async function waitForNpmVersion( + names: string[], + version: string, + { + cwd = process.cwd(), + timeoutMs = 10 * 60_000, + delayMs = 5_000, + maxDelayMs = 30_000, + } = {}, +): Promise { + const deadline = Date.now() + timeoutMs; + for (const name of names) { + for (let delay = delayMs; ; delay = Math.min(delay * 2, maxDelayMs)) { + // --prefer-online: revalidate npm's local cache, which would keep serving + // the packument from before the publish. + const { stdout, stderr } = await execFileAsync( + "npm", + ["view", `${name}@${version}`, "version", "--prefer-online"], + { cwd }, + ).catch((error) => ({ + stdout: "", + stderr: String(error.stderr ?? error), + })); + if (stdout.trim() === version) { + console.log(`✓ ${name}@${version} is on the npm registry`); + break; + } + if (Date.now() + delay > deadline) { + throw new Error( + `${name}@${version} is still not on the npm registry after ${Math.round(timeoutMs / 1000)}s. ` + + `Last npm view output:\n${stderr.trim() || stdout.trim()}`, + ); + } + console.warn( + `${name}@${version} is not on the npm registry yet, checking again in ${delay / 1000}s...`, + ); + await sleep(delay); + } + } +} From 5d44365f4fb9e5f4fe2a93974b212b101a4f53b4 Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Tue, 24 Nov 2026 10:28:48 +0000 Subject: [PATCH 2/5] docs(release): say why npm view still passes --prefer-online npm view already revalidates its cache by default, so the flag is a guard against a config change, not what defeats a stale packument. Co-authored-by: Isaac Signed-off-by: mario.cadenas --- tools/wait-for-npm-version.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/wait-for-npm-version.ts b/tools/wait-for-npm-version.ts index 2a05f1c23..6611049d4 100644 --- a/tools/wait-for-npm-version.ts +++ b/tools/wait-for-npm-version.ts @@ -22,8 +22,8 @@ export async function waitForNpmVersion( const deadline = Date.now() + timeoutMs; for (const name of names) { for (let delay = delayMs; ; delay = Math.min(delay * 2, maxDelayMs)) { - // --prefer-online: revalidate npm's local cache, which would keep serving - // the packument from before the publish. + // npm view already revalidates its cache by default; --prefer-online + // keeps it that way if a config default changes. const { stdout, stderr } = await execFileAsync( "npm", ["view", `${name}@${version}`, "version", "--prefer-online"], From 391a3a5c8e945cab31ab8ed9f05a614dbb15f18c Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Tue, 24 Nov 2026 10:42:32 +0000 Subject: [PATCH 3/5] fix(release): bound each npm view probe by the wait's deadline npm's own fetch timeout (5 minutes, retried twice) let a single stalled `npm view` outlast the 10-minute wait, so the release job could time out without the package/version message. Each probe now gets at most 60 s, and never more than the time left before the deadline; a probe that is cut off is reported as "npm view did not answer in time". Co-authored-by: Isaac Signed-off-by: mario.cadenas --- tools/wait-for-npm-version.test.ts | 33 ++++++++++++++++++++++++++---- tools/wait-for-npm-version.ts | 14 +++++++++++-- 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/tools/wait-for-npm-version.test.ts b/tools/wait-for-npm-version.test.ts index 0a54dfed7..2ac470652 100644 --- a/tools/wait-for-npm-version.test.ts +++ b/tools/wait-for-npm-version.test.ts @@ -17,18 +17,20 @@ const requests = new Map(); /** * A registry that serves `name@VERSION` only from request `servedFrom[name]` * on; before that it returns the pre-publish packument, cacheable like npm's. + * A "stall" package gets no answer at all. */ -async function fakeRegistry(servedFrom: Record) { +async function fakeRegistry(servedFrom: Record) { server = createServer((req, res) => { const name = decodeURIComponent(req.url?.slice(1) ?? ""); const count = (requests.get(name) ?? 0) + 1; requests.set(name, count); - if (!(name in servedFrom)) { + const from = servedFrom[name]; + if (from === "stall") return; + if (from === undefined) { res.writeHead(404).end(); return; } - const versions = - count >= servedFrom[name] ? ["0.103.0", VERSION] : ["0.103.0"]; + const versions = count >= from ? ["0.103.0", VERSION] : ["0.103.0"]; res.writeHead(200, { "content-type": "application/json", "cache-control": "public, max-age=300", @@ -65,6 +67,7 @@ beforeEach(() => { }); afterEach(() => { + server?.closeAllConnections(); server?.close(); requests.clear(); vi.unstubAllEnvs(); @@ -117,3 +120,25 @@ test( ); }, ); + +test( + "a registry that never answers still ends the wait on time", + { timeout: 60_000 }, + async () => { + await fakeRegistry({ "@databricks/appkit": "stall" }); + const started = Date.now(); + + await expect( + waitForNpmVersion(["@databricks/appkit"], VERSION, { + cwd: directory, + timeoutMs: 2_000, + ...fast, + }), + ).rejects.toThrow( + `@databricks/appkit@${VERSION} is still not on the npm registry after 2s. ` + + "Last npm view output:\nnpm view did not answer in time", + ); + // npm alone would wait out its 5-minute fetch timeout. + expect(Date.now() - started).toBeLessThan(10_000); + }, +); diff --git a/tools/wait-for-npm-version.ts b/tools/wait-for-npm-version.ts index 6611049d4..a9abfce44 100644 --- a/tools/wait-for-npm-version.ts +++ b/tools/wait-for-npm-version.ts @@ -3,6 +3,8 @@ import { setTimeout as sleep } from "node:timers/promises"; import { promisify } from "node:util"; const execFileAsync = promisify(execFile); +// npm's own fetch timeout (5 min, retried) could outlast the whole wait. +const PROBE_TIMEOUT_MS = 60_000; /** * Waits until the npm registry serves `name@version` for every name. A @@ -27,10 +29,18 @@ export async function waitForNpmVersion( const { stdout, stderr } = await execFileAsync( "npm", ["view", `${name}@${version}`, "version", "--prefer-online"], - { cwd }, + { + cwd, + timeout: Math.max( + 1, + Math.min(PROBE_TIMEOUT_MS, deadline - Date.now()), + ), + }, ).catch((error) => ({ stdout: "", - stderr: String(error.stderr ?? error), + stderr: error.killed + ? "npm view did not answer in time" + : String(error.stderr || error.message), })); if (stdout.trim() === version) { console.log(`✓ ${name}@${version} is on the npm registry`); From 335553b92b387e67e40608fbe7c33659ed305ae4 Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Tue, 24 Nov 2026 11:17:50 +0000 Subject: [PATCH 4/5] fix(release): tag the template on the released code, not later merges Rebasing the sync commit onto the latest branch before tagging let template-v include commits merged after the release was cut, which never went through the release pipeline yet would ship to every app created from that template. The tag now goes on the sync commit on top of the checked-out release; only the branch gets the sync replayed onto newer commits. The git steps move into tools/push-template-tag.ts with a test that recreates the race. Co-authored-by: Isaac Signed-off-by: mario.cadenas --- tools/publish-template-tag.ts | 39 +++++------------ tools/push-template-tag.test.ts | 74 +++++++++++++++++++++++++++++++++ tools/push-template-tag.ts | 36 ++++++++++++++++ 3 files changed, 120 insertions(+), 29 deletions(-) create mode 100644 tools/push-template-tag.test.ts create mode 100644 tools/push-template-tag.ts diff --git a/tools/publish-template-tag.ts b/tools/publish-template-tag.ts index d13d34e38..4df8c8518 100644 --- a/tools/publish-template-tag.ts +++ b/tools/publish-template-tag.ts @@ -11,6 +11,7 @@ import { spawnSync } from "node:child_process"; import { readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import { pushTemplateTag } from "./push-template-tag"; import { waitForNpmVersion } from "./wait-for-npm-version"; const ROOT = process.cwd(); @@ -158,37 +159,17 @@ if (pnpmExit !== 0) { console.log("✓ template/pnpm-lock.yaml updated (pnpm install)"); // 3. Git add, commit, tag, push -const branch = spawnSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { - encoding: "utf-8", -}).stdout.trim(); -const commands: [string, string[]][] = [ +const pushed = pushTemplateTag( + version, [ - "git", - [ - "add", - "template/package.json", - "template/package-lock.json", - "template/pnpm-lock.yaml", - ], + "template/package.json", + "template/package-lock.json", + "template/pnpm-lock.yaml", ], - [ - "git", - ["commit", "-s", "-m", `chore: sync template to v${version} [skip ci]`], - ], - // The branch may have moved while we waited for the registry. - ["git", ["pull", "--rebase", "origin", branch]], - ["git", ["tag", "-a", `template-v${version}`, "-m", `Template v${version}`]], - // --atomic: never leave the tag pushed without the commit (or the reverse). - [ - "git", - ["push", "--atomic", "origin", "HEAD", `refs/tags/template-v${version}`], - ], -]; - -for (const [command, args] of commands) { - if (run(command, args) !== 0) { - process.exit(1); - } + ROOT, +); +if (!pushed) { + process.exit(1); } console.log(`✓ template tag template-v${version} pushed`); diff --git a/tools/push-template-tag.test.ts b/tools/push-template-tag.test.ts new file mode 100644 index 000000000..3d759f213 --- /dev/null +++ b/tools/push-template-tag.test.ts @@ -0,0 +1,74 @@ +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, beforeEach, expect, test, vi } from "vitest"; + +import { pushTemplateTag } from "./push-template-tag"; + +let directory: string; + +function git(cwd: string, ...args: string[]): string { + const result = spawnSync("git", args, { cwd, encoding: "utf-8" }); + if (result.status !== 0) + throw new Error(`git ${args.join(" ")}: ${result.stderr}`); + return result.stdout.trim(); +} + +function commitFile( + cwd: string, + file: string, + content: string, + message: string, +) { + mkdirSync(join(cwd, "template"), { recursive: true }); + writeFileSync(join(cwd, file), content); + git(cwd, "add", file); + git(cwd, "commit", "-m", message); +} + +beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), "appkit-template-tag-test-")); + // No user config or hooks; a fixed identity. + writeFileSync(join(directory, "gitconfig"), ""); + vi.stubEnv("GIT_CONFIG_GLOBAL", join(directory, "gitconfig")); + vi.stubEnv("GIT_CONFIG_NOSYSTEM", "1"); + for (const role of ["AUTHOR", "COMMITTER"]) { + vi.stubEnv(`GIT_${role}_NAME`, "Release Bot"); + vi.stubEnv(`GIT_${role}_EMAIL`, "release@example.com"); + } +}); + +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(directory, { recursive: true, force: true }); +}); + +test("tags the released code even when the branch moved meanwhile", () => { + const origin = join(directory, "origin.git"); + const runner = join(directory, "runner"); + const other = join(directory, "other"); + git(directory, "init", "-q", "--bare", "-b", "main", origin); + git(directory, "clone", "-q", origin, runner); + commitFile(runner, "template/app.ts", "released\n", "chore: release v2"); + git(runner, "push", "-q", "origin", "main"); + const released = git(runner, "rev-parse", "HEAD"); + + // A change merged to main after the release was cut. + git(directory, "clone", "-q", origin, other); + commitFile(other, "template/app.ts", "unreleased\n", "feat: after release"); + git(other, "push", "-q", "origin", "main"); + + writeFileSync(join(runner, "template/package.json"), '{"v":"2.0.0"}\n'); + expect(pushTemplateTag("2.0.0", ["template/package.json"], runner)).toBe( + true, + ); + + const show = (rev: string) => git(origin, "show", rev); + expect(show("template-v2.0.0:template/app.ts")).toBe("released"); + expect(show("template-v2.0.0:template/package.json")).toBe('{"v":"2.0.0"}'); + expect(git(origin, "rev-parse", "template-v2.0.0^{commit}^")).toBe(released); + expect(show("main:template/app.ts")).toBe("unreleased"); + expect(show("main:template/package.json")).toBe('{"v":"2.0.0"}'); +}); diff --git a/tools/push-template-tag.ts b/tools/push-template-tag.ts new file mode 100644 index 000000000..90b608d8e --- /dev/null +++ b/tools/push-template-tag.ts @@ -0,0 +1,36 @@ +import { spawnSync } from "node:child_process"; + +/** + * Commits the synced template files, tags the commit template-v and + * pushes both. The tag stays on the code the release was cut from; if the + * branch moved meanwhile, only the branch gets the sync replayed on top. + */ +export function pushTemplateTag( + version: string, + files: string[], + cwd: string, +): boolean { + const git = (...args: string[]) => + spawnSync("git", args, { cwd, stdio: "inherit" }).status === 0; + const branch = spawnSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { + cwd, + encoding: "utf-8", + }).stdout.trim(); + const tag = `template-v${version}`; + return ( + git("add", ...files) && + git( + "commit", + "-s", + "-m", + `chore: sync template to v${version} [skip ci]`, + ) && + // Tag before the pull: commits merged after the release never went + // through the release pipeline, so they must not ship in the template. + git("tag", "-a", tag, "-m", `Template v${version}`) && + // The branch may have moved while we waited for the registry. + git("pull", "--rebase", "origin", branch) && + // --atomic: never leave the tag pushed without the branch (or the reverse). + git("push", "--atomic", "origin", "HEAD", `refs/tags/${tag}`) + ); +} From ebd918b0bd30ac826c132a00b8b109a1bf75beaf Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Thu, 26 Nov 2026 11:37:03 +0000 Subject: [PATCH 5/5] fix(release): address review on the template sync wait - npm view runs with --json and its answer is parsed, so an inherited npm_config_json no longer turns "0.104.0" into a value that never matches. - Only not-yet-published (E404), throttling, 5xx and the network errors npm itself retries are waited out; auth, config or a missing npm fail at once with npm's error code. - A probe may run until the deadline instead of being killed after 60 s, so a slow registry that npm install would wait for is not cut off early. - Near the deadline the wait sleeps only the time left and checks once more, instead of quitting while it still had time. - git pull --rebase uses --autostash: the job's own install can leave unrelated tracked files modified, which made the pull refuse to run. - Tests: minimum request counts, a single never-served package for the timeout message, a deadline check, a fail-fast case, a stall measured from the request's arrival, and a dirty-checkout push. Narrating comments dropped. Co-authored-by: Isaac Signed-off-by: mario.cadenas --- tools/publish-template-tag.ts | 1 - tools/push-template-tag.test.ts | 32 +++++++- tools/push-template-tag.ts | 3 +- tools/wait-for-npm-version.test.ts | 120 +++++++++++++++++++---------- tools/wait-for-npm-version.ts | 101 +++++++++++++++++------- 5 files changed, 188 insertions(+), 69 deletions(-) diff --git a/tools/publish-template-tag.ts b/tools/publish-template-tag.ts index 4df8c8518..a9705122e 100644 --- a/tools/publish-template-tag.ts +++ b/tools/publish-template-tag.ts @@ -37,7 +37,6 @@ function run( // 1. Update template package.json const templatePath = join(ROOT, "template", "package.json"); const templateJson = JSON.parse(readFileSync(templatePath, "utf-8")); -// The packages this release just published. const pinned = ["@databricks/appkit", "@databricks/appkit-ui"].filter( (name) => name in (templateJson.dependencies ?? {}), ); diff --git a/tools/push-template-tag.test.ts b/tools/push-template-tag.test.ts index 3d759f213..de02be019 100644 --- a/tools/push-template-tag.test.ts +++ b/tools/push-template-tag.test.ts @@ -1,5 +1,11 @@ import { spawnSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -55,7 +61,6 @@ test("tags the released code even when the branch moved meanwhile", () => { git(runner, "push", "-q", "origin", "main"); const released = git(runner, "rev-parse", "HEAD"); - // A change merged to main after the release was cut. git(directory, "clone", "-q", origin, other); commitFile(other, "template/app.ts", "unreleased\n", "feat: after release"); git(other, "push", "-q", "origin", "main"); @@ -72,3 +77,26 @@ test("tags the released code even when the branch moved meanwhile", () => { expect(show("main:template/app.ts")).toBe("unreleased"); expect(show("main:template/package.json")).toBe('{"v":"2.0.0"}'); }); + +test("pushes from a checkout with an unrelated modified file", () => { + const origin = join(directory, "origin.git"); + const runner = join(directory, "runner"); + git(directory, "init", "-q", "--bare", "-b", "main", origin); + git(directory, "clone", "-q", origin, runner); + commitFile(runner, "template/lock.json", "committed\n", "chore: release v2"); + git(runner, "push", "-q", "origin", "main"); + writeFileSync(join(runner, "template/lock.json"), "rewritten by install\n"); + + writeFileSync(join(runner, "template/package.json"), '{"v":"2.0.0"}\n'); + expect(pushTemplateTag("2.0.0", ["template/package.json"], runner)).toBe( + true, + ); + + expect(git(origin, "show", "template-v2.0.0:template/package.json")).toBe( + '{"v":"2.0.0"}', + ); + expect(git(origin, "show", "main:template/lock.json")).toBe("committed"); + expect(readFileSync(join(runner, "template/lock.json"), "utf-8")).toBe( + "rewritten by install\n", + ); +}); diff --git a/tools/push-template-tag.ts b/tools/push-template-tag.ts index 90b608d8e..62ee40752 100644 --- a/tools/push-template-tag.ts +++ b/tools/push-template-tag.ts @@ -29,7 +29,8 @@ export function pushTemplateTag( // through the release pipeline, so they must not ship in the template. git("tag", "-a", tag, "-m", `Template v${version}`) && // The branch may have moved while we waited for the registry. - git("pull", "--rebase", "origin", branch) && + // --autostash: the job's own install can leave unrelated files modified. + git("pull", "--rebase", "--autostash", "origin", branch) && // --atomic: never leave the tag pushed without the branch (or the reverse). git("push", "--atomic", "origin", "HEAD", `refs/tags/${tag}`) ); diff --git a/tools/wait-for-npm-version.test.ts b/tools/wait-for-npm-version.test.ts index 2ac470652..0dcbbb7ca 100644 --- a/tools/wait-for-npm-version.test.ts +++ b/tools/wait-for-npm-version.test.ts @@ -14,25 +14,26 @@ let directory: string; let server: Server; const requests = new Map(); -/** - * A registry that serves `name@VERSION` only from request `servedFrom[name]` - * on; before that it returns the pre-publish packument, cacheable like npm's. - * A "stall" package gets no answer at all. - */ -async function fakeRegistry(servedFrom: Record) { +async function fakeRegistry( + servedFrom: Record, +) { + let arrived = () => {}; + const firstRequest = new Promise((resolve) => (arrived = resolve)); server = createServer((req, res) => { + arrived(); const name = decodeURIComponent(req.url?.slice(1) ?? ""); const count = (requests.get(name) ?? 0) + 1; requests.set(name, count); const from = servedFrom[name]; if (from === "stall") return; - if (from === undefined) { - res.writeHead(404).end(); + if (from === undefined || from === "deny") { + res.writeHead(from === "deny" ? 401 : 404).end(); return; } const versions = count >= from ? ["0.103.0", VERSION] : ["0.103.0"]; res.writeHead(200, { "content-type": "application/json", + // Cacheable like the real registry: npm must revalidate, not reuse it. "cache-control": "public, max-age=300", }); res.end( @@ -57,6 +58,7 @@ async function fakeRegistry(servedFrom: Record) { // Both spellings: npm reads either, and the developer's env may set one. vi.stubEnv("npm_config_registry", registry); vi.stubEnv("NPM_CONFIG_REGISTRY", registry); + return { firstRequest }; } beforeEach(() => { @@ -83,62 +85,102 @@ test( await waitForNpmVersion( ["@databricks/appkit", "@databricks/appkit-ui"], VERSION, - { - cwd: directory, - timeoutMs: 50_000, - ...fast, - }, + { cwd: directory, timeoutMs: 50_000, ...fast }, ); - // One request per try: the cached stale packument is never trusted. - expect(requests.get("@databricks/appkit")).toBe(3); - expect(requests.get("@databricks/appkit-ui")).toBe(2); + expect(requests.get("@databricks/appkit")).toBeGreaterThanOrEqual(3); + expect(requests.get("@databricks/appkit-ui")).toBeGreaterThanOrEqual(2); }, ); test( - "names the package and version when the wait times out", + "reads npm's answer when the environment sets npm_config_json", { timeout: 60_000 }, async () => { - await fakeRegistry({ - "@databricks/appkit": 1, - "@databricks/appkit-ui": Infinity, + await fakeRegistry({ "@databricks/appkit": 1 }); + vi.stubEnv("npm_config_json", "true"); + + await waitForNpmVersion(["@databricks/appkit"], VERSION, { + cwd: directory, + timeoutMs: 50_000, + ...fast, }); + }, +); + +test( + "names the package and version when the wait times out", + { timeout: 60_000 }, + async () => { + await fakeRegistry({ "@databricks/appkit-ui": Infinity }); await expect( - waitForNpmVersion( - ["@databricks/appkit", "@databricks/appkit-ui"], - VERSION, - { - cwd: directory, - timeoutMs: 1_000, - ...fast, - }, - ), + waitForNpmVersion(["@databricks/appkit-ui"], VERSION, { + cwd: directory, + timeoutMs: 2_000, + ...fast, + }), ).rejects.toThrow( - `@databricks/appkit-ui@${VERSION} is still not on the npm registry`, + `@databricks/appkit-ui@${VERSION} is still not on the npm registry after 2s`, ); }, ); test( - "a registry that never answers still ends the wait on time", + "checks once more at the deadline instead of giving up early", + { timeout: 60_000 }, + async () => { + await fakeRegistry({ "@databricks/appkit": 2 }); + + await waitForNpmVersion(["@databricks/appkit"], VERSION, { + cwd: directory, + timeoutMs: 3_000, + delayMs: 60_000, + maxDelayMs: 60_000, + }); + + expect(requests.get("@databricks/appkit")).toBeGreaterThanOrEqual(2); + }, +); + +test( + "fails at once on an error that waiting can't fix", { timeout: 60_000 }, async () => { - await fakeRegistry({ "@databricks/appkit": "stall" }); - const started = Date.now(); + await fakeRegistry({ "@databricks/appkit": "deny" }); await expect( waitForNpmVersion(["@databricks/appkit"], VERSION, { cwd: directory, - timeoutMs: 2_000, + timeoutMs: 50_000, ...fast, }), - ).rejects.toThrow( - `@databricks/appkit@${VERSION} is still not on the npm registry after 2s. ` + - "Last npm view output:\nnpm view did not answer in time", - ); + ).rejects.toThrow(`npm view @databricks/appkit@${VERSION} failed (E401)`); + expect(requests.get("@databricks/appkit")).toBe(1); + }, +); + +test( + "a registry that never answers still ends the wait on time", + { timeout: 60_000 }, + async () => { + const { firstRequest } = await fakeRegistry({ + "@databricks/appkit": "stall", + }); + + const failed = expect( + waitForNpmVersion(["@databricks/appkit"], VERSION, { + cwd: directory, + timeoutMs: 3_000, + lastProbeMs: 500, + ...fast, + }), + ).rejects.toThrow("npm view did not answer in time"); + await firstRequest; + const stalledAt = Date.now(); + await failed; + // npm alone would wait out its 5-minute fetch timeout. - expect(Date.now() - started).toBeLessThan(10_000); + expect(Date.now() - stalledAt).toBeLessThan(10_000); }, ); diff --git a/tools/wait-for-npm-version.ts b/tools/wait-for-npm-version.ts index a9abfce44..44872e44c 100644 --- a/tools/wait-for-npm-version.ts +++ b/tools/wait-for-npm-version.ts @@ -3,13 +3,18 @@ import { setTimeout as sleep } from "node:timers/promises"; import { promisify } from "node:util"; const execFileAsync = promisify(execFile); -// npm's own fetch timeout (5 min, retried) could outlast the whole wait. -const PROBE_TIMEOUT_MS = 60_000; +// Not published yet (E404), a registry hiccup, or a network error npm itself +// retries (make-fetch-happen's list); anything else won't go away by waiting. +const RETRYABLE = new RegExp( + "^(E404|E408|E429|E5\\d\\d|EAI_AGAIN|ECONNRESET|ECONNREFUSED|EADDRINUSE|ETIMEDOUT|" + + "ECONNECTIONTIMEOUT|EIDLETIMEOUT|ERESPONSETIMEOUT|ETRANSFERTIMEOUT)$", +); /** * Waits until the npm registry serves `name@version` for every name. A * just-published version takes minutes to reach the registry's packument and - * CDN cache, so installing it right away fails with ETARGET. + * CDN cache, so installing it right away fails with ETARGET. Errors that + * waiting can't fix (auth, config, no npm) fail at once. */ export async function waitForNpmVersion( names: string[], @@ -19,43 +24,87 @@ export async function waitForNpmVersion( timeoutMs = 10 * 60_000, delayMs = 5_000, maxDelayMs = 30_000, + lastProbeMs = 30_000, } = {}, ): Promise { const deadline = Date.now() + timeoutMs; for (const name of names) { for (let delay = delayMs; ; delay = Math.min(delay * 2, maxDelayMs)) { - // npm view already revalidates its cache by default; --prefer-online - // keeps it that way if a config default changes. - const { stdout, stderr } = await execFileAsync( - "npm", - ["view", `${name}@${version}`, "version", "--prefer-online"], - { - cwd, - timeout: Math.max( - 1, - Math.min(PROBE_TIMEOUT_MS, deadline - Date.now()), - ), - }, - ).catch((error) => ({ - stdout: "", - stderr: error.killed - ? "npm view did not answer in time" - : String(error.stderr || error.message), - })); - if (stdout.trim() === version) { + // A probe may run until the deadline (npm's own fetch timeout is 5 + // minutes, retried); the one at the deadline still gets lastProbeMs. + const answer = await npmView( + name, + version, + cwd, + Math.max(deadline - Date.now(), lastProbeMs), + ); + if (answer.code === "OK") { console.log(`✓ ${name}@${version} is on the npm registry`); break; } - if (Date.now() + delay > deadline) { + if (!RETRYABLE.test(answer.code)) { + throw new Error( + `npm view ${name}@${version} failed (${answer.code}): ${answer.summary}`, + ); + } + const left = deadline - Date.now(); + if (left <= 0) { throw new Error( `${name}@${version} is still not on the npm registry after ${Math.round(timeoutMs / 1000)}s. ` + - `Last npm view output:\n${stderr.trim() || stdout.trim()}`, + `Last npm view answer: ${answer.code} ${answer.summary}`, ); } + const wait = Math.min(delay, left); console.warn( - `${name}@${version} is not on the npm registry yet, checking again in ${delay / 1000}s...`, + `${name}@${version} is not on the npm registry yet (${answer.code}), checking again in ${wait / 1000}s...`, ); - await sleep(delay); + await sleep(wait); } } } + +function npmView( + name: string, + version: string, + cwd: string, + timeout: number, +): Promise<{ code: string; summary: string }> { + // --json: plain output changes shape when the environment sets + // npm_config_json, and errors come back with npm's error code. + return execFileAsync( + "npm", + ["view", `${name}@${version}`, "version", "--json", "--prefer-online"], + { cwd, timeout }, + ).then( + ({ stdout }) => + parseJson(stdout) === version + ? { code: "OK", summary: "" } + : { + code: "E404", + summary: `npm view printed ${stdout.trim() || "nothing"}`, + }, + (error) => { + if (error.killed) { + return { + code: "ETIMEDOUT", + summary: "npm view did not answer in time", + }; + } + const reported = parseJson(error.stdout)?.error; + return { + code: String(reported?.code ?? error.code), + summary: String( + reported?.summary ?? (error.stderr || error.message), + ).trim(), + }; + }, + ); +} + +function parseJson(text: string | undefined) { + try { + return JSON.parse(text ?? ""); + } catch { + return undefined; + } +}