rvlib-shipkit 2.11.0 → 2.12.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/CHANGELOG.md CHANGED
@@ -1,3 +1,12 @@
1
+ ## 2.12.0
2
+
3
+ - **`sk media versioning [--check]`: the Space's versioning, turned on or read.** PutBucketVersioning then GetBucketVersioning, signed by hand (SigV4) since Bun's S3 client has no verb for them (`Space.versioning`, `Space.enableVersioning`). On the house Space today the read answers `off` and the PUT answers 403 AccessDenied: its key is limited to the bucket's objects.
4
+ - **Comment images and the trailer's shots folders join the media store.** A review message's image (`thread/<file>`) is a file of the `review` kind: its fact in `item.json` under `media["thread/<file>"]`, up and purged by the card's rules, served from the Space by `GET /api/review/<id>/thread/<file>` once the disk let it go, fetched back by `sk review show`. Each build's shelf `out/<cut>-shots/` and each version's `versions/<v>/shots/` are files of the `trailer` kind, their facts in the folder's `.media.json`: the shelf of each trailer's newest build and a folder whose cut has an open note stay on the disk, the rest goes once quiet for 14 days from the folder's birth. `sk trailer keep` fetches a purged shelf back before it clones it, and clones its facts with it.
5
+ - **The inbox folds the red checks of a quiet repo into « can wait ».** A repo whose last commit of its own is older than 7 days (a subject 3 house repos share, numbers taken out, is a sweep and never counts: the toolkit bumps landed in every repo yesterday; the log asked at most once every 10 minutes per repo) keeps its review cards and asks in the main list, but its red checks go to the folded list, still red, their line saying « quiet repo, last commit <day> ». A repo git cannot date stays as it was. 23 of the main rows were red checks of repos nobody works in.
6
+ - **`sk media put` and `sk media link`: any repo keeps a file in the private Space through the store.** `sk media put <file…> --kind <label> [--link <dur>] [--json]` keeps each file by its content as `<label>/<sha256>.<ext>` (`files` when no label is given): its index row with its original name first, then the upload, checked by a HEAD; a content already up is only marked. A label no `MediaKind` owns is the generic kind under that prefix, purgeable off the Mac by the usual rules (its bytes must still hash to its key), never deleted from the Space; `review` and `trailer` are refused. `sk media link <key|sha|path> [--for <dur>] [--name <filename>] [--json]` signs a fresh link at any time. Every link carries `response-content-disposition: attachment; filename="<name>"` and `response-content-type`, inside the signature, so a download keeps its name through the CDN edge. A link lasts at most 7d, the SigV4 limit; more is refused with that reason. `--json` prints one line a file, `{ key, sha, size, name, url, expires }`. The content types gain zip, gz, tar, dmg, pdf, gif, json, txt, md and csv.
7
+
8
+ - **A hub page loads a quarter of the bytes.** `/api/resources.json` is serialized once per compute, carries an ETag over the list and its live parts, is gzipped for a browser that takes it, and answers 304 to a page that holds it; the page then parses and swaps nothing on that poll. A test file carries its last run only in the list, and its page reads the whole list from `GET /api/test-runs.json?file=<file>`. The web answers 304 for a page file whose ETag the browser holds, so the 3.3 MB bundle no longer comes again on every load. The review page's boot reads its list, its watchers and the unit's words once, not three times. Measured on pkm-multi's review page: 12.8 MB on the wire before, 3.7 MB cold and 1.3 to 1.5 MB warm after; its list 2.18 MB to 1.18 MB (107 kB gzipped).
9
+
1
10
  ## 2.11.0
2
11
 
3
12
  - **One media store for any kind of media, and the trailer renders join it.** `src/review/space/` becomes `src/media-store/`, the machine's one store: a caller writes a `MediaKind` (where its files live in a repo, what they are, what stays on the disk) and adds it to `src/media-kinds.ts`; the store does the index, the upload, the signed URL, the fetch back and the purge. Keys are `<kind>/<sha256>.<ext>`. Review is the kind `review`, unchanged on the Space. The trailer renders are the kind `trailer`: each settled render's video and strip (the desk's clones in `.shipkit/cache/trailer-view/`, recorded by the daemon even when the desk never opened) and each kept version's own files go up; the newest render of each live cut and a render an open frame note was written on stay on the disk, the rest goes once quiet for 14 days and only after its bytes hash to its key. The desk plays a render the disk let go from a URL signed on the CDN edge; a new note fetches its video back; `sk trailer clip --version` fetches a version's video back. `sk trailer prune` no longer deletes views: an old render was lost there before it went up. A purge never deletes a file a process holds open. The verbs move: `sk media`, `sk media upload [--kind]`, `sk media purge [--kind] [--dry --list] [--auto on|off]` replace `sk review media`, `sk review media upload` and `sk review purge`; the daemon's switch is `media-purge-auto` (off until turned on). The house config key is `serve.mediaSpace`; the index file is `media.sqlite` (`SHIPKIT_MEDIA_DB`). The purge works six files at a time and sends a review image's previews with a PUT and a HEAD each, none when they are up: 524 ms a file down to 62 ms on a fake S3 at 40 ms a request. Page: build/shipkit/media-store.md.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rvlib-shipkit",
3
- "version": "2.11.0",
3
+ "version": "2.12.0",
4
4
  "funding": "https://github.com/sponsors/rvion",
5
5
  "description": "All-in-one repo companion: ci gate (task DAG), auto-discovered health checks, release-contract fulfillness, asks queue, md-wiki tools, asset atelier, live tui",
6
6
  "license": "MIT",
@@ -20,7 +20,8 @@ async function run(context: Ctx, o: { repo?: string | undefined; kind?: string |
20
20
  const err = (l: string): void => void context.stderr.write(`${l}\n`)
21
21
  try {
22
22
  const { findRepoRoot } = await import('../ts/config.ts')
23
- const { MEDIA_KINDS } = await import('../media-kinds.ts')
23
+ const { mediaKinds } = await import('../media-kinds.ts')
24
+ const MEDIA_KINDS = mediaKinds()
24
25
  const { existsSync } = await import('node:fs')
25
26
  const { basename, dirname, join } = await import('node:path')
26
27
  const here = findRepoRoot(process.cwd())
@@ -40,7 +41,7 @@ async function run(context: Ctx, o: { repo?: string | undefined; kind?: string |
40
41
  }
41
42
 
42
43
  const repoOpt = (): string | undefined => Option.String('--repo', { description: 'a sibling repo by name, in place of this one' })
43
- const kindOpt = (): string | undefined => Option.String('--kind', { description: 'one kind alone: review, trailer' })
44
+ const kindOpt = (): string | undefined => Option.String('--kind', { description: 'one kind alone: review, trailer, or a label sk media put wrote' })
44
45
 
45
46
  export class MediaCommand extends Command {
46
47
  static override paths = [['media']]
@@ -161,4 +162,92 @@ export class MediaPurgeCommand extends Command {
161
162
  }
162
163
  }
163
164
 
164
- export const MEDIA_COMMANDS = [MediaCommand, MediaUploadCommand, MediaPurgeCommand]
165
+ const PUT_DETAILS = `The one way an agent of any repo keeps a file in the owner's private Space: never call the Space client directly. Each file is kept by its content as <label>/<sha256>.<ext>, private: its index row (its repo, its place, its original name) first, then the upload, checked by a HEAD of its size; a content the Space already holds is only marked. The object never expires and nothing deletes it from the Space; the file stays on the disk, purgeable by the usual rules (sk media purge). A link is signed on the CDN edge and downloads under the file's name; it lasts at most 7d, the SigV4 limit of a signed URL, and sk media link makes a new one at any time. Page: wiki build/shipkit/media-store.md, Put a file from any repo`
166
+
167
+ export class MediaPutCommand extends Command {
168
+ static override paths = [['media', 'put']]
169
+ static override usage = Command.Usage({
170
+ category: 'Media',
171
+ description: 'keep files in the private Space by content, a signed link at most 7 days',
172
+ details: `${PUT_DETAILS}\n\n--json prints one line a file: { key, sha, size, name, url, expires }, url and expires only with --link.`,
173
+ examples: [
174
+ ['a file, its key printed', 'sk media put notes.txt'],
175
+ ['release zips, a week long link each, as json', 'sk media put dist/a.zip dist/b.zip --kind private-build --link 7d --json'],
176
+ ],
177
+ })
178
+ kind = Option.String('--kind', { description: 'the label, the key prefix: lowercase letters, digits, dashes (files)' })
179
+ link = Option.String('--link', { description: 'a signed link for this long: 30m, 2h, 7d (at most 7d)' })
180
+ json = Option.Boolean('--json', false, { description: 'one JSON line a file' })
181
+ files = Option.Rest({ required: 1 })
182
+ async execute(): Promise<number> {
183
+ return run(this.context, {}, async (h) => {
184
+ const { durationS, linkMedia, putMedia } = await import('../media-store/put.ts')
185
+ const { mb } = await import('../media-store/upload.ts')
186
+ const seconds = this.link === undefined ? null : durationS(this.link)
187
+ for (const f of this.files) {
188
+ const p = await putMedia(f, { ...(this.kind !== undefined ? { kind: this.kind } : {}) })
189
+ const l = seconds === null ? null : await linkMedia(p.key, { seconds, name: p.name })
190
+ if (this.json) h.out(JSON.stringify({ key: p.key, sha: p.sha, size: p.size, name: p.name, ...(l ? { url: l.url, expires: l.expires } : {}) }))
191
+ else {
192
+ h.out(`${p.key} ${p.name} ${mb(p.size)} ${p.sent ? 'up' : 'already in the Space'}`)
193
+ if (l) h.out(` ${l.url}\n expires ${l.expires}`)
194
+ }
195
+ }
196
+ return 0
197
+ })
198
+ }
199
+ }
200
+
201
+ export class MediaLinkCommand extends Command {
202
+ static override paths = [['media', 'link']]
203
+ static override usage = Command.Usage({
204
+ category: 'Media',
205
+ description: 'a fresh signed link to a file the Space holds, by key, sha or path',
206
+ details: `${PUT_DETAILS}\n\nThe reference is a key (<label>/<sha256>.<ext>), a sha (12 hex of it are enough), or a file the store holds. The link downloads under the name the index keeps for it, or --name. --for defaults to 24h, at most 7d. --json prints { key, sha, size, name, url, expires }.`,
207
+ examples: [
208
+ ['a link for a day', 'sk media link private-build/<sha>.zip'],
209
+ ['a week, under a name, as json', 'sk media link private-build/<sha>.zip --for 7d --name dgen-1.2.0-mac-arm64.zip --json'],
210
+ ],
211
+ })
212
+ for = Option.String('--for', { description: 'how long the link lasts: 30m, 2h, 7d (24h, at most 7d)' })
213
+ name = Option.String('--name', { description: 'the file name the link downloads under (the index row\'s name)' })
214
+ json = Option.Boolean('--json', false, { description: 'one JSON line' })
215
+ ref = Option.String({ required: true })
216
+ async execute(): Promise<number> {
217
+ return run(this.context, {}, async (h) => {
218
+ const { durationS, linkMedia } = await import('../media-store/put.ts')
219
+ const l = await linkMedia(this.ref, { seconds: durationS(this.for ?? '24h'), ...(this.name !== undefined ? { name: this.name } : {}) })
220
+ if (this.json) h.out(JSON.stringify(l))
221
+ else h.out(`${l.url}\n ${l.key} ${l.name}, expires ${l.expires}`)
222
+ return 0
223
+ })
224
+ }
225
+ }
226
+
227
+ export class MediaVersioningCommand extends Command {
228
+ static override paths = [['media', 'versioning']]
229
+ static override usage = Command.Usage({
230
+ category: 'Media',
231
+ description: "turn on the Space's versioning: a delete from outside can be undone; --check reads it",
232
+ details: `PutBucketVersioning, then GetBucketVersioning to confirm: an object deleted or overwritten from the DigitalOcean dashboard or by a stray key keeps its older version. DigitalOcean offers it through the S3 API only. Once on, it can only be suspended, never turned off. Page: wiki build/shipkit/media-store.md, Versioning`,
233
+ examples: [
234
+ ['turn it on', 'sk media versioning'],
235
+ ['read it', 'sk media versioning --check'],
236
+ ],
237
+ })
238
+ check = Option.Boolean('--check', false, { description: 'read the state, change nothing' })
239
+ async execute(): Promise<number> {
240
+ return run(this.context, {}, async (h) => {
241
+ const { machineSpace } = await import('../media-store/space.ts')
242
+ const { space, why } = await machineSpace()
243
+ if (!space) throw new Error(`no Space: ${why}`)
244
+ const before = await space.versioning()
245
+ if (!this.check && before !== 'Enabled') await space.enableVersioning()
246
+ const now = this.check ? before : await space.versioning()
247
+ h.out(`${space.where}: versioning ${now}${this.check || before === now ? '' : ` (was ${before})`}`)
248
+ return this.check || now === 'Enabled' ? 0 : 1
249
+ })
250
+ }
251
+ }
252
+
253
+ export const MEDIA_COMMANDS = [MediaCommand, MediaUploadCommand, MediaPurgeCommand, MediaPutCommand, MediaLinkCommand, MediaVersioningCommand]
@@ -374,6 +374,10 @@ export class ReviewShowCommand extends Command {
374
374
  return 0
375
375
  }
376
376
  const t = threadOfItem(x.item.id, threadsOf(all.items))
377
+ // the image paths it prints are on the disk: a message image the purge let go comes back first
378
+ const { ensureLocal } = await import('../review/media-read.ts')
379
+ const { membersOf } = await import('../review/threads.ts')
380
+ await Promise.all((t ? membersOf(t) : [x]).flatMap((y) => y.thread.flatMap((m) => (m.image ? [ensureLocal(h.dir, y.item.id, `thread/${m.image}`).catch((e: Error) => h.err(`review: WARN thread/${m.image}: ${e.message}`))] : []))))
377
381
  h.out(t && (t.head.item.id === x.item.id || t.answers.length > 0) ? threadDetail(t, h.dir, true, h.say) : detail(x, h.dir, true, false, h.say))
378
382
  return 0
379
383
  })
@@ -247,6 +247,10 @@ export class TrailerKeepCommand extends Command {
247
247
  return run(this.context, async (say, root, cwd) => {
248
248
  const l = await loaded(this.file, say, root, cwd)
249
249
  if (!l) return 1
250
+ // a shot the media store let go comes back first, so the version holds every take
251
+ const { join } = await import('node:path')
252
+ const lost = await (await import('../review/trailer-shots.ts')).shotsBack(l.root, join(l.dir, 'out', `${l.t.name}-shots`))
253
+ if (lost.length > 0) say(`WARN ${lost.length} shots not fetched back, kept by their facts only: ${lost.join(', ')}`)
250
254
  ;(await import('../trailer/passage.ts')).keep(l, this.version, say, cwd)
251
255
  return 0
252
256
  })
@@ -44,6 +44,8 @@ export interface InboxSource {
44
44
  repo: string
45
45
  review: { tag: string; ix: ThreadIndex } | null
46
46
  needs: Resource[]
47
+ /** epoch ms of its last commit when that is older than `QUIET_DAYS`: its red rows can wait */
48
+ quietSince?: number | null
47
49
  }
48
50
 
49
51
  export interface InboxAnswer {
@@ -61,6 +63,8 @@ export interface InboxAnswer {
61
63
  }
62
64
 
63
65
  export const INBOX_PAGE = 50
66
+ /** a repo with no commit for this long is quiet: nobody works there, its red checks fold into « can wait » */
67
+ export const QUIET_DAYS = 7
64
68
  export const INBOX_MAX = 500
65
69
 
66
70
  /** where a repo's hub answers on the home */
@@ -124,7 +128,7 @@ function needRow(repo: string, n: Resource, dated: Dated): InboxRow {
124
128
  }
125
129
 
126
130
  /** one repo's rows: the main list (the cards and questions waiting on him, the asks, what is red) and the folded one
127
- * (what is yellow, the raised items in the agents' hands) */
131
+ * (what is yellow, the raised items in the agents' hands, what is red in a quiet repo) */
128
132
  export function repoRows(s: InboxSource, dated: Dated): Record<InboxList, InboxRow[]> {
129
133
  const out: Record<InboxList, InboxRow[]> = { main: [], yellow: [] }
130
134
  for (const { row } of s.review?.ix.entries ?? []) {
@@ -134,7 +138,9 @@ export function repoRows(s: InboxSource, dated: Dated): Record<InboxList, InboxR
134
138
  for (const n of s.needs) {
135
139
  if (n.severity == null || n.collection === REVIEW_COL || n.askOwned === true) continue
136
140
  const r = needRow(s.repo, n, dated)
137
- out[r.kind === 'ask' || r.tone === 'red' ? 'main' : 'yellow'].push(r)
141
+ const quiet = s.quietSince != null && r.kind !== 'ask' && r.tone === 'red'
142
+ if (quiet) r.sub = [`quiet repo, last commit ${new Date(s.quietSince!).toISOString().slice(0, 10)}`, r.sub].filter((x) => x != null).join(' · ')
143
+ out[!quiet && (r.kind === 'ask' || r.tone === 'red') ? 'main' : 'yellow'].push(r)
138
144
  }
139
145
  return out
140
146
  }
package/src/home/inbox.ts CHANGED
@@ -6,7 +6,60 @@ import { join } from 'path'
6
6
  import type { Resource } from '../collections/collection-types.ts'
7
7
  import { storeIndex } from '../review/routes.ts'
8
8
  import type { Hubs } from './hubs.ts'
9
- import { inboxPage, inboxQuery, inboxRows, type Dated, type InboxAnswer, type InboxSource } from './inbox-shape.ts'
9
+ import { inboxPage, inboxQuery, inboxRows, QUIET_DAYS, type Dated, type InboxAnswer, type InboxSource } from './inbox-shape.ts'
10
+
11
+ const COMMIT_TTL = 10 * 60_000
12
+ /** a subject this many repos share is a sweep over the house (a toolkit bump, a doc pass), never work on the repo */
13
+ const SWEEP_REPOS = 3
14
+ const LOG_DEPTH = 200
15
+
16
+ /** one commit of a repo's log: when, and its subject with the numbers taken out (`rvlib-shipkit ^2.11.0` and
17
+ * `rvlib-shipkit 2.10.0` are one sweep) */
18
+ export interface LogLine {
19
+ at: number
20
+ subject: string
21
+ }
22
+
23
+ const logs = new Map<string, { asked: number; lines: Promise<LogLine[] | null> }>()
24
+
25
+ /** a repo's newest commits on HEAD, asked of git at most once every 10 minutes; null when git cannot say */
26
+ export function recentCommits(root: string, now = Date.now()): Promise<LogLine[] | null> {
27
+ const hit = logs.get(root)
28
+ if (hit != null && now - hit.asked < COMMIT_TTL) return hit.lines
29
+ const lines = (async () => {
30
+ try {
31
+ const p = Bun.spawn(['git', 'log', `-${LOG_DEPTH}`, '--format=%ct%x09%s', 'HEAD'], { cwd: root, stdout: 'pipe', stderr: 'ignore' })
32
+ const out = await new Response(p.stdout).text()
33
+ if ((await p.exited) !== 0) return null
34
+ return out.split('\n').flatMap((l) => {
35
+ const tab = l.indexOf('\t')
36
+ const at = Number(l.slice(0, tab)) * 1000
37
+ return tab > 0 && Number.isFinite(at) ? [{ at, subject: l.slice(tab + 1).toLowerCase().replace(/[\d^~.]+/g, '') }] : []
38
+ })
39
+ } catch {
40
+ return null
41
+ }
42
+ })()
43
+ logs.set(root, { asked: now, lines })
44
+ return lines
45
+ }
46
+
47
+ /** per repo, its last commit of its own when the repo is quiet (none for `QUIET_DAYS`), else null. A commit whose
48
+ * subject `SWEEP_REPOS` repos share is a sweep and never counts; a repo git cannot read is never quiet */
49
+ export function quietOf(byRepo: ReadonlyMap<string, LogLine[] | null>, now = Date.now()): Map<string, number | null> {
50
+ const seen = new Map<string, Set<string>>()
51
+ for (const [repo, lines] of byRepo) for (const l of lines ?? []) seen.set(l.subject, (seen.get(l.subject) ?? new Set()).add(repo))
52
+ const out = new Map<string, number | null>()
53
+ for (const [repo, lines] of byRepo) {
54
+ if (lines == null || lines.length === 0) {
55
+ out.set(repo, null)
56
+ continue
57
+ }
58
+ const own = lines.find((l) => (seen.get(l.subject)?.size ?? 0) < SWEEP_REPOS) ?? lines[lines.length - 1]!
59
+ out.set(repo, now - own.at > QUIET_DAYS * 86_400_000 ? own.at : null)
60
+ }
61
+ return out
62
+ }
10
63
 
11
64
  /** a need's file dated: an ask by its birth (its front matter keeps only the day), any other file by its last write */
12
65
  export const datedIn = (root: string): Dated => (n: Resource) => {
@@ -25,14 +78,17 @@ export async function inboxSources(hubs: Pick<Hubs, 'loaded'>): Promise<{ source
25
78
  const read = await Promise.all(
26
79
  hubs.loaded().map(async ({ repo, rt }) => {
27
80
  try {
28
- return { repo: repo.name, root: repo.path, review: storeIndex(repo.path), needs: await rt.handler.needs() }
81
+ const [needs, log] = await Promise.all([rt.handler.needs(), recentCommits(repo.path)])
82
+ return { repo: repo.name, root: repo.path, review: storeIndex(repo.path), needs, log }
29
83
  } catch (e) {
30
84
  missing.push({ repo: repo.name, why: `its items could not be read: ${(e as Error).message}` })
31
85
  return null
32
86
  }
33
87
  }),
34
88
  )
35
- return { sources: read.filter((s) => s != null), missing }
89
+ const ok = read.filter((s) => s != null)
90
+ const quiet = quietOf(new Map(ok.map((s) => [s.repo, s.log])))
91
+ return { sources: ok.map(({ log: _, ...s }) => ({ ...s, quietSince: quiet.get(s.repo) ?? null })), missing }
36
92
  }
37
93
 
38
94
  /** one page of the inbox, 304 when the page holds this answer already; gzipped when the browser takes it */
@@ -25,7 +25,7 @@ import { machineCatchUp } from '../plan/catch-up.ts'
25
25
  import { serveDaemon } from './serve-daemon.ts'
26
26
  import { startSweeps } from './machine-stores.ts'
27
27
  import { startMediaStore } from '../media-store/daemon.ts'
28
- import { MEDIA_KINDS } from '../media-kinds.ts'
28
+ import { mediaKinds } from '../media-kinds.ts'
29
29
  import { landMotherhome } from '../core/motherhome.ts'
30
30
  import { Widgets } from './widgets.ts'
31
31
 
@@ -123,7 +123,7 @@ export async function runDaemon(root: string, io: HomeIo, o: { port?: number } =
123
123
  also: (now) => { for (const n of landMotherhome({ now })) io.printErr(n) },
124
124
  })
125
125
  // every kind's media into the machine index, up to the Space, purged when the owner turned it on
126
- const media = startMediaStore({ roots: () => house.repos.filter((r) => only == null || only.has(r.name)).map((r) => r.path), kinds: MEDIA_KINDS, print: io.print, printErr: io.printErr })
126
+ const media = startMediaStore({ roots: () => house.repos.filter((r) => only == null || only.has(r.name)).map((r) => r.path), kinds: mediaKinds, print: io.print, printErr: io.printErr })
127
127
  const code = reloadOnOwnCode({ role: 'daemon', entry: fileURLToPath(import.meta.url), busy: () => hubs.busy(), before: () => { sweeps.stop(); media.stop(); home.stop() }, keep: true, io })
128
128
  io.print(` ${house.repos.length} repos, state in ${dir}, reloads on ${code.files} lib files`)
129
129
  for (const sig of ['SIGINT', 'SIGTERM'] as const)
@@ -212,6 +212,12 @@ export function serveWeb<T extends Bun.HTMLBundle | Response>(d: WebDeps<T>) {
212
212
  return new HTMLRewriter().on('head', { element: (e) => { e.append(APP_HEAD, { html: true }) } }).transform(page)
213
213
  }
214
214
  const etag = out.get('etag')
215
+ // the page server answers 200 to a tag the browser holds: the bundle (3 MB) is then a 304 here
216
+ if (r.status === 200 && etag != null && req.headers.get('if-none-match') === etag) {
217
+ await r.body?.cancel()
218
+ return new Response(null, { status: 304, headers: { etag, 'cache-control': 'no-cache' } })
219
+ }
220
+ if (etag != null) out.set('cache-control', 'no-cache')
215
221
  if (r.status !== 200 || etag == null || !ZIPS.test(type) || !/\bgzip\b/.test(req.headers.get('accept-encoding') ?? '')) return new Response(r.body, { status: r.status, headers: out })
216
222
  const key = `${url.pathname}${url.search}|${etag}`
217
223
  let zipped = zips.get(key)
@@ -1,7 +1,14 @@
1
1
  // every kind the machine's media store holds (wiki build/shipkit/media-store.md, A kind): the daemon and `sk media` read
2
2
  // this list. A new caller writes its kind beside its own code and adds its line here
3
3
  import type { MediaKind } from './media-store/kind.ts'
4
+ import { handKind, labelsInIndex } from './media-store/hand.ts'
4
5
  import { reviewMedia } from './review/media-kind.ts'
5
6
  import { trailerMedia } from './review/trailer-media.ts'
6
7
 
7
8
  export const MEDIA_KINDS: readonly MediaKind[] = [reviewMedia, trailerMedia]
9
+
10
+ /** the kinds of the code, then the generic kind of every other label the index holds (`sk media put`) */
11
+ export function mediaKinds(): MediaKind[] {
12
+ const code = new Set(MEDIA_KINDS.map((k) => k.kind))
13
+ return [...MEDIA_KINDS, ...labelsInIndex().filter((l) => !code.has(l)).map(handKind)]
14
+ }
@@ -17,6 +17,16 @@ const TYPES: Record<string, string> = {
17
17
  '.ogg': 'audio/ogg',
18
18
  '.opus': 'audio/opus',
19
19
  '.m4a': 'audio/mp4',
20
+ '.gif': 'image/gif',
21
+ '.pdf': 'application/pdf',
22
+ '.zip': 'application/zip',
23
+ '.gz': 'application/gzip',
24
+ '.tar': 'application/x-tar',
25
+ '.dmg': 'application/x-apple-diskimage',
26
+ '.json': 'application/json',
27
+ '.txt': 'text/plain; charset=utf-8',
28
+ '.md': 'text/markdown; charset=utf-8',
29
+ '.csv': 'text/csv; charset=utf-8',
20
30
  }
21
31
 
22
32
  export const typeOf = (name: string): string => TYPES[extname(name).toLowerCase()] ?? 'application/octet-stream'
@@ -48,4 +58,4 @@ export async function factsOf(folder: string, names: readonly string[], keep: Re
48
58
  export const mediaKey = (kind: string, f: Pick<MediaFact, 'sha'>, name: string): string => `${kind}/${f.sha}${extname(name).toLowerCase()}`
49
59
 
50
60
  /** the sha a key names, null when it is no content key */
51
- export const shaOfKey = (key: string): string | null => /^[a-z][a-z0-9-]*\/([0-9a-f]{64})\./.exec(key)?.[1] ?? null
61
+ export const shaOfKey = (key: string): string | null => /^[a-z0-9-]+\/([0-9a-f]{64})(?:\.|$)/.exec(key)?.[1] ?? null
@@ -23,14 +23,14 @@ export interface MediaLoop {
23
23
  once(): Promise<void>
24
24
  }
25
25
 
26
- export function startMediaStore(o: { roots: () => string[]; kinds: readonly MediaKind[]; print: (l: string) => void; printErr: (l: string) => void; tickMs?: number }): MediaLoop {
26
+ export function startMediaStore(o: { roots: () => string[]; kinds: () => readonly MediaKind[]; print: (l: string) => void; printErr: (l: string) => void; tickMs?: number }): MediaLoop {
27
27
  const synced = new Map<string, string>()
28
28
  let busy = false
29
29
  let lastPurge = 0
30
30
  let toldNoSpace = false
31
31
  const stores = (): { kind: MediaKind; root: string; dir: string }[] =>
32
32
  o.roots().flatMap((root) =>
33
- o.kinds.flatMap((kind) => {
33
+ o.kinds().flatMap((kind) => {
34
34
  const dir = kind.storeOf(root)
35
35
  return dir && existsSync(dir) ? [{ kind, root, dir }] : []
36
36
  }),
@@ -0,0 +1,58 @@
1
+ // the generic kind (wiki build/shipkit/media-store.md, Put a file from any repo): a label no `MediaKind` of the code
2
+ // owns, its files named by hand through `sk media put`. The index is its only record, so its scan reads the index's
3
+ // own rows back and asks the disk whether each file still holds the bytes of its key; nothing else names them
4
+ import { statSync } from 'node:fs'
5
+ import { join, resolve } from 'node:path'
6
+ import { shaOf, shaOfKey, typeOf } from './content.ts'
7
+ import { mediaDb } from './db.ts'
8
+ import type { MediaKind, MediaRow } from './kind.ts'
9
+
10
+ /** a label `sk media put` takes: the key prefix in the Space */
11
+ export const LABEL = /^[a-z0-9-]+$/
12
+ export const DEFAULT_LABEL = 'files'
13
+
14
+ /** the stores the index holds rows of under this label */
15
+ function storesOf(label: string): string[] {
16
+ const db = mediaDb()
17
+ if (!db) return []
18
+ const p = `${label}/`
19
+ return (db.query('select distinct store from files where substr(key, 1, ?) = ?').all(p.length, p) as { store: string }[]).map((r) => r.store)
20
+ }
21
+
22
+ /** every label the index holds rows of */
23
+ export function labelsInIndex(): string[] {
24
+ const db = mediaDb()
25
+ if (!db) return []
26
+ return (db.query(`select distinct substr(key, 1, instr(key, '/') - 1) as label from files`).all() as { label: string }[]).map((r) => r.label).filter((l) => LABEL.test(l))
27
+ }
28
+
29
+ const rowsOf = (label: string, store: string): { item: string; name: string; key: string; size: number }[] => {
30
+ const p = `${label}/`
31
+ return (mediaDb()?.query('select item, name, key, size from files where store = ? and substr(key, 1, ?) = ?').all(store, p.length, p) ?? []) as { item: string; name: string; key: string; size: number }[]
32
+ }
33
+
34
+ export function handKind(label: string): MediaKind {
35
+ return {
36
+ kind: label,
37
+ storeOf: (root) => (storesOf(label).includes(resolve(root)) ? resolve(root) : null),
38
+ // the index is the record: read it again every 10 min, to see a file the disk let go
39
+ stamp: () => String(Math.floor(Date.now() / 600_000)),
40
+ async scan(store) {
41
+ const rows: MediaRow[] = []
42
+ for (const r of rowsOf(label, store)) {
43
+ const sha = shaOfKey(r.key)
44
+ if (!sha) continue
45
+ const size = statSync(join(store, r.item, r.name), { throwIfNoEntry: false })?.size
46
+ rows.push({ item: r.item, name: r.name, fact: { sha, size: r.size, type: typeOf(r.name) }, local: size === r.size })
47
+ }
48
+ return { rows, filled: 0, left: 0 }
49
+ },
50
+ async holds(store) {
51
+ return (row) => ({ pinned: false, used: statSync(join(store, row.item, row.name), { throwIfNoEntry: false })?.mtimeMs })
52
+ },
53
+ async beforePurge(store, _space, row) {
54
+ const sha = await shaOf(join(store, row.item, row.name))
55
+ if (sha !== shaOfKey(row.key)) throw new Error(`${join(row.item, row.name)} changed since it was put: its bytes hash to ${sha.slice(0, 12)}, the key says ${row.key}`)
56
+ },
57
+ }
58
+ }
@@ -0,0 +1,120 @@
1
+ // a file put in the store by hand, and a fresh link to anything it holds (wiki build/shipkit/media-store.md, Put a file
2
+ // from any repo): the one way a repo's agent keeps a file in the private Space. The index row is written before the
3
+ // upload, so a failed upload waits for the daemon like any other; a link lasts at most 7 days, the object for good
4
+ import { realpathSync, statSync } from 'node:fs'
5
+ import { basename, dirname, join, relative } from 'node:path'
6
+ import { findRepoRoot } from '../ts/config.ts'
7
+ import { factOf, mediaKey, shaOf, shaOfKey, typeOf } from './content.ts'
8
+ import { mediaDb } from './db.ts'
9
+ import { DEFAULT_LABEL, LABEL } from './hand.ts'
10
+ import { confirmedUp } from './remote.ts'
11
+ import { machineSpace, SIGNED_MAX_S } from './space.ts'
12
+ import { uploadOne } from './upload.ts'
13
+
14
+ /** a duration as seconds: `90s`, `30m`, `2h`, `7d`, or a bare number of seconds; never over 7 days */
15
+ export function durationS(text: string): number {
16
+ const m = /^(\d+(?:\.\d+)?)([smhd]?)$/.exec(text.trim())
17
+ if (!m) throw new Error(`${text}: a duration is a number and a unit, like 30m, 2h or 7d`)
18
+ const s = Math.round(Number(m[1]) * { '': 1, s: 1, m: 60, h: 3600, d: 86_400 }[m[2] as '' | 's' | 'm' | 'h' | 'd'])
19
+ if (s < 1) throw new Error(`${text}: a link lasts at least 1 s`)
20
+ if (s > SIGNED_MAX_S) throw new Error(`${text}: a signed link lasts at most 7d (the SigV4 limit); the object never expires, sk media link makes a new one`)
21
+ return s
22
+ }
23
+
24
+ export interface Put {
25
+ key: string
26
+ sha: string
27
+ size: number
28
+ /** the file's own name, the one a link downloads under */
29
+ name: string
30
+ /** false: the Space already held this content */
31
+ sent: boolean
32
+ }
33
+
34
+ export interface Link {
35
+ key: string
36
+ sha: string
37
+ size: number
38
+ name: string
39
+ url: string
40
+ /** ISO time */
41
+ expires: string
42
+ }
43
+
44
+ /** the labels a kind of the code owns: their rows come from their own scan, never a hand put */
45
+ async function codeLabels(): Promise<Set<string>> {
46
+ const { MEDIA_KINDS } = await import('../media-kinds.ts')
47
+ return new Set(MEDIA_KINDS.map((k) => k.kind))
48
+ }
49
+
50
+ /** where the index keeps a file: its repo (else its folder) as the store, the folder in it, its name */
51
+ function placeOf(file: string): { store: string; item: string; name: string } {
52
+ const real = realpathSync(file)
53
+ const store = findRepoRoot(dirname(real))
54
+ return { store, item: relative(store, dirname(real)), name: basename(real) }
55
+ }
56
+
57
+ /** the file kept by its content under the label: its index row first, then up at once, checked by a HEAD */
58
+ export async function putMedia(file: string, o: { kind?: string } = {}): Promise<Put> {
59
+ const label = o.kind ?? DEFAULT_LABEL
60
+ if (!LABEL.test(label)) throw new Error(`--kind ${label}: a label is lowercase letters, digits and dashes`)
61
+ if ((await codeLabels()).has(label)) throw new Error(`--kind ${label}: that kind's files come from its own scan, never a hand put; pick another label`)
62
+ const st = statSync(file, { throwIfNoEntry: false })
63
+ if (!st?.isFile()) throw new Error(`${file}: no such file`)
64
+ const at = placeOf(file)
65
+ const path = join(at.store, at.item, at.name)
66
+ const fact = await factOf(path)
67
+ const key = mediaKey(label, fact, at.name)
68
+ const db = mediaDb()
69
+ if (!db) throw new Error('the media index does not open: nothing is put without its record')
70
+ db.transaction(() => {
71
+ db.query('insert or replace into files (store, item, name, key, size, local, purged) values (?, ?, ?, ?, ?, 1, null)').run(at.store, at.item, at.name, key, fact.size)
72
+ db.query('insert or ignore into objects (key, size) values (?, ?)').run(key, fact.size)
73
+ })()
74
+ const { space, why } = await machineSpace()
75
+ if (!space) throw new Error(`${key} recorded, not up: ${why}; the daemon sends it once the Space answers`)
76
+ const sent = await uploadOne(space, { key, size: fact.size, path })
77
+ return { key, sha: fact.sha, size: fact.size, name: at.name, sent }
78
+ }
79
+
80
+ /** the key a reference names: a key, a sha (or 12 hex of one), or a file the store holds */
81
+ async function keyOf(ref: string): Promise<{ key: string; size: number; name: string | null }> {
82
+ const db = mediaDb()
83
+ if (!db) throw new Error('the media index does not open')
84
+ const sizeOf = (key: string): number | null => (db.query('select size from objects where key = ?').get(key) as { size: number } | null)?.size ?? null
85
+ const nameOf = (key: string): string | null => (db.query('select name from files where key = ? order by name limit 1').get(key) as { name: string } | null)?.name ?? null
86
+ if (shaOfKey(ref)) {
87
+ const size = sizeOf(ref)
88
+ if (size === null) throw new Error(`${ref}: the index holds no such key`)
89
+ return { key: ref, size, name: nameOf(ref) }
90
+ }
91
+ const asFile = statSync(ref, { throwIfNoEntry: false })?.isFile()
92
+ if (!asFile && /^[0-9a-f]{12,64}$/.test(ref)) {
93
+ const keys = (db.query(`select key, size from objects where substr(key, instr(key, '/') + 1, ?) = ?`).all(ref.length, ref) as { key: string; size: number }[]).filter((r) => shaOfKey(r.key)?.startsWith(ref))
94
+ if (keys.length === 0) throw new Error(`${ref}: no object of the index has that sha`)
95
+ if (keys.length > 1) throw new Error(`${ref}: ${keys.length} objects match (${keys.map((k) => k.key).join(', ')}); name the key`)
96
+ const k = keys[0]!
97
+ return { key: k.key, size: k.size, name: nameOf(k.key) }
98
+ }
99
+ if (!asFile) throw new Error(`${ref}: neither a key, a sha, nor a file`)
100
+ const at = placeOf(ref)
101
+ const row = db.query('select key, size from files where store = ? and item = ? and name = ?').get(at.store, at.item, at.name) as { key: string; size: number } | null
102
+ const sha = await shaOf(join(at.store, at.item, at.name))
103
+ if (row && shaOfKey(row.key) === sha) return { key: row.key, size: row.size, name: at.name }
104
+ const same = db.query(`select key, size from objects where instr(key, ?) > 0`).all(`/${sha}`) as { key: string; size: number }[]
105
+ if (same.length === 0) throw new Error(`${ref}: not in the store; sk media put ${ref} first`)
106
+ if (same.length > 1) throw new Error(`${ref}: its content is kept under ${same.map((k) => k.key).join(', ')}; name the key`)
107
+ return { key: same[0]!.key, size: same[0]!.size, name: at.name }
108
+ }
109
+
110
+ /** a fresh signed link to what the Space holds, downloading under the index's name (or `name`) */
111
+ export async function linkMedia(ref: string, o: { seconds: number; name?: string; now?: number }): Promise<Link> {
112
+ if (o.seconds > SIGNED_MAX_S) throw new Error(`a signed link lasts at most 7d (the SigV4 limit); the object never expires, sk media link makes a new one`)
113
+ const k = await keyOf(ref)
114
+ const { space, why } = await machineSpace()
115
+ if (!space) throw new Error(why)
116
+ if (!(await confirmedUp(k.key, k.size))) throw new Error(`${k.key}: not in the Space yet (sk media upload sends what waits)`)
117
+ const name = o.name ?? k.name ?? basename(k.key)
118
+ const url = space.signed(k.key, o.seconds, { name, type: typeOf(name) })
119
+ return { key: k.key, sha: shaOfKey(k.key) ?? '', size: k.size, name, url, expires: new Date((o.now ?? Date.now()) + o.seconds * 1000).toISOString() }
120
+ }
@@ -40,11 +40,15 @@ export interface Space {
40
40
  /** the object's size, null when it is not there; throws on any other answer */
41
41
  head(key: string): Promise<{ size: number } | null>
42
42
  /** a GET URL good for `seconds`, on the CDN edge when the Space has one: signed for the origin host, which the edge
43
- * checks it against (a URL signed for the edge's own host answers SignatureDoesNotMatch) */
44
- signed(key: string, seconds?: number): string
43
+ * checks it against (a URL signed for the edge's own host answers SignatureDoesNotMatch). `as` signs a download
44
+ * under that file name: `response-content-disposition` and `response-content-type` ride in the signed query */
45
+ signed(key: string, seconds?: number, as?: { name: string; type: string }): string
45
46
  /** the object written at `to`, through a file beside it renamed: no reader sees half of it */
46
47
  get(key: string, to: string): Promise<void>
47
- delete(key: string): Promise<void>
48
+ /** the bucket's versioning: `Enabled`, `Suspended`, or `off` when it was never turned on (GetBucketVersioning) */
49
+ versioning(): Promise<'Enabled' | 'Suspended' | 'off'>
50
+ /** turns versioning on, so an object deleted or overwritten from outside keeps its older version (PutBucketVersioning) */
51
+ enableVersioning(): Promise<void>
48
52
  }
49
53
 
50
54
  const missing = (e: unknown): boolean => {
@@ -52,6 +56,41 @@ const missing = (e: unknown): boolean => {
52
56
  return x.code === 'NoSuchKey' || x.code === 'NotFound' || /\b404\b|NoSuchKey|not found/i.test(`${x.name ?? ''} ${x.message ?? ''}`)
53
57
  }
54
58
 
59
+ /** the longest a signed URL can last: the SigV4 limit */
60
+ export const SIGNED_MAX_S = 7 * 86_400
61
+
62
+ /** `attachment` under the name: a plain ascii fallback, the exact name in `filename*` when it is not ascii */
63
+ export function attachment(name: string): string {
64
+ const plain = name.replace(/[^\x20-\x7e]|["\\]/g, '_')
65
+ return plain === name ? `attachment; filename="${name}"` : `attachment; filename="${plain}"; filename*=UTF-8''${encodeURIComponent(name)}`
66
+ }
67
+
68
+ const hex = (b: ArrayBuffer | Uint8Array): string => Buffer.from(b instanceof Uint8Array ? b : new Uint8Array(b)).toString('hex')
69
+ const sha256 = (s: string): string => new Bun.CryptoHasher('sha256').update(s).digest('hex')
70
+ const hmac = (key: string | Uint8Array, s: string): Uint8Array => new Uint8Array(new Bun.CryptoHasher('sha256', key).update(s).digest())
71
+
72
+ /** one bucket call Bun's S3 client has no verb for, signed by hand (SigV4, header auth): `?<sub>` on the bucket */
73
+ async function bucketCall(c: SpaceConfig, method: 'GET' | 'PUT', sub: string, body = ''): Promise<string> {
74
+ const url = new URL(c.path === true ? `${c.endpoint}/${c.bucket}` : `${c.endpoint}/`)
75
+ url.search = sub
76
+ const now = new Date().toISOString().replace(/[-:]|\.\d{3}/g, '')
77
+ const day = now.slice(0, 8)
78
+ const payload = sha256(body)
79
+ const headers: Record<string, string> = { host: url.host, 'x-amz-content-sha256': payload, 'x-amz-date': now }
80
+ const names = Object.keys(headers).sort()
81
+ const canonical = [method, url.pathname, `${sub}=`, ...names.map((n) => `${n}:${headers[n]}`), '', names.join(';'), payload].join('\n')
82
+ const scope = `${day}/${c.region}/s3/aws4_request`
83
+ const toSign = ['AWS4-HMAC-SHA256', now, scope, sha256(canonical)].join('\n')
84
+ const k = hmac(hmac(hmac(hmac(`AWS4${c.creds.secretAccessKey}`, day), c.region), 's3'), 'aws4_request')
85
+ const auth = `AWS4-HMAC-SHA256 Credential=${c.creds.accessKeyId}/${scope}, SignedHeaders=${names.join(';')}, Signature=${hex(hmac(k, toSign))}`
86
+ const { host: _, ...sent } = headers
87
+ const md5: Record<string, string> = body !== '' ? { 'Content-MD5': new Bun.CryptoHasher('md5').update(body).digest('base64') } : {}
88
+ const r = await fetch(url, { method, headers: { ...sent, ...md5, Authorization: auth }, ...(body !== '' ? { body } : {}) })
89
+ const text = await r.text()
90
+ if (!r.ok) throw new Error(`${method} ?${sub} on ${c.bucket}: ${r.status} ${/<Code>([^<]+)<\/Code>/.exec(text)?.[1] ?? text.slice(0, 200)}`)
91
+ return text
92
+ }
93
+
55
94
  export function spaceOf(c: SpaceConfig): Space {
56
95
  const client = new S3Client({ ...c.creds, bucket: c.bucket, region: c.region, endpoint: c.endpoint, virtualHostedStyle: c.path !== true })
57
96
  const origin = new URL(c.endpoint).host
@@ -70,8 +109,8 @@ export function spaceOf(c: SpaceConfig): Space {
70
109
  throw e
71
110
  }
72
111
  },
73
- signed(key, seconds = SIGNED_S) {
74
- const url = new URL(client.presign(key, { expiresIn: seconds, method: 'GET' }))
112
+ signed(key, seconds = SIGNED_S, as) {
113
+ const url = new URL(client.presign(key, { expiresIn: seconds, method: 'GET', ...(as ? { contentDisposition: attachment(as.name), type: as.type } : {}) }))
75
114
  if (edge && url.host === origin) url.host = edge
76
115
  return url.toString()
77
116
  },
@@ -85,8 +124,12 @@ export function spaceOf(c: SpaceConfig): Space {
85
124
  rmSync(tmp, { force: true })
86
125
  }
87
126
  },
88
- async delete(key) {
89
- await client.delete(key)
127
+ async versioning() {
128
+ const s = /<Status>([^<]+)<\/Status>/.exec(await bucketCall(c, 'GET', 'versioning'))?.[1]
129
+ return s === 'Enabled' || s === 'Suspended' ? s : 'off'
130
+ },
131
+ async enableVersioning() {
132
+ await bucketCall(c, 'PUT', 'versioning', '<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Status>Enabled</Status></VersioningConfiguration>')
90
133
  },
91
134
  }
92
135
  }
@@ -8,7 +8,7 @@ import { isUp, recordUp } from '../media-store/remote.ts'
8
8
  import type { Space } from '../media-store/space.ts'
9
9
  import { threadIndex } from './cells.ts'
10
10
  import { previewKey, REVIEW_KIND } from './media-read.ts'
11
- import { viewFilesOf } from './model.ts'
11
+ import { mediaFilesOf } from './model.ts'
12
12
  import { previewFile, PREVIEW_W, type PreviewSize } from './previews.ts'
13
13
  import { fillMedia, readAll, readAllCached, storeDir, storeStamp } from './store.ts'
14
14
  import { membersOf } from './threads.ts'
@@ -27,7 +27,7 @@ export const reviewMedia: MediaKind = {
27
27
  for (const x of readAllCached(dir).items) {
28
28
  const id = x.item.id
29
29
  let item = x.item
30
- const names = viewFilesOf(item)
30
+ const names = mediaFilesOf({ item, thread: x.thread })
31
31
  if (names.length === 0) continue
32
32
  const size = (n: string): number | undefined => statSync(join(dir, id, n), { throwIfNoEntry: false })?.size
33
33
  const lacks = names.some((n) => {
@@ -63,7 +63,7 @@ export const reviewMedia: MediaKind = {
63
63
  return (r) => ({ pinned: pinned.has(r.item), used: used.get(r.item) })
64
64
  },
65
65
  async beforePurge(dir, space, r) {
66
- if (IMAGE.test(r.name)) await previewsUp(dir, space, r)
66
+ if (IMAGE.test(r.name) && !r.name.startsWith('thread/')) await previewsUp(dir, space, r)
67
67
  },
68
68
  }
69
69
 
@@ -5,7 +5,7 @@ import { join } from 'node:path'
5
5
  import { mediaKey } from '../media-store/content.ts'
6
6
  import type { MediaFact } from '../media-store/fact.ts'
7
7
  import { fetchBack, signedIfUp, signedUrl } from '../media-store/remote.ts'
8
- import { FILE_RE, ID_RE } from './model.ts'
8
+ import { ID_RE, isMediaName } from './model.ts'
9
9
 
10
10
  export const REVIEW_KIND = 'review'
11
11
 
@@ -16,7 +16,7 @@ export const previewKey = (f: Pick<MediaFact, 'sha'>, size: string): string => `
16
16
 
17
17
  /** the fact a head keeps for one of its files, read from its item.json alone */
18
18
  export function factOfFile(dir: string, id: string, name: string): MediaFact | null {
19
- if (!ID_RE.test(id) || !FILE_RE.test(name)) return null
19
+ if (!ID_RE.test(id) || !isMediaName(name)) return null
20
20
  try {
21
21
  const head = JSON.parse(readFileSync(join(dir, id, 'item.json'), 'utf8')) as { media?: Record<string, MediaFact> }
22
22
  return head.media?.[name] ?? null
@@ -40,7 +40,7 @@ export async function remotePreviewUrl(dir: string, id: string, name: string, si
40
40
  /** the path of an item's file on the disk, fetched back from the Space first when the disk let it go; null when neither
41
41
  * holds it */
42
42
  export async function ensureLocal(dir: string, id: string, name: string): Promise<string | null> {
43
- if (!ID_RE.test(id) || !FILE_RE.test(name)) return null
43
+ if (!ID_RE.test(id) || !isMediaName(name)) return null
44
44
  const path = join(dir, id, name)
45
45
  if (existsSync(path)) return path
46
46
  const f = factOfFile(dir, id, name)
@@ -650,6 +650,14 @@ export function untakenOf(x: ReviewItem, superseded: boolean, watchers: readonly
650
650
 
651
651
  export const ID_RE = /^\d{8}-\d{6}-[a-z0-9-]+$/
652
652
  export const FILE_RE = /^((v\d+-)?((image|before|after|poster|wave|before-wave)\.(png|jpe?g|webp)|(video|before|after)\.(webm|mp4)|(audio|before|after)\.(wav|mp3|flac|ogg|opus|m4a))|v\d+-g\d+\.(png|jpe?g|webp))$/
653
+ /** a message's image as an item's media names it: `thread/<file>` */
654
+ export const isThreadMedia = (n: string): boolean => n.startsWith('thread/') && MESSAGE_FILE_RE.test(n.slice('thread/'.length))
655
+ /** a name an item's media may hold: a view's file or a message's image */
656
+ export const isMediaName = (n: string): boolean => FILE_RE.test(n) || isThreadMedia(n)
657
+ /** every file of an item the media store keeps: its views' files, then its messages' images */
658
+ export const mediaFilesOf = (x: { item: Item; thread: readonly Message[] }): string[] => [...viewFilesOf(x.item), ...x.thread.flatMap((m) => (m.image ? [`thread/${m.image}`] : []))]
659
+ /** the message images an item's media already holds: a rewrite of its views keeps their facts */
660
+ export const threadMediaOf = (i: Item): string[] => Object.keys(i.media ?? {}).filter(isThreadMedia)
653
661
  const TILE_RE = /^v\d+-g\d+\.(png|jpe?g|webp)$/
654
662
  const POSTER_RE = /^(v\d+-)?poster\.png$/
655
663
 
@@ -757,7 +765,7 @@ export function itemProblems(v: unknown): string[] {
757
765
  if (!obj(v.media)) out.push('media: { <file name>: { sha, size, type } }, or absent')
758
766
  else
759
767
  for (const [n, f] of Object.entries(v.media))
760
- if (!FILE_RE.test(n) || !obj(f) || typeof f.sha !== 'string' || !SHA_RE.test(f.sha) || !Number.isInteger(f.size) || (f.size as number) < 0 || typeof f.type !== 'string')
768
+ if (!isMediaName(n) || !obj(f) || typeof f.sha !== 'string' || !SHA_RE.test(f.sha) || !Number.isInteger(f.size) || (f.size as number) < 0 || typeof f.type !== 'string')
761
769
  out.push(`media.${n}: a file of the item, { sha: sha256 hex, size: bytes, type }`)
762
770
  }
763
771
  return out
@@ -209,7 +209,10 @@ async function reviewRoute(req: Request, path: string, dir: string, unit: Review
209
209
  const t = /^\/api\/review\/([^/]+)\/thread\/([^/]+)$/.exec(path)
210
210
  if (t && req.method === 'GET') {
211
211
  const f = threadImage(dir, t[1] ?? '', t[2] ?? '')
212
- return f ? new Response(Bun.file(f), { headers: { 'Content-Type': TYPES[extname(f)] ?? 'application/octet-stream', ...KEEP } }) : bad('no such image', 404)
212
+ if (f) return new Response(Bun.file(f), { headers: { 'Content-Type': TYPES[extname(f)] ?? 'application/octet-stream', ...KEEP } })
213
+ // a message's image the disk let go: the Space's copy
214
+ const url = await remoteUrl(dir, t[1] ?? '', `thread/${t[2] ?? ''}`)
215
+ return url ? toSpace(url) : bad('no such image', 404)
213
216
  }
214
217
  // a view's image at the size the page draws it; `thumb/<name>` is the preview's thumb size
215
218
  const pv = /^\/api\/review\/([^/]+)\/(?:preview\/([^/]+)|thumb)\/([^/]+)$/.exec(path)
@@ -50,6 +50,8 @@ import {
50
50
  type Spec,
51
51
  type Subject,
52
52
  viewFilesOf,
53
+ mediaFilesOf,
54
+ threadMediaOf,
53
55
  } from './model.ts'
54
56
  import { beatRole, roleOf } from './role.ts'
55
57
  import { chainOf, coveringHead, followedIds, isFollowed } from './threads.ts'
@@ -432,7 +434,7 @@ export async function fillMedia(dir: string, id: string): Promise<Item | null> {
432
434
  if (!x) return null
433
435
  const folder = join(dir, id)
434
436
  const held = x.item.media ?? {}
435
- const names = viewFilesOf(x.item)
437
+ const names = mediaFilesOf(x)
436
438
  const size = (n: string): number | undefined => statSync(join(folder, n), { throwIfNoEntry: false })?.size
437
439
  const stale = new Set(names.filter((n) => held[n] && size(n) !== undefined && size(n) !== held[n]?.size))
438
440
  const lacks = names.filter((n) => !held[n] && existsSync(join(folder, n)))
@@ -936,7 +938,7 @@ export async function refreshDraft(dir: string, id: string, o: { image: string;
936
938
  }
937
939
  const next: Item = { ...r, views, wip: { live: r.wip.live, frame: r.wip.frame + 1 } }
938
940
  const fresh = new Set([image, ...views.flatMap((v) => ('gallery' in v ? v.gallery.map((g) => g.file) : []))])
939
- const media = await factsOf(folder, viewFilesOf(next), r.media, fresh)
941
+ const media = await factsOf(folder, [...viewFilesOf(next), ...threadMediaOf(r)], r.media, fresh)
940
942
  return updateHead(dir, id, () => ({ ...next, media }))
941
943
  }
942
944
 
@@ -961,7 +963,7 @@ export async function readyItem(dir: string, id: string, o: { image?: string; no
961
963
  const now = 'image' in files ? files.image : undefined
962
964
  if (old && old !== now) rmSync(join(folder, old), { force: true })
963
965
  item = { ...rest, views: [{ ...f0, files, size: loaded.size }, ...rest.views.slice(1)] }
964
- item = { ...item, media: await factsOf(folder, viewFilesOf(item), rest.media, new Set(Object.values(files))) }
966
+ item = { ...item, media: await factsOf(folder, [...viewFilesOf(item), ...threadMediaOf(rest)], rest.media, new Set(Object.values(files))) }
965
967
  }
966
968
  updateHead(dir, id, () => item)
967
969
  appendMessage(dir, id, { who: agentName(), op: 'ready' }, o.now ? { now: o.now } : {})
@@ -1,5 +1,6 @@
1
1
  // the trailer renders as a kind of the media store (wiki build/trailer.md, Renders in the media store): each settled
2
- // render's clone in the view folder and a kept version's own files, by the facts its view record keeps. Kept on the
2
+ // render's clone in the view folder and a kept version's own files, by the facts its view record keeps, and the shots
3
+ // folders (trailer-shots.ts). Kept on the
3
4
  // disk: the newest render of each live cut, the render an open frame note was written on, and any render seen in the
4
5
  // window. A file goes only when its own bytes hash to the key. The takes and footage cache is never this kind's
5
6
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
@@ -12,6 +13,7 @@ import { isFrame } from './model.ts'
12
13
  import { readAllCached, storeDir } from './store.ts'
13
14
  import { cutOf, cutsOf, pngSize, stripOf, TRAILER_KIND, trailerDir, trailerIds, trailerKey, trailerStamp, videoOf, VIEW_ITEM, viewDir, viewOf, writeView, type View } from './trailer-desk.ts'
14
15
  import { noteOf } from './trailer-model.ts'
16
+ import { newestShelves, shotFolders, shotRows } from './trailer-shots.ts'
15
17
 
16
18
  /** a view record's name, `<trailer>--<cut>--<mtime>` */
17
19
  const BASE_RE = /^(.+?)--(.+)--(\d+)$/
@@ -51,7 +53,7 @@ async function sameAs(root: string, file: string, f: MediaFact): Promise<string
51
53
  export const trailerMedia: MediaKind = {
52
54
  kind: TRAILER_KIND,
53
55
  storeOf: (root) => (existsSync(join(root, 'trailer')) ? root : null),
54
- stamp: (root) => `${trailerStamp(root)}#${existsSync(viewDir(root)) ? readdirSync(viewDir(root)).length : 0}`,
56
+ stamp: (root) => `${trailerStamp(root)}#${existsSync(viewDir(root)) ? readdirSync(viewDir(root)).length : 0}#shots:${shotFolders(root).map((f) => `${f.item}@${f.born}`).join(',')}`,
55
57
  async scan(root, o) {
56
58
  // every settled render gets its record, whether or not the page was opened since
57
59
  for (const id of trailerIds(root)) {
@@ -112,6 +114,7 @@ export const trailerMedia: MediaKind = {
112
114
  if (media.from?.video) row(join(root, media.from.video), media.video)
113
115
  if (media.from?.strip) row(join(root, media.from.strip), media.strip)
114
116
  }
117
+ for (const f of shotFolders(root)) rows.push(...(await shotRows(root, f, take)))
115
118
  return { rows, filled, left }
116
119
  },
117
120
  async holds(root) {
@@ -136,7 +139,22 @@ export const trailerMedia: MediaKind = {
136
139
  const at = Math.max(Date.parse(x.item.created) || 0, ...x.thread.map((m) => Date.parse(m.at) || 0))
137
140
  used.set(base, Math.max(used.get(base) ?? 0, at))
138
141
  }
142
+ // a shots folder: the shelf of each trailer's newest build stays, any other goes once quiet, unless a note is open on its cut
143
+ const folders = new Map(shotFolders(root).map((f) => [f.item, f]))
144
+ const shelves = newestShelves([...folders.values()])
145
+ const cutUse = (id: string, cut: string): { open: boolean; at: number } => {
146
+ let at = 0
147
+ let isOpen = false
148
+ for (const [base, t] of used) if (base.startsWith(`${id}--${cut}--`)) at = Math.max(at, t)
149
+ for (const base of open) if (base.startsWith(`${id}--${cut}--`)) isOpen = true
150
+ return { open: isOpen, at }
151
+ }
139
152
  return (row) => {
153
+ const f = folders.get(row.item)
154
+ if (f) {
155
+ const u = cutUse(f.trailer, f.cut)
156
+ return { pinned: shelves.has(f.item) || u.open, used: Math.max(f.born, u.at) }
157
+ }
140
158
  const r = owner.get(`${row.item}/${row.name}`)
141
159
  if (!r) return { pinned: false, used: undefined }
142
160
  const pinned = newest.get(`${r.id}--${r.cut}`) === r.v.mtime || open.has(r.base)
@@ -0,0 +1,89 @@
1
+ // the shots folders of the trailer kind (wiki build/trailer.md, Renders in the media store): each build's shelf
2
+ // `out/<cut>-shots/` and each kept version's `versions/<v>/shots/`. Their facts sit in the folder's own `.media.json`,
3
+ // which a build's new shelf drops with the old files. The shelf of each trailer's newest build stays on the disk
4
+ import { existsSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs'
5
+ import { join, relative } from 'node:path'
6
+ import { factOf, mediaKey } from '../media-store/content.ts'
7
+ import type { MediaRow } from '../media-store/kind.ts'
8
+ import { fetchBack } from '../media-store/remote.ts'
9
+ import { SHOT_FACTS, shotFacts } from '../trailer/shelf.ts'
10
+ import { TRAILER_KIND, trailerIds } from './trailer-desk.ts'
11
+
12
+ const SHELF_RE = /^(.+)-shots$/
13
+
14
+ export interface ShotFolder {
15
+ /** the folder, relative to the repo: the item of its rows */
16
+ item: string
17
+ trailer: string
18
+ /** the cut it shelves, or the version it keeps */
19
+ cut: string
20
+ version: boolean
21
+ /** when it was made: a build makes its shelf anew, a keep its version's; its facts file moves no clock */
22
+ born: number
23
+ }
24
+
25
+ /** every shots folder of the repo's trailers */
26
+ export function shotFolders(root: string): ShotFolder[] {
27
+ const out: ShotFolder[] = []
28
+ for (const id of trailerIds(root)) {
29
+ const dir = join(root, 'trailer', id)
30
+ const add = (path: string, cut: string, version: boolean): void => {
31
+ const s = statSync(path, { throwIfNoEntry: false })
32
+ if (s?.isDirectory()) out.push({ item: relative(root, path), trailer: id, cut, version, born: s.birthtimeMs })
33
+ }
34
+ for (const f of existsSync(join(dir, 'out')) ? readdirSync(join(dir, 'out')) : []) {
35
+ const m = SHELF_RE.exec(f)
36
+ if (m) add(join(dir, 'out', f), m[1]!, false)
37
+ }
38
+ for (const v of existsSync(join(dir, 'versions')) ? readdirSync(join(dir, 'versions')) : []) if (/^v\d+$/.test(v)) add(join(dir, 'versions', v, 'shots'), v, true)
39
+ }
40
+ return out
41
+ }
42
+
43
+ /** a folder's rows: its facts filled while `take()` allows, written back when they moved */
44
+ export async function shotRows(root: string, f: ShotFolder, take: () => boolean): Promise<MediaRow[]> {
45
+ const folder = join(root, f.item)
46
+ const facts = shotFacts(folder)
47
+ let moved = false
48
+ const rows: MediaRow[] = []
49
+ const names = new Set([...Object.keys(facts), ...readdirSync(folder).filter((n) => !n.startsWith('.'))])
50
+ for (const name of [...names].sort()) {
51
+ const size = statSync(join(folder, name), { throwIfNoEntry: false })?.size
52
+ let fact = facts[name]
53
+ if (size !== undefined && fact?.size !== size) {
54
+ if (!take()) continue
55
+ fact = facts[name] = await factOf(join(folder, name))
56
+ moved = true
57
+ }
58
+ if (fact) rows.push({ item: f.item, name, fact, local: size !== undefined })
59
+ }
60
+ if (moved) {
61
+ const file = join(folder, SHOT_FACTS)
62
+ writeFileSync(`${file}.${process.pid}.tmp`, JSON.stringify(facts))
63
+ renameSync(`${file}.${process.pid}.tmp`, file)
64
+ }
65
+ return rows
66
+ }
67
+
68
+ /** the shelf the purge keeps: per trailer, the one its newest build wrote */
69
+ export function newestShelves(folders: readonly ShotFolder[]): Set<string> {
70
+ const best = new Map<string, ShotFolder>()
71
+ for (const f of folders) if (!f.version && (best.get(f.trailer)?.born ?? -1) < f.born) best.set(f.trailer, f)
72
+ return new Set([...best.values()].map((f) => f.item))
73
+ }
74
+
75
+ /** every file of a shots folder on the disk, the ones the purge let go fetched back first; the names that came back
76
+ * missing are returned, never dropped in silence */
77
+ export async function shotsBack(root: string, folder: string): Promise<string[]> {
78
+ const facts = shotFacts(folder)
79
+ const item = relative(root, folder)
80
+ const lost: string[] = []
81
+ await Promise.all(
82
+ Object.entries(facts).map(async ([name, f]) => {
83
+ const path = join(folder, name)
84
+ if (!(await fetchBack(path, mediaKey(TRAILER_KIND, f, name), f, { store: root, item, name }))) lost.push(name)
85
+ }),
86
+ )
87
+ return lost.sort()
88
+ }
89
+
@@ -53,6 +53,8 @@ export class ColsSvc {
53
53
  private last: Answer | null = null
54
54
  private keptCat: string | null | undefined = undefined
55
55
  private restoring: Promise<void> | null = null
56
+ /** the ETag of the last answer taken */
57
+ private tag: string | null = null
56
58
  actErr = ''
57
59
  remarkDraft = ''
58
60
  proofDraft = ''
@@ -64,7 +66,7 @@ export class ColsSvc {
64
66
  private timer: ReturnType<typeof setInterval> | null = null
65
67
 
66
68
  constructor(private st: RepoSt) {
67
- makeAutoObservable<this, 'st' | 'timer' | 'keptAt' | 'restoring' | 'readKept' | 'last' | 'keptCat'>(this, { st: false, timer: false, keptAt: false, restoring: false, readKept: false, last: false, keptCat: false })
69
+ makeAutoObservable<this, 'st' | 'timer' | 'keptAt' | 'restoring' | 'readKept' | 'last' | 'keptCat' | 'tag'>(this, { st: false, timer: false, keptAt: false, restoring: false, readKept: false, last: false, keptCat: false, tag: false })
68
70
  }
69
71
 
70
72
  /** one check's row of the plan, null when no plan covers it */
@@ -135,7 +137,16 @@ export class ColsSvc {
135
137
  try {
136
138
  const r = await reach(this.st.url(fresh ? '/api/resources.json?fresh=1' : '/api/resources.json'))
137
139
  if (!r.ok) throw new Error(await r.text())
140
+ // the browser revalidates the tag and hands back what it holds:
141
+ // the same tag is the same answer, so nothing is parsed or swapped
142
+ const tag = r.headers.get('ETag')
143
+ if (tag != null && tag === this.tag && this.loaded) {
144
+ await r.body?.cancel()
145
+ runInAction(() => { this.fetchErr = null })
146
+ return
147
+ }
138
148
  const j = (await r.json()) as Answer
149
+ this.tag = tag
139
150
  runInAction(() => {
140
151
  this.colMeta = j.collections
141
152
  this.fetched = j.resources
@@ -142,6 +142,10 @@ export class ReviewSt {
142
142
  private toastTimer: ReturnType<typeof setTimeout> | null = null
143
143
  private searchTimer: ReturnType<typeof setTimeout> | null = null
144
144
  private timer: ReturnType<typeof setInterval> | null = null
145
+ /** the read a start began, while it runs */
146
+ private starting: { card: ThreadSt | null; p: Promise<void> } | null = null
147
+ /** the unit's words, read once a start, again after a stop */
148
+ private specRead: Promise<unknown> | null = null
145
149
  private readonly loadPage: () => Promise<ThreadPage>
146
150
  private readonly loadWatchers: () => Promise<Watcher[]>
147
151
  private readonly loadBoard: () => Promise<{ role: Role | null; rows: BoardRow[] }>
@@ -163,11 +167,13 @@ export class ReviewSt {
163
167
  } catch {
164
168
  // a broken pref is the default
165
169
  }
166
- makeAutoObservable<this, 'st' | 'toastTimer' | 'searchTimer' | 'timer' | 'loadPage' | 'loadWatchers' | 'loadBoard' | 'prefix'>(this, {
170
+ makeAutoObservable<this, 'st' | 'toastTimer' | 'searchTimer' | 'timer' | 'starting' | 'specRead' | 'loadPage' | 'loadWatchers' | 'loadBoard' | 'prefix'>(this, {
167
171
  st: false,
168
172
  toastTimer: false,
169
173
  searchTimer: false,
170
174
  timer: false,
175
+ starting: false,
176
+ specRead: false,
171
177
  loadPage: false,
172
178
  loadWatchers: false,
173
179
  loadBoard: false,
@@ -210,8 +216,12 @@ export class ReviewSt {
210
216
 
211
217
  /** the list, the watches and the open card, read now and every 2 s while the page shows; the unit's words once */
212
218
  start(): void {
213
- void this.refresh()
214
- void fetch(this.st.url('/api/review/spec'))
219
+ // the page starts more than once at boot (its resume, its address): one read while the first runs
220
+ if (this.starting?.card !== this.card) {
221
+ const p = this.refresh().finally(() => { if (this.starting?.p === p) this.starting = null })
222
+ this.starting = { card: this.card, p }
223
+ }
224
+ this.specRead ??= fetch(this.st.url('/api/review/spec'))
215
225
  .then((r) => (r.ok ? (r.json() as Promise<RepoSpec>) : null))
216
226
  .catch(() => null)
217
227
  .then((spec) => runInAction(() => (this.spec = spec)))
@@ -221,6 +231,7 @@ export class ReviewSt {
221
231
  stop(): void {
222
232
  if (this.timer !== null) clearInterval(this.timer)
223
233
  this.timer = null
234
+ this.specRead = null
224
235
  }
225
236
 
226
237
  async refresh(): Promise<void> {
@@ -4,6 +4,7 @@
4
4
  // suite adds the case its declaration argued and the way back to the quick
5
5
  // tier.
6
6
  import { observer } from 'mobx-react-lite'
7
+ import { useEffect } from 'react'
7
8
  import { durationTone, fmtMs } from './dur.ts'
8
9
  import type { RepoSt } from './repo-st.ts'
9
10
  import type { Resource, SuiteFacts, TestFacts, TestRun } from './hub-types.ts'
@@ -69,8 +70,14 @@ const Declaration = observer(({ app, s }: { app: RepoSt; s: SuiteFacts }) => {
69
70
 
70
71
  export const TestCard = observer(({ app, id }: { app: RepoSt; id: string }) => {
71
72
  const i: Resource | null = app.cols.find('tests', id)
73
+ const file = i?.test?.file ?? null
74
+ const lastAt = i?.test?.runs[0]?.at ?? null
75
+ // the poll carries the last run only: the whole list is read here, again when a new run lands
76
+ useEffect(() => { if (file != null) void app.tests.loadRuns(file) }, [app, file, lastAt])
72
77
  if (i == null || i.test == null) return <div className="ph">this test file is gone: the repo moved on</div>
73
78
  const t = i.test
79
+ const kept = app.tests.runs.get(t.file)
80
+ const runs = kept != null && (kept[0]?.at ?? null) === lastAt ? kept : t.runs
74
81
  const fix = fixWords(t)
75
82
  const cmd = testCommand(t)
76
83
  return (
@@ -97,9 +104,9 @@ export const TestCard = observer(({ app, id }: { app: RepoSt; id: string }) => {
97
104
  <Row k="budget" help="what one file may cost in the quick tier"><span className="dnum dim">{fmtMs(t.budgetMs)}</span> per file</Row>
98
105
  </div>
99
106
  <Section title="last runs" help="the suite record: every run of this file the suite runner timed, newest first">
100
- {t.runs.length === 0
107
+ {runs.length === 0
101
108
  ? <div className="dim">no run recorded yet: the next run of {t.checkId ?? 'a test check'} records one</div>
102
- : <div className="rlist">{t.runs.map((r, n) => <RunLine key={`${r.at}:${n}`} app={app} r={r} slow={t.suite != null} />)}</div>}
109
+ : <div className="rlist">{runs.map((r, n) => <RunLine key={`${r.at}:${n}`} app={app} r={r} slow={t.suite != null} />)}</div>}
103
110
  </Section>
104
111
  {t.suite == null ? null : <Declaration app={app} s={t.suite} />}
105
112
  </div>
@@ -6,6 +6,7 @@ import { makeAutoObservable, observableRef, runInAction } from 'mobx'
6
6
  import type { TestCheckView, TestsRootView } from '../../collections/test-time.ts'
7
7
  import { testId } from '../../collections/collection-types.ts'
8
8
  import type { RepoSt } from './repo-st.ts'
9
+ import type { TestRun } from './hub-types.ts'
9
10
 
10
11
  export type { TestCheckView, TestsRootView }
11
12
 
@@ -16,9 +17,23 @@ export class TestsSvc {
16
17
  views = new Map<string, TestsRootView | TestCheckView>()
17
18
  errors = new Map<string, string>()
18
19
  loading = new Set<string>()
20
+ /** a test file's whole run list, read when its page opens: the poll
21
+ * carries its last run only (resources-wire.ts) */
22
+ runs = new Map<string, TestRun[]>()
19
23
 
20
24
  constructor(private st: RepoSt) {
21
- makeAutoObservable<this, 'st'>(this, { st: false, views: observableRef })
25
+ makeAutoObservable<this, 'st'>(this, { st: false, views: observableRef, runs: observableRef })
26
+ }
27
+
28
+ async loadRuns(file: string): Promise<void> {
29
+ try {
30
+ const r = await fetch(this.st.url(`/api/test-runs.json?file=${encodeURIComponent(file)}`))
31
+ if (!r.ok) return
32
+ const v = (await r.json()) as { runs: TestRun[] }
33
+ runInAction(() => { this.runs = new Map(this.runs).set(file, v.runs) })
34
+ } catch {
35
+ // the last run the poll carries stays on the page
36
+ }
22
37
  }
23
38
 
24
39
  root(): TestsRootView | null {
@@ -0,0 +1,48 @@
1
+ // /api/resources.json on the wire: the one flat list a page polls every ten
2
+ // seconds, serialized once per compute and answered 304 while the page holds
3
+ // it. A test file carries its last run only: its page reads the whole run
4
+ // list from /api/test-runs.json when it opens (the history is half the bytes
5
+ // of a big repo).
6
+ //
7
+ // the one constraint a reader breaks first: the ETag covers the live parts
8
+ // (the plan rows, the hub problems) too, so a moved plan is never a 304.
9
+ import type { Resource } from '../collections/collection-types.ts'
10
+
11
+ /** the list as the page receives it: a test file's runs cut to the last one */
12
+ export const leanResources = (rs: readonly Resource[]): Resource[] =>
13
+ rs.map((r) => (r.test == null || r.test.runs.length <= 1 ? r : { ...r, test: { ...r.test, runs: r.test.runs.slice(0, 1) } }))
14
+
15
+ type Rows = { collections: unknown; resources: Resource[] }
16
+ type Wire = { head: string; tag: string }
17
+
18
+ /** the serialized list, once per computed answer */
19
+ const wires = new WeakMap<Rows, Wire>()
20
+ const wireOf = (rows: Rows): Wire => {
21
+ let w = wires.get(rows)
22
+ if (w == null) {
23
+ const head = JSON.stringify({ collections: rows.collections, resources: leanResources(rows.resources) }).slice(0, -1)
24
+ w = { head, tag: Bun.hash(head).toString(36) }
25
+ wires.set(rows, w)
26
+ }
27
+ return w
28
+ }
29
+
30
+ /** the answer, 304 when the page sent the same tag; gzipped (and kept for the next page) when it takes it */
31
+ export function resourcesAnswer(req: Request, rows: Rows, live: Record<string, unknown>, zipped: { tag: string; body: Uint8Array<ArrayBuffer> } | null): { res: Response; zipped: typeof zipped } {
32
+ const w = wireOf(rows)
33
+ const tail = JSON.stringify(live).slice(1)
34
+ const tag = `"${w.tag}-${Bun.hash(tail).toString(36)}"`
35
+ const headers = { 'Content-Type': 'application/json', ETag: tag, 'Cache-Control': 'no-cache', Vary: 'Accept-Encoding' }
36
+ if (req.headers.get('If-None-Match') === tag) return { res: new Response(null, { status: 304, headers: { ETag: tag, 'Cache-Control': 'no-cache' } }), zipped }
37
+ const text = tail === '}' ? `${w.head}}` : `${w.head},${tail}`
38
+ if (!/\bgzip\b/.test(req.headers.get('Accept-Encoding') ?? '')) return { res: new Response(text, { headers }), zipped }
39
+ const z = zipped?.tag === tag ? zipped : { tag, body: Bun.gzipSync(new TextEncoder().encode(text)) }
40
+ return { res: new Response(z.body, { headers: { ...headers, 'Content-Encoding': 'gzip' } }), zipped: z }
41
+ }
42
+
43
+ /** one test file's whole run list, newest first, for its page */
44
+ export function testRunsAnswer(rows: Rows, file: string | null): Response {
45
+ const r = rows.resources.find((x) => x.test != null && x.test.file === file)
46
+ if (r?.test == null) return new Response(`no test file ${file ?? '(none named)'} in this repo`, { status: 404 })
47
+ return Response.json({ file, runs: r.test.runs }, { headers: { 'Cache-Control': 'no-store' } })
48
+ }
@@ -33,6 +33,7 @@ import { sameOrigin } from './same-origin.ts'
33
33
  import { LAYOUT } from '../core/layout.ts'
34
34
  import { heldNow, heldText } from '../core/last-good.ts'
35
35
  import { WarmCell } from './warm-cell.ts'
36
+ import { resourcesAnswer, testRunsAnswer } from './resources-wire.ts'
36
37
  import { readmeRoutes } from './readme-route.ts'
37
38
  import { reviewRoutes } from '../review/routes.ts'
38
39
  import { embedRoute } from './embed.ts'
@@ -190,6 +191,8 @@ export function hubHandler(d: HubDeps, o: { base?: string; projects?: Gutter } =
190
191
  const timeline = d.timeline == null ? null : new WarmCell(d.timeline, { stamp: d.stamp })
191
192
  const graphs = new Map(d.graphs.map((g) => [g.id, new WarmCell(async () => g.load(), { maxAgeMs: WARM_MAX_AGE_MS })]))
192
193
  const fresh = (req: Request): boolean => new URL(req.url).searchParams.get('fresh') === '1'
194
+ /** the last gzipped list, answered again to the next page while it holds */
195
+ let zipped: Parameters<typeof resourcesAnswer>[3] = null
193
196
  return {
194
197
  tools,
195
198
  invalidate: () => {
@@ -246,13 +249,11 @@ export function hubHandler(d: HubDeps, o: { base?: string; projects?: Gutter } =
246
249
  // under its sections, and a second endpoint would be a
247
250
  // second answer to drift from this one
248
251
  const r = await rows.get({ fresh: fresh(req) })
249
- return Response.json({
250
- collections: r.collections,
251
- resources: r.resources,
252
- planned: d.planned?.() ?? null,
253
- hub: [...(d.hubProblems?.list() ?? []), ...heldProblem()],
254
- })
252
+ const a = resourcesAnswer(req, r, { planned: d.planned?.() ?? null, hub: [...(d.hubProblems?.list() ?? []), ...heldProblem()] }, zipped)
253
+ zipped = a.zipped
254
+ return a.res
255
255
  }
256
+ if (path === '/api/test-runs.json') return testRunsAnswer(await rows.get({}), new URL(req.url).searchParams.get('file'))
256
257
  // the previous address, answered while pages opened before the
257
258
  // tree are still on screen
258
259
  if (path === '/api/collections.json') {
@@ -5,6 +5,7 @@ import { basename, join, relative } from 'node:path'
5
5
  import { type Loaded, load, Refused, type Say, takesOfLoaded } from './build.ts'
6
6
  import { ffmpeg } from './ffmpeg.ts'
7
7
  import { starts, type Trailer } from './grammar.ts'
8
+ import { shotFacts } from './shelf.ts'
8
9
 
9
10
  const outOf = (l: Pick<Loaded, 'dir'>): string => join(l.dir, 'out')
10
11
 
@@ -105,13 +106,15 @@ export function keep(l: Loaded, v: string, say: Say, cwd: string): void {
105
106
  const strip = join(outOf(l), `${l.t.name}.strip.png`)
106
107
  if (existsSync(strip)) clone(strip, join(dir, `${l.t.name}.strip.png`))
107
108
  const shots = join(outOf(l), `${l.t.name}-shots`)
109
+ // the shelf's facts go with it: a shot the media store let go stays known to the version, fetched back on demand
108
110
  const files = existsSync(shots) ? readdirSync(shots) : []
109
111
  for (const f of files) clone(join(shots, f), join(dir, 'shots', f))
112
+ const count = new Set([...files.filter((f) => !f.startsWith('.')), ...Object.keys(shotFacts(shots))]).size
110
113
  // the clones are the machine's: git keeps the text and the index, never a version's folder
111
114
  const ignored = Bun.spawnSync(['git', 'check-ignore', '-q', dir], { cwd: l.root }).exitCode === 0
112
115
  const ignore = join(l.dir, 'versions', '.gitignore')
113
116
  if (!ignored && !existsSync(ignore)) writeFileSync(ignore, '*/\n')
114
- say(`ok: kept ${v}: ${relative(cwd, text)}, ${relative(cwd, dir)}/ (the video, the strip, ${files.length} shots)`)
117
+ say(`ok: kept ${v}: ${relative(cwd, text)}, ${relative(cwd, dir)}/ (the video, the strip, ${count} shots)`)
115
118
  say(`then: its row in ${relative(cwd, join(l.dir, 'versions', 'index.md'))}, commit ${relative(cwd, text)} and that index, git tag trailer-${basename(l.dir)}-${v}, push the commit and the tag`)
116
119
  }
117
120
 
@@ -0,0 +1,16 @@
1
+ // the facts of a shots folder (a build's shelf, a version's shots): each file's content by name, kept in the folder
2
+ // so a shot the media store let go stays known (src/review/trailer-shots.ts reads and writes them)
3
+ import { readFileSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import type { MediaFact } from '../media-store/fact.ts'
6
+
7
+ export const SHOT_FACTS = '.media.json'
8
+
9
+ /** the facts a shots folder keeps, by file name; none when it has no record */
10
+ export function shotFacts(folder: string): Record<string, MediaFact> {
11
+ try {
12
+ return JSON.parse(readFileSync(join(folder, SHOT_FACTS), 'utf8')) as Record<string, MediaFact>
13
+ } catch {
14
+ return {}
15
+ }
16
+ }