cornfield 0.37.0 → 0.39.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.37.0",
3
+ "version": "0.39.0",
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)",
@@ -83,7 +83,7 @@ const toFile = (f) => ({ path: f.filename, status: FILE_STATUS[f.status] || 'mod
83
83
 
84
84
  /** @returns {import('./forge.js').Comment} */
85
85
  /** @returns {import('./forge.js').PullCommit} */
86
- const toCommit = (c) => ({ sha: String(c.sha ?? ''), message: typeof c.commit?.message === 'string' ? c.commit.message : '' });
86
+ const toCommit = (c) => ({ sha: String(c.sha ?? ''), message: typeof c.commit?.message === 'string' ? c.commit.message : '', date: c.commit?.committer?.date ?? c.commit?.author?.date ?? null });
87
87
 
88
88
  const toComment = (c) => ({ id: String(c.id), author: author(c.user), body: c.body ?? '', url: c.html_url, createdAt: c.created_at, updatedAt: c.updated_at });
89
89
 
@@ -67,7 +67,7 @@ const toPull = (p) => ({
67
67
  });
68
68
 
69
69
  /** @returns {import('./forge.js').PullCommit} */
70
- const toCommit = (c) => ({ sha: String(c.sha ?? ''), message: typeof c.commit?.message === 'string' ? c.commit.message : '' });
70
+ const toCommit = (c) => ({ sha: String(c.sha ?? ''), message: typeof c.commit?.message === 'string' ? c.commit.message : '', date: c.commit?.committer?.date ?? c.commit?.author?.date ?? null });
71
71
 
72
72
  const FILE_STATUS = { added: 'added', copied: 'added', removed: 'removed', renamed: 'renamed', modified: 'modified', changed: 'modified', unchanged: 'modified' };
73
73
  /** @returns {import('./forge.js').PullFile} */
package/server/forge.js CHANGED
@@ -60,7 +60,7 @@
60
60
  * @typedef {{ number: number, title: string, body: string, state: 'open' | 'closed' | 'merged', draft: boolean, author: Author | null, labels: string[], head: { ref: string, sha: string }, base: { ref: string }, url: string, createdAt: string, updatedAt: string, mergedAt: string | null }} Pull
61
61
  * @typedef {{ path: string, status: 'added' | 'modified' | 'removed' | 'renamed', previousPath: string | null, additions: number, deletions: number }} PullFile
62
62
  * @typedef {{ id: string, author: Author | null, body: string, url: string, createdAt: string, updatedAt: string }} Comment
63
- * @typedef {{ sha: string, message: string }} PullCommit
63
+ * @typedef {{ sha: string, message: string, date: string | null }} PullCommit `date`: when it was committed (the committer's date, else the author's), or null when the forge gave none
64
64
  * @typedef {'queued' | 'running' | 'success' | 'failure' | 'neutral' | 'skipped' | 'cancelled'} CheckState
65
65
  * @typedef {{ id: string, name: string, state: CheckState, url: string | null, rerunnable: boolean }} Check
66
66
  * @typedef {{ name: string, sha: string, protected: boolean }} Branch
@@ -16,12 +16,22 @@
16
16
  * head. Every maintainer of the repo sees the same PRs, so what one maintainer's token read is shown to another.
17
17
  * Answers are kept only when the forge gave them; a failure is asked again next time.
18
18
  *
19
- * @typedef {{ slug: string, source: string, path: string, sha: string, pull: { number: number, title: string, url: string, draft: boolean, author: string | null } }} PullEntry
19
+ * **What the review state costs** (spec 0010 D4). A listed proposal of a ready PR also carries its review state (`reviewStates`): the
20
+ * latest maintainer review, whether it still holds (`current`), and when the head was pushed. It is read once for a PR at a head and kept
21
+ * for `REVIEW_KEEP_MS` (5 minutes): one `comments` call for the PR, a `permission` call for each author of a review block (once per listing, whatever the number of PRs), and a
22
+ * `pullCommits` call for the head (kept by sha for good: a commit never changes). A draft PR is not read at all. A review posted from cornfield
23
+ * is forgotten at once (`forgetReviewState`); one posted on the forge shows within the 5 minutes. A read that fails is never kept, and says so
24
+ * (`review: { error }`), so a PR whose review could not be read never looks unreviewed.
25
+ *
26
+ * @typedef {{ slug: string, source: string, path: string, sha: string, pull: { number: number, title: string, url: string, draft: boolean, author: string | null, createdAt: string, updatedAt: string } }} PullEntry
27
+ * @typedef {{ verdict: 'approved' | 'notes', by: string, at: string, current: boolean }} ReviewState `current`: an approval is of the file as the head holds it now; a send-back has had no push since
28
+ * @typedef {{ pushedAt: string | null, review: ReviewState | { error: string } | null }} PullReviewState
20
29
  */
21
30
 
22
31
  import path from 'node:path';
23
32
  import { ForgeError } from './forge.js';
24
33
  import { PROPOSAL_FILE } from './files.js';
34
+ import { latestReview, proposalHash } from './reviews.js';
25
35
 
26
36
  /** How many pull requests have their files asked at once */
27
37
  const PARALLEL = 6;
@@ -72,7 +82,7 @@ function entryOf(pull, file) {
72
82
  source: pullSource(pull.number),
73
83
  path: file.path,
74
84
  sha: pull.head.sha,
75
- pull: { number: pull.number, title: pull.title, url: pull.url, draft: pull.draft, author: pull.author ? pull.author.login : null },
85
+ pull: { number: pull.number, title: pull.title, url: pull.url, draft: pull.draft, author: pull.author ? pull.author.login : null, createdAt: pull.createdAt, updatedAt: pull.updatedAt },
76
86
  };
77
87
  }
78
88
 
@@ -161,3 +171,84 @@ export async function readPullProposal(forge, where, entry) {
161
171
  if (text === null) throw new ForgeError(`${entry.path} is not at the head of pull request #${entry.pull.number}.`, { code: 'not-found' });
162
172
  return text;
163
173
  }
174
+
175
+ // ---------------------------------------------------------------------------
176
+ // The review state of each listed proposal (spec 0010 D4)
177
+ // ---------------------------------------------------------------------------
178
+
179
+ /** How long a PR's review state is kept at one head: a review posted on the forge itself shows within this */
180
+ export const REVIEW_KEEP_MS = 5 * 60_000;
181
+
182
+ /** @type {WeakMap<object, Map<string, { at: number, value: { byIndex: Record<string, PullReviewState> } }>>} */
183
+ const reviewCaches = new WeakMap();
184
+
185
+ /** Forgets what was kept of PR `n`'s reviews (a review was just posted on it), so the next listing reads it again */
186
+ export function forgetReviewState(where, n) {
187
+ const kept = reviewCaches.get(where);
188
+ if (!kept) return;
189
+ for (const key of [...kept.keys()]) if (key.startsWith(`${n}@`)) kept.delete(key);
190
+ }
191
+
192
+ /**
193
+ * The review state of every listed proposal, in the order of `entries`: `{ pushedAt, review }`. A draft PR is not read (it waits on the agent,
194
+ * whatever was said on it before): `{ pushedAt: null, review: null }`. For a ready PR, `review` is null (none yet), the latest maintainer review
195
+ * with `current`, or `{ error }` when the forge could not say. Never throws.
196
+ * @param {import('./forge.js').Forge} forge
197
+ * @param {{ proposals: string }} where
198
+ * @param {PullEntry[]} entries
199
+ * @param {{ now?: () => number }} [opts]
200
+ * @returns {Promise<PullReviewState[]>}
201
+ */
202
+ export async function reviewStates(forge, where, entries, { now = Date.now } = {}) {
203
+ let kept = reviewCaches.get(where);
204
+ if (!kept) reviewCaches.set(where, (kept = new Map()));
205
+ const out = entries.map(() => ({ pushedAt: null, review: null }));
206
+ /** @type {Map<number, number[]>} the indexes of the ready PRs' entries, by PR number */
207
+ const byPull = new Map();
208
+ entries.forEach((e, i) => { if (!e.pull.draft) byPull.set(e.pull.number, [...(byPull.get(e.pull.number) || []), i]); });
209
+ const numbers = [...byPull.keys()];
210
+ /** Who is a maintainer, asked once for this listing whatever the number of PRs they reviewed (not kept past it: a role can change) */
211
+ const admins = new Map();
212
+ let next = 0;
213
+ const worker = async () => {
214
+ while (next < numbers.length) {
215
+ const n = numbers[next++];
216
+ const at = byPull.get(n);
217
+ const head = entries[at[0]].sha;
218
+ const key = `${n}@${head}`;
219
+ const hit = kept.get(key);
220
+ if (hit && now() - hit.at < REVIEW_KEEP_MS && at.every((i) => hit.value.byIndex[entries[i].slug])) {
221
+ at.forEach((i) => { out[i] = hit.value.byIndex[entries[i].slug]; });
222
+ continue;
223
+ }
224
+ let pushedAt = null;
225
+ try {
226
+ const commits = await atSha(where, `commits ${n}@${head}`, () => forge.pullCommits(n));
227
+ pushedAt = commits.length ? commits[commits.length - 1].date : null;
228
+ const comments = await forge.comments(n);
229
+ /** @type {Record<string, PullReviewState>} */
230
+ const byIndex = {};
231
+ for (const i of at) {
232
+ const entry = entries[i];
233
+ const found = await latestReview(forge, n, entry.slug, comments, admins);
234
+ let review = null;
235
+ if (found) {
236
+ let current;
237
+ if (found.verdict === 'approved') current = found.proposal === proposalHash(await readPullProposal(forge, where, entry));
238
+ else current = !(pushedAt && Date.parse(pushedAt) > Date.parse(found.at)); // a send-back stands until something is pushed after it
239
+ review = { verdict: found.verdict, by: found.by, at: found.at, current };
240
+ }
241
+ byIndex[entry.slug] = { pushedAt, review };
242
+ out[i] = byIndex[entry.slug];
243
+ }
244
+ kept.set(key, { at: now(), value: { byIndex } });
245
+ if (kept.size > CACHE_MAX) kept.delete(kept.keys().next().value);
246
+ } catch (err) {
247
+ const failed = { pushedAt, review: { error: forgeWords(err) } }; // not kept: asked again next time
248
+ at.forEach((i) => { out[i] = failed; });
249
+ }
250
+ }
251
+ };
252
+ await Promise.all(Array.from({ length: Math.min(PARALLEL, numbers.length) }, worker));
253
+ return out;
254
+ }
@@ -47,7 +47,7 @@ import { summarize, proposalProblems } from '../core/proposal.js';
47
47
  import { ForgeError } from './forge.js';
48
48
  import { REVIEW_LIMIT, latestReview, migrateStage1Reviews } from './reviews.js';
49
49
  import { submitReview, refusal } from './submit-review.js';
50
- import { findPullProposal, forgeWords, listPullProposals, pullNumber, readPullProposal } from './proposal-pulls.js';
50
+ import { findPullProposal, forgeWords, listPullProposals, pullNumber, readPullProposal, reviewStates } from './proposal-pulls.js';
51
51
  import { serveMockups } from './mockups.js';
52
52
 
53
53
  // The review's checks live in server/reviews.js; these are re-exported for the callers that always had them here
@@ -211,7 +211,9 @@ async function listWithPulls(where, forgeFor, signedIn) {
211
211
  }
212
212
  const { entries, problem } = await listPullProposals(forge, where, { hooks: signedIn?.hooks });
213
213
  if (signedIn && entries.length) await migrateStage1Reviews({ forge, dataDir: where.dataDir, entries, login: signedIn.login, record: signedIn.record });
214
- const pulls = await Promise.all(entries.map((entry) => describePull(entry, forge, where, topology)));
214
+ // Each ready PR's review state rides along (spec 0010 D4), kept by head; a draft PR is not read
215
+ const [pulls, states] = await Promise.all([Promise.all(entries.map((entry) => describePull(entry, forge, where, topology))), reviewStates(forge, where, entries)]);
216
+ pulls.forEach((p, i) => { p.review = states[i].review; if (p.pull) p.pull = { ...p.pull, pushedAt: states[i].pushedAt }; });
215
217
  const list = [...local, ...pulls].sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0));
216
218
  return { list, problem };
217
219
  }
package/server/reviews.js CHANGED
@@ -187,19 +187,20 @@ export function parseReviewBlocks(body) {
187
187
  * @param {number} n
188
188
  * @param {string} slug
189
189
  * @param {import('./forge.js').Comment[]} [comments] when the caller already has them
190
+ * @param {Map<string, Promise<boolean>>} [admins] who was found to be a maintainer, shared by the caller across one read of several PRs (never kept longer)
190
191
  * @returns {Promise<FoundReview | null>}
191
192
  */
192
- export async function latestReview(forge, n, slug, comments) {
193
+ export async function latestReview(forge, n, slug, comments, admins = new Map()) {
193
194
  const all = comments ?? (await forge.comments(n));
194
- const admins = new Map();
195
195
  for (let i = all.length - 1; i >= 0; i--) {
196
196
  const c = all[i];
197
197
  if (!c.author) continue; // a deleted account: nobody to ask about
198
198
  const found = parseReviewBlocks(c.body).filter((b) => b.slug === slug).pop();
199
199
  if (!found) continue;
200
200
  const login = c.author.login;
201
- if (!admins.has(login)) admins.set(login, isMaintainer(await forge.permission(forge.repo, login)));
202
- if (!admins.get(login)) continue;
201
+ // the answer is kept as a promise, so PRs read side by side ask about one person once
202
+ if (!admins.has(login)) admins.set(login, Promise.resolve(forge.permission(forge.repo, login)).then(isMaintainer));
203
+ if (!(await admins.get(login))) continue;
203
204
  // A maintainer's review someone may have rewritten: it does not stand, and an older one does not take its place
204
205
  if (wasEdited(c)) return null;
205
206
  return { version: 1, slug, ...found.review, at: c.createdAt, by: login, comment: { id: c.id, url: c.url } };
@@ -36,7 +36,7 @@
36
36
 
37
37
  import { ForgeError, isMaintainer } from './forge.js';
38
38
  import { PROPOSAL_FILE } from './files.js';
39
- import { findPullProposal, forgeWords, readPullProposal } from './proposal-pulls.js';
39
+ import { findPullProposal, forgeWords, forgetReviewState, readPullProposal } from './proposal-pulls.js';
40
40
  import { hashPullMockups } from './mockups.js';
41
41
  import { postReview, proposalHash, validateReview } from './reviews.js';
42
42
  import { Refused, countAttempt, throttle } from './throttle.js';
@@ -130,6 +130,7 @@ export async function submitReview(ctx, { pull, slug, review, sha256 = null, pro
130
130
  if (why) throw new Refused(403, why, 'forbidden');
131
131
  }
132
132
  const posted = await postReview(forge, pull, slug, checkedReview, { login: me.login, record, via });
133
+ forgetReviewState(ctx.where, pull); // the listing's review state for this PR is read again (spec 0010)
133
134
  // The one place a review is posted, so the button and the API fire the same event; the actor is who the forge says
134
135
  // the poster is (with the API, the token's owner), never a name the caller sent
135
136
  ctx.hooks?.emit(posted.verdict === 'approved' ? 'spec.approved' : 'spec.sentBack', () => proposalPayload(forge, ctx.where, entry, { actor: me.login, note: checkedReview.note, edits: checkedReview.edits }));