@preventive/triage 1.0.0-alpha.83 → 1.0.0-alpha.84

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.
@@ -37,23 +37,24 @@
37
37
  // waited for, its page asking for it again (GET
38
38
  // /api/admin/repositories/risk/stasis), or why it failed. A repository GitHub
39
39
  // has archived is told so as it is opened, and read no further: nothing
40
- // installs from it anew.
40
+ // installs from it anew. What a scan told of each repository is kept for its
41
+ // reader and, where asked, told first (repository-risk-kept.ts).
41
42
  import type { LockfileFormat } from '@preventive/upstream/github.js'
42
- import { type ActionsSource, type Severity, npmMalwareAdvisory } from '../risk/index.js'
43
+ import type { ActionsSource, Severity } from '../risk/index.js'
43
44
  import { isNpmPackageName, isNpmPackageSpec } from '../common/managed/npm-packages.js'
44
- import { type RiskCaches, riskCaches } from './repository-risk-caches.ts'
45
+ import { type RiskCaches, keptRiskLines, riskCaches } from './repository-risk-caches.ts'
45
46
  import type { KeptStore } from './npm-kept.ts'
46
47
  import type { LockedPackage } from './locked-packages.ts'
47
48
  import { type Queue, inTurns, queue } from './queue.ts'
48
49
  import type { DownloadsSource } from './scan-downloads.ts'
49
- import { type AssessedPackage, type AssessingSource, RISK_KEPT_MS, type RiskFailure, assessPackage, failureOf } from './repository-risk-assess.ts'
50
+ import { type AssessedPackage, type AssessingSource, RISK_KEPT_MS, type RiskFailure, type ToldFinding, assessPackage, failureOf } from './repository-risk-assess.ts'
50
51
  import { type AdvisoryRow, type Audit, type AuditSource, auditLockfiles } from './repository-risk-audit.ts'
51
- import { type DependabotRead, type ListedLockfile, type LockfileRead, type OpenedRepository, type RepositoryArchived, type RepositoryFailure, type RepositoryRead, SCAN_READ_KEPT_MS,
52
- type StasisConfigsRead, readRepository, stasisBuilding, stasisVersions } from './repository-risk-read.ts'
52
+ import { type DependabotAlertRow, type ListedLockfile, type LockfileRead, type OpenedRepository, type RepositoryArchived, type RepositoryFailure, type RepositoryRead, SCAN_READ_KEPT_MS,
53
+ type StasisConfigsRead, dependabotLine, readRepository, rechecked, stasisBuilding, stasisVersions } from './repository-risk-read.ts'
54
+ import { type KeptRepositories, tellKept } from './repository-risk-kept.ts'
53
55
  import { STASIS_AGAIN_MS, type StasisBuild, type StasisReach, stasisReach } from './repository-risk-stasis.ts'
54
56
  import { type Turn, assessingTurn } from './repository-risk-turn.ts'
55
57
  import type { StasisRead } from './stasis-dependencies.ts'
56
- import { type DependabotAlert, alertVersions } from './dependabot-alerts.ts'
57
58
  import { type ActionLine, type ActionRef, type WorkflowLine, type WorkflowsLine, type WorkflowsRead, actionsLines,
58
59
  lockedNames, resolvingActions } from './repository-actions.ts'
59
60
 
@@ -99,13 +100,12 @@ interface RepositoryRiskSource<R extends RepositoryRiskRepo> extends AuditSource
99
100
  // read, as known now, asking GitHub nothing, nor for a build, as its page
100
101
  // asks for them; none watched without it.
101
102
  stasisBuilt?(build: StasisBuild): Promise<StasisRead>
103
+ // What a scan told of each repository, for its reader, told first where
104
+ // asked, of those its reader may read now (`readable`; none without it).
105
+ kept?: KeptRepositories
106
+ readable?(repo: R): Promise<boolean>
102
107
  }
103
108
 
104
- // A Dependabot alert as a scan tells it: with the versions of its package
105
- // the lockfile it is of locks that it covers, none where it is of none read
106
- // (a package.json, bun's lockfile), and whether it is of malware, by the rule
107
- // upstream tells an advisory's by (risk's npmMalwareAdvisory).
108
- type DependabotAlertRow = DependabotAlert & { versions: string[]; malware: boolean }
109
109
 
110
110
  // A risk line is of npm's package of its name and version, or, with an
111
111
  // `integrity`, of a mirror's that its lockfiles hold to it; its `score` risk's
@@ -115,7 +115,7 @@ export type RepositoryRiskLine =
115
115
  | ({ type: 'repo'; id: number } & ({ commit: string; lockfiles: { path: string; format: LockfileFormat }[] } | RiskFailure | { archived: true }))
116
116
  | ({ type: 'lockfile'; repo: number; path: string; format: LockfileFormat } & ({ packages: LockedPackage[] } | RiskFailure))
117
117
  | ({ type: 'risk'; name: string; version: string; integrity?: string; stale?: { assessedAt: number } }
118
- & ({ published: string | null; severity: Severity | null; score: number; findings: { id: string; severity: Severity; takenDown?: true }[] } | RiskFailure))
118
+ & ({ published: string | null; severity: Severity | null; score: number; findings: ToldFinding[] } | RiskFailure))
119
119
  | ({ type: 'advisories'; repo: number; path: string } & ({ advisories: AdvisoryRow[] } | RiskFailure))
120
120
  | ({ type: 'dependabot'; repo: number } & ({ alerts: DependabotAlertRow[] } | RiskFailure))
121
121
  | ({ type: 'stasis'; repo: number } & StasisConfigsRead)
@@ -146,8 +146,6 @@ const READ_AHEAD = 6
146
146
  const AUDITS_AT_ONCE = 4
147
147
  // How long a part's progress, written as it ends (`progress`), is waited on.
148
148
  const PROGRESS_WRITE_MS = 5000
149
- // How many kept risk lines are read of the source's `risks` at once.
150
- const KEPT_READ = 500
151
149
  const shared = riskCaches()
152
150
 
153
151
  interface Scan {
@@ -173,6 +171,9 @@ interface Scan {
173
171
  told: Map<number, ToldRepository>
174
172
  actions: ReturnType<typeof resolvingActions> | null
175
173
  audits: ReturnType<typeof inTurns>
174
+ // Whether what is kept is told first; its writes under way, waited for as it or its part ends.
175
+ keptFirst: boolean
176
+ keeping: Promise<unknown>[]
176
177
  }
177
178
 
178
179
  // A package as a scan meets it: by its name, version and a mirror's integrity.
@@ -202,20 +203,6 @@ async function assessed(scan: Scan, pkg: AssessedPackage): Promise<void> {
202
203
  if (line) scan.lines.add(line)
203
204
  }
204
205
 
205
- // Risk lines kept of `keys`, by key: in this instance's memory, else the
206
- // source's `risks`, KEPT_READ at a time.
207
- async function keptLines({ source, caches }: Scan, keys: string[]) {
208
- const kept = new Map<string, { at: number; line: RiskLine }>()
209
- const left = keys.filter(key => { const hit = caches.risks.get(key); if (hit) kept.set(key, hit); return !hit })
210
- for (let from = 0; source.risks && from < left.length; from += KEPT_READ) {
211
- for (const [key, { at, value }] of await source.risks.readMany(left.slice(from, from + KEPT_READ))) {
212
- caches.risks.set(key, { at, line: value })
213
- kept.set(key, { at, line: value })
214
- }
215
- }
216
- return kept
217
- }
218
-
219
206
  // Each lockfile's packages, as assessLater gives them: their risk lines as
220
207
  // kept, however old, told at once, a fresh one as it is and an older one as
221
208
  // stale (`stale`, when it was assessed), its package assessed again once
@@ -228,7 +215,7 @@ async function lookUp(scan: Scan, assess: (packages: AssessedPackage[]) => void)
228
215
  for (const pkg of packages) {
229
216
  try { keyed.push({ pkg, key: riskKey(pkg, await scan.source.teamScoped(pkg.name)) }) } catch (error) { scan.lines.add({ type: 'risk', ...pkg, ...failureOf(error) }) }
230
217
  }
231
- const kept = await keptLines(scan, keyed.map(({ key }) => key))
218
+ const kept = await keptRiskLines(scan.caches, scan.source.risks, keyed.map(({ key }) => key))
232
219
  const missing: AssessedPackage[] = []
233
220
  for (const { pkg, key } of keyed) {
234
221
  const hit = kept.get(key)
@@ -304,27 +291,6 @@ type Audited = (RepositoryRead & { audits: Promise<Audit | null>[] }) | Reposito
304
291
  const audited = (scan: Scan, read: RepositoryRead | RepositoryFailure | RepositoryArchived | null): Audited | null => (read === null || 'type' in read ? read : { ...read, audits: auditLockfiles(scan.source, scan.caches.advisories,
305
292
  scan.signal, read.lockfiles.map(({ sha, line }) => ({ key: `${line.format}\0${sha}`, packages: 'packages' in line ? line.packages : null })), scan.audits) })
306
293
 
307
- type DependabotLine = Extract<RepositoryRiskLine, { type: 'dependabot' }>
308
-
309
- // A repository's Dependabot alerts' line, each alert with the versions the
310
- // lockfile it is of locks that it covers (`lockfiles`, a repository read's),
311
- // or why they couldn't be had.
312
- function dependabotLine(repo: number, read: DependabotRead, lockfiles: RepositoryRead['lockfiles']): DependabotLine {
313
- if ('error' in read) return { type: 'dependabot', repo, ...read }
314
- const locked = new Map(lockfiles.flatMap(({ line }) => 'packages' in line ? [[line.path, line.packages] as const] : []))
315
- return { type: 'dependabot', repo, alerts: read.alerts.map(alert => ({ ...alert, versions: alertVersions(alert, locked.get(alert.manifest)),
316
- malware: npmMalwareAdvisory({ id: alert.ghsa, aliases: alert.aliases, cwe: alert.cwe, title: alert.title }) })) }
317
- }
318
-
319
- // A repository's alerts checked again just before they are told, as access to
320
- // the repository is (DependabotRead `recheck`): why not, where the user's
321
- // access to them is withdrawn since they were read.
322
- async function rechecked(read: DependabotRead): Promise<DependabotRead> {
323
- if (!('alerts' in read) || !read.recheck) return read
324
- try { await read.recheck() } catch (error) { return failureOf(error, 'checking access to its Dependabot alerts again') }
325
- return read
326
- }
327
-
328
294
  // A repository read (repository-risk-read.ts readRepository) told: its
329
295
  // line, or why it couldn't be read, then its lockfiles', and their
330
296
  // advisories, asked as it was read, its packages assessed meanwhile, then
@@ -333,27 +299,33 @@ async function rechecked(read: DependabotRead): Promise<DependabotRead> {
333
299
  // just before, however long ago it was read, as GitHub may have withdrawn it.
334
300
  async function tellRepository(scan: Scan, repo: RepositoryRiskRepo, read: Audited | null) {
335
301
  if (!read || scan.signal.aborted) return
336
- if ('type' in read) { scan.lines.add(read); return }
302
+ // One failing, or archived, kept no more, lest it be told as it was.
303
+ const keep = (work: Promise<unknown> | undefined) => { if (work) scan.keeping.push(work.catch(() => {})) }
304
+ if ('type' in read) { scan.lines.add(read); keep(scan.source.kept?.remove(repo)); return }
337
305
  try { await read.recheck() } catch (error) {
338
306
  if (!scan.signal.aborted) scan.lines.add({ type: 'repo', id: repo.repoId, ...failureOf(error, 'checking access to it again') })
307
+ keep(scan.source.kept?.remove(repo))
339
308
  return
340
309
  }
341
310
  if (scan.signal.aborted) return
311
+ // Its lines as told, but its Dependabot alerts', kept once all are.
312
+ const told: RepositoryRiskLine[] = []
313
+ const tell = (line: RepositoryRiskLine) => { told.push(line); scan.lines.add(line) }
342
314
  const { commit, lockfiles } = read
343
- scan.lines.add({ type: 'repo', id: repo.repoId, commit, lockfiles: lockfiles.map(({ line: { path, format } }) => ({ path, format })) })
315
+ tell({ type: 'repo', id: repo.repoId, commit, lockfiles: lockfiles.map(({ line: { path, format } }) => ({ path, format })) })
344
316
  const building = stasisBuilding(read.stasis), reached = stasisVersions(read.stasis)
345
317
  reach(scan, reached)
346
318
  scan.reach.building(building.map(config => ({ repoId: repo.repoId, commit, config })))
347
319
  for (const { line } of lockfiles) {
348
- scan.lines.add(line)
320
+ tell(line)
349
321
  if ('packages' in line) assessLater(scan, line.packages)
350
322
  }
351
- if (read.stasis) scan.lines.add({ type: 'stasis', repo: repo.repoId, ...read.stasis })
352
- const refs = read.actions ? tellActions(scan, repo, read.actions, lockfiles) : []
323
+ if (read.stasis) tell({ type: 'stasis', repo: repo.repoId, ...read.stasis })
324
+ const refs = read.actions ? tellActions(scan, repo, read.actions, lockfiles, tell) : []
353
325
  for (const [at, { line }] of lockfiles.entries()) {
354
326
  if (scan.signal.aborted) return
355
327
  const audit = await read.audits[at]
356
- if (audit) scan.lines.add(advisoriesLine(line, audit))
328
+ if (audit) tell(advisoriesLine(line, audit))
357
329
  }
358
330
  if (scan.signal.aborted) return
359
331
  const dependabot = read.dependabot && await rechecked(read.dependabot)
@@ -362,17 +334,28 @@ async function tellRepository(scan: Scan, repo: RepositoryRiskRepo, read: Audite
362
334
  scan.told.set(repo.repoId, { id: repo.repoId, name: repo.fullName, paths: repo.paths ?? null,
363
335
  lockfiles: lockfiles.flatMap(({ sha, line }) => 'packages' in line ? [`${line.format}\0${sha}`] : []), ...refs.length > 0 ? { actions: refs } : {}, ...reached.length > 0 ? { stasis: reached } : {},
364
336
  ...building.length > 0 ? { building: { commit, configs: building } } : {} })
337
+ keep(scan.source.kept?.write(repo, { name: repo.fullName, lines: told, refs }, Date.now()))
365
338
  }
366
339
 
367
- // A repository's Actions told, and the references they make to resolve.
368
- function tellActions(scan: Scan, repo: RepositoryRiskRepo, read: WorkflowsRead, lockfiles: RepositoryRead['lockfiles']) {
340
+ // A repository's Actions told (by `tell`), and the references they make to resolve.
341
+ function tellActions(scan: Scan, repo: RepositoryRiskRepo, read: WorkflowsRead, lockfiles: RepositoryRead['lockfiles'], tell: (line: RepositoryRiskLine) => void) {
369
342
  const locked = lockfiles.flatMap(({ line }) => 'packages' in line ? [lockedNames(line.path, line.packages)] : [])
370
343
  const { lines, refs } = actionsLines(repo.repoId, repo.fullName.split('/')[0]!, read, locked)
371
- for (const line of lines) scan.lines.add(line)
344
+ for (const line of lines) tell(line)
372
345
  scan.actions?.add(refs)
373
346
  return refs
374
347
  }
375
348
 
349
+ // A repository told before, as kept or by a part before, given to the scan
350
+ // again, GitHub asked nothing: its Stasis versions and builds to watch, its
351
+ // packages to assess and its Actions' references to resolve.
352
+ function reseed(scan: Scan, { stasis, building = [], packages, refs }: { stasis: readonly string[]; building?: StasisBuild[]; packages: LockedPackage[][]; refs: ActionRef[] }) {
353
+ reach(scan, stasis)
354
+ scan.reach.building(building)
355
+ for (const each of packages) assessLater(scan, each)
356
+ scan.actions?.add(refs)
357
+ }
358
+
376
359
  // Whether an earlier part told `repo` whole, by its name and a team's
377
360
  // directories in it as they are now, its packages then looked up as its
378
361
  // lockfiles are kept, those its Stasis builds made install before the rest,
@@ -388,11 +371,9 @@ async function toldBefore(scan: Scan, repo: RepositoryRiskRepo) {
388
371
  if (!read || !('packages' in read)) return false
389
372
  reads.push(read.packages)
390
373
  }
391
- reach(scan, told.stasis ?? [])
392
374
  const { building } = told
393
- if (building) scan.reach.building(building.configs.map(config => ({ repoId: told.id, commit: building.commit, config })))
394
- for (const packages of reads) assessLater(scan, packages)
395
- scan.actions?.add(told.actions ?? [])
375
+ reseed(scan, { stasis: told.stasis ?? [], building: building?.configs.map(config => ({ repoId: told.id, commit: building.commit, config })) ?? [], packages: reads,
376
+ refs: told.actions ?? [] })
396
377
  return true
397
378
  }
398
379
 
@@ -416,6 +397,14 @@ async function readRepositories(scan: Scan) {
416
397
  started.catch(() => {})
417
398
  return started
418
399
  }
400
+ // The first read meanwhile, which tells nothing till its turn: what is
401
+ // kept of those not told already, first, where asked.
402
+ for (let ahead = 0; ahead < Math.min(READ_AHEAD, repos.length); ahead++) void read(ahead)
403
+ const { kept: keptRepos, readable } = scan.source
404
+ if (scan.keptFirst && keptRepos && readable) {
405
+ await tellKept(keptRepos, repos.filter(repo => !scan.told.has(repo.repoId)), { signal: scan.signal, readable, tell: line => { scan.lines.add(line) },
406
+ reseed: told => { reseed(scan, told) } })
407
+ }
419
408
  for (const [at, repo] of repos.entries()) {
420
409
  if (scan.signal.aborted) return
421
410
  for (let ahead = at; ahead < Math.min(at + READ_AHEAD, repos.length); ahead++) void read(ahead)
@@ -455,6 +444,7 @@ async function runScan(scan: Scan, fail: (error: unknown) => void, everyMs: numb
455
444
  if (!scan.signal.aborted && left.length > 0) await assessing(scan, assess => { assess(left); return Promise.resolve() }, stale)
456
445
  }
457
446
  await scan.actions?.close()
447
+ await Promise.all(scan.keeping)
458
448
  if (!scan.signal.aborted) scan.lines.add({ type: 'done' })
459
449
  } catch (error) { fail(error) } finally { watching.abort(); await watch; scan.lines.close() }
460
450
  }
@@ -474,9 +464,10 @@ async function runScan(scan: Scan, fail: (error: unknown) => void, everyMs: numb
474
464
  // stops once that long, as a function time-limited must (Vercel's), the work
475
465
  // under way given up on, its last line `continue`, for its reader to ask
476
466
  // again: those it assessed are kept, and told at once then, and the
477
- // repositories it told whole kept as its source's `progress`.
467
+ // repositories it told whole kept as its source's `progress`. With `kept`,
468
+ // what is kept for its reader is told first (tellKept).
478
469
  export async function* repositoryRiskLines<R extends RepositoryRiskRepo>(source: RepositoryRiskSource<R>, signal: AbortSignal, caches = shared,
479
- { partMs = null, stasisEveryMs = STASIS_AGAIN_MS }: { partMs?: number | null; stasisEveryMs?: number } = {}): AsyncGenerator<RepositoryRiskLine> {
470
+ { partMs = null, stasisEveryMs = STASIS_AGAIN_MS, kept = false }: { partMs?: number | null; stasisEveryMs?: number; kept?: boolean } = {}): AsyncGenerator<RepositoryRiskLine> {
480
471
  const part = new AbortController(), stopped = new AbortController()
481
472
  const parting = partMs === null ? undefined : setTimeout(() => { part.abort() }, partMs)
482
473
  const running = AbortSignal.any([signal, stopped.signal, part.signal])
@@ -487,7 +478,7 @@ export async function* repositoryRiskLines<R extends RepositoryRiskRepo>(source:
487
478
  const actions = source.actions ? resolvingActions({ source: source.actions, signal: running, tell: line => { lines.add(line) }, memory: caches.actions,
488
479
  answers: caches.actionAnswers, store: source.actionLines }) : null
489
480
  const scan: Scan = { source, caches, signal: running, lines, lookups: queue(running), seen: new Map(), dev: new Map(), stale: new Map(), reach: stasisReach(),
490
- turn: null, told: new Map(), actions, audits: inTurns(AUDITS_AT_ONCE) }
481
+ turn: null, told: new Map(), actions, audits: inTurns(AUDITS_AT_ONCE), keptFirst: kept, keeping: [] }
491
482
  // A failure of the scan itself kept, to throw once the lines before it are
492
483
  // told, and the scan stopped.
493
484
  const failed: unknown[] = []
@@ -503,7 +494,7 @@ export async function* repositoryRiskLines<R extends RepositoryRiskRepo>(source:
503
494
  // Not waited on past PROGRESS_WRITE_MS, within what Vercel's limit
504
495
  // leaves past the part's: the next part then goes on from less.
505
496
  let timer
506
- await Promise.race([source.progress?.write({ repos: [...scan.told.values()] }), new Promise(resolve => { timer = setTimeout(resolve, PROGRESS_WRITE_MS) })])
497
+ await Promise.race([Promise.all([source.progress?.write({ repos: [...scan.told.values()] }), ...scan.keeping]), new Promise(resolve => { timer = setTimeout(resolve, PROGRESS_WRITE_MS) })])
507
498
  clearTimeout(timer)
508
499
  yield { type: 'continue' }
509
500
  }
@@ -11,7 +11,11 @@
11
11
  // priority first, then the one asked for last; one following another at once
12
12
  // while the first of them began a minute ago or less, else as one is asked
13
13
  // for again, as its page asks. A failed one is held in this instance, then
14
- // built again as asked.
14
+ // built again as asked. The commit of the last one built of each file at
15
+ // the head of a branch, as a risk scan reads one (`headAt`, when it read it
16
+ // so), is kept too, for it to tell what it reached while one of a later
17
+ // commit is still to be built (last): one read as the head later alone
18
+ // replaces it, whenever each is built.
15
19
  import { BundleBuildError, type LockfileInput, type StasisDependency } from './bundle-build.ts'
16
20
  import { directoryOf, installsBundle, lockedVersions } from './bundle-dependency-reviews.ts'
17
21
  import type { CommitLockfiles } from './commit-lockfiles.ts'
@@ -44,10 +48,13 @@ const MAX_WAITING = 500
44
48
  const STOPPING_EVERY_MS = 1000
45
49
 
46
50
  export type StasisRead = { status: 'ready'; dependencies: StasisDependency[] } | { status: 'pending' } | { status: 'failed'; error: string; transient: boolean }
51
+ // What a file reached as last built at the head of a branch, and of which commit (last).
52
+ export interface StasisBuilt { commit: string; dependencies: StasisDependency[] }
47
53
  // A build an answer asks for: of the stasis.config.json at `config` of
48
54
  // `repo` at `commit`, with `token`, its asker's, told the `branch` the commit
49
- // is of, where its asker knows it, and its priority.
50
- export interface StasisWant { repo: { repoId: number; fullName: string }; token: string; commit: string; config: string; branch?: string; priority: number }
55
+ // is of, where its asker knows it, and its priority; `headAt` where its
56
+ // asker read the commit as that branch's head, when (last).
57
+ export interface StasisWant { repo: { repoId: number; fullName: string }; token: string; commit: string; config: string; branch?: string; priority: number; headAt?: number }
51
58
 
52
59
  export interface StasisDependencyReader {
53
60
  // What the stasis.config.json at `config` of repository `repoId` reaches at
@@ -55,6 +62,13 @@ export interface StasisDependencyReader {
55
62
  read(repoId: number, commit: string, config: string): Promise<StasisRead>
56
63
  // Those of `wants` not known built behind the answer asking for them.
57
64
  build(wants: StasisWant[]): void
65
+ // What the stasis.config.json at `config` reached at the commit it was
66
+ // last built of at the head of `branch` (StasisWant `headAt`); null where
67
+ // none was.
68
+ last(repoId: number, branch: string, config: string): Promise<StasisBuilt | null>
69
+ // One built already, read at the head of `branch` at `headAt` (as a risk
70
+ // scan reads it): the last built there, as one built so is.
71
+ atTip(input: LockfileInput & { branch: string }, headAt: number): Promise<void>
58
72
  }
59
73
  interface ReaderOptions {
60
74
  store: KeptStore<unknown>
@@ -65,8 +79,13 @@ interface ReaderOptions {
65
79
  stopping(): boolean
66
80
  }
67
81
 
68
- type Job = { key: string; input: LockfileInput; github: string; token: string; priority: number; asked: number }
82
+ // A build waiting or under way, and the latest read of its commit as a branch's head (`head`), where one was.
83
+ type Head = { branch: string; at: number }
84
+ type Job = { key: string; input: LockfileInput; github: string; token: string; priority: number; asked: number; head: Head | null }
85
+ const later = (one: Head | null, other: Head | null) => !one || (other && other.at > one.at) ? other : one
69
86
  const keyOf = (repoId: number, commit: string, config: string) => `${repoId}\0${STASIS_DEPENDENCIES_READ}\0${commit}\0${config}`
87
+ // Where the commit it was last built of at a branch's head is kept.
88
+ const lastKeyOf = (repoId: number, branch: string, config: string) => `${repoId}\0${STASIS_DEPENDENCIES_READ}\0last\0${branch}\0${config}`
70
89
  const optional = (value: unknown) => value === undefined || typeof value === 'string'
71
90
  const dependenciesOf = (value: unknown) => Array.isArray(value) && value.every(one => plainObject(one) && typeof one['name'] === 'string'
72
91
  && typeof one['version'] === 'string' && optional(one['integrity']) && optional(one['patch'])) ? value as StasisDependency[] : null
@@ -80,7 +99,7 @@ export function stasisDependencyReader({ store, build, behind, stopping }: Reade
80
99
  }
81
100
  // Those waiting, the one asked for longest ago first; the one being built here; and till when none is tried after one found its slot busy.
82
101
  const waiting = new Map<string, Job>()
83
- let building: string | null = null, busyTill = 0
102
+ let building: Job | null = null, busyTill = 0
84
103
 
85
104
  // The one to build next: of the highest priority, then asked for last; those not asked for since LAPSED_MS let go.
86
105
  function next(): Job | null {
@@ -103,6 +122,7 @@ export function stasisDependencyReader({ store, build, behind, stopping }: Reade
103
122
  const dependencies = await build(job.input, job.github, job.token, stop.signal)
104
123
  await store.write(job.key, dependencies, Date.now())
105
124
  hold(job.key, { status: 'ready', dependencies })
125
+ if (job.head) await lasts.keep({ ...job.input, branch: job.head.branch }, job.head.at)
106
126
  } catch (err) {
107
127
  if (stop.signal.aborted) return
108
128
  const refused = err instanceof BundleBuildError
@@ -120,32 +140,62 @@ export function stasisDependencyReader({ store, build, behind, stopping }: Reade
120
140
  const began = Date.now()
121
141
  try {
122
142
  for (let job = next(); job; job = Date.now() - began < FOLLOWED_WITHIN_MS && Date.now() >= busyTill && !stopping() ? next() : null) {
123
- building = job.key
143
+ building = job
124
144
  await built(job)
125
145
  }
126
146
  } finally { building = null }
127
147
  }
128
148
 
149
+ const read = async (repoId: number, commit: string, config: string): Promise<StasisRead> => {
150
+ const key = keyOf(repoId, commit, config)
151
+ const held = known.get(key)
152
+ if (held && Date.now() < held.until) return held.read
153
+ return await kept(key) ?? { status: 'pending' }
154
+ }
155
+ const lasts = lastBuilds(store, read)
156
+
129
157
  return {
130
- async read(repoId, commit, config) {
131
- const key = keyOf(repoId, commit, config)
132
- const held = known.get(key)
133
- if (held && Date.now() < held.until) return held.read
134
- return await kept(key) ?? { status: 'pending' }
135
- },
158
+ read,
136
159
  build(wants) {
137
- for (const { repo, token, commit, config, branch, priority } of wants) {
160
+ for (const { repo, token, commit, config, branch, priority, headAt } of wants) {
138
161
  const key = keyOf(repo.repoId, commit, config)
139
- if (key === building) continue
140
- // Asked for again: last in line, at the higher of its priorities, with its latest asker's token and branch.
162
+ const head = branch && headAt !== undefined ? { branch, at: headAt } : null
163
+ // The one being built told, too, where it is read as a branch's head since.
164
+ if (key === building?.key) {
165
+ building.head = later(building.head, head)
166
+ continue
167
+ }
168
+ // Asked for again: last in line, at the higher of its priorities, with
169
+ // its latest asker's token and branch, and its latest read as a branch's head.
141
170
  const had = waiting.get(key)
142
171
  waiting.delete(key)
143
172
  waiting.set(key, { key, input: { repoId: repo.repoId, commit, config, ...branch === undefined ? had?.input.branch === undefined ? {} : { branch: had.input.branch } : { branch } },
144
- github: repo.fullName, token, priority: Math.max(priority, had?.priority ?? priority), asked: Date.now() })
173
+ github: repo.fullName, token, priority: Math.max(priority, had?.priority ?? priority), asked: Date.now(),
174
+ head: later(had?.head ?? null, head) })
145
175
  if (waiting.size > MAX_WAITING) waiting.delete(waiting.keys().next().value!)
146
176
  }
147
177
  if (building === null && waiting.size > 0 && Date.now() >= busyTill && !stopping()) behind(run())
148
178
  },
179
+ last: lasts.last,
180
+ atTip: lasts.keep,
181
+ }
182
+ }
183
+
184
+ // The commit each file was last built of at a branch's head, kept in `store`
185
+ // as of when it was read as the head (`headAt`), which keeps none read so
186
+ // before what it has, whichever instance kept that; and what that build
187
+ // reached, as `read` tells it.
188
+ function lastBuilds(store: KeptStore<unknown>, read: (repoId: number, commit: string, config: string) => Promise<StasisRead>) {
189
+ return {
190
+ async keep({ repoId, commit, config, branch }: LockfileInput, headAt: number) {
191
+ if (branch) await store.write(lastKeyOf(repoId, branch, config), commit, headAt)
192
+ },
193
+ async last(repoId: number, branch: string, config: string): Promise<StasisBuilt | null> {
194
+ const commit = (await store.read(lastKeyOf(repoId, branch, config)))?.value
195
+ if (typeof commit !== 'string') return null
196
+ const built = await read(repoId, commit, config)
197
+ return built.status === 'ready' ? { commit, dependencies: built.dependencies } : null
198
+ },
149
199
  }
150
200
  }
151
201
 
@@ -30,7 +30,8 @@ export interface TeamAppSummaryStore {
30
30
  // is raised, is worked out again.
31
31
  // 2: a report that opens as an App view on its own holds its team off it with
32
32
  // none of its findings (common/managed/team-app.js).
33
- const SUMMARY_VERSION = 2
33
+ // 3: how many findings each report shows (team-reports.ts).
34
+ const SUMMARY_VERSION = 3
34
35
  const DEPLOYMENT = process.env['VERCEL_DEPLOYMENT_ID'] ?? null
35
36
 
36
37
  export const teamAppSummaryKey = (key: string): string => createHash('sha256').update(JSON.stringify([SUMMARY_VERSION, DEPLOYMENT, key])).digest('base64url')
@@ -26,7 +26,9 @@ import { teamAppSummaryKey } from './team-app-summaries.ts'
26
26
  import { eachOf } from './queue.ts'
27
27
 
28
28
  export type { TeamAppMetadata }
29
- export interface TeamWorkspaceSummary { app: TeamAppMetadata; empty: readonly string[] }
29
+ // Its App classification, the reports a restricted reader finds nothing in,
30
+ // and how many findings each report shows its reader (`findings`, by its ID).
31
+ export interface TeamWorkspaceSummary { app: TeamAppMetadata; empty: readonly string[]; findings?: Readonly<Record<string, number>> }
30
32
  const NO_APP: TeamWorkspaceSummary = { app: { appMode: false }, empty: [] }
31
33
 
32
34
  const CACHE_MAX_ENTRIES = 4096
@@ -79,7 +81,9 @@ async function storedSummaries(db: ManagedDb, keys: readonly string[]): Promise<
79
81
  function readSummary(text: string): TeamWorkspaceSummary | null {
80
82
  try {
81
83
  const summary = JSON.parse(text) as TeamWorkspaceSummary
82
- return typeof summary?.app?.appMode === 'boolean' && Array.isArray(summary.empty) && summary.empty.every(id => typeof id === 'string') ? summary : null
84
+ const counts = summary?.findings
85
+ return typeof summary?.app?.appMode === 'boolean' && Array.isArray(summary.empty) && summary.empty.every(id => typeof id === 'string')
86
+ && (counts === undefined || typeof counts === 'object' && counts !== null && Object.values(counts).every(n => Number.isSafeInteger(n) && n >= 0)) ? summary : null
83
87
  } catch { return null }
84
88
  }
85
89
 
@@ -128,10 +132,12 @@ async function classify(db: ManagedDb, store: BlobStore, key: string, team: User
128
132
  }
129
133
 
130
134
  // The catalog's view of a classified team: its App classification, and its
131
- // reports without the ones its restricted reader would find empty.
132
- export function withWorkspaceSummary<T extends { reports: readonly { id: string }[] }>(team: T, summary: TeamWorkspaceSummary | null | undefined) {
133
- const empty = new Set(summary?.empty)
134
- return { ...team, app: summary?.app ?? null, reports: team.reports.filter(report => !empty.has(report.id)) }
135
+ // reports without the ones its restricted reader would find empty, each with
136
+ // how many findings it shows them where the summary counts them.
137
+ export function withWorkspaceSummary<R extends { id: string }, T extends { reports: readonly R[] }>(team: T, summary: TeamWorkspaceSummary | null | undefined) {
138
+ const counts = summary?.findings ?? {}, empty = new Set(summary?.empty)
139
+ return { ...team, app: summary?.app ?? null, reports: team.reports.filter(report => !empty.has(report.id))
140
+ .map(report => Object.hasOwn(counts, report.id) ? { ...report, findings: counts[report.id] } : report) }
135
141
  }
136
142
 
137
143
  // Classify a user's catalog, keyed by teamAppKey. `known` carries results from
@@ -235,9 +235,10 @@ async function buildTeamWorkspace(db: ManagedDb, store: BlobStore, snapshot: Tea
235
235
  reports: encodeReports(reports, links, trees.length),
236
236
  lite: encodeReports(lite.reports, links, 0, { folded: lite.folded, lens: lite.lens }),
237
237
  trees,
238
- // Its App classification, and the reports a restricted reader finds
239
- // nothing in, which its catalog leaves out.
240
- summary: { app: view.app, empty: restricted ? reports.filter(report => !hasContent(report.data)).map(report => report.id) : [] },
238
+ // Its App classification, the reports a restricted reader finds nothing
239
+ // in, which its catalog leaves out, and how many findings each shows.
240
+ summary: { app: view.app, empty: restricted ? reports.filter(report => !hasContent(report.data)).map(report => report.id) : [],
241
+ findings: Object.fromEntries(reports.map(report => [report.id, visible.get(report.id)?.ids.size ?? 0])) },
241
242
  }
242
243
  retainVisibility(db, workspaceKey(snapshot), visible)
243
244
  retainReports(db, workspaceKey(snapshot), encoded)