Repository navigation
Expand file tree
/
Copy pathcheck-api-drift.mjs
More file actions
223 lines (201 loc) · 8.24 KB
/
Copy pathcheck-api-drift.mjs
File metadata and controls
223 lines (201 loc) · 8.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// Checks pages that list values the production API serves against that API.
// Hosting kept these checks while the pages lived there; docs merge when a
// change reaches production, so production is the reference.
//
// Run: node scripts/check-api-drift.mjs [content-dir]
import fs from "node:fs";
import path from "node:path";
import url from "node:url";
import yaml from "js-yaml";
const API = "https://api.volcano.dev";
// Function preview operations: creating, listing, deploying and deleting
// previews, promoting one, and rolling back.
const PREVIEW_PATH =
/^\/projects\/\{id\}\/functions\/\{functionId\}\/(candidates(\/.*)?|serving\/rollback)$/;
// The code refusing a variable write because a promoted preview serves the
// function. Frontend and source previews have codes of their own.
const SERVED_BY_PREVIEW_CODE = /^function_served_by_candidate$/;
const CODE = /`code: ([a-z_]+)`|code `([a-z_]+)`/g;
function codesIn(text) {
return [...text.matchAll(CODE)].map((m) => m[1] ?? m[2]);
}
// Error codes the OpenAPI document names for the function preview API:
// operationCodes from the preview operations, and the variable write code.
export function previewErrorCodes(openapi) {
const operationCodes = new Set();
const writeCodes = new Set();
for (const [route, operations] of Object.entries(openapi.paths ?? {})) {
for (const operation of Object.values(operations)) {
for (const [status, response] of Object.entries(operation?.responses ?? {})) {
if (!/^4\d\d$/.test(status)) continue;
for (const code of codesIn(JSON.stringify(response))) {
if (PREVIEW_PATH.test(route)) operationCodes.add(code);
else if (SERVED_BY_PREVIEW_CODE.test(code)) writeCodes.add(code);
}
}
}
}
return { operationCodes: [...operationCodes].sort(), writeCodes: [...writeCodes].sort() };
}
function cells(row) {
return row
.trim()
.replace(/^\||\|$/g, "")
.split("|")
.map((cell) => cell.trim());
}
// Codes with no row in the Code column of a table in the previews guide.
export function missingPreviewCodes(previewsPage, codes) {
const documented = new Set();
let column = -1;
for (const line of previewsPage.split("\n")) {
if (!line.startsWith("|")) {
column = -1;
continue;
}
const row = cells(line);
if (column === -1) {
column = row.indexOf("Code");
continue;
}
const code = row[column]?.match(/^`([a-z_]+)`$/);
if (code) documented.add(code[1]);
}
return codes.filter((code) => !documented.has(code));
}
// Runtime IDs a page does not mention.
export function missingRuntimes(page, runtimes) {
return runtimes.map((r) => r.name).filter((name) => !page.includes(name));
}
// The text under a heading, up to the next heading of the same or higher level.
function section(page, heading) {
const lines = page.split("\n");
const start = lines.indexOf(heading);
if (start === -1) return undefined;
const level = heading.match(/^#+/)[0].length;
const next = new RegExp(`^#{1,${level}} `);
let fenced = false;
let end = lines.length;
for (let i = start + 1; i < lines.length; i++) {
if (/^\s*(```|~~~)/.test(lines[i])) fenced = !fenced;
else if (!fenced && next.test(lines[i])) {
end = i;
break;
}
}
return lines.slice(start + 1, end).join("\n");
}
function sameList(a, b) {
return [...a].sort().join(",") === [...b].sort().join(",");
}
// Problems in databases/overview.md against GET /databases/postgres-versions.
export function postgresOverviewProblems(page, versions) {
const supported = versions.map((v) => v.version);
const preferred = versions.find((v) => v.default)?.version;
const problems = [];
const feature = page.split("\n").find((line) => /^\| PostgreSQL\s*\|/.test(line));
const named = feature?.match(/\b\d{2}\b/g) ?? [];
if (!sameList(named, supported)) {
problems.push(`the "| PostgreSQL |" feature row names ${named.join(", ") || "no versions"}`);
}
const table = section(page, "### PostgreSQL versions");
if (table === undefined) {
problems.push(`has no "### PostgreSQL versions" section`);
return problems;
}
const rows = table
.split("\n")
.map((line) => line.match(/^\|\s*(\d+)\s*\|(.*)\|\s*$/))
.filter(Boolean);
const listed = rows.map((row) => row[1]);
if (!sameList(listed, supported)) {
problems.push(`the PostgreSQL versions table lists ${listed.join(", ") || "no versions"}`);
}
const markedDefault = rows.filter((row) => /\bdefault\b/.test(row[2])).map((row) => row[1]);
if (!sameList(markedDefault, [preferred])) {
problems.push(
`the PostgreSQL versions table marks ${markedDefault.join(", ") || "no version"} as default, not ${preferred}`,
);
}
return problems;
}
// Problems in the example response in databases/creating-databases.md.
export function postgresExampleProblems(page, versions) {
const body = section(page, "## List Available PostgreSQL Versions");
if (body === undefined) return [`has no "## List Available PostgreSQL Versions" section`];
const block = body.match(/```json\n([\s\S]*?)```/);
if (!block) return ["the List Available PostgreSQL Versions section has no JSON example"];
let example;
try {
example = JSON.parse(block[1]);
} catch (error) {
return [`the example response is not valid JSON: ${error.message}`];
}
const problems = [];
const listed = example.map((v) => v.version);
if (!sameList(listed, versions.map((v) => v.version))) {
problems.push(`the example response lists ${listed.join(", ")}`);
}
const exampleDefault = example.filter((v) => v.default === true).map((v) => v.version);
const preferred = versions.filter((v) => v.default).map((v) => v.version);
if (!sameList(exampleDefault, preferred)) {
problems.push(`the example response marks ${exampleDefault.join(", ") || "no version"} as default`);
}
return problems;
}
async function get(route, parse) {
const response = await fetch(`${API}${route}`);
if (!response.ok) throw new Error(`GET ${API}${route} answered ${response.status}`);
return parse(await response.text());
}
async function main() {
const content = path.resolve(process.argv[2] ?? "content/platform");
const read = (page) => fs.readFileSync(path.join(content, page), "utf8");
const [openapi, runtimes, versions] = await Promise.all([
get("/openapi.yaml", (text) => yaml.load(text)),
get("/functions/runtimes", (text) => JSON.parse(text).runtimes),
get("/databases/postgres-versions", (text) => JSON.parse(text)),
]);
const failures = [];
function report(page, problems) {
for (const problem of problems) failures.push(`${page}: ${problem}`);
}
const { operationCodes, writeCodes } = previewErrorCodes(openapi);
const codes = [...operationCodes, ...writeCodes];
// An empty list means the API moved, not that the pages match it.
if (operationCodes.length === 0) {
failures.push("the production OpenAPI document names no error codes for the function preview operations");
}
if (runtimes.length === 0) failures.push("GET /functions/runtimes lists no runtimes");
if (versions.length === 0) failures.push("GET /databases/postgres-versions lists no versions");
report(
"functions/previews.md",
missingPreviewCodes(read("functions/previews.md"), codes).map(
(code) => `the error code table has no row for \`${code}\``,
),
);
for (const page of ["functions/overview.md", "functions/upload-api.md"]) {
report(page, missingRuntimes(read(page), runtimes).map((name) => `does not list the ${name} runtime`));
}
const served = `production serves ${versions.map((v) => v.version).join(", ")}`;
report(
"databases/overview.md",
postgresOverviewProblems(read("databases/overview.md"), versions).map((p) => `${p}; ${served}`),
);
report(
"databases/creating-databases.md",
postgresExampleProblems(read("databases/creating-databases.md"), versions).map((p) => `${p}; ${served}`),
);
if (failures.length > 0) {
console.error(`These pages disagree with ${API}:\n`);
for (const failure of failures) console.error(`- ${failure}`);
process.exit(1);
}
console.log(
`Pages match ${API}: ${codes.length} preview error codes, ${runtimes.length} runtimes, ` +
`${versions.length} PostgreSQL versions.`,
);
}
if (process.argv[1] === url.fileURLToPath(import.meta.url)) {
await main();
}