rvlib-shipkit 2.10.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.
Files changed (73) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/package.json +1 -1
  3. package/src/cli/cmd_Media.ts +253 -0
  4. package/src/cli/cmd_Review.ts +4 -0
  5. package/src/cli/cmd_Trailer.ts +4 -0
  6. package/src/cli/family-pages.ts +1 -0
  7. package/src/cli/registry.ts +2 -0
  8. package/src/collections/pings.ts +6 -4
  9. package/src/core/app-icon.ts +17 -4
  10. package/src/core/scratch-objects.ts +56 -0
  11. package/src/core/trace-audit.ts +13 -1
  12. package/src/home/home-paths.ts +4 -0
  13. package/src/home/home-routes.ts +36 -2
  14. package/src/home/hubs.ts +5 -0
  15. package/src/home/inbox-shape.ts +188 -0
  16. package/src/home/inbox.ts +104 -0
  17. package/src/home/run-daemon.ts +12 -2
  18. package/src/home/serve-web.ts +161 -16
  19. package/src/ledger/git-scan.ts +73 -25
  20. package/src/ledger/repo-view.ts +2 -22
  21. package/src/media-kinds.ts +14 -0
  22. package/src/media-store/content.ts +61 -0
  23. package/src/media-store/daemon.ts +91 -0
  24. package/src/media-store/db.ts +74 -0
  25. package/src/media-store/fact.ts +9 -0
  26. package/src/media-store/hand.ts +58 -0
  27. package/src/media-store/kind.ts +44 -0
  28. package/src/media-store/purge.ts +139 -0
  29. package/src/media-store/put.ts +120 -0
  30. package/src/media-store/remote.ts +93 -0
  31. package/src/media-store/space.ts +167 -0
  32. package/src/media-store/sync.ts +101 -0
  33. package/src/media-store/upload.ts +98 -0
  34. package/src/repo-config.ts +4 -0
  35. package/src/review/anim.ts +6 -5
  36. package/src/review/cells.ts +5 -1
  37. package/src/review/media-kind.ts +84 -0
  38. package/src/review/media-read.ts +48 -0
  39. package/src/review/model.ts +22 -1
  40. package/src/review/previews.ts +41 -12
  41. package/src/review/routes.ts +32 -8
  42. package/src/review/store.ts +102 -40
  43. package/src/review/trailer-desk.ts +79 -46
  44. package/src/review/trailer-media.ts +181 -0
  45. package/src/review/trailer-routes.ts +5 -2
  46. package/src/review/trailer-shots.ts +89 -0
  47. package/src/serve/hub-app/cols-svc.ts +12 -1
  48. package/src/serve/hub-app/home-st.ts +39 -9
  49. package/src/serve/hub-app/home.html +2 -1
  50. package/src/serve/hub-app/hub-app.tsx +7 -23
  51. package/src/serve/hub-app/icons.tsx +2 -0
  52. package/src/serve/hub-app/inbox-st.ts +144 -0
  53. package/src/serve/hub-app/inbox-view.tsx +205 -0
  54. package/src/serve/hub-app/inbox.css +73 -0
  55. package/src/serve/hub-app/item-view.tsx +19 -0
  56. package/src/serve/hub-app/keys.ts +4 -3
  57. package/src/serve/hub-app/palette-st.ts +2 -1
  58. package/src/serve/hub-app/project-list.tsx +1 -0
  59. package/src/serve/hub-app/projects-svc.ts +1 -1
  60. package/src/serve/hub-app/repo-st.ts +1 -1
  61. package/src/serve/hub-app/review/review-st.ts +15 -3
  62. package/src/serve/hub-app/review/review-thread.tsx +5 -4
  63. package/src/serve/hub-app/review.css +1 -1
  64. package/src/serve/hub-app/test-view.tsx +9 -2
  65. package/src/serve/hub-app/tests-svc.ts +16 -1
  66. package/src/serve/hub-runtime.ts +9 -4
  67. package/src/serve/resources-wire.ts +48 -0
  68. package/src/serve/serve-hub.ts +11 -7
  69. package/src/serve/warm-cell.ts +6 -1
  70. package/src/trailer/footage.ts +6 -2
  71. package/src/trailer/passage.ts +8 -3
  72. package/src/trailer/prune.ts +6 -10
  73. package/src/trailer/shelf.ts +16 -0
@@ -0,0 +1,98 @@
1
+ // every object the index holds on the disk and not up, sent to the Space: a HEAD first (a file already there is only
2
+ // marked), the PUT, then a HEAD of the same size before it counts as up. A failure waits 1 min, doubling up to 6 h
3
+ import { statSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { typeOf } from './content.ts'
6
+ import { mediaDb, tryWrite } from './db.ts'
7
+ import { recordUp } from './remote.ts'
8
+ import type { Space } from './space.ts'
9
+
10
+ const RETRY_MS = 60_000
11
+ const RETRY_MAX_MS = 6 * 3600_000
12
+
13
+ export interface Waiting {
14
+ key: string
15
+ size: number
16
+ path: string
17
+ }
18
+
19
+ /** the objects waiting with a local copy, oldest retry first; `store` limits them to one store */
20
+ export function waitingObjects(o: { now?: number; limit?: number; store?: string } = {}): Waiting[] {
21
+ const db = mediaDb()
22
+ if (!db) return []
23
+ const rows = db
24
+ .query(
25
+ `select o.key as key, o.size as size, min(f.store || char(0) || f.item || char(0) || f.name) as at
26
+ from objects o join files f on f.key = o.key and f.local = 1
27
+ where o.up is null and o.next <= ? ${o.store ? 'and f.store = ?' : ''}
28
+ group by o.key order by o.next, o.key limit ?`,
29
+ )
30
+ .all(...([o.now ?? Date.now(), ...(o.store ? [o.store] : []), o.limit ?? 1_000_000] as [number, ...(string | number)[]])) as { key: string; size: number; at: string }[]
31
+ return rows.map((r) => {
32
+ const [store = '', item = '', name = ''] = r.at.split('\0')
33
+ return { key: r.key, size: r.size, path: join(store, item, name) }
34
+ })
35
+ }
36
+
37
+ export interface UploadResult {
38
+ up: number
39
+ /** already in the Space: marked, not sent */
40
+ there: number
41
+ bytes: number
42
+ failed: { key: string; error: string }[]
43
+ }
44
+
45
+ /** one object up: true when it was sent, false when the Space already held it; throws with the reason */
46
+ export async function uploadOne(space: Space, w: Waiting): Promise<boolean> {
47
+ const size = statSync(w.path, { throwIfNoEntry: false })?.size
48
+ if (size !== w.size) throw new Error(`${w.path}: ${size === undefined ? 'gone' : `${size} bytes, the index says ${w.size}`}`)
49
+ const before = await space.head(w.key)
50
+ if (before?.size === w.size) {
51
+ recordUp(w.key, w.size)
52
+ return false
53
+ }
54
+ await space.put(w.key, w.path, typeOf(w.path))
55
+ const after = await space.head(w.key)
56
+ if (after?.size !== w.size) throw new Error(`${w.key}: the Space holds ${after ? `${after.size} bytes` : 'nothing'} after the upload, ${w.size} sent`)
57
+ recordUp(w.key, w.size)
58
+ return true
59
+ }
60
+
61
+ /** every waiting object (or `limit` of them), `jobs` at a time; `say` hears progress lines */
62
+ export async function uploadWaiting(space: Space, o: { limit?: number; jobs?: number; store?: string; now?: number; say?: (l: string) => void } = {}): Promise<UploadResult> {
63
+ const list = waitingObjects({ ...(o.limit !== undefined ? { limit: o.limit } : {}), ...(o.store ? { store: o.store } : {}), ...(o.now !== undefined ? { now: o.now } : {}) })
64
+ const out: UploadResult = { up: 0, there: 0, bytes: 0, failed: [] }
65
+ const total = list.reduce((n, w) => n + w.size, 0)
66
+ let next = 0
67
+ let done = 0
68
+ let said = Date.now()
69
+ const work = async (): Promise<void> => {
70
+ for (;;) {
71
+ const w = list[next++]
72
+ if (!w) return
73
+ try {
74
+ if (await uploadOne(space, w)) {
75
+ out.up++
76
+ out.bytes += w.size
77
+ } else out.there++
78
+ } catch (e) {
79
+ const error = (e as Error).message
80
+ out.failed.push({ key: w.key, error })
81
+ tryWrite(`${w.key} failed`, (db) => {
82
+ const r = db.query('select tries from objects where key = ?').get(w.key) as { tries: number } | null
83
+ const tries = (r?.tries ?? 0) + 1
84
+ db.query('update objects set tries = ?, next = ?, error = ? where key = ?').run(tries, Date.now() + Math.min(RETRY_MS * 2 ** (tries - 1), RETRY_MAX_MS), error, w.key)
85
+ })
86
+ }
87
+ done += w.size
88
+ if (o.say && Date.now() - said > 10_000) {
89
+ said = Date.now()
90
+ o.say(` ${out.up + out.there + out.failed.length}/${list.length} objects, ${mb(done)} of ${mb(total)}`)
91
+ }
92
+ }
93
+ }
94
+ await Promise.all(Array.from({ length: Math.max(1, o.jobs ?? 4) }, work))
95
+ return out
96
+ }
97
+
98
+ export const mb = (b: number): string => (b >= 1e9 ? `${(b / 1e9).toFixed(2)} GB` : `${(b / 1e6).toFixed(1)} MB`)
@@ -70,6 +70,10 @@ export type ServeConfig = {
70
70
  /** the ids of the global processes this repo needs (any house repo's
71
71
  * `globalProcess` unit files). The home rail marks the repo while one is off */
72
72
  uses?: string[]
73
+ /** the house's private S3 bucket that keeps every file of the machine's
74
+ * media store (review cards, trailer cuts...), read only in the house
75
+ * config; its key pair read through `credsReadCommand` */
76
+ mediaSpace?: import('./media-store/space.ts').MediaSpace
73
77
  }
74
78
 
75
79
  export type RepoConfig = {
@@ -7,7 +7,8 @@ import { basename, join, resolve } from 'node:path'
7
7
  import { ffmpeg } from '../trailer/ffmpeg.ts'
8
8
  import { sizeOf } from './media.ts'
9
9
  import { isGallery, isPair } from './model.ts'
10
- import { imageFile, readItem } from './store.ts'
10
+ import { ensureLocal } from './media-read.ts'
11
+ import { readItem } from './store.ts'
11
12
 
12
13
  export const ANIM_MODES = ['cut', 'fade', 'wipe'] as const
13
14
  export type AnimMode = (typeof ANIM_MODES)[number]
@@ -156,7 +157,7 @@ function graph(mode: AnimMode, w: number, h: number, fps: number, labels: boolea
156
157
  const making = new Map<string, Promise<Anim>>()
157
158
 
158
159
  /** the animation of view `ask.view` of card `id`, made once and kept under `<dir>/.anims/` (readAll skips dot names) */
159
- export function pairAnimation(dir: string, id: string, ask: AnimAsk): Promise<Anim> {
160
+ export async function pairAnimation(dir: string, id: string, ask: AnimAsk): Promise<Anim> {
160
161
  const x = readItem(dir, id)
161
162
  if (!x) return Promise.reject(new Error(`no card ${id}`))
162
163
  const v = x.item.views[ask.view]
@@ -164,14 +165,14 @@ export function pairAnimation(dir: string, id: string, ask: AnimAsk): Promise<An
164
165
  if (isGallery(v) || !isPair(v.files)) return Promise.reject(new Error(`view ${ask.view} of ${id} is not a before and after`))
165
166
  if (v.clip) return Promise.reject(new Error(`view ${ask.view} of ${id} is a pair of clips: no animation`))
166
167
  if (v.audio) return Promise.reject(new Error(`view ${ask.view} of ${id} is a pair of sounds: no animation`))
167
- const before = imageFile(dir, id, v.files.before)
168
- const after = imageFile(dir, id, v.files.after)
168
+ // a pair the disk let go comes back from the Space first
169
+ const [before, after] = await Promise.all([ensureLocal(dir, id, v.files.before), ensureLocal(dir, id, v.files.after)])
169
170
  if (!before || !after) return Promise.reject(new Error(`view ${ask.view} of ${id}: an image is missing`))
170
171
  const viewPart = ask.view > 0 ? `-${asciiName(v.label || `view-${ask.view + 1}`, 30)}` : ''
171
172
  const name = `${asciiName(x.item.title)}${viewPart}-${ask.mode}.${ask.format}`
172
173
  const out = join(dir, '.anims', id, `L${LOOK}-v${ask.view}-${ask.mode}-${ask.labels}.${ask.format}`)
173
174
  const newest = Math.max(statSync(before).mtimeMs, statSync(after).mtimeMs)
174
- if (existsSync(out) && statSync(out).mtimeMs >= newest) return Promise.resolve({ file: out, name, ms: 0 })
175
+ if (existsSync(out) && statSync(out).mtimeMs >= newest) return { file: out, name, ms: 0 }
175
176
  const pending = making.get(out)
176
177
  if (pending) return pending
177
178
  const job = render(before, after, out, v.size, ask)
@@ -430,6 +430,8 @@ export interface ThreadIndex {
430
430
  counts: ThreadPage['counts']
431
431
  subjects: string[]
432
432
  lanes: string[]
433
+ /** the heads that wait on the owner, the threads `counts.waiting` counts */
434
+ waiting: ReadonlySet<string>
433
435
  }
434
436
 
435
437
  function rowOf(t: Thread, items: readonly ReviewItem[], followed: ReadonlySet<string>, now: Date): ThreadRow {
@@ -481,11 +483,13 @@ const textOf = (t: Thread): string =>
481
483
  export function threadIndex(items: readonly ReviewItem[], now = new Date()): ThreadIndex {
482
484
  const followed = followedIds(items)
483
485
  const entries = orderedThreads(items).map((t) => ({ t, row: rowOf(t, items, followed, now), text: textOf(t) }))
486
+ const waiting = new Set(waitingOnOwner(items).map((t) => t.head.item.id))
484
487
  return {
485
488
  entries,
486
- counts: { threads: entries.length, active: entries.filter((e) => e.row.active).length, waiting: waitingOnOwner(items).length },
489
+ counts: { threads: entries.length, active: entries.filter((e) => e.row.active).length, waiting: waiting.size },
487
490
  subjects: [...new Set(items.map((x) => x.item.subject.kind))].sort(),
488
491
  lanes: [...new Set(entries.flatMap((e) => (e.row.lane ? [e.row.lane] : [])))].sort(),
492
+ waiting,
489
493
  }
490
494
  }
491
495
 
@@ -0,0 +1,84 @@
1
+ // the review store as a kind of the media store (wiki build/shipkit/review.md, Media in the Space): each file a card's
2
+ // views name, by the facts its item.json keeps; kept on the disk while its thread is active or spoke in the window; an
3
+ // image's previews sent up before it goes
4
+ import { existsSync, statSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import type { MediaKind, MediaRow } from '../media-store/kind.ts'
7
+ import { isUp, recordUp } from '../media-store/remote.ts'
8
+ import type { Space } from '../media-store/space.ts'
9
+ import { threadIndex } from './cells.ts'
10
+ import { previewKey, REVIEW_KIND } from './media-read.ts'
11
+ import { mediaFilesOf } from './model.ts'
12
+ import { previewFile, PREVIEW_W, type PreviewSize } from './previews.ts'
13
+ import { fillMedia, readAll, readAllCached, storeDir, storeStamp } from './store.ts'
14
+ import { membersOf } from './threads.ts'
15
+
16
+ const IMAGE = /\.(png|jpe?g|webp)$/i
17
+
18
+ export const reviewMedia: MediaKind = {
19
+ kind: REVIEW_KIND,
20
+ storeOf: (root) => storeDir(root),
21
+ stamp: (dir) => storeStamp(dir),
22
+ async scan(dir, o) {
23
+ const rows: MediaRow[] = []
24
+ let budget = o.fill
25
+ let filled = 0
26
+ let left = 0
27
+ for (const x of readAllCached(dir).items) {
28
+ const id = x.item.id
29
+ let item = x.item
30
+ const names = mediaFilesOf({ item, thread: x.thread })
31
+ if (names.length === 0) continue
32
+ const size = (n: string): number | undefined => statSync(join(dir, id, n), { throwIfNoEntry: false })?.size
33
+ const lacks = names.some((n) => {
34
+ const s = size(n)
35
+ return s !== undefined && item.media?.[n]?.size !== s
36
+ })
37
+ if (lacks) {
38
+ if (budget > 0) {
39
+ budget--
40
+ item = (await fillMedia(dir, id)) ?? item
41
+ filled++
42
+ } else left++
43
+ }
44
+ for (const n of new Set(names)) {
45
+ const f = item.media?.[n] ?? null
46
+ const s = size(n)
47
+ rows.push({ item: id, name: n, fact: f, local: s !== undefined && (f === null || s === f.size) })
48
+ }
49
+ }
50
+ return { rows, filled, left }
51
+ },
52
+ async holds(dir, now) {
53
+ const ix = threadIndex(readAll(dir).items, new Date(now))
54
+ const used = new Map<string, number>()
55
+ const pinned = new Set<string>()
56
+ for (const e of ix.entries) {
57
+ const at = Date.parse(e.row.updated)
58
+ for (const x of membersOf(e.t)) {
59
+ if (e.row.active) pinned.add(x.item.id)
60
+ used.set(x.item.id, Math.max(used.get(x.item.id) ?? 0, at))
61
+ }
62
+ }
63
+ return (r) => ({ pinned: pinned.has(r.item), used: used.get(r.item) })
64
+ },
65
+ async beforePurge(dir, space, r) {
66
+ if (IMAGE.test(r.name) && !r.name.startsWith('thread/')) await previewsUp(dir, space, r)
67
+ },
68
+ }
69
+
70
+ /** an image's previews made (when the cache lacks them) and sent up, before the image leaves the disk: a PUT and a
71
+ * HEAD each, none for a preview the index saw up */
72
+ async function previewsUp(dir: string, space: Space, r: { item: string; name: string; key: string }): Promise<void> {
73
+ const sha = r.key.slice(`${REVIEW_KIND}/`.length).replace(/\.[^.]+$/, '')
74
+ for (const size of Object.keys(PREVIEW_W) as PreviewSize[]) {
75
+ const key = previewKey({ sha }, size)
76
+ // up already: a card that shares the image, or a purge that stopped after it
77
+ if (isUp(key)) continue
78
+ const file = await previewFile(dir, r.item, r.name, size)
79
+ if (!file || !existsSync(file)) continue
80
+ const n = statSync(file).size
81
+ await space.put(key, file, 'image/webp')
82
+ if ((await space.head(key))?.size === n) recordUp(key, n)
83
+ }
84
+ }
@@ -0,0 +1,48 @@
1
+ // the reads a route or a tool makes of a card's file (wiki build/shipkit/review.md, Media in the Space): its key in the
2
+ // Space by the facts its item.json keeps, a URL signed for a file the disk let go, the file fetched back for its bytes
3
+ import { existsSync, readFileSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { mediaKey } from '../media-store/content.ts'
6
+ import type { MediaFact } from '../media-store/fact.ts'
7
+ import { fetchBack, signedIfUp, signedUrl } from '../media-store/remote.ts'
8
+ import { ID_RE, isMediaName } from './model.ts'
9
+
10
+ export const REVIEW_KIND = 'review'
11
+
12
+ /** where the Space keeps a file of a card */
13
+ export const reviewKey = (f: Pick<MediaFact, 'sha'>, name: string): string => mediaKey(REVIEW_KIND, f, name)
14
+ /** where the Space keeps an image's preview at a size: by the image's own sha, so it is found from the item alone */
15
+ export const previewKey = (f: Pick<MediaFact, 'sha'>, size: string): string => `${REVIEW_KIND}/${f.sha}.${size}.webp`
16
+
17
+ /** the fact a head keeps for one of its files, read from its item.json alone */
18
+ export function factOfFile(dir: string, id: string, name: string): MediaFact | null {
19
+ if (!ID_RE.test(id) || !isMediaName(name)) return null
20
+ try {
21
+ const head = JSON.parse(readFileSync(join(dir, id, 'item.json'), 'utf8')) as { media?: Record<string, MediaFact> }
22
+ return head.media?.[name] ?? null
23
+ } catch {
24
+ return null
25
+ }
26
+ }
27
+
28
+ /** a signed URL for a file of an item that the disk no longer holds and the Space does; null otherwise */
29
+ export async function remoteUrl(dir: string, id: string, name: string): Promise<string | null> {
30
+ const f = factOfFile(dir, id, name)
31
+ return f ? signedUrl(reviewKey(f, name), f.size) : null
32
+ }
33
+
34
+ /** a signed URL for an image's preview at a size, when the Space holds it */
35
+ export async function remotePreviewUrl(dir: string, id: string, name: string, size: string): Promise<string | null> {
36
+ const f = factOfFile(dir, id, name)
37
+ return f ? signedIfUp(previewKey(f, size)) : null
38
+ }
39
+
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
+ * holds it */
42
+ export async function ensureLocal(dir: string, id: string, name: string): Promise<string | null> {
43
+ if (!ID_RE.test(id) || !isMediaName(name)) return null
44
+ const path = join(dir, id, name)
45
+ if (existsSync(path)) return path
46
+ const f = factOfFile(dir, id, name)
47
+ return f ? fetchBack(path, reviewKey(f, name), f, { store: dir, item: id, name }) : null
48
+ }
@@ -3,6 +3,7 @@
3
3
  // (verdicts, replies, ratings, state changes, read marks). The state is derived from the thread, never stored, so the
4
4
  // hub and every CLI write at once with no lost update. Pure and browser safe: the store, the routes and the hub page
5
5
  // share it. The on disk shape is pkm-multi's (scripts/review/store.ts) verbatim, so either store opens in the other.
6
+ import type { MediaFact } from '../media-store/fact.ts'
6
7
 
7
8
  /** WHAT is judged: `shot` (a plain image or clip), `screen`, `frame` (a frame of a trailer cut), or a kind a repo names
8
9
  * for itself (pkm-multi's place, creature, song...), read as is */
@@ -145,7 +146,10 @@ export type ReviewView = MediaView | GalleryView
145
146
 
146
147
  export const isGallery = (v: ReviewView): v is GalleryView => 'gallery' in v
147
148
 
148
- /** `item.json`: the head, written at creation, changed only by `add-view` */
149
+
150
+ export const SHA_RE = /^[0-9a-f]{64}$/
151
+
152
+ /** `item.json`: the head, written at creation, changed by `add-view`, a draft's refresh and the media facts it lacks */
149
153
  export interface Item {
150
154
  id: string
151
155
  /** ISO time */
@@ -172,6 +176,8 @@ export interface Item {
172
176
  wip?: { live: string; frame: number }
173
177
  /** a choice: every view is an option, he scores them and picks one */
174
178
  choice?: true
179
+ /** each media file the views name, by its name: what the Space keeps it under once the disk lets it go */
180
+ media?: Record<string, MediaFact>
175
181
  }
176
182
 
177
183
  /** a choice card: he picks one of its views */
@@ -644,6 +650,14 @@ export function untakenOf(x: ReviewItem, superseded: boolean, watchers: readonly
644
650
 
645
651
  export const ID_RE = /^\d{8}-\d{6}-[a-z0-9-]+$/
646
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)
647
661
  const TILE_RE = /^v\d+-g\d+\.(png|jpe?g|webp)$/
648
662
  const POSTER_RE = /^(v\d+-)?poster\.png$/
649
663
 
@@ -747,6 +761,13 @@ export function itemProblems(v: unknown): string[] {
747
761
  if (v.light !== undefined && v.light !== 'review') out.push('light: review, or absent')
748
762
  if (v.wip !== undefined && !(obj(v.wip) && typeof v.wip.live === 'string' && v.wip.live !== '' && Number.isInteger(v.wip.frame))) out.push('wip: { live, frame }, or absent')
749
763
  if (v.choice !== undefined && !(v.choice === true && Array.isArray(v.views) && v.views.length >= 2)) out.push('choice: true on a card of two views or more, or absent')
764
+ if (v.media !== undefined) {
765
+ if (!obj(v.media)) out.push('media: { <file name>: { sha, size, type } }, or absent')
766
+ else
767
+ for (const [n, f] of Object.entries(v.media))
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')
769
+ out.push(`media.${n}: a file of the item, { sha: sha256 hex, size: bytes, type }`)
770
+ }
750
771
  return out
751
772
  }
752
773
 
@@ -4,9 +4,9 @@
4
4
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs'
5
5
  import { dirname, join } from 'node:path'
6
6
  import { LAYOUT } from '../core/layout.ts'
7
- import { firstView, isGallery, isPair, thumbFileOf, type Item, type ReviewItem } from './model.ts'
7
+ import { FILE_RE, firstView, ID_RE, isGallery, isPair, thumbFileOf, type Item, type ReviewItem } from './model.ts'
8
8
  import { probe, stillAt } from './media.ts'
9
- import { imageFile } from './store.ts'
9
+ import { ensureLocal, remotePreviewUrl } from './media-read.ts'
10
10
 
11
11
  /** `thumb` a list row's picture, `fit` a view in the card column: the widest each is drawn, at 2x */
12
12
  export const PREVIEW_W = { thumb: 480, fit: 1600 } as const
@@ -34,14 +34,19 @@ async function slot<T>(work: () => Promise<T>): Promise<T> {
34
34
  /** the preview folder of a store: `<repo>/.shipkit/cache/review-previews`, the store being `<repo>/.shipkit/review` */
35
35
  export const previewDir = (dir: string): string => join(dirname(dirname(dir)), LAYOUT.cache, 'review-previews')
36
36
 
37
+ // a poster's preview may come from a lit frame of its clip: its own name, so the black ones made before are not reused
38
+ const outOf = (dir: string, id: string, name: string, size: PreviewSize): string => join(previewDir(dir), id, `${name}.${size}${POSTER.test(name) ? '.lit' : ''}.webp`)
39
+
37
40
  /** the preview of an item's image at a size, made on the first ask; null when the name is no image of the item or
38
- * the image does not read */
39
- export function previewFile(dir: string, id: string, name: string, size: PreviewSize): Promise<string | null> {
40
- const src = imageFile(dir, id, name)
41
- if (!src || !IMAGE.test(name)) return Promise.resolve(null)
42
- // a poster's preview may come from a lit frame of its clip: its own name, so the black ones made before are not reused
43
- const out = join(previewDir(dir), id, `${name}.${size}${POSTER.test(name) ? '.lit' : ''}.webp`)
44
- if (existsSync(out) && statSync(out).mtimeMs >= statSync(src).mtimeMs) return Promise.resolve(out)
41
+ * the image does not read. A made preview of an image the disk let go stays good; else the image is fetched back */
42
+ export async function previewFile(dir: string, id: string, name: string, size: PreviewSize): Promise<string | null> {
43
+ if (!ID_RE.test(id) || !FILE_RE.test(name) || !IMAGE.test(name)) return null
44
+ const out = outOf(dir, id, name, size)
45
+ const here = join(dir, id, name)
46
+ if (!existsSync(here) && existsSync(out)) return out
47
+ const src = await ensureLocal(dir, id, name)
48
+ if (!src) return null
49
+ if (existsSync(out) && statSync(out).mtimeMs >= statSync(src).mtimeMs) return out
45
50
  const pending = making.get(out)
46
51
  if (pending) return pending
47
52
  const job = slot(async () => {
@@ -66,6 +71,20 @@ export function previewFile(dir: string, id: string, name: string, size: Preview
66
71
  return job
67
72
  }
68
73
 
74
+ /** every preview being made has landed: a test removes its folder only after */
75
+ export const previewsSettled = async (): Promise<void> => void (await Promise.all([...making.values()]))
76
+
77
+ /** a preview to answer: its file, or when neither it nor its image is on the disk, a signed URL of the Space's copy */
78
+ export async function previewOrRemote(dir: string, id: string, name: string, size: PreviewSize): Promise<{ file: string } | { url: string } | null> {
79
+ if (!ID_RE.test(id) || !FILE_RE.test(name) || !IMAGE.test(name)) return null
80
+ if (!existsSync(join(dir, id, name)) && !existsSync(outOf(dir, id, name, size))) {
81
+ const url = await remotePreviewUrl(dir, id, name, size)
82
+ if (url) return { url }
83
+ }
84
+ const file = await previewFile(dir, id, name, size)
85
+ return file ? { file } : null
86
+ }
87
+
69
88
 
70
89
  const POSTER = /^(v\d+-)?poster\.png$/
71
90
  /** a picture whose brightest channel averages under this is black: a trailer's first frame fades in from black */
@@ -85,9 +104,10 @@ const isBlack = async (png: string): Promise<boolean> => {
85
104
  async function litStill(dir: string, id: string, name: string, poster: string, out: string): Promise<string> {
86
105
  if (!(await isBlack(poster))) return poster
87
106
  const prefix = name.slice(0, name.length - 'poster.png'.length)
88
- const clip = readdirSync(join(dir, id)).find((f) => new RegExp(`^${prefix}(video|after)\\.(mp4|webm)$`).test(f))
89
- if (!clip) return poster
90
- const video = join(dir, id, clip)
107
+ const clipRe = new RegExp(`^${prefix}(video|after)\\.(mp4|webm)$`)
108
+ const clip = readdirSync(join(dir, id)).find((f) => clipRe.test(f)) ?? Object.keys(mediaOf(dir, id)).find((f) => clipRe.test(f))
109
+ const video = clip ? await ensureLocal(dir, id, clip) : null
110
+ if (!video) return poster
91
111
  const still = `${out}.still.png`
92
112
  try {
93
113
  const { duration } = probe(video)
@@ -101,6 +121,15 @@ async function litStill(dir: string, id: string, name: string, poster: string, o
101
121
  return poster
102
122
  }
103
123
 
124
+ /** the media facts a head keeps, by name: what names a file the disk let go */
125
+ const mediaOf = (dir: string, id: string): Record<string, unknown> => {
126
+ try {
127
+ return (JSON.parse(readFileSync(join(dir, id, 'item.json'), 'utf8')) as { media?: Record<string, unknown> }).media ?? {}
128
+ } catch {
129
+ return {}
130
+ }
131
+ }
132
+
104
133
  /** every image a card draws: each view's image or pair, a clip's poster, a sound's waveforms, a gallery's tiles */
105
134
  export function imagesOf(i: Item): string[] {
106
135
  const names = i.views.flatMap((v) => {
@@ -10,11 +10,13 @@ import { bad, KEEP, NO_STORE, ranged, TYPES } from './http.ts'
10
10
  import { viewFilesOf, type Rect, type ReviewItem, type Subject } from './model.ts'
11
11
  import { pasteHosts } from './paste.ts'
12
12
  import { openReview, partFile, viewOfItem } from './project.ts'
13
- import { isPreviewSize, previewFile, warmPreviews } from './previews.ts'
13
+ import { isPreviewSize, previewOrRemote, warmPreviews } from './previews.ts'
14
14
  import { roleOf } from './role.ts'
15
15
  import { addMessage, imageFile, itemOfRef, markRead, raiseItem, rateSubject, readAllCached, readItem, specOf, storeDir, storeStamp, threadImage, writeVerdict } from './store.ts'
16
16
  import { boardOf, pageOf, queryOf, threadIndex, threadOfId, threadView, type ThreadIndex } from './cells.ts'
17
17
  import { membersOf, threadsOf, type Thread } from './threads.ts'
18
+ import { upKeys } from '../media-store/remote.ts'
19
+ import { remoteUrl, reviewKey } from './media-read.ts'
18
20
  import { trailerRoutes } from './trailer-routes.ts'
19
21
  import { specData, type ReviewUnit } from './unit.ts'
20
22
  import { liveWatchers } from './watchers.ts'
@@ -91,9 +93,25 @@ function indexOf(dir: string): Indexed {
91
93
  return made
92
94
  }
93
95
 
94
- /** the media files the thread's views name that the store no longer holds (a clip deleted to free the disk) */
95
- const missingOf = (dir: string, members: readonly ReviewItem[]): string[] =>
96
- members.flatMap((x) => viewFilesOf(x.item).flatMap((n) => (existsSync(join(dir, x.item.id, n)) ? [] : [`${x.item.id}/${n}`])))
96
+ /** the store's thread index as the list reads it, its build's tag beside it: the home's inbox reads every repo's.
97
+ * null for a repo with no store */
98
+ export function storeIndex(root: string): { tag: string; ix: ThreadIndex } | null {
99
+ const dir = storeDir(root)
100
+ if (storeStamp(dir) === 'none') return null
101
+ const x = indexOf(dir)
102
+ return { tag: x.tag, ix: x.ix }
103
+ }
104
+
105
+ /** the media files the thread's views name that neither the disk nor the Space holds (a clip deleted before it went up) */
106
+ function missingOf(dir: string, members: readonly ReviewItem[]): string[] {
107
+ const away = members.flatMap((x) => viewFilesOf(x.item).flatMap((n) => (existsSync(join(dir, x.item.id, n)) ? [] : [{ x, n }])))
108
+ const keyOf = ({ x, n }: (typeof away)[number]): string | null => (x.item.media?.[n] ? reviewKey(x.item.media[n], n) : null)
109
+ const up = upKeys(away.flatMap((a) => keyOf(a) ?? []))
110
+ return away.flatMap((a) => (up.has(keyOf(a) ?? '') ? [] : [`${a.x.item.id}/${a.n}`]))
111
+ }
112
+
113
+ /** a file the disk let go, answered by the Space: the signed URL lives an hour, the browser keeps the redirect half of it */
114
+ const toSpace = (url: string): Response => new Response(null, { status: 302, headers: { Location: url, 'Cache-Control': 'private, max-age=1800' } })
97
115
 
98
116
  /** a json answer with its ETag, 304 when the page holds it; gzipped when the page takes it */
99
117
  function tagged(req: Request, tag: string, body: () => unknown): Response {
@@ -191,15 +209,19 @@ async function reviewRoute(req: Request, path: string, dir: string, unit: Review
191
209
  const t = /^\/api\/review\/([^/]+)\/thread\/([^/]+)$/.exec(path)
192
210
  if (t && req.method === 'GET') {
193
211
  const f = threadImage(dir, t[1] ?? '', t[2] ?? '')
194
- 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)
195
216
  }
196
217
  // a view's image at the size the page draws it; `thumb/<name>` is the preview's thumb size
197
218
  const pv = /^\/api\/review\/([^/]+)\/(?:preview\/([^/]+)|thumb)\/([^/]+)$/.exec(path)
198
219
  if (pv && req.method === 'GET') {
199
220
  const size = pv[2] ?? 'thumb'
200
221
  if (!isPreviewSize(size)) return bad(`preview size ${size}: thumb or fit`, 404)
201
- const f = await previewFile(dir, pv[1] ?? '', pv[3] ?? '', size)
202
- return f ? new Response(Bun.file(f), { headers: { 'Content-Type': 'image/webp', ...KEEP } }) : bad('no such image', 404)
222
+ const p = await previewOrRemote(dir, pv[1] ?? '', pv[3] ?? '', size)
223
+ if (p && 'url' in p) return toSpace(p.url)
224
+ return p ? new Response(Bun.file(p.file), { headers: { 'Content-Type': 'image/webp', ...KEEP } }) : bad('no such image', 404)
203
225
  }
204
226
  const m = /^\/api\/review\/([^/]+)\/([^/]+)$/.exec(path)
205
227
  if (!m) return null
@@ -267,7 +289,9 @@ async function reviewRoute(req: Request, path: string, dir: string, unit: Review
267
289
  }
268
290
  }
269
291
  const f = imageFile(dir, id, name)
270
- return f ? ranged(req, f) : bad(`no file ${id}/${name}`, 404)
292
+ if (f) return ranged(req, f)
293
+ const url = await remoteUrl(dir, id, name)
294
+ return url ? toSpace(url) : bad(`no file ${id}/${name}`, 404)
271
295
  }
272
296
 
273
297
  /** the review and trailer routes of the repo at `root`; null for any other path */