Skip to content

Commit 68e6128

Browse files
NelmadTMHSDigitalclaude
authored
Fix transient server errors reported as dead links (#300)
* Fix transient server errors reported as dead links * Pass the test preload to --import as a file URL On Windows an absolute path like C:\... is read as a URL with scheme "c:", so the #275 CLI test failed with ERR_UNSUPPORTED_ESM_URL_SCHEME. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LpkeXPtfg3jGzhfoGMshTE --------- Co-authored-by: TM Hospitality Strategies <TMHospitalityStrategies@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent ea44b24 commit 68e6128

3 files changed

Lines changed: 117 additions & 9 deletions

File tree

‎site/check-links.mjs‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
* Fetches every entry's `url` and reports the ones that need a person:
44
* node site/check-links.mjs [--report <file.md>] [--stale-days 365]
55
*
6-
* - dead: 404/410, 5xx, DNS failure or timeout
6+
* - dead: 404/410 and other HTTP errors, DNS failure or timeout
7+
* - unavailable: 502/503/504, a temporary server failure; listed under
8+
* "Could not check", never counted as a problem
79
* - moved: the final URL is on another domain, or another GitHub repository
810
* - stale: `verified` is older than --stale-days (365 by default)
911
* - blocked: 401/403/429, which is usually a site refusing robots rather
@@ -84,7 +86,7 @@ async function run(entries) {
8486
let r = await check(entries[i]);
8587
// One retry for anything that did not answer cleanly, except a full
8688
// 20 s timeout: a second one would cost a worker 40 s per dead host.
87-
if (r.kind === "dead" && !r.timedOut) r = await check(entries[i]);
89+
if ((r.kind === "dead" || r.kind === "unavailable") && !r.timedOut) r = await check(entries[i]);
8890
// A refusal is not retried, and the checker never poses as a browser:
8991
// a host that refuses scripts goes on the manual list (config.json).
9092
results[i] = r;
@@ -118,11 +120,13 @@ if (staleArg.error) {
118120
const staleDays = staleArg.days;
119121
const entries = loadEntries().filter(isListed);
120122
const results = await run(entries);
121-
// Licence pages quoted in Evidence or linked in Notes, each fetched once (#89, #289). Only a page that
122-
// is gone is reported; a refusal says nothing about the licence.
123+
// Licence pages quoted in Evidence or linked in Notes, each fetched once (#89, #289).
124+
// Only a page that is gone counts as a problem; a refusal says nothing about the licence.
125+
// Temporary server errors are listed under "Could not check".
123126
const pageJobs = [...new Map(entries.flatMap((e) => e.licencePages.map((url) => [url, { id: e.id, rel: e.rel, url }]))).values()];
124127
const pageResults = await run(pageJobs);
125-
const deadPages = pageJobs.map((j, i) => ({ ...j, ...pageResults[i] })).filter((r) => r.kind === "dead");
128+
const pageRows = pageJobs.map((j, i) => ({ ...j, ...pageResults[i] }));
129+
const deadPages = pageRows.filter((r) => r.kind === "dead");
126130
const { mismatches: maintenance, skipped } = await checkMaintenance(entries);
127131
const cutoff = new Date(Date.now() - staleDays * 86400000).toISOString().slice(0, 10);
128132
const rows = entries.map((e, i) => ({ ...e, ...results[i] }));
@@ -132,6 +136,8 @@ const line = (r) => `- [ ] [\`${r.id}\`](${REPO}/blob/main/${r.rel}): ${reportUr
132136

133137
const dead = pick("dead");
134138
const moved = pick("moved");
139+
const unavailable = [...pick("unavailable"), ...pageRows.filter((r) => r.kind === "unavailable")];
140+
const unchecked = [...unavailable, ...skipped];
135141
const refused = pick("blocked");
136142
const blocked = refused.filter((r) => !manualHostReason(r.url, MANUAL_HOSTS));
137143
const byHand = refused.filter((r) => manualHostReason(r.url, MANUAL_HOSTS));
@@ -162,10 +168,12 @@ const report = [
162168
"",
163169
...(maintenance.length ? maintenance.map(line) : ["None."]),
164170
"",
165-
// API trouble is the checker's problem, not the catalog's: listed, not counted.
166-
`### Could not check (${skipped.length} skipped)`,
171+
// Temporary server and API trouble: listed, not counted as catalog problems.
172+
`### Could not check (${unchecked.length} skipped)`,
167173
"",
168-
...(skipped.length ? skipped.map(line) : ["None."]),
174+
"Temporary server errors and GitHub API failures are not counted as problems.",
175+
"",
176+
...(unchecked.length ? unchecked.map(line) : ["None."]),
169177
"",
170178
`<details><summary>Refused the checker (${blocked.length}): usually bot blocking, check by hand</summary>`,
171179
"",
@@ -185,4 +193,4 @@ const reportPath = flags.report ?? null;
185193
if (reportPath) fs.writeFileSync(reportPath, report);
186194
else process.stdout.write(report);
187195
if (process.env.GITHUB_OUTPUT) fs.appendFileSync(process.env.GITHUB_OUTPUT, `problems=${problems}\n`);
188-
console.error(`${entries.length} checked: ${dead.length} dead, ${moved.length} moved, ${stale.length} stale, ${maintenance.length} maintenance, ${deadPages.length} dead licence pages, ${blocked.length} blocked, ${byHand.length} checked by hand, ${skipped.length} API checks skipped`);
196+
console.error(`${entries.length} checked: ${dead.length} dead, ${moved.length} moved, ${stale.length} stale, ${maintenance.length} maintenance, ${deadPages.length} dead licence pages, ${unavailable.length} temporarily unavailable, ${blocked.length} blocked, ${byHand.length} checked by hand, ${skipped.length} API checks skipped`);

‎site/lib/lib.test.mjs‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -892,6 +892,105 @@ eq("403 is blocked", classify("https://a.test/", 403, "https://a.test/").kind, "
892892
eq("404 is dead", classify("https://a.test/", 404, "https://a.test/").kind, "dead");
893893
eq("report url is an inert code span", reportUrl("https://a.test/@x](y)`z"), "`https://a.test/@x](y)%60z`");
894894

895+
/* transient link-check failures (#275) ------------------------------------ */
896+
await section("link-check transient classification (#275)", async () => {
897+
const url = "https://assets.test/pack";
898+
for (const status of [502, 503, 504]) {
899+
const result = classify(url, status, url);
900+
eq(`HTTP ${status} is unavailable`, result.kind, "unavailable");
901+
eq(`HTTP ${status} keeps its status`, result.detail, `HTTP ${status}`);
902+
eq(`HTTP ${status} after a redirect is still unavailable`, classify(url, status, "https://other.test/").kind, "unavailable");
903+
}
904+
for (const status of [400, 404, 405, 410, 422, 500, 501]) {
905+
eq(`HTTP ${status} stays dead`, classify(url, status, url).kind, "dead");
906+
}
907+
for (const status of [401, 403, 429]) {
908+
eq(`HTTP ${status} stays blocked`, classify(url, status, url).kind, "blocked");
909+
}
910+
eq("HTTP 200 stays ok", classify(url, 200, url).kind, "ok");
911+
});
912+
913+
await section("link-check transient report (#275)", async () => {
914+
const { execFileSync } = await import("node:child_process");
915+
const { pathToFileURL } = await import("node:url");
916+
const root = nodeFs.mkdtempSync(nodePath.join(nodeOs.tmpdir(), "fgda-links-"));
917+
try {
918+
// Run the real CLI against a tiny catalog, with all network I/O stubbed
919+
// in a child process so neither the real catalog nor other tests change.
920+
nodeFs.cpSync(new URL("../", import.meta.url), nodePath.join(root, "site"), {
921+
recursive: true,
922+
filter: (src) => nodeFs.statSync(src).isDirectory()
923+
? !["public", "dist"].includes(nodePath.basename(src))
924+
: src.endsWith(".mjs") || nodePath.basename(src) === "config.json",
925+
});
926+
const catalog = nodePath.join(root, "catalog");
927+
nodeFs.mkdirSync(catalog);
928+
const put = (id, url, evidence = "", heading = "Evidence") => nodeFs.writeFileSync(nodePath.join(catalog, `${id}.md`),
929+
`---\nid: ${id}\nurl: ${url}\nstatus: active\n---\n\n## ${heading}\n\n${evidence}\n`);
930+
for (const status of [502, 503, 504]) {
931+
put(`source-${status}`, `https://assets.test/source-${status}`, `https://assets.test/licence-${status}`, status === 504 ? "Notes" : "Evidence");
932+
}
933+
put("recovered", "https://assets.test/recovered-503");
934+
const preload = nodePath.join(root, "network.mjs");
935+
nodeFs.writeFileSync(preload, `
936+
import dns from "node:dns/promises";
937+
import { syncBuiltinESMExports } from "node:module";
938+
dns.lookup = async () => [{ address: "8.8.8.8", family: 4 }];
939+
syncBuiltinESMExports();
940+
const calls = new Map();
941+
globalThis.fetch = async (url) => {
942+
const u = new URL(url);
943+
if (u.hostname === "api.github.com") return new Response(null, { status: 503 });
944+
if (u.hostname !== "assets.test") throw new Error("unexpected test host");
945+
const n = (calls.get(url) || 0) + 1;
946+
calls.set(url, n);
947+
const status = u.pathname.includes("recovered") && n > 1 ? 200 : Number(u.pathname.match(/(\\d+)$/)[1]);
948+
return new Response(null, { status });
949+
};
950+
`);
951+
const output = nodePath.join(root, "github-output");
952+
const reportPath = nodePath.join(root, "report.md");
953+
const run = () => {
954+
nodeFs.writeFileSync(output, "");
955+
execFileSync(process.execPath, ["--import", pathToFileURL(preload).href,nodePath.join(root, "site/check-links.mjs"), "--report", reportPath], {
956+
env: { ...process.env, GITHUB_OUTPUT: output, GITHUB_TOKEN: "" },
957+
stdio: ["ignore", "pipe", "pipe"], timeout: 10000,
958+
});
959+
return nodeFs.readFileSync(reportPath, "utf8");
960+
};
961+
const transient = run();
962+
has("transient report: no dead sources", transient, "### Dead (0)");
963+
has("transient report: no dead licence pages", transient, "### Pages quoted in Evidence or linked in Notes that no longer load (0)");
964+
has("transient report: sources and licence pages could not be checked", transient, "### Could not check (6 skipped)");
965+
const skipped = transient.split("### Could not check")[1] || "";
966+
for (const status of [502, 503, 504]) {
967+
has(`transient report: source HTTP ${status}`, skipped, `\`https://assets.test/source-${status}\` (HTTP ${status})`);
968+
has(`transient report: licence HTTP ${status}`, skipped, `\`https://assets.test/licence-${status}\` (HTTP ${status})`);
969+
}
970+
lacks("transient report: a successful retry is not reported", transient, "https://assets.test/recovered-503");
971+
eq("transient report: no sources need a look", nodeFs.readFileSync(output, "utf8"), "problems=0\n");
972+
973+
for (const status of [404, 410]) {
974+
put(`dead-${status}`, `https://assets.test/source-${status}`, `https://assets.test/licence-${status}`);
975+
}
976+
put("api-failure", "https://github.com/o/r");
977+
// GitHub's page is healthy, but its API is temporarily unavailable.
978+
nodeFs.appendFileSync(preload, `
979+
const stubFetch = globalThis.fetch;
980+
globalThis.fetch = async (url) => new URL(url).hostname === "github.com"
981+
? new Response(null, { status: 200 }) : stubFetch(url);
982+
`);
983+
const mixed = run();
984+
has("mixed report: 404/410 sources stay dead", mixed, "### Dead (2)");
985+
has("mixed report: 404/410 licence pages stay dead", mixed, "### Pages quoted in Evidence or linked in Notes that no longer load (2)");
986+
has("mixed report: transient answers and API failures stay visible", mixed, "### Could not check (7 skipped)");
987+
has("mixed report: API failure keeps its reason", mixed, "GitHub API HTTP 503 for o/r");
988+
eq("mixed report: only dead sources and licence pages need a look", nodeFs.readFileSync(output, "utf8"), "problems=4\n");
989+
} finally {
990+
nodeFs.rmSync(root, { recursive: true, force: true });
991+
}
992+
});
993+
895994
// #64: one entry walker; hidden and scratch folders are not entries.
896995
const tmp = nodeFs.mkdtempSync(nodePath.join(nodeOs.tmpdir(), "entries-"));
897996
for (const rel of ["2d/a.md", "2d/README.md", "2d/TEMPLATE.md", "2d/.hidden/b.md", "_scratch/c.md", "3d/sub/d.md", "3d/e.txt"]) {

‎site/lib/link-check.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ export const repoOf = (url) => new URL(url).pathname.split("/").slice(1, 3).join
6060
/** What a finished request says about an entry. */
6161
export function classify(entryUrl, status, finalUrl) {
6262
if ([401, 403, 429].includes(status)) return { kind: "blocked", detail: `HTTP ${status}` };
63+
if ([502, 503, 504].includes(status)) return { kind: "unavailable", detail: `HTTP ${status}` };
6364
if (status >= 400) return { kind: "dead", detail: `HTTP ${status}` };
6465
const from = siteOf(new URL(entryUrl).hostname);
6566
const to = siteOf(new URL(finalUrl).hostname);

0 commit comments

Comments
 (0)