rvlib-shipkit 2.9.0 → 2.11.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.
Files changed (75) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/package.json +1 -1
  3. package/src/cli/cmd_Media.ts +164 -0
  4. package/src/cli/cmd_Review.ts +2 -1
  5. package/src/cli/family-pages.ts +1 -0
  6. package/src/cli/registry.ts +2 -0
  7. package/src/collections/pings.ts +6 -4
  8. package/src/core/app-icon.ts +17 -4
  9. package/src/core/scratch-objects.ts +56 -0
  10. package/src/core/trace-audit.ts +13 -1
  11. package/src/home/home-paths.ts +4 -0
  12. package/src/home/home-routes.ts +36 -2
  13. package/src/home/hubs.ts +5 -0
  14. package/src/home/inbox-shape.ts +182 -0
  15. package/src/home/inbox.ts +48 -0
  16. package/src/home/run-daemon.ts +12 -2
  17. package/src/home/serve-web.ts +155 -16
  18. package/src/ledger/git-scan.ts +73 -25
  19. package/src/ledger/repo-view.ts +2 -22
  20. package/src/media-kinds.ts +7 -0
  21. package/src/media-store/content.ts +51 -0
  22. package/src/media-store/daemon.ts +91 -0
  23. package/src/media-store/db.ts +74 -0
  24. package/src/media-store/fact.ts +9 -0
  25. package/src/media-store/kind.ts +44 -0
  26. package/src/media-store/purge.ts +139 -0
  27. package/src/media-store/remote.ts +93 -0
  28. package/src/media-store/space.ts +124 -0
  29. package/src/media-store/sync.ts +101 -0
  30. package/src/media-store/upload.ts +98 -0
  31. package/src/repo-config.ts +4 -0
  32. package/src/review/anim.ts +6 -5
  33. package/src/review/cells.ts +552 -0
  34. package/src/review/format.ts +1 -1
  35. package/src/review/media-kind.ts +84 -0
  36. package/src/review/media-read.ts +48 -0
  37. package/src/review/model.ts +43 -5
  38. package/src/review/previews.ts +153 -0
  39. package/src/review/routes.ts +105 -47
  40. package/src/review/store.ts +106 -45
  41. package/src/review/trailer-desk.ts +79 -46
  42. package/src/review/trailer-media.ts +163 -0
  43. package/src/review/trailer-routes.ts +5 -2
  44. package/src/serve/hub-app/home-st.ts +39 -9
  45. package/src/serve/hub-app/home.html +2 -1
  46. package/src/serve/hub-app/hub-app.tsx +7 -23
  47. package/src/serve/hub-app/icons.tsx +2 -0
  48. package/src/serve/hub-app/inbox-st.ts +144 -0
  49. package/src/serve/hub-app/inbox-view.tsx +205 -0
  50. package/src/serve/hub-app/inbox.css +73 -0
  51. package/src/serve/hub-app/item-view.tsx +19 -0
  52. package/src/serve/hub-app/keys.ts +4 -3
  53. package/src/serve/hub-app/palette-st.ts +2 -1
  54. package/src/serve/hub-app/project-list.tsx +1 -0
  55. package/src/serve/hub-app/projects-svc.ts +1 -1
  56. package/src/serve/hub-app/repo-st.ts +1 -1
  57. package/src/serve/hub-app/review/kind-view.tsx +21 -22
  58. package/src/serve/hub-app/review/kit.tsx +11 -12
  59. package/src/serve/hub-app/review/review-board.tsx +15 -13
  60. package/src/serve/hub-app/review/review-cells.tsx +241 -0
  61. package/src/serve/hub-app/review/review-kit.ts +79 -0
  62. package/src/serve/hub-app/review/review-list.tsx +87 -122
  63. package/src/serve/hub-app/review/review-page.tsx +22 -79
  64. package/src/serve/hub-app/review/review-st.ts +269 -698
  65. package/src/serve/hub-app/review/review-thread.tsx +302 -0
  66. package/src/serve/hub-app/review/review-views.tsx +322 -253
  67. package/src/serve/hub-app/review/thread-st.ts +770 -0
  68. package/src/serve/hub-app/review.css +235 -91
  69. package/src/serve/hub-runtime.ts +9 -4
  70. package/src/serve/serve-hub.ts +4 -1
  71. package/src/serve/warm-cell.ts +6 -1
  72. package/src/trailer/footage.ts +6 -2
  73. package/src/trailer/passage.ts +4 -2
  74. package/src/trailer/prune.ts +6 -10
  75. package/src/serve/hub-app/review/review-answer.tsx +0 -249
@@ -8,6 +8,8 @@ import { basename, dirname, extname, join, resolve } from 'node:path'
8
8
  import { LAYOUT } from '../core/layout.ts'
9
9
  import { ffmpeg } from '../trailer/ffmpeg.ts'
10
10
  import { probe, sizeOf, stillAt } from './media.ts'
11
+ import { factsOf } from '../media-store/content.ts'
12
+ import { mediaDb, tryWrite } from '../media-store/db.ts'
11
13
  import {
12
14
  AGENT_RE,
13
15
  allowed,
@@ -47,6 +49,7 @@ import {
47
49
  type ReviewView,
48
50
  type Spec,
49
51
  type Subject,
52
+ viewFilesOf,
50
53
  } from './model.ts'
51
54
  import { beatRole, roleOf } from './role.ts'
52
55
  import { chainOf, coveringHead, followedIds, isFollowed } from './threads.ts'
@@ -370,9 +373,10 @@ export async function addItem(dir: string, input: AddInput): Promise<Item> {
370
373
  mkdirSync(tmp)
371
374
  loaded.forEach((v, n) => copyFiles(v, n, tmp))
372
375
  await Promise.all(loaded.map((v, n) => Promise.all([writePoster(v, n, tmp), writeWaves(v, n, tmp)])))
373
- writeJson(join(tmp, 'item.json'), item)
376
+ const head: Item = { ...item, media: await factsOf(tmp, viewFilesOf(item)) }
377
+ writeJson(join(tmp, 'item.json'), head)
374
378
  renameSync(tmp, join(dir, id))
375
- return item
379
+ return head
376
380
  }
377
381
 
378
382
  /** every file of view `n` into the folder, each as `<name>.tmp` renamed, so no reader sees half of one */
@@ -400,9 +404,41 @@ export async function addView(dir: string, id: string, v: ViewInput, o: { marks?
400
404
  copyFiles(loaded, n, folder)
401
405
  await writePoster(loaded, n, folder)
402
406
  await writeWaves(loaded, n, folder)
403
- const item: Item = { ...x.item, views: [...x.item.views, viewOf(loaded, n, o.marks, v.note)], ...(x.item.light || o.light ? { light: 'review' as const } : {}) }
404
- writeJson(join(folder, 'item.json'), item)
405
- return item
407
+ const view = viewOf(loaded, n, o.marks, v.note)
408
+ const facts = await factsOf(folder, viewFilesOf({ ...x.item, views: [view] }))
409
+ return updateHead(dir, id, (cur) => {
410
+ if (cur.views.length !== n) throw new Error(`${id}: another view landed while this one was written: add it again`)
411
+ return { ...cur, views: [...cur.views, view], media: { ...cur.media, ...facts }, ...(cur.light || o.light ? { light: 'review' as const } : {}) }
412
+ })
413
+ }
414
+
415
+ /** the head rewritten under the item's lock, from what the file says now: a write that raced this one is never lost */
416
+ export function updateHead(dir: string, id: string, fn: (cur: Item) => Item): Item {
417
+ return locked(dir, id, () => {
418
+ const f = join(dir, id, 'item.json')
419
+ const cur = JSON.parse(readFileSync(f, 'utf8')) as Item
420
+ const next = fn(cur)
421
+ const problems = itemProblems(next)
422
+ if (problems.length > 0) throw new Error(problems.join('; '))
423
+ writeJson(f, next)
424
+ return next
425
+ })
426
+ }
427
+
428
+ /** the media facts an item lacks (one written before facts were kept, a file whose size moved): each file still in the
429
+ * folder hashed, written under its lock; the item as it is when nothing was missing */
430
+ export async function fillMedia(dir: string, id: string): Promise<Item | null> {
431
+ const x = readRaw(dir, id)
432
+ if (!x) return null
433
+ const folder = join(dir, id)
434
+ const held = x.item.media ?? {}
435
+ const names = viewFilesOf(x.item)
436
+ const size = (n: string): number | undefined => statSync(join(folder, n), { throwIfNoEntry: false })?.size
437
+ const stale = new Set(names.filter((n) => held[n] && size(n) !== undefined && size(n) !== held[n]?.size))
438
+ const lacks = names.filter((n) => !held[n] && existsSync(join(folder, n)))
439
+ if (lacks.length === 0 && stale.size === 0) return x.item
440
+ const facts = await factsOf(folder, [...lacks, ...stale], {}, stale)
441
+ return updateHead(dir, id, (cur) => ({ ...cur, media: { ...cur.media, ...facts } }))
406
442
  }
407
443
 
408
444
  export interface ReadAll {
@@ -481,11 +517,12 @@ export function addMessage(dir: string, id: string, who: string, text: unknown,
481
517
  return appendMessage(dir, id, { who, text: t.text }, { ...(image !== undefined ? { image } : {}), now })
482
518
  }
483
519
 
484
- /** `party` read what the other party wrote on an item: one `seen` message naming them; how many it read */
485
- export function markRead(dir: string, id: string, party: Party, who: string = party === 'owner' ? 'owner' : agentName(), now = new Date()): number {
520
+ /** `party` read what the other party wrote on an item: one `seen` message naming them; how many it read. `only`: the
521
+ * messages a page drew, so a word that came after it is never marked read */
522
+ export function markRead(dir: string, id: string, party: Party, who: string = party === 'owner' ? 'owner' : agentName(), now = new Date(), only?: readonly string[]): number {
486
523
  const x = ID_RE.test(id) ? readItem(dir, id) : null
487
524
  if (!x) return 0
488
- const of = toAcknowledge(x, party)
525
+ const of = toAcknowledge(x, party).filter((m) => only === undefined || only.includes(m))
489
526
  if (of.length > 0) appendMessage(dir, id, { who, op: 'seen', of }, { now })
490
527
  return of.length
491
528
  }
@@ -508,19 +545,11 @@ function stampOf(folder: string): string {
508
545
  return `${one(folder)}:${one(`${folder}/thread`)}`
509
546
  }
510
547
 
511
- /** the index of a store: beside it, never inside it. Its own name, never `.review-index.json`: a second code that reads
512
- * the same store keys its index on its own code, and two codes sharing one file each throw the other's away */
513
- export const indexFile = (dir: string): string => join(dirname(resolve(dir)), `.${basename(dir)}-index.shipkit.json`)
514
-
515
548
  type Read = { x: ReviewItem } | { error: string }
516
549
 
517
- interface StoreIndex {
518
- /** the code that reads and checks an item: another code reads every item again */
519
- code: string
520
- items: Record<string, { stamp: string; read: Read }>
521
- }
522
-
523
550
  let codeKey: string | null = null
551
+ /** the code that reads and checks an item: the index keeps each code's reads apart, so two copies of the lib reading one
552
+ * store (the daemon's, a repo's own install) never throw each other's away */
524
553
  const indexCode = (): string => (codeKey ??= new Bun.CryptoHasher('sha1').update(readFileSync(import.meta.path)).update(readFileSync(join(import.meta.dir, 'model.ts'))).digest('hex'))
525
554
 
526
555
  function readOne(dir: string, id: string): Read {
@@ -553,39 +582,69 @@ function checked(raw: ReadAll, spec: Spec): ReadAll {
553
582
  return all
554
583
  }
555
584
 
556
- /** every item of the store, through its index: an item whose stamp moved is read again */
585
+ /** the json index each store kept beside it before the machine index, removed once per process */
586
+ const OLD_INDEX = (dir: string): string => join(dirname(resolve(dir)), `.${basename(dir)}-index.shipkit.json`)
587
+ const swept = new Set<string>()
588
+ /** the stores this process marked its code as using, once each */
589
+ const used = new Set<string>()
590
+ /** a code that read no store for this long: its reads go */
591
+ const CODE_KEEP_MS = 7 * 24 * 3600_000
592
+
593
+ /** every item of the store, through the machine index (space/db.ts): an item whose stamp moved is read again */
557
594
  function readRaws(dir: string): ReadAll {
558
595
  const out: ReadAll = { items: [], broken: [] }
559
596
  if (!existsSync(dir)) return out
560
- const file = indexFile(dir)
597
+ const store = resolve(dir)
561
598
  const code = indexCode()
562
- let was: StoreIndex['items'] = {}
563
- try {
564
- const ix = JSON.parse(readFileSync(file, 'utf8')) as StoreIndex
565
- if (ix.code === code) was = ix.items
566
- } catch {
567
- // no index yet, or one of another shape: read every item
599
+ const db = mediaDb()
600
+ const was = new Map<string, { stamp: string; read: string }>()
601
+ if (db)
602
+ try {
603
+ for (const r of db.query('select id, stamp, read from items where store = ? and code = ?').all(store, code) as { id: string; stamp: string; read: string }[]) was.set(r.id, r)
604
+ } catch (e) {
605
+ console.error(`WARN review index: ${store} read from its files: ${(e as Error).message}`)
606
+ }
607
+ if (!swept.has(store)) {
608
+ swept.add(store)
609
+ fs.rmSync(OLD_INDEX(dir), { force: true })
568
610
  }
569
- const next: StoreIndex = { code, items: {} }
570
- let moved = false
611
+ const moved: { id: string; stamp: string; read: Read }[] = []
612
+ const seen = new Set<string>()
571
613
  for (const id of readdirSync(dir).sort()) {
572
614
  if (id.startsWith('.')) continue
615
+ seen.add(id)
573
616
  const stamp = stampOf(join(dir, id))
574
- const held = was[id]
575
- const read = held && held.stamp === stamp ? held.read : readOne(dir, id)
576
- if (read !== held?.read) moved = true
577
- next.items[id] = { stamp, read }
617
+ const held = was.get(id)
618
+ let read: Read | null = null
619
+ if (held && held.stamp === stamp)
620
+ try {
621
+ read = JSON.parse(held.read) as Read
622
+ } catch {
623
+ read = null
624
+ }
625
+ if (!read) {
626
+ read = readOne(dir, id)
627
+ moved.push({ id, stamp, read })
628
+ }
578
629
  if ('x' in read) out.items.push(read.x)
579
630
  else out.broken.push({ id, error: read.error })
580
631
  }
581
- if (moved || Object.keys(was).length !== Object.keys(next.items).length)
582
- try {
583
- const tmp = `${file}.${process.pid}.tmp`
584
- fs.writeFileSync(tmp, JSON.stringify(next))
585
- fs.renameSync(tmp, file)
586
- } catch {
587
- // a read only store: the next read pays the whole read again
632
+ const gone = [...was.keys()].filter((id) => !seen.has(id))
633
+ const first = !used.has(store)
634
+ if (moved.length === 0 && gone.length === 0 && !first) return out
635
+ used.add(store)
636
+ tryWrite(`the reads of ${store}`, (d) => {
637
+ const now = Date.now()
638
+ d.query('insert or replace into codes (store, code, used) values (?, ?, ?)').run(store, code, now)
639
+ const put = d.query('insert or replace into items (store, code, id, stamp, read) values (?, ?, ?, ?, ?)')
640
+ for (const m of moved) put.run(store, code, m.id, m.stamp, JSON.stringify(m.read))
641
+ const drop = d.query('delete from items where store = ? and code = ? and id = ?')
642
+ for (const id of gone) drop.run(store, code, id)
643
+ for (const r of d.query('select code from codes where store = ? and used < ?').all(store, now - CODE_KEEP_MS) as { code: string }[]) {
644
+ d.query('delete from items where store = ? and code = ?').run(store, r.code)
645
+ d.query('delete from codes where store = ? and code = ?').run(store, r.code)
588
646
  }
647
+ })
589
648
  return out
590
649
  }
591
650
 
@@ -683,7 +742,7 @@ export async function raiseItem(dir: string, input: RaiseInput): Promise<ReviewI
683
742
  rmSync(tmp, { recursive: true, force: true })
684
743
  mkdirSync(tmp)
685
744
  if (input.image !== undefined && image) copyFileSync(input.image, join(tmp, image))
686
- writeJson(join(tmp, 'item.json'), item)
745
+ writeJson(join(tmp, 'item.json'), { ...item, ...(image ? { media: await factsOf(tmp, [image]) } : {}) })
687
746
  renameSync(tmp, join(dir, id))
688
747
  const who = input.origin.by === 'player' ? 'player' : 'owner'
689
748
  if (text) appendMessage(dir, id, { who, text, ...(input.rects && input.rects.length > 0 ? { rects: input.rects } : {}) }, { now })
@@ -876,8 +935,9 @@ export async function refreshDraft(dir: string, id: string, o: { image: string;
876
935
  views = [...views, viewOf(loaded, n)]
877
936
  }
878
937
  const next: Item = { ...r, views, wip: { live: r.wip.live, frame: r.wip.frame + 1 } }
879
- writeJson(join(folder, 'item.json'), next)
880
- return next
938
+ 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)
940
+ return updateHead(dir, id, () => ({ ...next, media }))
881
941
  }
882
942
 
883
943
  /** the label of a draft card's history view */
@@ -901,8 +961,9 @@ export async function readyItem(dir: string, id: string, o: { image?: string; no
901
961
  const now = 'image' in files ? files.image : undefined
902
962
  if (old && old !== now) rmSync(join(folder, old), { force: true })
903
963
  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))) }
904
965
  }
905
- writeJson(join(dir, id, 'item.json'), item)
966
+ updateHead(dir, id, () => item)
906
967
  appendMessage(dir, id, { who: agentName(), op: 'ready' }, o.now ? { now: o.now } : {})
907
968
  return item
908
969
  }
@@ -930,9 +991,9 @@ function watchOf(dir: string): Watched | null {
930
991
  if (watched.has(key)) return watched.get(key) ?? null
931
992
  const w: Watched = { moved: 0, dirty: new Set(), held: null, all: null }
932
993
  try {
933
- // a thumbnail or an item's lock is no change of the list
994
+ // an item's lock is no change of the list
934
995
  const watcher = watch(key, { recursive: true }, (_, name) => {
935
- if (name && (name.startsWith('.thumbs') || name.endsWith('.lock'))) return
996
+ if (name?.endsWith('.lock')) return
936
997
  w.moved++
937
998
  if (name) w.dirty.add(name.split('/')[0] ?? '')
938
999
  else w.held = null
@@ -2,9 +2,12 @@
2
2
  // is raised with: the note itself is an item of the one store, its subject the frame, anchored on its shot's name, so it
3
3
  // survives a new render of the cut. A cut is a `trailer/<id>/<cut>.trailer` and its render `out/<name>.mp4` (`<name>`
4
4
  // its `trailer` line), or a render with no file beside it. The trailer core (src/trailer/) is read, never changed
5
- import { constants, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
5
+ import { constants, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
6
6
  import { join, relative } from 'node:path'
7
7
  import { LAYOUT } from '../core/layout.ts'
8
+ import { mediaKey } from '../media-store/content.ts'
9
+ import type { MediaFact } from '../media-store/fact.ts'
10
+ import { fetchBack, signedUrl } from '../media-store/remote.ts'
8
11
  import { parseTrailer, starts, total, type Trailer } from '../trailer/grammar.ts'
9
12
  import { THUMB_W } from '../trailer/graph.ts'
10
13
  import { probe, stillAt } from './media.ts'
@@ -126,7 +129,7 @@ export function trailerIds(root: string): string[] {
126
129
  export const cutOf = (dir: string, cut: string): CutFiles | null => (CUT_RE.test(cut) ? (cutsOf(dir).find((c) => c.cut === cut) ?? null) : null)
127
130
  /** a cut's render: out/<name>.mp4, or a version's own */
128
131
  export const videoOf = (dir: string, c: CutFiles): string => (c.version ? (versionFile(dir, c.cut, '.mp4') ?? join(dir, 'versions', c.cut, `${c.cut}.mp4`)) : join(dir, 'out', `${c.name}.mp4`))
129
- const stripOf = (dir: string, c: CutFiles): string => (c.version ? (versionFile(dir, c.cut, '.strip.png') ?? join(dir, 'versions', c.cut, `${c.cut}.strip.png`)) : join(dir, 'out', `${c.name}.strip.png`))
132
+ export const stripOf = (dir: string, c: CutFiles): string => (c.version ? (versionFile(dir, c.cut, '.strip.png') ?? join(dir, 'versions', c.cut, `${c.cut}.strip.png`)) : join(dir, 'out', `${c.name}.strip.png`))
130
133
  export const montageOf = (dir: string, c: CutFiles): string => join(dir, 'out', `${c.name}.montage.md`)
131
134
 
132
135
  /** a cut's .trailer parsed: the film lines need the project CLI's words, which a timeline never does, so their errors
@@ -143,21 +146,32 @@ function parseCut(file: string): { trailer: Trailer; errors: string[] } {
143
146
  const SETTLE_MS = 2500
144
147
  const settled = (mtime: number, now: number): boolean => now - mtime > SETTLE_MS
145
148
 
146
- /** where each finished render is kept as the page plays it: an APFS clone, free, untouched by the next render */
149
+ /** where each finished render is recorded as the page plays it: its json, and an APFS clone of its video and strip
150
+ * (free, untouched by the next render) until the media store holds them (wiki build/trailer.md, Frame notes) */
147
151
  export const viewDir = (root: string): string => join(root, LAYOUT.cache, 'trailer-view')
148
- /** the versions kept per cut: the one on screen may be the one before the newest */
149
- const VIEWS_KEPT = 3
150
152
 
151
- /** a finished render of a cut: its clone, its length and rate, its size, the timeline it was rendered from (null: unknown) */
153
+ /** a render's files by their content, filled by the media store's scan (src/review/trailer-media.ts) */
154
+ export interface ViewMedia {
155
+ video?: MediaFact
156
+ strip?: MediaFact
157
+ /** the strip's width and height, so the timeline reads its grid once the clone is gone */
158
+ stripSize?: [number, number]
159
+ /** a kept version's own files with the same content, repo relative; set once checked */
160
+ from?: { video?: string; strip?: string }
161
+ }
162
+
163
+ /** a finished render of a cut: its length and rate, its size, the timeline it was rendered from (null: unknown), its
164
+ * files' content */
152
165
  export interface View {
153
166
  mtime: number
154
167
  duration: number
155
168
  fps: number
156
169
  size: [number, number]
157
170
  timeline: Timeline | null
171
+ media?: ViewMedia
158
172
  }
159
173
 
160
- const viewBase = (root: string, id: string, cut: string, mtime: number): string => join(viewDir(root), `${id}--${cut}--${Math.round(mtime)}`)
174
+ export const viewBase = (root: string, id: string, cut: string, mtime: number): string => join(viewDir(root), `${id}--${cut}--${Math.round(mtime)}`)
161
175
  export const viewVideo = (root: string, id: string, cut: string, mtime: number): string => `${viewBase(root, id, cut, mtime)}.mp4`
162
176
  export const viewStrip = (root: string, id: string, cut: string, mtime: number): string => `${viewBase(root, id, cut, mtime)}.strip.png`
163
177
 
@@ -169,10 +183,19 @@ function keepStrip(root: string, dir: string, id: string, c: CutFiles, mtime: nu
169
183
  copyFileSync(sf, kept, constants.COPYFILE_FICLONE)
170
184
  }
171
185
 
172
- /** a kept version by its mtime, null when it was pruned */
186
+ /** a render by its mtime, null when nothing holds its video: neither its clone nor the media store */
173
187
  export function readView(root: string, id: string, cut: string, mtime: number): View | null {
174
188
  const f = `${viewBase(root, id, cut, mtime)}.json`
175
- return existsSync(f) && existsSync(viewVideo(root, id, cut, mtime)) ? (JSON.parse(readFileSync(f, 'utf8')) as View) : null
189
+ if (!existsSync(f)) return null
190
+ const v = JSON.parse(readFileSync(f, 'utf8')) as View
191
+ return v.media?.video || existsSync(viewVideo(root, id, cut, mtime)) ? v : null
192
+ }
193
+
194
+ /** a render's record written whole, through a file beside it renamed */
195
+ export function writeView(root: string, id: string, cut: string, v: View): void {
196
+ const f = `${viewBase(root, id, cut, v.mtime)}.json`
197
+ writeFileSync(`${f}.${process.pid}.tmp`, JSON.stringify(v))
198
+ renameSync(`${f}.${process.pid}.tmp`, f)
176
199
  }
177
200
 
178
201
  function newestView(root: string, id: string, cut: string): View | null {
@@ -230,55 +253,63 @@ export function viewOf(root: string, dir: string, id: string, c: CutFiles, now =
230
253
  timeline = null
231
254
  }
232
255
  const view: View = { mtime, ...p, timeline }
233
- writeFileSync(`${viewBase(root, id, c.cut, mtime)}.json`, JSON.stringify(view))
256
+ writeView(root, id, c.cut, view)
234
257
  keepStrip(root, dir, id, c, mtime)
235
258
  views.set(key, view)
236
- pruneViews(root, id, c.cut)
237
259
  return { view, rendering: false }
238
260
  }
239
261
 
240
- function pruneViews(root: string, id: string, cut: string): void {
241
- const prefix = `${id}--${cut}--`
242
- for (const f of viewsToDrop(root)) if (f.slice(viewDir(root).length + 1).startsWith(prefix)) rmSync(f, { force: true })
243
- }
262
+ export const TRAILER_KIND = 'trailer'
244
263
 
245
- /** the kept renders that go: every one past the newest VIEWS_KEPT of a cut, and every one of a cut its folder no longer
246
- * has (a note keeps its own still) */
247
- export function viewsToDrop(root: string): string[] {
248
- const vd = viewDir(root)
249
- if (!existsSync(vd)) return []
250
- const live = new Set(trailerIds(root).flatMap((id) => cutsOf(join(trailersDir(root), id)).map((c) => `${id}--${c.cut}`)))
251
- const byCut = new Map<string, Set<number>>()
252
- const files = readdirSync(vd)
253
- for (const f of files) {
254
- const m = /^(.+)--(\d+)\./.exec(f)
255
- if (!m) continue
256
- const ms = byCut.get(m[1]!) ?? new Set<number>()
257
- byCut.set(m[1]!, ms.add(Number(m[2])))
264
+ /** where the Space keeps a render's file */
265
+ export const trailerKey = (f: MediaFact, part: 'video' | 'strip'): string => mediaKey(TRAILER_KIND, f, part === 'video' ? 'render.mp4' : 'strip.png')
266
+
267
+ /** the folder of the view clones, relative to the repo: the item of their rows in the media index */
268
+ export const VIEW_ITEM = join(LAYOUT.cache, 'trailer-view')
269
+
270
+ /** a render's video or strip as the page reads it: its clone, else the cut's own file while it is that render (a live
271
+ * cut's out/ file at the same mtime, a version's own file), else a URL the media store signs. `bytes` wants a file:
272
+ * the store's copy is fetched back into the clone's place. null when nothing holds it */
273
+ export async function viewMedia(root: string, id: string, cut: string, mtime: number, part: 'video' | 'strip', o: { bytes?: boolean } = {}): Promise<{ path: string } | { url: string } | null> {
274
+ const v = readView(root, id, cut, mtime)
275
+ if (!v) return null
276
+ const clone = part === 'video' ? viewVideo(root, id, cut, mtime) : viewStrip(root, id, cut, mtime)
277
+ if (existsSync(clone)) return { path: clone }
278
+ const dir = trailerDir(root, id)
279
+ const c = dir ? cutOf(dir, cut) : null
280
+ if (dir && c && part === 'video') {
281
+ const own = videoOf(dir, c)
282
+ if (existsSync(own) && Math.round(statSync(own).mtimeMs) === mtime) return { path: own }
258
283
  }
259
- const kept = new Set(
260
- [...byCut].flatMap(([cut, ms]) =>
261
- live.has(cut)
262
- ? [...ms]
263
- .sort((x, y) => y - x)
264
- .slice(0, VIEWS_KEPT)
265
- .map((m) => `${cut}--${m}`)
266
- : [],
267
- ),
268
- )
269
- return files.filter((f) => !kept.has(/^(.+--\d+)\./.exec(f)?.[1] ?? '')).map((f) => join(vd, f))
284
+ const fact = v.media?.[part]
285
+ const from = v.media?.from?.[part]
286
+ if (from && fact && existsSync(join(root, from)) && statSync(join(root, from)).size === fact.size) return { path: join(root, from) }
287
+ if (!fact) return null
288
+ const key = trailerKey(fact, part)
289
+ if (o.bytes) {
290
+ const back = await fetchBack(clone, key, fact, { store: root, item: VIEW_ITEM, name: clone.slice(viewDir(root).length + 1) })
291
+ return back ? { path: back } : null
292
+ }
293
+ const url = await signedUrl(key, fact.size)
294
+ return url ? { url } : null
270
295
  }
271
296
 
272
297
  /** the contact strip's grid as src/trailer/stitch.ts lays it: rows of six tiles THUMB_W wide, 6 px apart */
273
298
  const STRIP_COLS = 6
274
299
  const STRIP_PAD = 6
275
300
 
276
- /** the strip's grid, when the file's size fits this timeline's shots */
277
- function stripInfo(file: string, tl: Timeline): CutInfo['strip'] {
278
- if (!existsSync(file) || tl.shots.length === 0) return null
301
+ /** a png's width and height, read from its header */
302
+ export function pngSize(file: string): [number, number] {
279
303
  const head = readFileSync(file).subarray(0, 24)
280
- const w = head.readUInt32BE(16)
281
- const h = head.readUInt32BE(20)
304
+ return [head.readUInt32BE(16), head.readUInt32BE(20)]
305
+ }
306
+
307
+ /** the strip's grid, when its size fits this timeline's shots: read from the clone, else from the render's record */
308
+ function stripInfo(file: string, v: View, tl: Timeline): CutInfo['strip'] {
309
+ if (tl.shots.length === 0) return null
310
+ const wh = existsSync(file) ? pngSize(file) : v.media?.strip ? v.media.stripSize : undefined
311
+ if (!wh) return null
312
+ const [w, h] = wh
282
313
  const cols = Math.min(STRIP_COLS, tl.shots.length)
283
314
  const rows = Math.ceil(tl.shots.length / cols)
284
315
  const tileH = Math.round((THUMB_W * tl.size[1]) / tl.size[0] / 2) * 2
@@ -313,7 +344,7 @@ export function cutInfo(root: string, dir: string, id: string, c: CutFiles): Cut
313
344
  video: view ? { mtime: view.mtime, duration: view.duration, fps: view.fps } : null,
314
345
  rendering: !c.version && rendering,
315
346
  edited: !c.version && c.trailer !== null && view !== null && fileMtime > view.mtime,
316
- strip: timeline && view ? stripInfo(viewStrip(root, id, c.cut, view.mtime), timeline) : null,
347
+ strip: timeline && view ? stripInfo(viewStrip(root, id, c.cut, view.mtime), view, timeline) : null,
317
348
  fileMtime,
318
349
  version: c.version === true,
319
350
  }
@@ -362,7 +393,9 @@ export async function frameNote(root: string, trailer: string, input: NewNote, s
362
393
  const f = frameAt(input.time, v.fps, v.duration)
363
394
  const shot = shotAt(tl, f.time)
364
395
  if (!shot) throw new Error(`${input.cut} has no shot`)
365
- await stillAt(viewVideo(root, trailer, input.cut, v.mtime), (f.frame - 0.5) / v.fps, still)
396
+ const video = await viewMedia(root, trailer, input.cut, v.mtime, 'video', { bytes: true })
397
+ if (!video || !('path' in video)) throw new Error(`the render of ${input.cut} on screen is in neither the disk nor the media store`)
398
+ await stillAt(video.path, (f.frame - 0.5) / v.fps, still)
366
399
  return { kind: 'frame', trailer, cut: input.cut, version: String(v.mtime), time: round(f.time), frame: f.frame, shot: shot.name, shotTime: round(f.time - shot.start), section: shot.section }
367
400
  }
368
401
 
@@ -0,0 +1,163 @@
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
3
+ // disk: the newest render of each live cut, the render an open frame note was written on, and any render seen in the
4
+ // window. A file goes only when its own bytes hash to the key. The takes and footage cache is never this kind's
5
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
6
+ import { basename, dirname, join, relative } from 'node:path'
7
+ import { factOf, shaOf, shaOfKey } from '../media-store/content.ts'
8
+ import type { MediaFact } from '../media-store/fact.ts'
9
+ import type { MediaKind, MediaRow } from '../media-store/kind.ts'
10
+ import { fetchBack } from '../media-store/remote.ts'
11
+ import { isFrame } from './model.ts'
12
+ import { readAllCached, storeDir } from './store.ts'
13
+ import { cutOf, cutsOf, pngSize, stripOf, TRAILER_KIND, trailerDir, trailerIds, trailerKey, trailerStamp, videoOf, VIEW_ITEM, viewDir, viewOf, writeView, type View } from './trailer-desk.ts'
14
+ import { noteOf } from './trailer-model.ts'
15
+
16
+ /** a view record's name, `<trailer>--<cut>--<mtime>` */
17
+ const BASE_RE = /^(.+?)--(.+)--(\d+)$/
18
+
19
+ interface ViewRecord {
20
+ base: string
21
+ id: string
22
+ cut: string
23
+ v: View
24
+ }
25
+
26
+ function records(root: string): ViewRecord[] {
27
+ const d = viewDir(root)
28
+ if (!existsSync(d)) return []
29
+ return readdirSync(d)
30
+ .filter((f) => f.endsWith('.json'))
31
+ .sort()
32
+ .flatMap((f) => {
33
+ const base = f.slice(0, -'.json'.length)
34
+ const m = BASE_RE.exec(base)
35
+ if (!m) return []
36
+ try {
37
+ return [{ base, id: m[1]!, cut: m[2]!, v: JSON.parse(readFileSync(join(d, f), 'utf8')) as View }]
38
+ } catch {
39
+ return []
40
+ }
41
+ })
42
+ }
43
+
44
+ const sizeOf = (p: string): number | undefined => statSync(p, { throwIfNoEntry: false })?.size
45
+
46
+ /** a version's own file, recorded only when its bytes are the clone's */
47
+ async function sameAs(root: string, file: string, f: MediaFact): Promise<string | undefined> {
48
+ return existsSync(file) && sizeOf(file) === f.size && (await shaOf(file)) === f.sha ? relative(root, file) : undefined
49
+ }
50
+
51
+ export const trailerMedia: MediaKind = {
52
+ kind: TRAILER_KIND,
53
+ storeOf: (root) => (existsSync(join(root, 'trailer')) ? root : null),
54
+ stamp: (root) => `${trailerStamp(root)}#${existsSync(viewDir(root)) ? readdirSync(viewDir(root)).length : 0}`,
55
+ async scan(root, o) {
56
+ // every settled render gets its record, whether or not the page was opened since
57
+ for (const id of trailerIds(root)) {
58
+ const dir = trailerDir(root, id)
59
+ if (dir) for (const c of cutsOf(dir)) viewOf(root, dir, id, c)
60
+ }
61
+ const rows: MediaRow[] = []
62
+ let budget = o.fill
63
+ let filled = 0
64
+ let left = 0
65
+ const take = (): boolean => {
66
+ if (budget <= 0) {
67
+ left++
68
+ return false
69
+ }
70
+ budget--
71
+ filled++
72
+ return true
73
+ }
74
+ for (const r of records(root)) {
75
+ const media = { ...r.v.media }
76
+ let moved = false
77
+ const video = join(viewDir(root), `${r.base}.mp4`)
78
+ const strip = join(viewDir(root), `${r.base}.strip.png`)
79
+ if (!media.video && existsSync(video) && take()) {
80
+ media.video = await factOf(video)
81
+ moved = true
82
+ }
83
+ if (!media.strip && existsSync(strip) && take()) {
84
+ media.strip = await factOf(strip)
85
+ media.stripSize = pngSize(strip)
86
+ moved = true
87
+ }
88
+ const dir = trailerDir(root, r.id)
89
+ const c = dir ? cutOf(dir, r.cut) : null
90
+ if (!media.from && c?.version && dir && media.video && (media.strip || !existsSync(strip)) && take()) {
91
+ const own = videoOf(dir, c)
92
+ const from = {
93
+ ...(Math.round(statSync(own, { throwIfNoEntry: false })?.mtimeMs ?? -1) === r.v.mtime ? { video: await sameAs(root, own, media.video) } : {}),
94
+ ...(media.strip ? { strip: await sameAs(root, stripOf(dir, c), media.strip) } : {}),
95
+ }
96
+ media.from = Object.fromEntries(Object.entries(from).filter(([, x]) => x !== undefined))
97
+ moved = true
98
+ }
99
+ if (moved) writeView(root, r.id, r.cut, { ...r.v, media })
100
+ const row = (path: string, f: MediaFact | undefined): void => {
101
+ const s = sizeOf(path)
102
+ if (!f) {
103
+ if (s === undefined) rows.push({ item: relative(root, dirname(path)), name: basename(path), fact: null, local: false })
104
+ return
105
+ }
106
+ // a file of another content at that place is never this record's
107
+ if (s !== undefined && s !== f.size) return
108
+ rows.push({ item: relative(root, dirname(path)), name: basename(path), fact: f, local: s === f.size })
109
+ }
110
+ row(video, media.video)
111
+ if (media.strip || existsSync(strip)) row(strip, media.strip)
112
+ if (media.from?.video) row(join(root, media.from.video), media.video)
113
+ if (media.from?.strip) row(join(root, media.from.strip), media.strip)
114
+ }
115
+ return { rows, filled, left }
116
+ },
117
+ async holds(root) {
118
+ const recs = records(root)
119
+ const owner = new Map<string, ViewRecord>()
120
+ for (const r of recs) {
121
+ owner.set(`${VIEW_ITEM}/${r.base}.mp4`, r)
122
+ owner.set(`${VIEW_ITEM}/${r.base}.strip.png`, r)
123
+ for (const p of Object.values(r.v.media?.from ?? {})) if (p) owner.set(`${dirname(p)}/${basename(p)}`, r)
124
+ }
125
+ // the newest render of each live cut: the one the page plays first, and the cut's out/ file is that render
126
+ const newest = new Map<string, number>()
127
+ const live = new Set(trailerIds(root).flatMap((id) => cutsOf(join(root, 'trailer', id)).filter((c) => !c.version).map((c) => `${id}--${c.cut}`)))
128
+ for (const r of recs) if (live.has(`${r.id}--${r.cut}`)) newest.set(`${r.id}--${r.cut}`, Math.max(newest.get(`${r.id}--${r.cut}`) ?? 0, r.v.mtime))
129
+ const open = new Set<string>()
130
+ const used = new Map<string, number>()
131
+ for (const x of readAllCached(storeDir(root)).items) {
132
+ const s = x.item.subject
133
+ if (!isFrame(s)) continue
134
+ const base = `${s.trailer}--${s.cut}--${s.version}`
135
+ if (noteOf(x, 0)?.state === 'open') open.add(base)
136
+ const at = Math.max(Date.parse(x.item.created) || 0, ...x.thread.map((m) => Date.parse(m.at) || 0))
137
+ used.set(base, Math.max(used.get(base) ?? 0, at))
138
+ }
139
+ return (row) => {
140
+ const r = owner.get(`${row.item}/${row.name}`)
141
+ if (!r) return { pinned: false, used: undefined }
142
+ const pinned = newest.get(`${r.id}--${r.cut}`) === r.v.mtime || open.has(r.base)
143
+ return { pinned, used: Math.max(r.v.mtime, used.get(r.base) ?? 0) }
144
+ }
145
+ },
146
+ async beforePurge(root, _space, r) {
147
+ const want = shaOfKey(r.key)
148
+ const path = join(root, r.item, r.name)
149
+ if (!want || (await shaOf(path)) !== want) throw new Error(`${path} does not hash to its key ${r.key}: kept`)
150
+ },
151
+ }
152
+
153
+ /** a kept version's video on the disk, fetched back from the media store when the disk let it go; null when neither */
154
+ export async function versionVideoBack(root: string, id: string, v: string): Promise<string | null> {
155
+ for (const r of records(root).filter((x) => x.id === id && x.cut === v)) {
156
+ const from = r.v.media?.from?.video
157
+ const f = r.v.media?.video
158
+ if (!from || !f) continue
159
+ const path = join(root, from)
160
+ return fetchBack(path, trailerKey(f, 'video'), f, { store: root, item: dirname(from), name: basename(from) })
161
+ }
162
+ return null
163
+ }
@@ -7,7 +7,7 @@ import { join, relative } from 'node:path'
7
7
  import { bad, NO_STORE, ranged } from './http.ts'
8
8
  import { ID_RE, isFrame } from './model.ts'
9
9
  import { act, appendMessage, deleteRaised, raiseItem, readAllCached, readItem } from './store.ts'
10
- import { cutOf, frameNote, montagePage, trailerDir, trailerIds, trailerInfo, videoOf, viewStrip, viewVideo } from './trailer-desk.ts'
10
+ import { cutOf, frameNote, montagePage, trailerDir, trailerIds, trailerInfo, videoOf, viewMedia } from './trailer-desk.ts'
11
11
  import { CUT_RE, noteOf, TRAILER_ID_RE, type NotePin, type NoteState, type TrailerDesk } from './trailer-model.ts'
12
12
 
13
13
  const clamp = (v: number): number => Number(Math.min(1, Math.max(0, v)).toFixed(4))
@@ -54,7 +54,10 @@ export async function trailerRoutes(req: Request, path: string, root: string, di
54
54
  if (media && req.method === 'GET') {
55
55
  const [, kind, id = '', cut = '', version = ''] = media
56
56
  if (!TRAILER_ID_RE.test(id) || !CUT_RE.test(cut)) return bad(`${path}?`, 404)
57
- return ranged(req, kind === 'video' ? viewVideo(root, id, cut, Number(version)) : viewStrip(root, id, cut, Number(version)))
57
+ const at = await viewMedia(root, id, cut, Number(version), kind === 'video' ? 'video' : 'strip')
58
+ if (!at) return bad(`no render ${id}/${cut} at ${version}: neither the disk nor the media store holds it`, 404)
59
+ // a render the disk let go plays from the Space: the signed URL lives an hour, the browser keeps half of it
60
+ return 'path' in at ? ranged(req, at.path) : new Response(null, { status: 302, headers: { Location: at.url, 'Cache-Control': 'private, max-age=1800' } })
58
61
  }
59
62
  const mont = /^\/api\/trailer\/montage\/([^/]+)\/([^/]+)$/.exec(path)
60
63
  if (mont && req.method === 'GET') {