diff --git a/tools/publish-template-tag.ts b/tools/publish-template-tag.ts index 469f1db63..a9705122e 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,9 @@ 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(); const version = process.argv[2]; if (!version) { @@ -34,12 +37,12 @@ function run( // 1. Update template package.json const templatePath = join(ROOT, "template", "package.json"); const templateJson = JSON.parse(readFileSync(templatePath, "utf-8")); +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,28 +158,17 @@ if (pnpmExit !== 0) { console.log("✓ template/pnpm-lock.yaml updated (pnpm install)"); // 3. Git add, commit, tag, push -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]`], - ], - ["git", ["tag", "-a", `template-v${version}`, "-m", `Template v${version}`]], - ["git", ["push", "origin", "HEAD", "--follow-tags"]], -]; - -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..de02be019 --- /dev/null +++ b/tools/push-template-tag.test.ts @@ -0,0 +1,102 @@ +import { spawnSync } from "node:child_process"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + 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"); + + 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"}'); +}); + +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 new file mode 100644 index 000000000..62ee40752 --- /dev/null +++ b/tools/push-template-tag.ts @@ -0,0 +1,37 @@ +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. + // --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 new file mode 100644 index 000000000..0dcbbb7ca --- /dev/null +++ b/tools/wait-for-npm-version.test.ts @@ -0,0 +1,186 @@ +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(); + +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 || 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( + 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); + return { firstRequest }; +} + +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?.closeAllConnections(); + 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 }, + ); + + expect(requests.get("@databricks/appkit")).toBeGreaterThanOrEqual(3); + expect(requests.get("@databricks/appkit-ui")).toBeGreaterThanOrEqual(2); + }, +); + +test( + "reads npm's answer when the environment sets npm_config_json", + { timeout: 60_000 }, + async () => { + 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-ui"], VERSION, { + cwd: directory, + timeoutMs: 2_000, + ...fast, + }), + ).rejects.toThrow( + `@databricks/appkit-ui@${VERSION} is still not on the npm registry after 2s`, + ); + }, +); + +test( + "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": "deny" }); + + await expect( + waitForNpmVersion(["@databricks/appkit"], VERSION, { + cwd: directory, + timeoutMs: 50_000, + ...fast, + }), + ).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() - stalledAt).toBeLessThan(10_000); + }, +); diff --git a/tools/wait-for-npm-version.ts b/tools/wait-for-npm-version.ts new file mode 100644 index 000000000..44872e44c --- /dev/null +++ b/tools/wait-for-npm-version.ts @@ -0,0 +1,110 @@ +import { execFile } from "node:child_process"; +import { setTimeout as sleep } from "node:timers/promises"; +import { promisify } from "node:util"; + +const execFileAsync = promisify(execFile); +// 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. Errors that + * waiting can't fix (auth, config, no npm) fail at once. + */ +export async function waitForNpmVersion( + names: string[], + version: string, + { + cwd = process.cwd(), + 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)) { + // 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 (!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 answer: ${answer.code} ${answer.summary}`, + ); + } + const wait = Math.min(delay, left); + console.warn( + `${name}@${version} is not on the npm registry yet (${answer.code}), checking again in ${wait / 1000}s...`, + ); + 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; + } +}