@popcorn245/cornfield 0.13.0 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/core/config.js +16 -3
- package/package.json +1 -1
- package/server/files.js +28 -50
- package/server/mockups.js +23 -16
- package/server/proposal-walk.js +203 -0
- package/server/proposals.js +53 -35
- package/server/server.js +1 -1
package/core/config.js
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
* port: 3350,
|
|
18
18
|
* host: '127.0.0.1', // loopback, unless sign-in is configured with an https publicUrl (server/bind.js)
|
|
19
19
|
* publicUrl: null, // the origin people open it at; sign-in needs it (server/auth.js)
|
|
20
|
-
* worktrees: '.claude/worktrees', // a folder of git worktrees whose unpushed proposals are listed too
|
|
20
|
+
* worktrees: '.claude/worktrees', // a folder of git worktrees whose unpushed proposals are listed too; or { dir, maxAgeDays } to leave out worktrees untouched that long (docs/config.md#worktrees)
|
|
21
21
|
* proposals: 'docs/specs/proposals', // where proposal files live, in the checkout and in each worktree; or { dir, approveLands } (docs/config.md#proposals)
|
|
22
22
|
* topology: 'topology.json',
|
|
23
23
|
* personas: { roles: null }, // the roles a persona may have (null: any)
|
|
@@ -165,6 +165,9 @@ export const DEFAULTS = Object.freeze({
|
|
|
165
165
|
const KEYS = Object.keys(DEFAULTS);
|
|
166
166
|
/** The keys of `proposals` when it is an object: the folder, and whether an approval also lands the spec PR (opt-in, off unless true) */
|
|
167
167
|
export const PROPOSALS_KEYS = Object.freeze(['dir', 'approveLands']);
|
|
168
|
+
/** The keys of `worktrees` when it is an object: the folder, and how many days without a change leave a worktree out of the list (default: none is left out) */
|
|
169
|
+
export const WORKTREES_KEYS = Object.freeze(['dir', 'maxAgeDays']);
|
|
170
|
+
const MAX_WORKTREE_AGE_DAYS = 36500;
|
|
168
171
|
const AGENT_KEYS = ['authors', 'labels', 'branchPrefixes', 'bots', 'transport', 'maxOpen', 'profiles', 'runners', 'quietAfter', 'limits', 'on', 'refuseCollisions'];
|
|
169
172
|
const PROFILE_NAME = new RegExp(PROFILE_SOURCE);
|
|
170
173
|
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
@@ -301,8 +304,15 @@ export function configProblems(c) {
|
|
|
301
304
|
if (!isObject(c.releaseNotes)) out.push('"releaseNotes" is { breakingLabel }.');
|
|
302
305
|
else if (c.releaseNotes.breakingLabel !== undefined && (!isText(c.releaseNotes.breakingLabel) || c.releaseNotes.breakingLabel.includes(','))) out.push('releaseNotes.breakingLabel is a label\'s name, like "breaking".');
|
|
303
306
|
}
|
|
304
|
-
|
|
305
|
-
|
|
307
|
+
if (c.topology !== undefined && c.topology !== null && !inRepo(c.topology)) out.push('"topology" is a folder or file inside the repo, written relative to it.');
|
|
308
|
+
// The folder as a string (always so), or { dir?, maxAgeDays? }
|
|
309
|
+
if (c.worktrees !== undefined && c.worktrees !== null) {
|
|
310
|
+
if (isObject(c.worktrees)) {
|
|
311
|
+
for (const k of Object.keys(c.worktrees)) if (!WORKTREES_KEYS.includes(k)) out.push(`worktrees.${k}: the keys are ${WORKTREES_KEYS.join(', ')}.`);
|
|
312
|
+
if (c.worktrees.dir !== undefined && !inRepo(c.worktrees.dir)) out.push('worktrees.dir is the folder of git worktrees, inside the repo and written relative to it.');
|
|
313
|
+
const age = c.worktrees.maxAgeDays;
|
|
314
|
+
if (age !== undefined && !(typeof age === 'number' && Number.isFinite(age) && age > 0 && age <= MAX_WORKTREE_AGE_DAYS)) out.push(`worktrees.maxAgeDays is a number of days above 0 and at most ${MAX_WORKTREE_AGE_DAYS}: a worktree whose newest proposal is older is left out.`);
|
|
315
|
+
} else if (!inRepo(c.worktrees)) out.push('"worktrees" is a folder inside the repo, written relative to it (or { dir, maxAgeDays }).');
|
|
306
316
|
}
|
|
307
317
|
// The folder as a string (always so), or { dir?, approveLands? }: the object form is how the folder's options are set
|
|
308
318
|
if (c.proposals !== undefined && c.proposals !== null) {
|
|
@@ -453,6 +463,9 @@ export async function loadConfig(root, { env = process.env, file } = {}) {
|
|
|
453
463
|
// `proposals` is the folder to everything downstream, whichever way the file wrote it; the options are read from `approveLands`
|
|
454
464
|
config.approveLands = isObject(raw.proposals) && raw.proposals.approveLands === true;
|
|
455
465
|
config.proposals = (isObject(raw.proposals) ? raw.proposals.dir : raw.proposals) ?? DEFAULTS.proposals;
|
|
466
|
+
// `worktrees` is the folder to everything downstream (null: no worktrees are looked at); the age limit is read from `worktreeMaxAgeDays`
|
|
467
|
+
config.worktreeMaxAgeDays = isObject(raw.worktrees) && raw.worktrees.maxAgeDays !== undefined ? raw.worktrees.maxAgeDays : null;
|
|
468
|
+
config.worktrees = isObject(raw.worktrees) ? (raw.worktrees.dir ?? DEFAULTS.worktrees) : config.worktrees;
|
|
456
469
|
if (env.CORNFIELD_PORT) config.port = Number(env.CORNFIELD_PORT);
|
|
457
470
|
if (env.PORT && !env.CORNFIELD_PORT) config.port = Number(env.PORT);
|
|
458
471
|
if (env.CORNFIELD_HOST) config.host = env.CORNFIELD_HOST;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@popcorn245/cornfield",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.1",
|
|
4
4
|
"description": "A self-hostable dev dashboard with the topology map at its centre: proposals on the map, scenarios, outages and what-if edits, for any repo.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "popcorn245 (https://github.com/popcorn245)",
|
package/server/files.js
CHANGED
|
@@ -6,14 +6,16 @@
|
|
|
6
6
|
* repo's map and registry, and the folders of the browser modules its config names. Everything else in
|
|
7
7
|
* the checkout (.env files, databases, sources) is not reachable.
|
|
8
8
|
*
|
|
9
|
-
* Proposals are found here too: `<proposals>/*.json` in the
|
|
10
|
-
* the configured worktrees folder (git worktrees with unpushed drafts
|
|
11
|
-
* listing found itself; what it says is never joined
|
|
9
|
+
* Proposals are found here too (server/proposal-walk.js does the walking, asynchronously): `<proposals>/*.json` in the
|
|
10
|
+
* checkout and the same under each folder of the configured worktrees folder (git worktrees with unpushed drafts, those
|
|
11
|
+
* that differ from the checkout's). A request can only name one the listing found itself; what it says is never joined
|
|
12
|
+
* into a path.
|
|
12
13
|
*/
|
|
13
14
|
|
|
14
15
|
import fs from 'node:fs';
|
|
15
16
|
import path from 'node:path';
|
|
16
17
|
import { createHash } from 'node:crypto';
|
|
18
|
+
import { PROPOSAL_FILE, createProposalLister } from './proposal-walk.js';
|
|
17
19
|
|
|
18
20
|
/** Content-Type by lower-case file extension (with the dot) */
|
|
19
21
|
export const MIME_TYPES = {
|
|
@@ -112,64 +114,40 @@ export function sendFile(req, res, filePath, reqPath) {
|
|
|
112
114
|
// Proposals: listed from the checkout and its worktrees, served read-only
|
|
113
115
|
// ---------------------------------------------------------------------------
|
|
114
116
|
|
|
115
|
-
|
|
116
|
-
export const PROPOSAL_FILE = /^([A-Za-z0-9][A-Za-z0-9._-]*)\.json$/;
|
|
117
|
+
export { PROPOSAL_FILE };
|
|
117
118
|
|
|
118
|
-
/**
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
function
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
let entries = [];
|
|
127
|
-
try {
|
|
128
|
-
entries = fs.readdirSync(path.join(base, worktrees), { withFileTypes: true });
|
|
129
|
-
} catch { /* no worktrees here */ }
|
|
130
|
-
for (const w of entries) {
|
|
131
|
-
// A worktree called "checkout" would be taken for the checkout itself: not listed
|
|
132
|
-
if (w.isDirectory() && w.name !== 'checkout') folders.push({ source: w.name, dir: path.join(base, worktrees, w.name, proposals) });
|
|
133
|
-
}
|
|
134
|
-
return folders;
|
|
119
|
+
/** The listers by the `fs` they use: the real one, or a fake a test hands in as `where.fs`. Each keeps its own cache. */
|
|
120
|
+
const listers = new WeakMap();
|
|
121
|
+
const realLister = createProposalLister();
|
|
122
|
+
|
|
123
|
+
function listerOf(where) {
|
|
124
|
+
if (!where.fs) return realLister;
|
|
125
|
+
if (!listers.has(where.fs)) listers.set(where.fs, createProposalLister({ fs: where.fs }));
|
|
126
|
+
return listers.get(where.fs);
|
|
135
127
|
}
|
|
136
128
|
|
|
137
129
|
/**
|
|
138
|
-
* Every proposal the server may serve.
|
|
139
|
-
*
|
|
140
|
-
*
|
|
141
|
-
*
|
|
142
|
-
* @
|
|
130
|
+
* Every proposal the server may serve (server/proposal-walk.js has how: async, cached, without the worktree files
|
|
131
|
+
* that are copies of the checkout's). A review (`*.review.json`), a link, a directory and a name that is not a plain
|
|
132
|
+
* file name are left out. When a slug is in several places each is listed, the worktree copies first, as that is
|
|
133
|
+
* where it is being written. Each entry carries `parsed`, `{ proposal }` or `{ error }`: what the file holds.
|
|
134
|
+
* @param {{ root: string, proposals: string, worktrees?: string|null, worktreeMaxAgeDays?: number|null }} where
|
|
135
|
+
* @param {{ only?: string|null }} [opts] `only`: walk just this source (`checkout` or a worktree's name)
|
|
136
|
+
* @returns {Promise<{ slug: string, source: string, file: string, parsed: { proposal?: unknown, error?: string } }[]>} `source` is `checkout` or the worktree's name
|
|
143
137
|
*/
|
|
144
|
-
export function listProposalFiles(where) {
|
|
145
|
-
|
|
146
|
-
for (const { source, dir } of proposalFolders(where)) {
|
|
147
|
-
let names = [];
|
|
148
|
-
try {
|
|
149
|
-
names = fs.readdirSync(dir);
|
|
150
|
-
} catch { continue; }
|
|
151
|
-
for (const name of names) {
|
|
152
|
-
const m = PROPOSAL_FILE.exec(name);
|
|
153
|
-
if (!m || name.endsWith('.review.json')) continue;
|
|
154
|
-
const file = path.join(dir, name);
|
|
155
|
-
try {
|
|
156
|
-
if (!fs.lstatSync(file).isFile()) continue; // a directory, or a symlink to somewhere else
|
|
157
|
-
} catch { continue; }
|
|
158
|
-
out.push({ slug: m[1], source, file });
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
const rank = (e) => (e.source === 'checkout' ? 1 : 0);
|
|
162
|
-
return out.sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : rank(a) - rank(b) || (a.source < b.source ? -1 : a.source > b.source ? 1 : 0)));
|
|
138
|
+
export function listProposalFiles(where, opts) {
|
|
139
|
+
return listerOf(where).list(where, opts);
|
|
163
140
|
}
|
|
164
141
|
|
|
165
142
|
/**
|
|
166
143
|
* The listed proposal a request names, matched against the listing. No `source` means the first one
|
|
167
|
-
* listed for the slug (the worktree copy).
|
|
168
|
-
* @param {{ root: string, proposals: string, worktrees?: string|null }} where
|
|
144
|
+
* listed for the slug (the worktree copy). With a `source`, only that one place is walked.
|
|
145
|
+
* @param {{ root: string, proposals: string, worktrees?: string|null, worktreeMaxAgeDays?: number|null }} where
|
|
169
146
|
* @param {unknown} slug
|
|
170
147
|
* @param {unknown} [source]
|
|
171
148
|
*/
|
|
172
|
-
export function findProposalFile(where, slug, source) {
|
|
149
|
+
export async function findProposalFile(where, slug, source) {
|
|
173
150
|
if (typeof slug !== 'string' || (source !== undefined && source !== null && typeof source !== 'string')) return null;
|
|
174
|
-
|
|
151
|
+
const only = typeof source === 'string' && source !== '' ? source : null;
|
|
152
|
+
return (await listProposalFiles(where, { only })).find((e) => e.slug === slug && (only === null || e.source === only)) || null;
|
|
175
153
|
}
|
package/server/mockups.js
CHANGED
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
* `unreviewed` (or `missing`).
|
|
31
31
|
*/
|
|
32
32
|
|
|
33
|
-
import
|
|
33
|
+
import fsp from 'node:fs/promises';
|
|
34
34
|
import path from 'node:path';
|
|
35
35
|
import { createHash } from 'node:crypto';
|
|
36
36
|
import { mockupsOf } from '../core/proposal.js';
|
|
@@ -70,33 +70,40 @@ function sendJson(res, status, body) {
|
|
|
70
70
|
}
|
|
71
71
|
const refuse = (res, status, message) => sendJson(res, status, { error: message });
|
|
72
72
|
|
|
73
|
-
/** The proposal's parsed JSON for a local entry, or null */
|
|
74
|
-
function readLocalProposal(entry) {
|
|
73
|
+
/** The proposal's parsed JSON for a local entry, or null: what the listing parsed, else the file read without blocking */
|
|
74
|
+
async function readLocalProposal(entry) {
|
|
75
|
+
if (entry.parsed) return entry.parsed.error === undefined ? entry.parsed.proposal ?? null : null;
|
|
75
76
|
try {
|
|
76
|
-
return JSON.parse(
|
|
77
|
+
return JSON.parse(await fsp.readFile(entry.file, 'utf8'));
|
|
77
78
|
} catch {
|
|
78
79
|
return null;
|
|
79
80
|
}
|
|
80
81
|
}
|
|
81
82
|
|
|
82
83
|
/** The bytes of a mockup of a local proposal, or null: the path is resolved with links followed and must stay in the proposal's folder, be a plain file, and be at most MOCKUP_MAX_BYTES */
|
|
83
|
-
export function readLocalMockup(entry, rel) {
|
|
84
|
+
export async function readLocalMockup(entry, rel) {
|
|
84
85
|
try {
|
|
85
|
-
const dir =
|
|
86
|
-
const real =
|
|
86
|
+
const dir = await fsp.realpath(path.dirname(entry.file));
|
|
87
|
+
const real = await fsp.realpath(path.join(dir, ...rel.split('/')));
|
|
87
88
|
if (!real.startsWith(dir + path.sep)) return null;
|
|
88
|
-
const stats =
|
|
89
|
+
const stats = await fsp.stat(real);
|
|
89
90
|
if (!stats.isFile() || stats.size > MOCKUP_MAX_BYTES) return null;
|
|
90
|
-
return
|
|
91
|
+
return await fsp.readFile(real);
|
|
91
92
|
} catch {
|
|
92
93
|
return null;
|
|
93
94
|
}
|
|
94
95
|
}
|
|
95
96
|
|
|
96
|
-
|
|
97
|
-
|
|
97
|
+
/** One mockup at a time: a worktree on a slow mount is not hammered */
|
|
98
|
+
const hashItems = async (entry, items) => {
|
|
99
|
+
const out = [];
|
|
100
|
+
for (const m of items) out.push(await hashItem(entry, m));
|
|
101
|
+
return out;
|
|
102
|
+
};
|
|
103
|
+
const hashItem = async (entry, m) => {
|
|
104
|
+
const bytes = await readLocalMockup(entry, m.path);
|
|
98
105
|
return { node: m.node, path: m.path, sha256: bytes ? sha256(bytes) : null };
|
|
99
|
-
}
|
|
106
|
+
};
|
|
100
107
|
|
|
101
108
|
/**
|
|
102
109
|
* Whether each mockup is what was approved.
|
|
@@ -209,18 +216,18 @@ export async function serveMockups(req, res, match, url, where, forgeFor) {
|
|
|
209
216
|
const slug = match[1];
|
|
210
217
|
const position = match[2] === undefined ? null : Number(match[2]);
|
|
211
218
|
const source = url.searchParams.get('source') || null;
|
|
212
|
-
const entry = findProposalFile(where, slug, source);
|
|
219
|
+
const entry = await findProposalFile(where, slug, source);
|
|
213
220
|
if (!entry) {
|
|
214
221
|
if (forgeFor && pullNumber(source) !== null) return servePull(req, res, where, forgeFor, slug, /** @type {string} */ (source), position);
|
|
215
222
|
return refuse(res, 404, 'No such proposal');
|
|
216
223
|
}
|
|
217
|
-
const proposal = readLocalProposal(entry);
|
|
224
|
+
const proposal = await readLocalProposal(entry);
|
|
218
225
|
if (!proposal) return refuse(res, 422, 'The proposal could not be read');
|
|
219
226
|
const items = mockupsOf(proposal);
|
|
220
227
|
// A proposal here has no PR to be reviewed on: nothing it lists has been approved
|
|
221
|
-
if (position === null) return sendJson(res, 200, describe(slug, entry.source, items, hashItems(entry, items), null));
|
|
228
|
+
if (position === null) return sendJson(res, 200, describe(slug, entry.source, items, await hashItems(entry, items), null));
|
|
222
229
|
const item = items.find((m) => m.index === position);
|
|
223
|
-
const bytes = item ? readLocalMockup(entry, item.path) : null;
|
|
230
|
+
const bytes = item ? await readLocalMockup(entry, item.path) : null;
|
|
224
231
|
if (!item || !bytes) return refuse(res, 404, 'No such mockup');
|
|
225
232
|
return sendBytes(req, res, item.path, bytes);
|
|
226
233
|
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module server/proposal-walk
|
|
3
|
+
*
|
|
4
|
+
* Finding the proposal files of the checkout and of its worktrees without ever holding up the server.
|
|
5
|
+
*
|
|
6
|
+
* A worktrees folder can be huge and slow (147 worktrees of 50 proposals each on a Windows drive seen through WSL's 9p:
|
|
7
|
+
* minutes of reads). So the walk is:
|
|
8
|
+
*
|
|
9
|
+
* - **async**: only `fs.promises` calls, at most `CONCURRENCY` in flight at once across all walks (a slow mount is not hammered with
|
|
10
|
+
* thousands of opens), and a turn of the event loop given back every `YIELD_EVERY` calls, so `/healthz` and the
|
|
11
|
+
* other routes are answered meanwhile. No worker thread: nothing in it is CPU-bound, only waiting on the disk;
|
|
12
|
+
* - **cached by path, mtime and size**: a file whose stamp is unchanged is not read again, so a listing with nothing
|
|
13
|
+
* changed does a `readdir` per folder and an `lstat` per file, and no `readFile`;
|
|
14
|
+
* - **without copies**: a worktree starts as a copy of the checkout, so a worktree file whose contents equal the
|
|
15
|
+
* checkout's file of the same name (line endings ignored) is not a draft and is left out. The comparison is by
|
|
16
|
+
* SHA-256 of the contents with `\r\n` read as `\n`, and the hashes are cached with the files. The file's size
|
|
17
|
+
* says first whether it can be equal at all: only then is it hashed;
|
|
18
|
+
* - **single-flight**: listings asked for while one is under way share it;
|
|
19
|
+
* - **optionally pruned by age**: with `where.worktreeMaxAgeDays`, a worktree whose newest proposal is older than
|
|
20
|
+
* that is left out.
|
|
21
|
+
*
|
|
22
|
+
* The cache is bounded (`MAX_ENTRIES` files) and forgets the files that are gone.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import fsp from 'node:fs/promises';
|
|
26
|
+
import path from 'node:path';
|
|
27
|
+
import { createHash } from 'node:crypto';
|
|
28
|
+
|
|
29
|
+
/** A proposal's file name: letters, digits, `.`, `_`, `-`; never a leading dot or dash. The slug is the name without `.json` */
|
|
30
|
+
export const PROPOSAL_FILE = /^([A-Za-z0-9][A-Za-z0-9._-]*)\.json$/;
|
|
31
|
+
|
|
32
|
+
export const CONCURRENCY = 8;
|
|
33
|
+
export const YIELD_EVERY = 32;
|
|
34
|
+
export const MAX_ENTRIES = 20000;
|
|
35
|
+
const MAX_WALKS = 16;
|
|
36
|
+
const DAY_MS = 86_400_000;
|
|
37
|
+
|
|
38
|
+
const sha256 = (text) => createHash('sha256').update(text).digest('hex');
|
|
39
|
+
const countNewlines = (text) => { let n = 0; for (let i = text.indexOf('\n'); i !== -1; i = text.indexOf('\n', i + 1)) n++; return n; };
|
|
40
|
+
const turn = () => new Promise((resolve) => setImmediate(resolve));
|
|
41
|
+
|
|
42
|
+
/** Runs the calls it is given at most `limit` at a time, and lets the event loop breathe now and then */
|
|
43
|
+
function gateOf(limit) {
|
|
44
|
+
let active = 0;
|
|
45
|
+
let calls = 0;
|
|
46
|
+
const waiting = [];
|
|
47
|
+
return async (fn) => {
|
|
48
|
+
if (active < limit) active++;
|
|
49
|
+
else await new Promise((resolve) => waiting.push(resolve)); // the slot is handed over, not freed, so the limit holds
|
|
50
|
+
try {
|
|
51
|
+
return await fn();
|
|
52
|
+
} finally {
|
|
53
|
+
if (++calls % YIELD_EVERY === 0) await turn();
|
|
54
|
+
const next = waiting.shift();
|
|
55
|
+
if (next) next();
|
|
56
|
+
else active--;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** What a file's text is as a proposal: `{ proposal }` or `{ error }` (listed with the error rather than breaking the list) */
|
|
62
|
+
function parseProposal(text) {
|
|
63
|
+
try {
|
|
64
|
+
return { proposal: JSON.parse(text) };
|
|
65
|
+
} catch (err) {
|
|
66
|
+
return { error: `Not valid JSON: ${err.message}` };
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Makes a lister, which keeps the cache of what it walked. `fs` is the `fs.promises` surface it needs
|
|
72
|
+
* (`readdir`, `lstat`, `readFile`); tests pass a counting fake.
|
|
73
|
+
* @param {{ fs?: Pick<typeof fsp, 'readdir'|'lstat'|'readFile'>, concurrency?: number, maxEntries?: number, now?: () => number }} [opts]
|
|
74
|
+
*/
|
|
75
|
+
export function createProposalLister({ fs = fsp, concurrency = CONCURRENCY, maxEntries = MAX_ENTRIES, now = Date.now } = {}) {
|
|
76
|
+
/** One state per place walked: its cache (path -> record) and the walk under way */
|
|
77
|
+
const states = new Map();
|
|
78
|
+
/** One gate for every walk of this lister: two walks at once (a listing, and a lookup of one source) share the limit */
|
|
79
|
+
const io = gateOf(concurrency);
|
|
80
|
+
|
|
81
|
+
function stateOf(key) {
|
|
82
|
+
let state = states.get(key);
|
|
83
|
+
if (state) {
|
|
84
|
+
states.delete(key); // most recently used last
|
|
85
|
+
} else {
|
|
86
|
+
state = { cache: new Map(), flights: new Map() };
|
|
87
|
+
if (states.size >= MAX_WALKS) states.delete(states.keys().next().value);
|
|
88
|
+
}
|
|
89
|
+
states.set(key, state);
|
|
90
|
+
return state;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function walk(where, state, only) {
|
|
94
|
+
const { cache } = state;
|
|
95
|
+
const seen = new Set();
|
|
96
|
+
const base = path.resolve(where.root);
|
|
97
|
+
const maxAgeMs = where.worktreeMaxAgeDays > 0 ? where.worktreeMaxAgeDays * DAY_MS : null;
|
|
98
|
+
const clock = where.now || now;
|
|
99
|
+
|
|
100
|
+
/** The proposal files directly in `dir`, each with its lstat; a folder that is not there has none */
|
|
101
|
+
async function scan(dir) {
|
|
102
|
+
let names;
|
|
103
|
+
try {
|
|
104
|
+
names = await io(() => fs.readdir(dir));
|
|
105
|
+
} catch { return []; }
|
|
106
|
+
const wanted = names.filter((name) => PROPOSAL_FILE.test(name) && !name.endsWith('.review.json'));
|
|
107
|
+
const found = await Promise.all(wanted.map(async (name) => {
|
|
108
|
+
const file = path.join(dir, name);
|
|
109
|
+
try {
|
|
110
|
+
const st = await io(() => fs.lstat(file));
|
|
111
|
+
return st.isFile() ? { name, slug: PROPOSAL_FILE.exec(name)[1], file, mtimeMs: st.mtimeMs, size: st.size } : null; // not a directory, nor a link to somewhere else
|
|
112
|
+
} catch { return null; }
|
|
113
|
+
}));
|
|
114
|
+
return found.filter(Boolean);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Whether the cached record still answers for this file against the checkout's copy (`against`: its hash, or null) */
|
|
118
|
+
const usable = (rec, f, against) => !!rec && rec.mtimeMs === f.mtimeMs && rec.size === f.size
|
|
119
|
+
&& (rec.hash === null ? rec.against === against : rec.hash === against || rec.parsed !== undefined);
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The record of a file: read, hashed and parsed only when the cache cannot answer. `checkout` is the checkout's
|
|
123
|
+
* record of the same name for a worktree file (null when the checkout has none), undefined for the checkout's own file.
|
|
124
|
+
*/
|
|
125
|
+
async function recordOf(f, checkout) {
|
|
126
|
+
seen.add(f.file);
|
|
127
|
+
const against = checkout ? checkout.hash : null;
|
|
128
|
+
const hit = cache.get(f.file);
|
|
129
|
+
if (usable(hit, f, against)) return hit;
|
|
130
|
+
let text;
|
|
131
|
+
try {
|
|
132
|
+
text = await io(() => fs.readFile(f.file, 'utf8'));
|
|
133
|
+
} catch (err) {
|
|
134
|
+
return { mtimeMs: f.mtimeMs, size: f.size, hash: null, against, parsed: { error: `Not valid JSON: ${err.message}` } }; // not kept: asked again next time
|
|
135
|
+
}
|
|
136
|
+
const normal = text.replace(/\r\n/g, '\n');
|
|
137
|
+
const bytes = Buffer.byteLength(normal);
|
|
138
|
+
let hash = null;
|
|
139
|
+
// A copy can only be as long as the checkout's file with its line ends read as \r\n or \n
|
|
140
|
+
if (checkout === undefined || (checkout && f.size >= checkout.bytes && f.size <= checkout.bytes + checkout.newlines)) hash = sha256(normal);
|
|
141
|
+
const rec = { mtimeMs: f.mtimeMs, size: f.size, hash, against, bytes, newlines: checkout === undefined ? countNewlines(normal) : 0 };
|
|
142
|
+
if (!checkout || hash !== against) rec.parsed = parseProposal(text);
|
|
143
|
+
cache.delete(f.file);
|
|
144
|
+
cache.set(f.file, rec);
|
|
145
|
+
return rec;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const out = [];
|
|
149
|
+
const proposals = where.proposals;
|
|
150
|
+
const checkoutFiles = await scan(path.join(base, proposals));
|
|
151
|
+
const checkoutRecs = new Map();
|
|
152
|
+
await Promise.all(checkoutFiles.map(async (f) => checkoutRecs.set(f.name, await recordOf(f))));
|
|
153
|
+
if (!only || only === 'checkout') for (const f of checkoutFiles) out.push({ slug: f.slug, source: 'checkout', file: f.file, parsed: checkoutRecs.get(f.name).parsed });
|
|
154
|
+
|
|
155
|
+
if (where.worktrees && only !== 'checkout') {
|
|
156
|
+
const dir = path.join(base, where.worktrees);
|
|
157
|
+
let entries = [];
|
|
158
|
+
try {
|
|
159
|
+
entries = await io(() => fs.readdir(dir, { withFileTypes: true }));
|
|
160
|
+
} catch { /* no worktrees here */ }
|
|
161
|
+
// A worktree called "checkout" would be taken for the checkout itself: not listed
|
|
162
|
+
const names = entries.filter((w) => w.isDirectory() && w.name !== 'checkout' && (!only || w.name === only)).map((w) => w.name).sort();
|
|
163
|
+
await Promise.all(names.map(async (name) => {
|
|
164
|
+
const files = await scan(path.join(dir, name, proposals));
|
|
165
|
+
if (maxAgeMs !== null && files.length && clock() - Math.max(...files.map((f) => f.mtimeMs)) > maxAgeMs) return;
|
|
166
|
+
await Promise.all(files.map(async (f) => {
|
|
167
|
+
const rec = await recordOf(f, checkoutRecs.get(f.name) || null);
|
|
168
|
+
const peer = checkoutRecs.get(f.name);
|
|
169
|
+
const copy = !!peer && rec.hash !== null && rec.hash === peer.hash;
|
|
170
|
+
if (!copy) out.push({ slug: f.slug, source: name, file: f.file, parsed: rec.parsed });
|
|
171
|
+
}));
|
|
172
|
+
}));
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Forget what is gone (only after a whole walk: a walk of one source says nothing of the others), and keep the cache bounded
|
|
176
|
+
if (!only) for (const file of cache.keys()) if (!seen.has(file)) cache.delete(file);
|
|
177
|
+
while (cache.size > maxEntries) cache.delete(cache.keys().next().value);
|
|
178
|
+
|
|
179
|
+
const rank = (e) => (e.source === 'checkout' ? 1 : 0);
|
|
180
|
+
return out.sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : rank(a) - rank(b) || (a.source < b.source ? -1 : a.source > b.source ? 1 : 0)));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Every proposal the server may serve (a review, a link, a directory and a name that is not a plain file name are left
|
|
185
|
+
* out): the checkout's, then each worktree's that differs from the checkout's. When a slug is in several places each
|
|
186
|
+
* is listed, the worktree copies first, as that is where it is being written. `only` limits the walk to one source.
|
|
187
|
+
* @param {{ root: string, proposals: string, worktrees?: string|null, worktreeMaxAgeDays?: number|null, now?: () => number }} where
|
|
188
|
+
* @param {{ only?: string|null }} [opts]
|
|
189
|
+
* @returns {Promise<{ slug: string, source: string, file: string, parsed: { proposal?: unknown, error?: string } }[]>}
|
|
190
|
+
*/
|
|
191
|
+
async function list(where, { only = null } = {}) {
|
|
192
|
+
const state = stateOf(JSON.stringify([path.resolve(where.root), where.proposals, where.worktrees || null, where.worktreeMaxAgeDays || null]));
|
|
193
|
+
const flightKey = only || '';
|
|
194
|
+
let flight = state.flights.get(flightKey);
|
|
195
|
+
if (!flight) {
|
|
196
|
+
flight = walk(where, state, only).finally(() => state.flights.delete(flightKey));
|
|
197
|
+
state.flights.set(flightKey, flight);
|
|
198
|
+
}
|
|
199
|
+
return [...(await flight)];
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return { list };
|
|
203
|
+
}
|
package/server/proposals.js
CHANGED
|
@@ -26,7 +26,8 @@
|
|
|
26
26
|
* the review in the data folder; `migrateStage1Reviews` carries those over once, when the menu is opened.
|
|
27
27
|
*
|
|
28
28
|
* Which files exist, and that a request can only name one the server itself listed, is server/files.js
|
|
29
|
-
* (`listProposalFiles`, `findProposalFile
|
|
29
|
+
* (`listProposalFiles`, `findProposalFile`, server/proposal-walk.js: async and cached by path and mtime, so a slow
|
|
30
|
+
* worktrees folder never holds up the server); this module checks each
|
|
30
31
|
* against the checkout's topology.json and answers. Every function takes `where`:
|
|
31
32
|
* `{ root, proposals, worktrees, topology, dataDir, publicHost? }` (core/config.js names them). A file that does not
|
|
32
33
|
* parse is listed with an `error` instead of breaking the list. The listing's `review` is always null: a review lives on
|
|
@@ -39,7 +40,7 @@
|
|
|
39
40
|
* (percent-encoded) says why the PRs are not. Without `forgeFor` nothing is asked of a forge and the routes answer as they always have.
|
|
40
41
|
*/
|
|
41
42
|
|
|
42
|
-
import
|
|
43
|
+
import fsp from 'node:fs/promises';
|
|
43
44
|
import path from 'node:path';
|
|
44
45
|
import { findProposalFile, listProposalFiles } from './files.js';
|
|
45
46
|
import { summarize, proposalProblems } from '../core/proposal.js';
|
|
@@ -60,14 +61,24 @@ function send(res, status, body, extra = {}) {
|
|
|
60
61
|
}
|
|
61
62
|
|
|
62
63
|
/** The map the proposals are checked against: the checkout's topology.json, or null when it cannot be read */
|
|
63
|
-
function readTopology(where) {
|
|
64
|
+
async function readTopology(where) {
|
|
65
|
+
const file = path.join(where.root, where.topology || 'topology.json');
|
|
64
66
|
try {
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
+
const st = await fsp.stat(file);
|
|
68
|
+
const stamp = `${st.mtimeMs}:${st.size}`;
|
|
69
|
+
const known = topologies.get(file);
|
|
70
|
+
if (known && known.stamp === stamp) return known.topology;
|
|
71
|
+
const topology = JSON.parse(await fsp.readFile(file, 'utf8'));
|
|
72
|
+
const checked = Array.isArray(topology.nodes) && Array.isArray(topology.edges) ? topology : null;
|
|
73
|
+
topologies.set(file, { stamp, topology: checked });
|
|
74
|
+
if (topologies.size > 32) topologies.delete(topologies.keys().next().value);
|
|
75
|
+
return checked;
|
|
67
76
|
} catch {
|
|
68
77
|
return null;
|
|
69
78
|
}
|
|
70
79
|
}
|
|
80
|
+
/** The maps read, by file and the size and mtime they were read at: an unchanged map is not read or parsed again */
|
|
81
|
+
const topologies = new Map();
|
|
71
82
|
|
|
72
83
|
/** A host name that is the machine's own: localhost, an address, a tailnet name, a bare name, or the configured public host. Not an outside domain pointed here. */
|
|
73
84
|
function ownHostName(host, publicHost) {
|
|
@@ -136,15 +147,16 @@ export function readBody(req, limit) {
|
|
|
136
147
|
* a file that does not parse has `error` instead and no counts. `review` is null (see the module's head).
|
|
137
148
|
*/
|
|
138
149
|
function describeEntry(entry, topology) {
|
|
139
|
-
const { slug, source } = entry;
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
}
|
|
146
|
-
return { ...
|
|
150
|
+
const { slug, source, parsed } = entry;
|
|
151
|
+
if (parsed.error !== undefined) return { slug, title: slug, summary: '', spec: null, source, counts: null, errors: null, review: null, error: parsed.error };
|
|
152
|
+
// What a file says of itself against the map is kept with its parsed result, until either changes
|
|
153
|
+
const memo = described.get(parsed);
|
|
154
|
+
if (memo && memo.topology === topology && memo.slug === slug && memo.source === source) return { ...memo.value };
|
|
155
|
+
const value = { ...describeProposal(slug, source, parsed.proposal, topology), review: null };
|
|
156
|
+
described.set(parsed, { topology, slug, source, value });
|
|
157
|
+
return { ...value };
|
|
147
158
|
}
|
|
159
|
+
const described = new WeakMap();
|
|
148
160
|
|
|
149
161
|
/** What a listing entry says of a parsed proposal (the file may hold anything JSON can) */
|
|
150
162
|
function describeProposal(slug, source, proposal, topology) {
|
|
@@ -175,9 +187,9 @@ async function describePull(entry, forge, where, topology) {
|
|
|
175
187
|
}
|
|
176
188
|
|
|
177
189
|
/** The listing `GET /proposals` answers with */
|
|
178
|
-
export function listProposals(where) {
|
|
179
|
-
const topology = readTopology(where);
|
|
180
|
-
return
|
|
190
|
+
export async function listProposals(where) {
|
|
191
|
+
const [topology, files] = await Promise.all([readTopology(where), listProposalFiles(where)]);
|
|
192
|
+
return files.map((entry) => describeEntry(entry, topology));
|
|
181
193
|
}
|
|
182
194
|
|
|
183
195
|
/**
|
|
@@ -189,8 +201,8 @@ export function listProposals(where) {
|
|
|
189
201
|
* @returns {Promise<{ list: object[], problem: string | null }>}
|
|
190
202
|
*/
|
|
191
203
|
async function listWithPulls(where, forgeFor, signedIn) {
|
|
192
|
-
const topology = readTopology(where);
|
|
193
|
-
const local =
|
|
204
|
+
const [topology, files] = await Promise.all([readTopology(where), listProposalFiles(where)]);
|
|
205
|
+
const local = files.map((entry) => describeEntry(entry, topology));
|
|
194
206
|
let forge;
|
|
195
207
|
try {
|
|
196
208
|
forge = forgeFor();
|
|
@@ -285,7 +297,7 @@ async function putPullReview(req, res, where, forgeFor, signedIn, slug, n) {
|
|
|
285
297
|
* @param {{ root: string, proposals: string, worktrees?: string|null, topology?: string, dataDir: string, publicHost?: string|null }} where
|
|
286
298
|
* @param {(() => import('./forge.js').Forge) | null} [forgeFor] the forge as the signed-in user; null without sign-in
|
|
287
299
|
* @param {SignedIn | null} [signedIn] who is signed in, and where their actions are recorded; null without sign-in
|
|
288
|
-
* @returns {boolean} true when the
|
|
300
|
+
* @returns {boolean} true when the route is one of the proposals' (the answer may follow: the files are read without blocking the server)
|
|
289
301
|
*/
|
|
290
302
|
export function serveProposals(req, res, reqPath, url, where, forgeFor = null, signedIn = null) {
|
|
291
303
|
if (reqPath !== '/proposals' && !reqPath.startsWith('/proposals/')) return false;
|
|
@@ -310,7 +322,11 @@ export function serveProposals(req, res, reqPath, url, where, forgeFor = null, s
|
|
|
310
322
|
if (!res.headersSent) send(res, 500, { error: 'The review could not be read' });
|
|
311
323
|
});
|
|
312
324
|
} else {
|
|
313
|
-
|
|
325
|
+
findProposalFile(where, slug, url.searchParams.get('source') || null).then((found) => {
|
|
326
|
+
send(res, 404, { error: found ? 'No review yet' : 'No such proposal' });
|
|
327
|
+
}).catch(() => {
|
|
328
|
+
if (!res.headersSent) send(res, 500, { error: 'The proposal could not be looked up' });
|
|
329
|
+
});
|
|
314
330
|
}
|
|
315
331
|
} else {
|
|
316
332
|
req.resume();
|
|
@@ -334,7 +350,9 @@ export function serveProposals(req, res, reqPath, url, where, forgeFor = null, s
|
|
|
334
350
|
|
|
335
351
|
if (reqPath === '/proposals') {
|
|
336
352
|
if (!forgeFor) {
|
|
337
|
-
send(res, 200,
|
|
353
|
+
listProposals(where).then((list) => send(res, 200, list)).catch(() => {
|
|
354
|
+
if (!res.headersSent) send(res, 500, { error: 'The proposals could not be listed' });
|
|
355
|
+
});
|
|
338
356
|
return true;
|
|
339
357
|
}
|
|
340
358
|
listWithPulls(where, forgeFor, signedIn).then(({ list, problem }) => {
|
|
@@ -349,25 +367,25 @@ export function serveProposals(req, res, reqPath, url, where, forgeFor = null, s
|
|
|
349
367
|
// listing; it never becomes part of a path.
|
|
350
368
|
const m = /^\/proposals\/([^/]+)\.json$/.exec(reqPath);
|
|
351
369
|
const source = url.searchParams.get('source') || null;
|
|
352
|
-
|
|
370
|
+
serveFile(res, where, forgeFor, m ? m[1] : null, source).catch(() => {
|
|
371
|
+
if (!res.headersSent) send(res, 500, { error: 'The proposal could not be read' });
|
|
372
|
+
});
|
|
373
|
+
return true;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** GET /proposals/<slug>.json: the file the listing found, or (with a forge) the proposal of an open spec PR */
|
|
377
|
+
async function serveFile(res, where, forgeFor, slug, source) {
|
|
378
|
+
const entry = slug ? await findProposalFile(where, slug, source) : null;
|
|
353
379
|
if (!entry) {
|
|
354
|
-
if (
|
|
355
|
-
|
|
356
|
-
if (!res.headersSent) send(res, 500, { error: 'The proposal could not be read' });
|
|
357
|
-
});
|
|
358
|
-
return true;
|
|
359
|
-
}
|
|
360
|
-
send(res, 404, { error: 'No such proposal' });
|
|
361
|
-
return true;
|
|
380
|
+
if (slug && forgeFor) return servePull(res, where, forgeFor, slug, source);
|
|
381
|
+
return send(res, 404, { error: 'No such proposal' });
|
|
362
382
|
}
|
|
363
383
|
let text;
|
|
364
384
|
try {
|
|
365
|
-
text =
|
|
385
|
+
text = await fsp.readFile(entry.file, 'utf8');
|
|
366
386
|
JSON.parse(text);
|
|
367
387
|
} catch (err) {
|
|
368
|
-
send(res, 422, { error: `Not valid JSON: ${err.message}` });
|
|
369
|
-
return true;
|
|
388
|
+
return send(res, 422, { error: `Not valid JSON: ${err.message}` });
|
|
370
389
|
}
|
|
371
|
-
send(res, 200, text, { 'X-Proposal-Source': encodeURIComponent(entry.source) });
|
|
372
|
-
return true;
|
|
390
|
+
return send(res, 200, text, { 'X-Proposal-Source': encodeURIComponent(entry.source) });
|
|
373
391
|
}
|
package/server/server.js
CHANGED
|
@@ -169,7 +169,7 @@ export function createCornfieldServer(config, opts = {}) {
|
|
|
169
169
|
const csp = cspOf(importMap);
|
|
170
170
|
const repoModules = repoModuleDirs(config);
|
|
171
171
|
const publicHost = config.publicUrl ? new URL(config.publicUrl).hostname : null;
|
|
172
|
-
const where = { root, proposals: config.proposals, worktrees: config.worktrees, topology: config.topology, dataDir: config.dataDir, publicHost };
|
|
172
|
+
const where = { root, proposals: config.proposals, worktrees: config.worktrees, worktreeMaxAgeDays: config.worktreeMaxAgeDays, topology: config.topology, dataDir: config.dataDir, publicHost };
|
|
173
173
|
const fixtureCache = new Map();
|
|
174
174
|
const lander = config.approveLands ? createLander({ config, where, auth, hooks, now: opts.now, timer: opts.landTimer }) : null;
|
|
175
175
|
if (lander) {
|