diff --git a/.github/workflows/publish-version.yml b/.github/workflows/publish-version.yml
index cb4fa105..b95637bc 100644
--- a/.github/workflows/publish-version.yml
+++ b/.github/workflows/publish-version.yml
@@ -334,6 +334,16 @@ jobs:
node -e 'const p=require(process.argv[1]); for (const k of ["kind","id","root"]) console.log(`${k}=${p[k]}`)' "$RUNNER_TEMP/plan.json" >> "$GITHUB_OUTPUT"
cat "$RUNNER_TEMP/plan.json"
+ - name: Fetch the release schedule
+ # Before any content is on disk: this is the only step that holds the
+ # job's token, and the build reads the result from a file.
+ working-directory: engine/apps/docs
+ env:
+ DOCS_GITHUB_TOKEN: ${{ github.token }}
+ run: |
+ set -euo pipefail
+ pnpm run --silent publish:release-schedule -- --out "$RUNNER_TEMP/release-schedule.json"
+
- name: Check out the content tree at the resolved commit
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
@@ -401,9 +411,8 @@ jobs:
# variable is "1": it builds the semantic index and turns on the
# hybrid search dialog.
DOCS_SEMANTIC_SEARCH: ${{ vars.DOCS_SEMANTIC_SEARCH }}
- # Read-only: the release schedule is public, and the job's own token
- # only lifts the anonymous rate limit for the sync's GitHub fetch.
- DOCS_GITHUB_TOKEN: ${{ github.token }}
+ # Fetched above, before the content checkout.
+ DOCS_RELEASE_SCHEDULE_FILE: ${{ runner.temp }}/release-schedule.json
run: |
set -euo pipefail
pnpm turbo run build --filter=@coder/docs-site
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 3c888fa2..cd6a8e02 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -200,7 +200,10 @@ It is the next step if the sanitizer ever has to be weakened, and otherwise a la
The Releases page's release schedule is data, not content: coder/coder authors a `
` marker with a fallback link, and the engine fills it from GitHub.
`buildReleaseSchedule` in `@coder/docs-config` is the one definition of the rows: stable is the minor of GitHub's latest release, mainline and security support are the released minor lines either side of it (ordered by major, then minor), the ESR set comes from coder/coder's `scripts/release_channels/esr_versions.txt`, and an ESR drops out 365 days after its first release.
-The sync fetches the schedule once per build (`writeReleaseSchedule` in `@coder/docs-build`), a publish fails if it cannot, and `remarkReleasesTable` rewrites the marker into `ReleasesTable`, whose children carry the same rows as a Markdown table for search and the Markdown twin.
+The sync gets the schedule once per build (`writeReleaseSchedule` in `@coder/docs-build`), and `remarkReleasesTable` rewrites the marker into `ReleasesTable`, whose children carry the same rows as a Markdown table for search and the Markdown twin.
+In a publish, a separate `Fetch the release schedule` step fetches it with the job's token before the content checkout, and the sync reads that file through `DOCS_RELEASE_SCHEDULE_FILE` instead of fetching.
+That keeps the invariant that there is no token in the build step's environment, the step that compiles untrusted content, so never pass that step a token.
+A publish fails if the fetch does.
A tag build is never rebuilt, so on the public site `ReleasesTable` refreshes from the router's `/releases.json`, which fetches GitHub at most once an hour per isolate; the offline export keeps its build-time table.
Older refs carry a static table between `RELEASE_CALENDAR_START/END` comments; the sync strips comments, so `rewriteLegacyReleaseCalendar` turns that region into the marker first, line for line.
diff --git a/apps/docs/README.md b/apps/docs/README.md
index 9caeb2f2..fa8d382d 100644
--- a/apps/docs/README.md
+++ b/apps/docs/README.md
@@ -321,6 +321,13 @@ Any experiment with `DOCS_UPLOAD_CONCURRENCY` above `16` must be a single publis
`publish:cleanup` deletes an archive prefix once the manifest no longer references it and it has stayed unreferenced for at least seven days, giving an in-flight reader time to finish against a prefix the manifest just stopped pointing at.
A tag prefix (`versions///` for a `vX.Y.Z` tag) is never deleted by the pipeline, whatever the manifest says, since a tag is frozen forever once published.
+Every upload writes a small `_uploading.json` marker at the prefix root before any other object, and `_publish.json` last.
+A re-upload of the same commit leaves the old `_publish.json` in place until its final put, so cleanup takes the newer of the two as the prefix's last activity and keeps any prefix whose last activity falls inside the grace period.
+The listing ages each prefix by `_publish.json` alone to pick candidates; the check that decides is a re-read of both objects, made after the candidate's objects have been listed and immediately before each delete call, including a delete retried after a rate limit.
+A prefix without `_publish.json` is never deleted: at listing time it is an upload in flight, and at delete time it is already gone.
+A skipped candidate is logged with the reason, either `saw upload activity at ` or `its _publish.json is gone`.
+The one window left is between that re-read and the store acting on the delete.
+
### coder/coder trigger
`docs/superpowers/upstream/coder-coder-docs-publish-branches.yml` and `docs/superpowers/upstream/coder-coder-docs-publish-tags.yml` are the templates for the two workflows that land in coder/coder as `.github/workflows/docs-publish.yml` and `.github/workflows/docs-publish-tags.yml`.
@@ -457,7 +464,7 @@ A publish is visible everywhere within a minute; inside that window a navigation
The router serves archive objects from a route handler rather than middleware so that its own edge keeps the copy: Vercel's CDN never caches a middleware response.
`vercel.json` carries the same two rules for a Vercel deployment of the export.
The archive objects themselves are uploaded with a one-year store TTL, pages and payloads included, because every key lives under `versions///` and a publish never changes the bytes behind one; the router reads through the store's CDN and sets the client-facing `Cache-Control` above itself, so the TTL only decides whether a miss at the router's edge is answered by the store's CDN or by origin storage.
-Only `_publish.json` and `_objects.json` keep a 60-second TTL: both are rewritten with new content when the previous mainline is republished under its version segment, and only the publisher reads them.
+Only `_publish.json`, `_objects.json` and `_uploading.json` keep a 60-second TTL: the first two are rewritten with new content when the previous mainline is republished under its version segment, the marker is rewritten by every upload, and only the publish pipeline reads them.
The emergency tag republish (`republish-lines.yml` with `tags: true`) rewrites archive keys in place; Vercel propagates an overwrite through the store's cache within 60 seconds whatever the object's TTL, the same minute the edge rule already tolerates.
### Client-side navigation on a static host
diff --git a/apps/docs/package.json b/apps/docs/package.json
index a5922062..3005bc9e 100644
--- a/apps/docs/package.json
+++ b/apps/docs/package.json
@@ -36,7 +36,8 @@
"publish:cleanup": "node --import tsx scripts/publish/cleanup.mjs",
"publish:reconcile": "node --import tsx scripts/publish/reconcile.mjs",
"publish:smoke": "node --import tsx scripts/publish/smoke.mjs",
- "publish:rollback": "node --import tsx scripts/publish/rollback.mjs"
+ "publish:rollback": "node --import tsx scripts/publish/rollback.mjs",
+ "publish:release-schedule": "node --import tsx scripts/publish/release-schedule.mjs"
},
"dependencies": {
"@coder/docs-build": "workspace:*",
diff --git a/apps/docs/scripts/publish/cleanup.mjs b/apps/docs/scripts/publish/cleanup.mjs
index 0956b7ac..81c62e9e 100644
--- a/apps/docs/scripts/publish/cleanup.mjs
+++ b/apps/docs/scripts/publish/cleanup.mjs
@@ -5,7 +5,7 @@ import { del, list } from "@vercel/blob";
import { parseManifestItems, readManifestItems } from "@coder/docs-manifest";
import { withBlobRetry } from "./blob-retry.mjs";
import { need } from "./env.mjs";
-import { assertArchivePrefix, isArchivePrefix } from "./upload.mjs";
+import { UPLOADING_KEY, assertArchivePrefix, isArchivePrefix } from "./upload.mjs";
const TAG_PREFIX = /^versions\/\d+\.\d+\.\d+\//;
@@ -65,70 +65,135 @@ export function planCleanup({ prefixes, referenced, now, graceMs }) {
const listWithRetry = (options) =>
withBlobRetry(() => list(options), { key: `list ${options.prefix}` });
-async function* foldedFolders(prefix, token) {
+/** @typedef {(options: { prefix: string; limit?: number; mode?: "folded"; cursor?: string }) => Promise<{ blobs: { url?: string; uploadedAt: Date | string }[]; folders?: string[]; hasMore?: boolean; cursor?: string }>} ListPage */
+
+async function* pages(listPage, options) {
let cursor;
do {
- const page = await listWithRetry({ prefix, mode: "folded", limit: 1000, cursor, token });
- for (const folder of page.folders ?? []) yield folder;
+ const page = await listPage({ ...options, cursor });
+ yield page;
cursor = page.hasMore ? page.cursor : undefined;
} while (cursor);
}
-async function listPrefixes(token) {
- // versions///... : fold twice to enumerate prefixes, then read the
- // upload time from each prefix's _publish.json object.
+async function* foldedFolders(listPage, prefix) {
+ for await (const page of pages(listPage, { prefix, mode: "folded", limit: 1000 })) {
+ yield* page.folders ?? [];
+ }
+}
+
+async function indexTime(prefix, listPage) {
+ const [index] = (await listPage({ prefix: `${prefix}/_publish.json`, limit: 1 })).blobs;
+ return index ? new Date(index.uploadedAt) : undefined;
+}
+
+/**
+ * The newer of a prefix's index and upload marker; undefined when it has no index.
+ * @param {string} prefix
+ * @param {ListPage} listPage
+ */
+export async function lastActivity(prefix, listPage) {
+ const index = await indexTime(prefix, listPage);
+ if (!index) return undefined;
+ const [marker] = (await listPage({ prefix: `${prefix}/${UPLOADING_KEY}`, limit: 1 })).blobs;
+ return new Date(Math.max(index, marker ? new Date(marker.uploadedAt) : 0));
+}
+
+/**
+ * Why a prefix must be kept right now, or undefined when it may be deleted.
+ * @param {{ prefix: string; listPage: ListPage; now: Date; graceMs: number }} input
+ */
+export async function keepReason({ prefix, listPage, now, graceMs }) {
+ const latest = await lastActivity(prefix, listPage);
+ if (latest === undefined) return "its _publish.json is gone";
+ if (now.getTime() - latest.getTime() < graceMs) {
+ return `saw upload activity at ${latest.toISOString()}`;
+ }
+ return undefined;
+}
+
+async function listPrefixes(listPage, log) {
+ // versions///... : fold twice to enumerate prefixes, then age each by its _publish.json.
const prefixes = [];
- for await (const idFolder of foldedFolders("versions/", token)) {
- for await (const shaFolder of foldedFolders(idFolder, token)) {
- const page = await listWithRetry({ prefix: `${shaFolder}_publish.json`, limit: 1, token });
- const indexBlob = page.blobs[0];
- if (!indexBlob) {
- // upload.mjs writes _publish.json last, so a prefix without one is an
- // upload still in flight (or one that failed and will be retried), not
- // an old orphan. Never judge its age; leave it for a later run.
- console.log(`cleanup: ${shaFolder} has no _publish.json yet; skipping`);
+ for await (const idFolder of foldedFolders(listPage, "versions/")) {
+ for await (const shaFolder of foldedFolders(listPage, idFolder)) {
+ const prefix = shaFolder.replace(/\/$/, "");
+ const uploadedAt = await indexTime(prefix, listPage);
+ if (!uploadedAt) {
+ // upload.mjs writes _publish.json last, so this is an upload in flight, not an orphan.
+ log(`cleanup: ${shaFolder} has no _publish.json yet; skipping`);
continue;
}
- prefixes.push({
- prefix: shaFolder.replace(/\/$/, ""),
- uploadedAt: new Date(indexBlob.uploadedAt),
- });
+ prefixes.push({ prefix, uploadedAt });
}
}
return prefixes;
}
-if (process.argv[1]?.endsWith("cleanup.mjs")) {
- const dryRun = process.argv.includes("--dry-run");
- const token = need("BLOB_READ_WRITE_TOKEN");
- const items = await readManifestItems({
- token: need("DOCS_VERSIONS_WRITE_TOKEN"),
- teamId: need("VERCEL_TEAM_ID"),
- configId: need("DOCS_VERSIONS_GLOBAL_CONFIG_ID"),
- });
+/**
+ * @param {{
+ * items: unknown;
+ * listPage: ListPage;
+ * delPage: (urls: string[]) => Promise;
+ * now?: () => Date;
+ * graceMs: number;
+ * dryRun?: boolean;
+ * log?: (line: string) => void;
+ * retry?: Parameters[1];
+ * }} input
+ */
+export async function runCleanup({
+ items,
+ listPage,
+ delPage,
+ now = () => new Date(),
+ graceMs,
+ dryRun = false,
+ log = console.log,
+ retry = {},
+}) {
const referenced = referencedPrefixes(items);
- const prefixes = await listPrefixes(token);
const doomed = planCleanup({
- prefixes,
+ prefixes: await listPrefixes(listPage, log),
referenced,
- now: new Date(),
- graceMs: 7 * 24 * 60 * 60 * 1000,
+ now: now(),
+ graceMs,
});
for (const prefix of doomed) {
// Last gate before a destructive call: planCleanup already filtered on
// the shape, so this can only fail if that filter is ever loosened.
assertArchivePrefix(prefix);
const urls = [];
- let cursor;
- do {
- const page = await listWithRetry({ prefix: `${prefix}/`, limit: 1000, cursor, token });
+ for await (const page of pages(listPage, { prefix: `${prefix}/`, limit: 1000 })) {
urls.push(...page.blobs.map((b) => b.url));
- cursor = page.hasMore ? page.cursor : undefined;
- } while (cursor);
- console.log(`${dryRun ? "would delete" : "deleting"} ${prefix} (${urls.length} objects)`);
- if (!dryRun && urls.length > 0) {
- await withBlobRetry(() => del(urls, { token }), { key: `delete ${prefix}` });
}
+ // The re-read sits inside the retried closure so a delete retried after a 429 checks again.
+ const kept = await withBlobRetry(
+ async () => {
+ const reason = await keepReason({ prefix, listPage, now: now(), graceMs });
+ if (reason) return reason;
+ if (!dryRun && urls.length > 0) await delPage(urls);
+ return undefined;
+ },
+ { ...retry, key: `delete ${prefix}` },
+ );
+ if (kept) log(`cleanup: ${prefix} ${kept}; skipping`);
+ else log(`${dryRun ? "would delete" : "deleted"} ${prefix} (${urls.length} objects)`);
}
- if (doomed.length === 0) console.log("nothing to clean up");
+ if (doomed.length === 0) log("nothing to clean up");
+}
+
+if (process.argv[1]?.endsWith("cleanup.mjs")) {
+ const token = need("BLOB_READ_WRITE_TOKEN");
+ await runCleanup({
+ items: await readManifestItems({
+ token: need("DOCS_VERSIONS_WRITE_TOKEN"),
+ teamId: need("VERCEL_TEAM_ID"),
+ configId: need("DOCS_VERSIONS_GLOBAL_CONFIG_ID"),
+ }),
+ listPage: (options) => listWithRetry({ ...options, token }),
+ delPage: (urls) => del(urls, { token }),
+ graceMs: 7 * 24 * 60 * 60 * 1000,
+ dryRun: process.argv.includes("--dry-run"),
+ });
}
diff --git a/apps/docs/scripts/publish/cleanup.test.mjs b/apps/docs/scripts/publish/cleanup.test.mjs
index c187cb92..dfb8b008 100644
--- a/apps/docs/scripts/publish/cleanup.test.mjs
+++ b/apps/docs/scripts/publish/cleanup.test.mjs
@@ -1,6 +1,13 @@
import assert from "node:assert/strict";
import { test } from "node:test";
-import { planCleanup, referencedPrefixes } from "./cleanup.mjs";
+import { BlobServiceRateLimited } from "@vercel/blob";
+import {
+ keepReason,
+ lastActivity,
+ planCleanup,
+ referencedPrefixes,
+ runCleanup,
+} from "./cleanup.mjs";
const day = 24 * 60 * 60 * 1000;
const now = new Date("2026-09-20T00:00:00Z");
@@ -134,3 +141,158 @@ test("a version served from a Vercel deployment has no archive prefix to protect
});
assert.deepEqual([...refs], [`versions/2.35/${"b".repeat(40)}`]);
});
+
+// A fake store: `blobs` maps a full key to its upload time, and `onList` sees every list call.
+function fakeStore(blobs, onList = () => {}) {
+ const listPage = async (options) => {
+ onList(options);
+ const keys = Object.keys(blobs).filter((key) => key.startsWith(options.prefix));
+ if (options.mode === "folded") {
+ const folders = new Set(
+ keys.map((key) => `${options.prefix}${key.slice(options.prefix.length).split("/")[0]}/`),
+ );
+ return { blobs: [], folders: [...folders], hasMore: false };
+ }
+ return {
+ blobs: keys.map((pathname) => ({
+ pathname,
+ url: `${store}/${pathname}`,
+ uploadedAt: blobs[pathname],
+ })),
+ hasMore: false,
+ };
+ };
+ return { blobs, listPage };
+}
+
+const orphan = `versions/2.36/${"c".repeat(40)}`;
+const live = `versions/2.36/${"a".repeat(40)}`;
+const items = {
+ "line_2-36": {
+ id: "2.36",
+ label: "v2.36",
+ ref: "release/2.36",
+ sha: "a".repeat(40),
+ deployment: `${store}/${live}`,
+ publishedAt: "2026-09-01T00:00:00Z",
+ },
+ mainline: "2.36",
+};
+const old = new Date(now.getTime() - 30 * day);
+
+function archive(extra = {}) {
+ return {
+ [`${live}/_publish.json`]: old,
+ [`${live}/index.html`]: old,
+ [`${orphan}/_publish.json`]: old,
+ [`${orphan}/_uploading.json`]: old,
+ [`${orphan}/index.html`]: old,
+ ...extra,
+ };
+}
+
+async function cleanup(fake, options = {}) {
+ const deleted = [];
+ const lines = [];
+ await runCleanup({
+ items,
+ listPage: fake.listPage,
+ delPage: async (urls) => {
+ deleted.push(...urls);
+ },
+ now: () => now,
+ graceMs: 7 * day,
+ log: (line) => lines.push(line),
+ ...options,
+ ...(options.delPage ? { delPage: (urls) => options.delPage(urls, deleted) } : {}),
+ });
+ return { deleted, lines };
+}
+
+test("a prefix's last activity is the newer of its index and its upload marker", async () => {
+ const recent = new Date(now.getTime() - 1 * day);
+ const { listPage: idle } = fakeStore({ [`${orphan}/_publish.json`]: old });
+ assert.deepEqual(await lastActivity(orphan, idle), old);
+ const { listPage: busy } = fakeStore({
+ [`${orphan}/_publish.json`]: old,
+ [`${orphan}/_uploading.json`]: recent,
+ });
+ assert.deepEqual(await lastActivity(orphan, busy), recent);
+ assert.equal(await lastActivity(orphan, fakeStore({}).listPage), undefined);
+});
+
+test("an idle unreferenced prefix past the grace period is deleted, every object of it", async () => {
+ const { deleted } = await cleanup(fakeStore(archive()));
+ assert.deepEqual(deleted.toSorted(), [
+ `${store}/${orphan}/_publish.json`,
+ `${store}/${orphan}/_uploading.json`,
+ `${store}/${orphan}/index.html`,
+ ]);
+});
+
+test("a dry run deletes nothing", async () => {
+ const { deleted, lines } = await cleanup(fakeStore(archive()), { dryRun: true });
+ assert.deepEqual(deleted, []);
+ assert.ok(lines.includes(`would delete ${orphan} (3 objects)`));
+});
+
+test("a prefix whose upload marker is already fresh at listing time is never deleted", async () => {
+ const fake = fakeStore(
+ archive({ [`${orphan}/_uploading.json`]: new Date(now.getTime() - 1000) }),
+ );
+ const { deleted, lines } = await cleanup(fake);
+ assert.deepEqual(deleted, []);
+ assert.ok(lines.some((l) => l.startsWith(`cleanup: ${orphan} saw upload activity at `)));
+});
+
+test("a re-upload that starts while cleanup lists the prefix's objects keeps the prefix", async () => {
+ // The marker turns fresh during the object listing, after the listing that chose the prefix.
+ const fake = fakeStore(archive(), ({ prefix }) => {
+ if (prefix === `${orphan}/`)
+ fake.blobs[`${orphan}/_uploading.json`] = new Date(now.getTime() - 1000);
+ });
+ const { deleted } = await cleanup(fake);
+ assert.deepEqual(deleted, []);
+});
+
+test("a delete retried after a 429 re-checks the prefix first", async () => {
+ const fake = fakeStore(archive());
+ let attempts = 0;
+ const { deleted } = await cleanup(fake, {
+ retry: { sleep: async () => {}, onRetry: () => {}, jitter: () => 0 },
+ delPage: async (urls, sink) => {
+ attempts++;
+ if (attempts === 1) {
+ fake.blobs[`${orphan}/_uploading.json`] = new Date(now.getTime() - 1000);
+ throw new BlobServiceRateLimited(1);
+ }
+ sink.push(...urls);
+ },
+ });
+ assert.equal(attempts, 1);
+ assert.deepEqual(deleted, []);
+});
+
+test("a prefix whose index disappears before its delete is kept, and the log says why", async () => {
+ const fake = fakeStore(archive(), ({ prefix }) => {
+ if (prefix === `${orphan}/`) delete fake.blobs[`${orphan}/_publish.json`];
+ });
+ const { deleted, lines } = await cleanup(fake);
+ assert.deepEqual(deleted, []);
+ assert.ok(lines.includes(`cleanup: ${orphan} its _publish.json is gone; skipping`));
+});
+
+test("keepReason allows an idle prefix and names what keeps a busy one", async () => {
+ const graceMs = 7 * day;
+ const { listPage: idle } = fakeStore({ [`${orphan}/_publish.json`]: old });
+ assert.equal(await keepReason({ prefix: orphan, listPage: idle, now, graceMs }), undefined);
+ const recent = new Date(now.getTime() - 1000);
+ const { listPage: busy } = fakeStore({
+ [`${orphan}/_publish.json`]: old,
+ [`${orphan}/_uploading.json`]: recent,
+ });
+ assert.equal(
+ await keepReason({ prefix: orphan, listPage: busy, now, graceMs }),
+ `saw upload activity at ${recent.toISOString()}`,
+ );
+});
diff --git a/apps/docs/scripts/publish/env.mjs b/apps/docs/scripts/publish/env.mjs
index 16f5db1c..6344f401 100644
--- a/apps/docs/scripts/publish/env.mjs
+++ b/apps/docs/scripts/publish/env.mjs
@@ -1,4 +1,4 @@
-// Shared by the publish scripts (cleanup, mirror, plan, reconcile).
+// Shared by the publish scripts (cleanup, mirror, plan, reconcile, release-schedule).
export function need(name) {
const v = process.env[name];
if (!v) throw new Error(`${name} must be set`);
diff --git a/apps/docs/scripts/publish/release-schedule.mjs b/apps/docs/scripts/publish/release-schedule.mjs
new file mode 100644
index 00000000..fee72a75
--- /dev/null
+++ b/apps/docs/scripts/publish/release-schedule.mjs
@@ -0,0 +1,20 @@
+#!/usr/bin/env node
+// Fetch the release schedule with the job's token, so the build step that
+// compiles the corpus can read it from a file and never holds the token.
+import { writeReleaseSchedule } from "@coder/docs-build";
+import { need } from "./env.mjs";
+
+const flagAt = process.argv.indexOf("--out");
+const out = flagAt === -1 ? undefined : process.argv[flagAt + 1];
+if (!out || out.startsWith("--")) {
+ process.stderr.write(
+ "usage: DOCS_GITHUB_TOKEN=... release-schedule.mjs --out release-schedule.json\n",
+ );
+ process.exit(1);
+}
+const schedule = await writeReleaseSchedule({
+ outFile: out,
+ token: need("DOCS_GITHUB_TOKEN"),
+ required: true,
+});
+console.log(`release schedule: ${schedule?.generatedAt}`);
diff --git a/apps/docs/scripts/publish/upload.mjs b/apps/docs/scripts/publish/upload.mjs
index 2f058453..92625da7 100644
--- a/apps/docs/scripts/publish/upload.mjs
+++ b/apps/docs/scripts/publish/upload.mjs
@@ -110,6 +110,9 @@ export function liveArchivePrefix({ items, plan }) {
// `_publish.json` hashes are the untrusted build's claims.
const OBJECTS_KEY = "_objects.json";
+/** Written first by every upload, so cleanup can tell a prefix being re-uploaded from an idle orphan. */
+export const UPLOADING_KEY = "_uploading.json";
+
async function readRecordedObjects({ prefix, token, blobGet, onReuseSkipped }) {
try {
const result = await withBlobRetry(
@@ -264,6 +267,14 @@ export async function uploadDir({
storeOrigin ??= new URL(result.url).origin;
}
}
+ await putWithRetry(`${prefix}/${UPLOADING_KEY}`, JSON.stringify({ version: 1 }), {
+ access: "private",
+ addRandomSuffix: false,
+ allowOverwrite: true,
+ contentType: "application/json; charset=utf-8",
+ cacheControlMaxAge: 60,
+ token,
+ });
await Promise.all(Array.from({ length: concurrency }, (_, id) => worker(id)));
const recordedFiles = Object.fromEntries(
Object.entries(recorded).toSorted(([a], [b]) => (a < b ? -1 : 1)),
diff --git a/apps/docs/scripts/publish/upload.test.mjs b/apps/docs/scripts/publish/upload.test.mjs
index 63b216ac..01941e75 100644
--- a/apps/docs/scripts/publish/upload.test.mjs
+++ b/apps/docs/scripts/publish/upload.test.mjs
@@ -97,6 +97,11 @@ test("a tampered contentType in the publish index never reaches the uploaded obj
// Every archive object carries the year; only the index, which the publisher
// rewrites and reads back, keeps the short TTL.
assert.deepEqual(puts, [
+ {
+ key: `${prefix}/_uploading.json`,
+ contentType: "application/json; charset=utf-8",
+ maxAge: 60,
+ },
{
key: `${prefix}/_next/static/chunks/a.js`,
contentType: "text/javascript; charset=utf-8",
@@ -258,6 +263,7 @@ test("a rate-limited put is retried, logged with its key, and the file lands exa
store.succeeded.toSorted(),
[
...files.map((f) => `${prefix}/${f}`),
+ `${prefix}/_uploading.json`,
`${prefix}/_objects.json`,
`${prefix}/_publish.json`,
].toSorted(),
@@ -327,7 +333,12 @@ test("uploadDir sheds concurrency after a 429, down to the floor, and still uplo
`${overlap} new files were in flight together after the run reached the floor`,
);
// Every key once, each refused key exactly twice, the index last.
- const expected = [...sorted, `${prefix}/_objects.json`, `${prefix}/_publish.json`].toSorted();
+ const expected = [
+ ...sorted,
+ `${prefix}/_uploading.json`,
+ `${prefix}/_objects.json`,
+ `${prefix}/_publish.json`,
+ ].toSorted();
assert.deepEqual(store.succeeded.toSorted(), expected);
assert.ok([...store.attempts.values()].every((n) => n === 2));
assert.equal(store.succeeded.at(-1), `${prefix}/_publish.json`);
@@ -500,7 +511,12 @@ test("with reuseFrom, an object whose recorded hash matches is copied instead of
});
assert.deepEqual(
store.puts.map((p) => p.key),
- [`${prefix}/_next/static/chunks/a.js`, `${prefix}/_objects.json`, `${prefix}/_publish.json`],
+ [
+ `${prefix}/_uploading.json`,
+ `${prefix}/_next/static/chunks/a.js`,
+ `${prefix}/_objects.json`,
+ `${prefix}/_publish.json`,
+ ],
);
assert.equal(result.count, 2);
assert.equal(result.copied, 1);
@@ -529,7 +545,7 @@ test("a source prefix without a readable _objects.json means a full upload, not
});
assert.equal(store.copies.length, 0);
assert.equal(result.copied, 0);
- assert.equal(store.puts.length, 4);
+ assert.equal(store.puts.length, 5);
}
});
@@ -592,3 +608,25 @@ test("liveArchivePrefix finds the prefix the manifest serves this version from",
assert.equal(liveArchivePrefix({ items, plan: { kind: "line", id: "2.36" } }), undefined);
assert.equal(liveArchivePrefix({ items, plan: { kind: "line", id: "2.35" } }), undefined);
});
+
+test("the upload marker is written before any object, so a cleanup sweep sees the prefix as in flight", async () => {
+ const dir = await archiveFixture([entry("index.html"), entry("_next/static/chunks/a.js")]);
+ const prefix = `versions/main/${sha}`;
+ const marker = `${prefix}/_uploading.json`;
+ const keys = [];
+ let releaseMarker;
+ const markerHeld = new Promise((resolve) => {
+ releaseMarker = resolve;
+ });
+ const blobPut = async (key) => {
+ keys.push(key);
+ if (key === marker) await markerHeld;
+ return { url: `https://store.private.blob.vercel-storage.com/${key}` };
+ };
+ const upload = uploadDir({ dir, prefix, token: "t", concurrency: 4, blobPut });
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ assert.deepEqual(keys, [marker]);
+ releaseMarker();
+ await upload;
+ assert.deepEqual(keys.slice(-2), [`${prefix}/_objects.json`, `${prefix}/_publish.json`]);
+});
diff --git a/apps/docs/scripts/sync-docs.mjs b/apps/docs/scripts/sync-docs.mjs
index 2e22973d..d2e63793 100644
--- a/apps/docs/scripts/sync-docs.mjs
+++ b/apps/docs/scripts/sync-docs.mjs
@@ -153,15 +153,22 @@ await writeFile(imageSizesPath(appDir), `${JSON.stringify(imageSizes)}\n`);
// The fixture corpus renders the committed schedule, so CI needs no network;
// a publish must not ship the Releases page without its table.
const fixtureCorpus = !single && !process.env.DOCS_REPO;
+// A schedule fetched earlier by a step that held the token, so the build that
+// compiles the corpus never needs one.
+const scheduleFile = process.env.DOCS_RELEASE_SCHEDULE_FILE;
const schedule = await writeReleaseSchedule({
outFile: releaseSchedulePath(appDir),
token: process.env.DOCS_GITHUB_TOKEN || undefined,
required: process.env.DOCS_PUBLISH === "1",
- schedule: fixtureCorpus
- ? parseReleaseSchedule(
- JSON.parse(await readFile(path.join(appDir, "fixtures", "release-schedule.json"), "utf8")),
- )
- : undefined,
+ schedule: scheduleFile
+ ? parseReleaseSchedule(JSON.parse(await readFile(scheduleFile, "utf8")))
+ : fixtureCorpus
+ ? parseReleaseSchedule(
+ JSON.parse(
+ await readFile(path.join(appDir, "fixtures", "release-schedule.json"), "utf8"),
+ ),
+ )
+ : undefined,
});
console.log(`[sync] release schedule: ${schedule ? schedule.generatedAt : "unavailable"}`);
diff --git a/turbo.json b/turbo.json
index a6b3e9eb..a0decdff 100644
--- a/turbo.json
+++ b/turbo.json
@@ -31,7 +31,8 @@
"DOCS_SOURCE_REPO",
"DOCS_ENGINE_SHA",
"DOCS_PUBLISH",
- "DOCS_GITHUB_TOKEN"
+ "DOCS_GITHUB_TOKEN",
+ "DOCS_RELEASE_SCHEDULE_FILE"
]
},
// The app builds consume content/ and public/ written by the uncacheable