Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions .github/workflows/publish-version.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up: docs-pr-preview.yml:141 still passes DOCS_GITHUB_TOKEN: ${{ github.token }} to the step that builds pull-request content, and that job grants pull-requests: write, a broader token than the contents: read this PR removes here. The required reviewers on docs-preview reduce the risk but don't remove it. The same pattern would work there: fetch the schedule before the content checkout and point DOCS_RELEASE_SCHEDULE_FILE at it (apps/offlinedocs/scripts/sync-docs.mjs:71 would need the same file preference). Or list it under "Not done".

Small wording point: on a hosted runner, a step with code execution and passwordless sudo can still read runner memory, so "no token in the build step's environment" is more accurate than "no longer has any token".

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left docs-pr-preview.yml alone here, because that workflow belongs to another open change, and added it to the PR body's "Not done" list with the pattern you described, including the apps/offlinedocs sync change. I also changed the wording to "no token in the build step's environment" in the PR body and in ARCHITECTURE.md.

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:
Expand Down Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<div data-releases-table>` 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.

Expand Down
9 changes: 8 additions & 1 deletion apps/docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<id>/<sha>/` 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 <time>` 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`.
Expand Down Expand Up @@ -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/<id>/<sha>/` 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
Expand Down
3 changes: 2 additions & 1 deletion apps/docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*",
Expand Down
147 changes: 106 additions & 41 deletions apps/docs/scripts/publish/cleanup.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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+\//;

Expand Down Expand Up @@ -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/<id>/<sha>/... : 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/<id>/<sha>/... : 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<unknown>;
* now?: () => Date;
* graceMs: number;
* dryRun?: boolean;
* log?: (line: string) => void;
* retry?: Parameters<typeof withBlobRetry>[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"),
});
}
Loading
Loading