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,139 @@
1
+ // the disk lets go of media the Space holds (wiki build/shipkit/media-store.md, The purge). A file goes only when the
2
+ // index says up AND a HEAD answers its size AND its kind's `beforePurge` passed. Kept: every row its kind pins, every
3
+ // row used in the last `older` days, every row nothing names. Oldest first. The candidates and the delete read one path
4
+ // form, `join(store, item, name)`, from the same index rows
5
+ import { existsSync, rmSync, statSync, statfsSync } from 'node:fs'
6
+ import { join, resolve } from 'node:path'
7
+ import { mediaDb, tryWrite } from './db.ts'
8
+ import type { MediaKind } from './kind.ts'
9
+ import type { Space } from './space.ts'
10
+ import { syncKind } from './sync.ts'
11
+ import { mb } from './upload.ts'
12
+
13
+ export const KEEP_DAYS = 14
14
+ /** under this much free disk the daemon purges, when the owner turned it on */
15
+ export const FREE_MIN_BYTES = 40e9
16
+
17
+ export interface Candidate {
18
+ item: string
19
+ name: string
20
+ key: string
21
+ size: number
22
+ /** the row's last use */
23
+ used: number
24
+ }
25
+
26
+ export interface Kept {
27
+ n: number
28
+ bytes: number
29
+ /** of them, the rows the kind pins */
30
+ pinned: { n: number; bytes: number }
31
+ }
32
+
33
+ /** what a purge of the store may free, oldest first: on the disk, up in the index, neither pinned nor recent */
34
+ export async function purgeCandidates(kind: MediaKind, dir: string, o: { olderDays?: number; now?: number } = {}): Promise<{ candidates: Candidate[]; kept: Kept }> {
35
+ await syncKind(kind, dir, { fill: 0 })
36
+ const now = o.now ?? Date.now()
37
+ const since = now - (o.olderDays ?? KEEP_DAYS) * 86_400_000
38
+ const judge = await kind.holds(resolve(dir), now)
39
+ const db = mediaDb()
40
+ if (!db) throw new Error('the media index does not open: nothing is purged without it')
41
+ const prefix = `${kind.kind}/`
42
+ const rows = db
43
+ .query('select f.item as item, f.name as name, f.key as key, f.size as size from files f join objects o on o.key = f.key where f.store = ? and substr(f.key, 1, ?) = ? and f.local = 1 and o.up is not null')
44
+ .all(resolve(dir), prefix.length, prefix) as { item: string; name: string; key: string; size: number }[]
45
+ const candidates: Candidate[] = []
46
+ const kept: Kept = { n: 0, bytes: 0, pinned: { n: 0, bytes: 0 } }
47
+ for (const r of rows) {
48
+ const h = judge(r)
49
+ if (h.pinned || h.used === undefined || !(h.used < since)) {
50
+ kept.n++
51
+ kept.bytes += r.size
52
+ if (h.pinned) {
53
+ kept.pinned.n++
54
+ kept.pinned.bytes += r.size
55
+ }
56
+ continue
57
+ }
58
+ candidates.push({ ...r, used: h.used })
59
+ }
60
+ candidates.sort((a, b) => a.used - b.used || (a.item < b.item ? -1 : a.item > b.item ? 1 : a.name < b.name ? -1 : 1))
61
+ return { candidates, kept }
62
+ }
63
+
64
+ export interface PurgeResult {
65
+ freed: number
66
+ files: number
67
+ /** a file the HEAD or its kind did not confirm: left on the disk */
68
+ refused: { key: string; why: string }[]
69
+ }
70
+
71
+ /** free the disk of the candidates, oldest first, until `enough` says stop, `jobs` files at a time: each file waits
72
+ * on its HEAD and its kind's check, so one at a time spends the purge on round trips. A file some process holds open
73
+ * stays */
74
+ export async function purge(kind: MediaKind, dir: string, space: Space, list: readonly Candidate[], o: { enough?: () => boolean; say?: (l: string) => void; jobs?: number } = {}): Promise<PurgeResult> {
75
+ const out: PurgeResult = { freed: 0, files: 0, refused: [] }
76
+ const store = resolve(dir)
77
+ const open = openOf(list.map((c) => join(store, c.item, c.name)))
78
+ let said = Date.now()
79
+ let next = 0
80
+ const one = async (c: Candidate): Promise<void> => {
81
+ const path = join(store, c.item, c.name)
82
+ if (statSync(path, { throwIfNoEntry: false })?.size !== c.size) return
83
+ if (open.has(path)) {
84
+ out.refused.push({ key: c.key, why: `${path} is open in a process` })
85
+ return
86
+ }
87
+ try {
88
+ const h = await space.head(c.key)
89
+ if (h?.size !== c.size) {
90
+ out.refused.push({ key: c.key, why: h ? `the Space holds ${h.size} bytes, the disk ${c.size}` : 'not in the Space' })
91
+ tryWrite(`${c.key} not up`, (db) => void db.query('update objects set up = null where key = ?').run(c.key))
92
+ return
93
+ }
94
+ await kind.beforePurge?.(store, space, c)
95
+ } catch (e) {
96
+ out.refused.push({ key: c.key, why: (e as Error).message })
97
+ return
98
+ }
99
+ rmSync(path, { force: true })
100
+ tryWrite(`${c.item}/${c.name} purged`, (db) => void db.query('update files set local = 0, purged = ? where store = ? and item = ? and name = ?').run(Date.now(), store, c.item, c.name))
101
+ out.freed += c.size
102
+ out.files++
103
+ if (o.say && Date.now() - said > 10_000) {
104
+ said = Date.now()
105
+ o.say(` ${out.files} files, ${mb(out.freed)} freed`)
106
+ }
107
+ }
108
+ const work = async (): Promise<void> => {
109
+ for (;;) {
110
+ if (o.enough?.()) return
111
+ const c = list[next++]
112
+ if (!c) return
113
+ await one(c)
114
+ }
115
+ }
116
+ await Promise.all(Array.from({ length: Math.max(1, o.jobs ?? PURGE_JOBS) }, work))
117
+ return out
118
+ }
119
+
120
+ /** files purged at once: enough to hide the round trips, few enough that the kinds' checks (an image's previews, a
121
+ * render's sha) leave the machine its cores */
122
+ export const PURGE_JOBS = 6
123
+
124
+ /** the paths of `paths` some process holds open (lsof), so a purge never pulls a file from under a reader */
125
+ export function openOf(paths: readonly string[]): Set<string> {
126
+ const out = new Set<string>()
127
+ const here = paths.filter((p) => existsSync(p))
128
+ for (let i = 0; i < here.length; i += 400) {
129
+ const r = Bun.spawnSync(['lsof', '-Fn', '--', ...here.slice(i, i + 400)], { stdout: 'pipe', stderr: 'ignore' })
130
+ for (const l of r.stdout.toString().split('\n')) if (l.startsWith('n/')) out.add(l.slice(1))
131
+ }
132
+ return out
133
+ }
134
+
135
+ /** the disk's free bytes where the store lives */
136
+ export function freeBytes(path: string): number {
137
+ const s = statfsSync(existsSync(path) ? path : '/')
138
+ return Number(s.bavail) * Number(s.bsize)
139
+ }
@@ -0,0 +1,120 @@
1
+ // a file put in the store by hand, and a fresh link to anything it holds (wiki build/shipkit/media-store.md, Put a file
2
+ // from any repo): the one way a repo's agent keeps a file in the private Space. The index row is written before the
3
+ // upload, so a failed upload waits for the daemon like any other; a link lasts at most 7 days, the object for good
4
+ import { realpathSync, statSync } from 'node:fs'
5
+ import { basename, dirname, join, relative } from 'node:path'
6
+ import { findRepoRoot } from '../ts/config.ts'
7
+ import { factOf, mediaKey, shaOf, shaOfKey, typeOf } from './content.ts'
8
+ import { mediaDb } from './db.ts'
9
+ import { DEFAULT_LABEL, LABEL } from './hand.ts'
10
+ import { confirmedUp } from './remote.ts'
11
+ import { machineSpace, SIGNED_MAX_S } from './space.ts'
12
+ import { uploadOne } from './upload.ts'
13
+
14
+ /** a duration as seconds: `90s`, `30m`, `2h`, `7d`, or a bare number of seconds; never over 7 days */
15
+ export function durationS(text: string): number {
16
+ const m = /^(\d+(?:\.\d+)?)([smhd]?)$/.exec(text.trim())
17
+ if (!m) throw new Error(`${text}: a duration is a number and a unit, like 30m, 2h or 7d`)
18
+ const s = Math.round(Number(m[1]) * { '': 1, s: 1, m: 60, h: 3600, d: 86_400 }[m[2] as '' | 's' | 'm' | 'h' | 'd'])
19
+ if (s < 1) throw new Error(`${text}: a link lasts at least 1 s`)
20
+ if (s > SIGNED_MAX_S) throw new Error(`${text}: a signed link lasts at most 7d (the SigV4 limit); the object never expires, sk media link makes a new one`)
21
+ return s
22
+ }
23
+
24
+ export interface Put {
25
+ key: string
26
+ sha: string
27
+ size: number
28
+ /** the file's own name, the one a link downloads under */
29
+ name: string
30
+ /** false: the Space already held this content */
31
+ sent: boolean
32
+ }
33
+
34
+ export interface Link {
35
+ key: string
36
+ sha: string
37
+ size: number
38
+ name: string
39
+ url: string
40
+ /** ISO time */
41
+ expires: string
42
+ }
43
+
44
+ /** the labels a kind of the code owns: their rows come from their own scan, never a hand put */
45
+ async function codeLabels(): Promise<Set<string>> {
46
+ const { MEDIA_KINDS } = await import('../media-kinds.ts')
47
+ return new Set(MEDIA_KINDS.map((k) => k.kind))
48
+ }
49
+
50
+ /** where the index keeps a file: its repo (else its folder) as the store, the folder in it, its name */
51
+ function placeOf(file: string): { store: string; item: string; name: string } {
52
+ const real = realpathSync(file)
53
+ const store = findRepoRoot(dirname(real))
54
+ return { store, item: relative(store, dirname(real)), name: basename(real) }
55
+ }
56
+
57
+ /** the file kept by its content under the label: its index row first, then up at once, checked by a HEAD */
58
+ export async function putMedia(file: string, o: { kind?: string } = {}): Promise<Put> {
59
+ const label = o.kind ?? DEFAULT_LABEL
60
+ if (!LABEL.test(label)) throw new Error(`--kind ${label}: a label is lowercase letters, digits and dashes`)
61
+ if ((await codeLabels()).has(label)) throw new Error(`--kind ${label}: that kind's files come from its own scan, never a hand put; pick another label`)
62
+ const st = statSync(file, { throwIfNoEntry: false })
63
+ if (!st?.isFile()) throw new Error(`${file}: no such file`)
64
+ const at = placeOf(file)
65
+ const path = join(at.store, at.item, at.name)
66
+ const fact = await factOf(path)
67
+ const key = mediaKey(label, fact, at.name)
68
+ const db = mediaDb()
69
+ if (!db) throw new Error('the media index does not open: nothing is put without its record')
70
+ db.transaction(() => {
71
+ db.query('insert or replace into files (store, item, name, key, size, local, purged) values (?, ?, ?, ?, ?, 1, null)').run(at.store, at.item, at.name, key, fact.size)
72
+ db.query('insert or ignore into objects (key, size) values (?, ?)').run(key, fact.size)
73
+ })()
74
+ const { space, why } = await machineSpace()
75
+ if (!space) throw new Error(`${key} recorded, not up: ${why}; the daemon sends it once the Space answers`)
76
+ const sent = await uploadOne(space, { key, size: fact.size, path })
77
+ return { key, sha: fact.sha, size: fact.size, name: at.name, sent }
78
+ }
79
+
80
+ /** the key a reference names: a key, a sha (or 12 hex of one), or a file the store holds */
81
+ async function keyOf(ref: string): Promise<{ key: string; size: number; name: string | null }> {
82
+ const db = mediaDb()
83
+ if (!db) throw new Error('the media index does not open')
84
+ const sizeOf = (key: string): number | null => (db.query('select size from objects where key = ?').get(key) as { size: number } | null)?.size ?? null
85
+ const nameOf = (key: string): string | null => (db.query('select name from files where key = ? order by name limit 1').get(key) as { name: string } | null)?.name ?? null
86
+ if (shaOfKey(ref)) {
87
+ const size = sizeOf(ref)
88
+ if (size === null) throw new Error(`${ref}: the index holds no such key`)
89
+ return { key: ref, size, name: nameOf(ref) }
90
+ }
91
+ const asFile = statSync(ref, { throwIfNoEntry: false })?.isFile()
92
+ if (!asFile && /^[0-9a-f]{12,64}$/.test(ref)) {
93
+ const keys = (db.query(`select key, size from objects where substr(key, instr(key, '/') + 1, ?) = ?`).all(ref.length, ref) as { key: string; size: number }[]).filter((r) => shaOfKey(r.key)?.startsWith(ref))
94
+ if (keys.length === 0) throw new Error(`${ref}: no object of the index has that sha`)
95
+ if (keys.length > 1) throw new Error(`${ref}: ${keys.length} objects match (${keys.map((k) => k.key).join(', ')}); name the key`)
96
+ const k = keys[0]!
97
+ return { key: k.key, size: k.size, name: nameOf(k.key) }
98
+ }
99
+ if (!asFile) throw new Error(`${ref}: neither a key, a sha, nor a file`)
100
+ const at = placeOf(ref)
101
+ const row = db.query('select key, size from files where store = ? and item = ? and name = ?').get(at.store, at.item, at.name) as { key: string; size: number } | null
102
+ const sha = await shaOf(join(at.store, at.item, at.name))
103
+ if (row && shaOfKey(row.key) === sha) return { key: row.key, size: row.size, name: at.name }
104
+ const same = db.query(`select key, size from objects where instr(key, ?) > 0`).all(`/${sha}`) as { key: string; size: number }[]
105
+ if (same.length === 0) throw new Error(`${ref}: not in the store; sk media put ${ref} first`)
106
+ if (same.length > 1) throw new Error(`${ref}: its content is kept under ${same.map((k) => k.key).join(', ')}; name the key`)
107
+ return { key: same[0]!.key, size: same[0]!.size, name: at.name }
108
+ }
109
+
110
+ /** a fresh signed link to what the Space holds, downloading under the index's name (or `name`) */
111
+ export async function linkMedia(ref: string, o: { seconds: number; name?: string; now?: number }): Promise<Link> {
112
+ if (o.seconds > SIGNED_MAX_S) throw new Error(`a signed link lasts at most 7d (the SigV4 limit); the object never expires, sk media link makes a new one`)
113
+ const k = await keyOf(ref)
114
+ const { space, why } = await machineSpace()
115
+ if (!space) throw new Error(why)
116
+ if (!(await confirmedUp(k.key, k.size))) throw new Error(`${k.key}: not in the Space yet (sk media upload sends what waits)`)
117
+ const name = o.name ?? k.name ?? basename(k.key)
118
+ const url = space.signed(k.key, o.seconds, { name, type: typeOf(name) })
119
+ return { key: k.key, sha: shaOfKey(k.key) ?? '', size: k.size, name, url, expires: new Date((o.now ?? Date.now()) + o.seconds * 1000).toISOString() }
120
+ }
@@ -0,0 +1,93 @@
1
+ // a media file from the disk or the Space (wiki build/shipkit/media-store.md, Read): a URL signed for a file the disk
2
+ // let go, and the file fetched back into its place, checked by its sha, for a tool that needs its bytes
3
+ import { existsSync, renameSync, rmSync, statSync } from 'node:fs'
4
+ import { resolve } from 'node:path'
5
+ import { shaOf } from './content.ts'
6
+ import { mediaDb, tryWrite } from './db.ts'
7
+ import type { MediaFact } from './fact.ts'
8
+ import { machineSpace } from './space.ts'
9
+
10
+ /** true when the index saw the key up */
11
+ export function isUp(key: string): boolean {
12
+ const r = mediaDb()?.query('select up from objects where key = ?').get(key) as { up: number | null } | null | undefined
13
+ return r?.up != null
14
+ }
15
+
16
+ /** the keys of `keys` the index saw up */
17
+ export function upKeys(keys: readonly string[]): Set<string> {
18
+ const db = mediaDb()
19
+ const out = new Set<string>()
20
+ if (!db || keys.length === 0) return out
21
+ const q = db.query('select up from objects where key = ?')
22
+ for (const k of keys) if ((q.get(k) as { up: number | null } | null)?.up != null) out.add(k)
23
+ return out
24
+ }
25
+
26
+ /** the key marked up, its row made when the index had none (a derived file, an index built again) */
27
+ export const recordUp = (key: string, size: number): void =>
28
+ tryWrite(`${key} up`, (db) => void db.query('insert into objects (key, size, up) values (?, ?, ?) on conflict (key) do update set up = excluded.up, error = null, tries = 0, next = 0').run(key, size, Date.now()))
29
+
30
+ /** a key a HEAD found absent, asked again only after this long: a file deleted before it went up is asked once */
31
+ const ABSENT_MS = 10 * 60_000
32
+ const absent = new Map<string, number>()
33
+
34
+ /** the key is up: the index says so, else one HEAD answers its size (an index built again after a purge) */
35
+ export async function confirmedUp(key: string, size: number): Promise<boolean> {
36
+ if (isUp(key)) return true
37
+ const space = (await machineSpace()).space
38
+ if (!space || Date.now() - (absent.get(key) ?? 0) < ABSENT_MS) return false
39
+ try {
40
+ if ((await space.head(key))?.size !== size) {
41
+ absent.set(key, Date.now())
42
+ return false
43
+ }
44
+ } catch (e) {
45
+ console.error(`WARN media store: HEAD ${key}: ${(e as Error).message}`)
46
+ absent.set(key, Date.now())
47
+ return false
48
+ }
49
+ recordUp(key, size)
50
+ return true
51
+ }
52
+
53
+ /** a signed URL for the key when the Space holds it at `size`; null otherwise */
54
+ export async function signedUrl(key: string, size: number): Promise<string | null> {
55
+ const space = (await machineSpace()).space
56
+ if (!space) return null
57
+ return (await confirmedUp(key, size)) ? space.signed(key) : null
58
+ }
59
+
60
+ /** a signed URL for a derived object (a preview) the index saw up; never a HEAD */
61
+ export async function signedIfUp(key: string): Promise<string | null> {
62
+ const space = (await machineSpace()).space
63
+ return space && isUp(key) ? space.signed(key) : null
64
+ }
65
+
66
+ const fetching = new Map<string, Promise<string | null>>()
67
+
68
+ /** the file at `path`, fetched back from the Space first when the disk let it go: checked by its sha before it lands,
69
+ * its index row marked local again (`row`: the store, item and name it is indexed under). null when neither holds it */
70
+ export function fetchBack(path: string, key: string, f: MediaFact, row?: { store: string; item: string; name: string }): Promise<string | null> {
71
+ if (existsSync(path)) return Promise.resolve(path)
72
+ const held = fetching.get(path)
73
+ if (held) return held
74
+ const job = (async (): Promise<string | null> => {
75
+ const space = (await machineSpace()).space
76
+ if (!space || !(await confirmedUp(key, f.size))) return null
77
+ const tmp = `${path}.${process.pid}.back`
78
+ try {
79
+ await space.get(key, tmp)
80
+ const sha = await shaOf(tmp)
81
+ if (sha !== f.sha || statSync(tmp).size !== f.size) throw new Error(`${key}: the bytes fetched back hash to ${sha.slice(0, 12)}, the record says ${f.sha.slice(0, 12)}`)
82
+ renameSync(tmp, path)
83
+ } catch (e) {
84
+ rmSync(tmp, { force: true })
85
+ console.error(`FAIL: media store: ${path} not fetched back: ${(e as Error).message}`)
86
+ return null
87
+ }
88
+ if (row) tryWrite(`${row.item}/${row.name} back`, (db) => void db.query('update files set local = 1, purged = null where store = ? and item = ? and name = ?').run(resolve(row.store), row.item, row.name))
89
+ return path
90
+ })().finally(() => fetching.delete(path))
91
+ fetching.set(path, job)
92
+ return job
93
+ }
@@ -0,0 +1,167 @@
1
+ // the private S3 bucket that keeps every media file of the machine's store (wiki build/shipkit/media-store.md), named by
2
+ // the house config's `serve.mediaSpace`. Every object is PRIVATE: never a public-read ACL, never a bucket policy. A page
3
+ // reads one through a URL signed for one hour, on the CDN edge. The key pair (`KEY:SECRET`) is read through the house's
4
+ // `credsReadCommand`, held in memory only: never written to a file, never printed
5
+ import { S3Client } from 'bun'
6
+ import { mkdirSync, renameSync, rmSync } from 'node:fs'
7
+ import { dirname } from 'node:path'
8
+ import { readSecret } from '../smoke/run-smoke.ts'
9
+
10
+ /** the house config's `serve.mediaSpace`: where the media store's files go up, and the NAME of the secret holding the key pair */
11
+ export interface MediaSpace {
12
+ /** the origin, the bucket in its host: `https://<bucket>.<region>.digitaloceanspaces.com` */
13
+ endpoint: string
14
+ bucket: string
15
+ region: string
16
+ /** the CDN edge a signed URL is handed out on */
17
+ cdn?: string
18
+ /** the secret whose value is `KEY:SECRET`, read through `credsReadCommand` */
19
+ secret: string
20
+ }
21
+
22
+ export interface SpaceConfig {
23
+ /** the origin, with the bucket in its host (virtual hosted) or in its path (`path: true`, a fake server) */
24
+ endpoint: string
25
+ bucket: string
26
+ region: string
27
+ path?: boolean
28
+ /** the CDN edge a signed URL is handed out on: the URL is signed for the origin, the edge checks it there */
29
+ cdn?: string | null
30
+ creds: { accessKeyId: string; secretAccessKey: string }
31
+ }
32
+
33
+ /** how long a signed URL stays good */
34
+ export const SIGNED_S = 3600
35
+
36
+ export interface Space {
37
+ /** where the objects live, for a line a person reads (never a credential) */
38
+ readonly where: string
39
+ put(key: string, file: string, type: string): Promise<void>
40
+ /** the object's size, null when it is not there; throws on any other answer */
41
+ head(key: string): Promise<{ size: number } | null>
42
+ /** a GET URL good for `seconds`, on the CDN edge when the Space has one: signed for the origin host, which the edge
43
+ * checks it against (a URL signed for the edge's own host answers SignatureDoesNotMatch). `as` signs a download
44
+ * under that file name: `response-content-disposition` and `response-content-type` ride in the signed query */
45
+ signed(key: string, seconds?: number, as?: { name: string; type: string }): string
46
+ /** the object written at `to`, through a file beside it renamed: no reader sees half of it */
47
+ get(key: string, to: string): Promise<void>
48
+ /** the bucket's versioning: `Enabled`, `Suspended`, or `off` when it was never turned on (GetBucketVersioning) */
49
+ versioning(): Promise<'Enabled' | 'Suspended' | 'off'>
50
+ /** turns versioning on, so an object deleted or overwritten from outside keeps its older version (PutBucketVersioning) */
51
+ enableVersioning(): Promise<void>
52
+ }
53
+
54
+ const missing = (e: unknown): boolean => {
55
+ const x = e as { code?: string; name?: string; message?: string }
56
+ return x.code === 'NoSuchKey' || x.code === 'NotFound' || /\b404\b|NoSuchKey|not found/i.test(`${x.name ?? ''} ${x.message ?? ''}`)
57
+ }
58
+
59
+ /** the longest a signed URL can last: the SigV4 limit */
60
+ export const SIGNED_MAX_S = 7 * 86_400
61
+
62
+ /** `attachment` under the name: a plain ascii fallback, the exact name in `filename*` when it is not ascii */
63
+ export function attachment(name: string): string {
64
+ const plain = name.replace(/[^\x20-\x7e]|["\\]/g, '_')
65
+ return plain === name ? `attachment; filename="${name}"` : `attachment; filename="${plain}"; filename*=UTF-8''${encodeURIComponent(name)}`
66
+ }
67
+
68
+ const hex = (b: ArrayBuffer | Uint8Array): string => Buffer.from(b instanceof Uint8Array ? b : new Uint8Array(b)).toString('hex')
69
+ const sha256 = (s: string): string => new Bun.CryptoHasher('sha256').update(s).digest('hex')
70
+ const hmac = (key: string | Uint8Array, s: string): Uint8Array => new Uint8Array(new Bun.CryptoHasher('sha256', key).update(s).digest())
71
+
72
+ /** one bucket call Bun's S3 client has no verb for, signed by hand (SigV4, header auth): `?<sub>` on the bucket */
73
+ async function bucketCall(c: SpaceConfig, method: 'GET' | 'PUT', sub: string, body = ''): Promise<string> {
74
+ const url = new URL(c.path === true ? `${c.endpoint}/${c.bucket}` : `${c.endpoint}/`)
75
+ url.search = sub
76
+ const now = new Date().toISOString().replace(/[-:]|\.\d{3}/g, '')
77
+ const day = now.slice(0, 8)
78
+ const payload = sha256(body)
79
+ const headers: Record<string, string> = { host: url.host, 'x-amz-content-sha256': payload, 'x-amz-date': now }
80
+ const names = Object.keys(headers).sort()
81
+ const canonical = [method, url.pathname, `${sub}=`, ...names.map((n) => `${n}:${headers[n]}`), '', names.join(';'), payload].join('\n')
82
+ const scope = `${day}/${c.region}/s3/aws4_request`
83
+ const toSign = ['AWS4-HMAC-SHA256', now, scope, sha256(canonical)].join('\n')
84
+ const k = hmac(hmac(hmac(hmac(`AWS4${c.creds.secretAccessKey}`, day), c.region), 's3'), 'aws4_request')
85
+ const auth = `AWS4-HMAC-SHA256 Credential=${c.creds.accessKeyId}/${scope}, SignedHeaders=${names.join(';')}, Signature=${hex(hmac(k, toSign))}`
86
+ const { host: _, ...sent } = headers
87
+ const md5: Record<string, string> = body !== '' ? { 'Content-MD5': new Bun.CryptoHasher('md5').update(body).digest('base64') } : {}
88
+ const r = await fetch(url, { method, headers: { ...sent, ...md5, Authorization: auth }, ...(body !== '' ? { body } : {}) })
89
+ const text = await r.text()
90
+ if (!r.ok) throw new Error(`${method} ?${sub} on ${c.bucket}: ${r.status} ${/<Code>([^<]+)<\/Code>/.exec(text)?.[1] ?? text.slice(0, 200)}`)
91
+ return text
92
+ }
93
+
94
+ export function spaceOf(c: SpaceConfig): Space {
95
+ const client = new S3Client({ ...c.creds, bucket: c.bucket, region: c.region, endpoint: c.endpoint, virtualHostedStyle: c.path !== true })
96
+ const origin = new URL(c.endpoint).host
97
+ const edge = c.cdn ? new URL(c.cdn).host : null
98
+ return {
99
+ where: `${c.cdn ?? c.endpoint} (${c.bucket})`,
100
+ async put(key, file, type) {
101
+ await client.write(key, Bun.file(file), { type, acl: 'private' })
102
+ },
103
+ async head(key) {
104
+ try {
105
+ const s = await client.stat(key)
106
+ return { size: s.size }
107
+ } catch (e) {
108
+ if (missing(e)) return null
109
+ throw e
110
+ }
111
+ },
112
+ signed(key, seconds = SIGNED_S, as) {
113
+ const url = new URL(client.presign(key, { expiresIn: seconds, method: 'GET', ...(as ? { contentDisposition: attachment(as.name), type: as.type } : {}) }))
114
+ if (edge && url.host === origin) url.host = edge
115
+ return url.toString()
116
+ },
117
+ async get(key, to) {
118
+ mkdirSync(dirname(to), { recursive: true })
119
+ const tmp = `${to}.${process.pid}.get`
120
+ try {
121
+ await Bun.write(tmp, client.file(key))
122
+ renameSync(tmp, to)
123
+ } finally {
124
+ rmSync(tmp, { force: true })
125
+ }
126
+ },
127
+ async versioning() {
128
+ const s = /<Status>([^<]+)<\/Status>/.exec(await bucketCall(c, 'GET', 'versioning'))?.[1]
129
+ return s === 'Enabled' || s === 'Suspended' ? s : 'off'
130
+ },
131
+ async enableVersioning() {
132
+ await bucketCall(c, 'PUT', 'versioning', '<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Status>Enabled</Status></VersioningConfiguration>')
133
+ },
134
+ }
135
+ }
136
+
137
+ let held: Promise<{ space: Space | null; why: string }> | null = null
138
+
139
+ /** the machine's Space, from the house config and its key, read once per process; null with the reason when there is none */
140
+ export function machineSpace(): Promise<{ space: Space | null; why: string }> {
141
+ held ??= (async () => {
142
+ if (process.env.SHIPKIT_SPACES === 'off') return { space: null, why: 'SHIPKIT_SPACES=off' }
143
+ const { houseRootOf } = await import('../home/home-start.ts')
144
+ const { loadRepoConfig } = await import('../repo-config.ts')
145
+ const house = houseRootOf(process.cwd())
146
+ if (!house) return { space: null, why: `no house repo seen from ${process.cwd()}` }
147
+ const c = await loadRepoConfig(house)
148
+ const r = c.serve?.mediaSpace
149
+ if (!r) return { space: null, why: `the house config (${house}) names no serve.mediaSpace` }
150
+ if (!c.credsReadCommand) return { space: null, why: `the house config (${house}) declares no credsReadCommand to read ${r.secret}` }
151
+ let v = ''
152
+ try {
153
+ v = readSecret(c.credsReadCommand, r.secret)
154
+ } catch (e) {
155
+ return { space: null, why: (e as Error).message }
156
+ }
157
+ const at = v.indexOf(':')
158
+ if (at <= 0) return { space: null, why: `the secret ${r.secret} is no KEY:SECRET pair` }
159
+ return { space: spaceOf({ ...r, cdn: r.cdn ?? null, creds: { accessKeyId: v.slice(0, at), secretAccessKey: v.slice(at + 1) } }), why: '' }
160
+ })().catch((e: unknown) => ({ space: null, why: `the house config does not load: ${(e as Error).message}` }))
161
+ return held
162
+ }
163
+
164
+ /** a test's own Space in place of the machine's; undefined gives the machine's back */
165
+ export function useSpace(space: Space | null | undefined): void {
166
+ held = space === undefined ? null : Promise.resolve({ space, why: space ? '' : 'no Space in this test' })
167
+ }
@@ -0,0 +1,101 @@
1
+ // a kind's scan into the machine index (db.ts): each file by its key, whether the disk holds it; each key an object row
2
+ // the uploader takes. The rows of one store are written as a whole: a row the scan no longer names goes
3
+ import { resolve } from 'node:path'
4
+ import { mediaKey } from './content.ts'
5
+ import { mediaDb, tryWrite } from './db.ts'
6
+ import type { MediaKind } from './kind.ts'
7
+
8
+ export interface SyncResult {
9
+ files: number
10
+ filled: number
11
+ left: number
12
+ /** files with no fact and no copy on the disk: lost before they went up */
13
+ unknown: number
14
+ }
15
+
16
+ /** the rows of `kind` in the index are only the keys of its prefix: two kinds never drop each other's rows */
17
+ const prefixOf = (kind: string): string => `${kind}/`
18
+
19
+ /** the store's files into the index. `fill` caps how many files are hashed this pass (Infinity: all) */
20
+ export async function syncKind(kind: MediaKind, dir: string, o: { fill?: number } = {}): Promise<SyncResult> {
21
+ const store = resolve(dir)
22
+ const scan = await kind.scan(store, { fill: o.fill ?? Infinity })
23
+ const out: SyncResult = { files: 0, filled: scan.filled, left: scan.left, unknown: 0 }
24
+ const rows: { item: string; name: string; key: string; size: number; local: number }[] = []
25
+ for (const r of scan.rows) {
26
+ if (!r.fact) {
27
+ if (!r.local) out.unknown++
28
+ continue
29
+ }
30
+ rows.push({ item: r.item, name: r.name, key: mediaKey(kind.kind, r.fact, r.name), size: r.fact.size, local: r.local ? 1 : 0 })
31
+ }
32
+ out.files = rows.length
33
+ const prefix = prefixOf(kind.kind)
34
+ tryWrite(`the ${kind.kind} media of ${store}`, (db) => {
35
+ const was = new Map(
36
+ (db.query('select item, name, key, size, local, purged from files where store = ? and substr(key, 1, ?) = ?').all(store, prefix.length, prefix) as { item: string; name: string; key: string; size: number; local: number; purged: number | null }[]).map(
37
+ (r) => [`${r.item}/${r.name}`, r],
38
+ ),
39
+ )
40
+ const put = db.query('insert or replace into files (store, item, name, key, size, local, purged) values (?, ?, ?, ?, ?, ?, ?)')
41
+ const obj = db.query('insert or ignore into objects (key, size) values (?, ?)')
42
+ const seen = new Set<string>()
43
+ for (const r of rows) {
44
+ const k = `${r.item}/${r.name}`
45
+ seen.add(k)
46
+ const held = was.get(k)
47
+ if (held && held.key === r.key && held.size === r.size && held.local === r.local) continue
48
+ put.run(store, r.item, r.name, r.key, r.size, r.local, r.local === 1 ? null : (held?.purged ?? null))
49
+ obj.run(r.key, r.size)
50
+ }
51
+ const drop = db.query('delete from files where store = ? and item = ? and name = ?')
52
+ for (const [k, r] of was) if (!seen.has(k)) drop.run(store, r.item, r.name)
53
+ })
54
+ return out
55
+ }
56
+
57
+ type Count = { n: number; bytes: number }
58
+
59
+ export interface MediaCounts {
60
+ store: string
61
+ kind: string
62
+ local: Count
63
+ up: Count
64
+ purged: Count
65
+ waiting: Count
66
+ gone: Count
67
+ failing: { n: number; error: string | null }
68
+ }
69
+
70
+ /** per store and kind the index knows: what the disk holds, what is up, purged, waiting, gone; the uploads that failed */
71
+ export function mediaCounts(): MediaCounts[] {
72
+ const db = mediaDb()
73
+ if (!db) return []
74
+ const rows = db
75
+ .query(
76
+ `select f.store as store, substr(f.key, 1, instr(f.key, '/') - 1) as kind, f.local as local, f.size as size, o.up is not null as up, o.error as error
77
+ from files f left join objects o on o.key = f.key`,
78
+ )
79
+ .all() as { store: string; kind: string; local: number; size: number; up: number; error: string | null }[]
80
+ const by = new Map<string, MediaCounts>()
81
+ const zero = (): Count => ({ n: 0, bytes: 0 })
82
+ for (const r of rows) {
83
+ const id = `${r.store}\0${r.kind}`
84
+ let c = by.get(id)
85
+ if (!c) by.set(id, (c = { store: r.store, kind: r.kind, local: zero(), up: zero(), purged: zero(), waiting: zero(), gone: zero(), failing: { n: 0, error: null } }))
86
+ const add = (b: Count): void => {
87
+ b.n++
88
+ b.bytes += r.size
89
+ }
90
+ if (r.local) add(c.local)
91
+ if (r.up) add(c.up)
92
+ if (r.up && !r.local) add(c.purged)
93
+ if (r.local && !r.up) add(c.waiting)
94
+ if (!r.local && !r.up) add(c.gone)
95
+ if (r.local && !r.up && r.error) {
96
+ c.failing.n++
97
+ c.failing.error ??= r.error
98
+ }
99
+ }
100
+ return [...by.values()].sort((a, b) => (a.store < b.store ? -1 : a.store > b.store ? 1 : a.kind < b.kind ? -1 : 1))
101
+ }