rvlib-shipkit 2.10.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 (63) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/package.json +1 -1
  3. package/src/cli/cmd_Media.ts +164 -0
  4. package/src/cli/family-pages.ts +1 -0
  5. package/src/cli/registry.ts +2 -0
  6. package/src/collections/pings.ts +6 -4
  7. package/src/core/app-icon.ts +17 -4
  8. package/src/core/scratch-objects.ts +56 -0
  9. package/src/core/trace-audit.ts +13 -1
  10. package/src/home/home-paths.ts +4 -0
  11. package/src/home/home-routes.ts +36 -2
  12. package/src/home/hubs.ts +5 -0
  13. package/src/home/inbox-shape.ts +182 -0
  14. package/src/home/inbox.ts +48 -0
  15. package/src/home/run-daemon.ts +12 -2
  16. package/src/home/serve-web.ts +155 -16
  17. package/src/ledger/git-scan.ts +73 -25
  18. package/src/ledger/repo-view.ts +2 -22
  19. package/src/media-kinds.ts +7 -0
  20. package/src/media-store/content.ts +51 -0
  21. package/src/media-store/daemon.ts +91 -0
  22. package/src/media-store/db.ts +74 -0
  23. package/src/media-store/fact.ts +9 -0
  24. package/src/media-store/kind.ts +44 -0
  25. package/src/media-store/purge.ts +139 -0
  26. package/src/media-store/remote.ts +93 -0
  27. package/src/media-store/space.ts +124 -0
  28. package/src/media-store/sync.ts +101 -0
  29. package/src/media-store/upload.ts +98 -0
  30. package/src/repo-config.ts +4 -0
  31. package/src/review/anim.ts +6 -5
  32. package/src/review/cells.ts +5 -1
  33. package/src/review/media-kind.ts +84 -0
  34. package/src/review/media-read.ts +48 -0
  35. package/src/review/model.ts +14 -1
  36. package/src/review/previews.ts +41 -12
  37. package/src/review/routes.ts +28 -7
  38. package/src/review/store.ts +100 -40
  39. package/src/review/trailer-desk.ts +79 -46
  40. package/src/review/trailer-media.ts +163 -0
  41. package/src/review/trailer-routes.ts +5 -2
  42. package/src/serve/hub-app/home-st.ts +39 -9
  43. package/src/serve/hub-app/home.html +2 -1
  44. package/src/serve/hub-app/hub-app.tsx +7 -23
  45. package/src/serve/hub-app/icons.tsx +2 -0
  46. package/src/serve/hub-app/inbox-st.ts +144 -0
  47. package/src/serve/hub-app/inbox-view.tsx +205 -0
  48. package/src/serve/hub-app/inbox.css +73 -0
  49. package/src/serve/hub-app/item-view.tsx +19 -0
  50. package/src/serve/hub-app/keys.ts +4 -3
  51. package/src/serve/hub-app/palette-st.ts +2 -1
  52. package/src/serve/hub-app/project-list.tsx +1 -0
  53. package/src/serve/hub-app/projects-svc.ts +1 -1
  54. package/src/serve/hub-app/repo-st.ts +1 -1
  55. package/src/serve/hub-app/review/review-st.ts +1 -0
  56. package/src/serve/hub-app/review/review-thread.tsx +5 -4
  57. package/src/serve/hub-app/review.css +1 -1
  58. package/src/serve/hub-runtime.ts +9 -4
  59. package/src/serve/serve-hub.ts +4 -1
  60. package/src/serve/warm-cell.ts +6 -1
  61. package/src/trailer/footage.ts +6 -2
  62. package/src/trailer/passage.ts +4 -2
  63. package/src/trailer/prune.ts +6 -10
@@ -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 { viewFilesOf } 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 = viewFilesOf(item)
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)) 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 { FILE_RE, ID_RE } 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) || !FILE_RE.test(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) || !FILE_RE.test(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 */
@@ -747,6 +753,13 @@ export function itemProblems(v: unknown): string[] {
747
753
  if (v.light !== undefined && v.light !== 'review') out.push('light: review, or absent')
748
754
  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
755
  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')
756
+ if (v.media !== undefined) {
757
+ if (!obj(v.media)) out.push('media: { <file name>: { sha, size, type } }, or absent')
758
+ else
759
+ 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')
761
+ out.push(`media.${n}: a file of the item, { sha: sha256 hex, size: bytes, type }`)
762
+ }
750
763
  return out
751
764
  }
752
765
 
@@ -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 {
@@ -198,8 +216,9 @@ async function reviewRoute(req: Request, path: string, dir: string, unit: Review
198
216
  if (pv && req.method === 'GET') {
199
217
  const size = pv[2] ?? 'thumb'
200
218
  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)
219
+ const p = await previewOrRemote(dir, pv[1] ?? '', pv[3] ?? '', size)
220
+ if (p && 'url' in p) return toSpace(p.url)
221
+ return p ? new Response(Bun.file(p.file), { headers: { 'Content-Type': 'image/webp', ...KEEP } }) : bad('no such image', 404)
203
222
  }
204
223
  const m = /^\/api\/review\/([^/]+)\/([^/]+)$/.exec(path)
205
224
  if (!m) return null
@@ -267,7 +286,9 @@ async function reviewRoute(req: Request, path: string, dir: string, unit: Review
267
286
  }
268
287
  }
269
288
  const f = imageFile(dir, id, name)
270
- return f ? ranged(req, f) : bad(`no file ${id}/${name}`, 404)
289
+ if (f) return ranged(req, f)
290
+ const url = await remoteUrl(dir, id, name)
291
+ return url ? toSpace(url) : bad(`no file ${id}/${name}`, 404)
271
292
  }
272
293
 
273
294
  /** the review and trailer routes of the repo at `root`; null for any other path */
@@ -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 {
@@ -509,19 +545,11 @@ function stampOf(folder: string): string {
509
545
  return `${one(folder)}:${one(`${folder}/thread`)}`
510
546
  }
511
547
 
512
- /** the index of a store: beside it, never inside it. Its own name, never `.review-index.json`: a second code that reads
513
- * the same store keys its index on its own code, and two codes sharing one file each throw the other's away */
514
- export const indexFile = (dir: string): string => join(dirname(resolve(dir)), `.${basename(dir)}-index.shipkit.json`)
515
-
516
548
  type Read = { x: ReviewItem } | { error: string }
517
549
 
518
- interface StoreIndex {
519
- /** the code that reads and checks an item: another code reads every item again */
520
- code: string
521
- items: Record<string, { stamp: string; read: Read }>
522
- }
523
-
524
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 */
525
553
  const indexCode = (): string => (codeKey ??= new Bun.CryptoHasher('sha1').update(readFileSync(import.meta.path)).update(readFileSync(join(import.meta.dir, 'model.ts'))).digest('hex'))
526
554
 
527
555
  function readOne(dir: string, id: string): Read {
@@ -554,39 +582,69 @@ function checked(raw: ReadAll, spec: Spec): ReadAll {
554
582
  return all
555
583
  }
556
584
 
557
- /** 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 */
558
594
  function readRaws(dir: string): ReadAll {
559
595
  const out: ReadAll = { items: [], broken: [] }
560
596
  if (!existsSync(dir)) return out
561
- const file = indexFile(dir)
597
+ const store = resolve(dir)
562
598
  const code = indexCode()
563
- let was: StoreIndex['items'] = {}
564
- try {
565
- const ix = JSON.parse(readFileSync(file, 'utf8')) as StoreIndex
566
- if (ix.code === code) was = ix.items
567
- } catch {
568
- // 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 })
569
610
  }
570
- const next: StoreIndex = { code, items: {} }
571
- let moved = false
611
+ const moved: { id: string; stamp: string; read: Read }[] = []
612
+ const seen = new Set<string>()
572
613
  for (const id of readdirSync(dir).sort()) {
573
614
  if (id.startsWith('.')) continue
615
+ seen.add(id)
574
616
  const stamp = stampOf(join(dir, id))
575
- const held = was[id]
576
- const read = held && held.stamp === stamp ? held.read : readOne(dir, id)
577
- if (read !== held?.read) moved = true
578
- 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
+ }
579
629
  if ('x' in read) out.items.push(read.x)
580
630
  else out.broken.push({ id, error: read.error })
581
631
  }
582
- if (moved || Object.keys(was).length !== Object.keys(next.items).length)
583
- try {
584
- const tmp = `${file}.${process.pid}.tmp`
585
- fs.writeFileSync(tmp, JSON.stringify(next))
586
- fs.renameSync(tmp, file)
587
- } catch {
588
- // 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)
589
646
  }
647
+ })
590
648
  return out
591
649
  }
592
650
 
@@ -684,7 +742,7 @@ export async function raiseItem(dir: string, input: RaiseInput): Promise<ReviewI
684
742
  rmSync(tmp, { recursive: true, force: true })
685
743
  mkdirSync(tmp)
686
744
  if (input.image !== undefined && image) copyFileSync(input.image, join(tmp, image))
687
- writeJson(join(tmp, 'item.json'), item)
745
+ writeJson(join(tmp, 'item.json'), { ...item, ...(image ? { media: await factsOf(tmp, [image]) } : {}) })
688
746
  renameSync(tmp, join(dir, id))
689
747
  const who = input.origin.by === 'player' ? 'player' : 'owner'
690
748
  if (text) appendMessage(dir, id, { who, text, ...(input.rects && input.rects.length > 0 ? { rects: input.rects } : {}) }, { now })
@@ -877,8 +935,9 @@ export async function refreshDraft(dir: string, id: string, o: { image: string;
877
935
  views = [...views, viewOf(loaded, n)]
878
936
  }
879
937
  const next: Item = { ...r, views, wip: { live: r.wip.live, frame: r.wip.frame + 1 } }
880
- writeJson(join(folder, 'item.json'), next)
881
- 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 }))
882
941
  }
883
942
 
884
943
  /** the label of a draft card's history view */
@@ -902,8 +961,9 @@ export async function readyItem(dir: string, id: string, o: { image?: string; no
902
961
  const now = 'image' in files ? files.image : undefined
903
962
  if (old && old !== now) rmSync(join(folder, old), { force: true })
904
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))) }
905
965
  }
906
- writeJson(join(dir, id, 'item.json'), item)
966
+ updateHead(dir, id, () => item)
907
967
  appendMessage(dir, id, { who: agentName(), op: 'ready' }, o.now ? { now: o.now } : {})
908
968
  return item
909
969
  }