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
@@ -30,12 +30,21 @@
30
30
  // `git add` on one index file, 9 fail with `Unable to create …lock`. Three
31
31
  // agents in one checkout is the normal case here, so lock contention is
32
32
  // retried and only a NON lock failure is fatal.
33
+ //
34
+ // AND IT STORES NOTHING. `git add` writes every blob it hashes into the repo's
35
+ // object store, and nothing ever reaches those blobs: measured in a game repo,
36
+ // 14.3 GiB of unreachable loose objects, a 172 MB blob per trailer render under
37
+ // a declared ignored dir. So every git run of a scan writes into an object dir
38
+ // of its own (core/scratch-objects.ts), dropped when the scan returns: the ids
39
+ // stay, the objects go, and every tree the scan reads is read before the drop.
33
40
  import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'fs'
34
- import { isAbsolute, join, normalize, resolve } from 'path'
41
+ import { dirname, isAbsolute, join, normalize, resolve } from 'path'
35
42
  import { probeGitRoot } from '../core/git-root.ts'
36
43
  import { treePrefix } from '../core/nesting.ts'
37
44
  import { gitBin } from '../core/git-bin.ts'
38
45
  import { blobOid } from '../core/read-set.ts'
46
+ import { scratchObjects } from '../core/scratch-objects.ts'
47
+ import { pidAlive } from './live-runs.ts'
39
48
 
40
49
  /** what a scan measured. Every OID is a git object id of the CURRENT disk
41
50
  * content, tracked or not. */
@@ -54,6 +63,10 @@ export type ScanResult = {
54
63
  ignored: string[]
55
64
  /** root tree of the force-add index, null when nothing was force-added */
56
65
  ignoredTreeOid: string | null
66
+ /** a `treeOnly` scan: every file of the whole tree, repo-relative,
67
+ * sorted. Listed inside the scan, because its tree objects are gone
68
+ * once the scan returns */
69
+ files?: readonly string[]
57
70
  /** wall time of the whole scan */
58
71
  ms: number
59
72
  }
@@ -79,22 +92,24 @@ export const SCAN_INDEX_VERSION = 2
79
92
  const LOCK_RE = /Unable to create '.*\.lock'|index\.lock/i
80
93
  const RETRIES = 12
81
94
 
82
- const git = (root: string, args: string[], indexFile: string): { code: number; out: string } => {
95
+ type GitEnv = Record<string, string>
96
+
97
+ const git = (root: string, args: string[], env: GitEnv): { code: number; out: string } => {
83
98
  const p = Bun.spawnSync([gitBin(), ...args], {
84
99
  cwd: root,
85
100
  stdout: 'pipe',
86
101
  stderr: 'pipe',
87
- env: { ...process.env, GIT_INDEX_FILE: indexFile },
102
+ env: { ...process.env, ...env },
88
103
  })
89
104
  return { code: p.exitCode, out: `${p.stdout.toString()}${p.stderr.toString()}` }
90
105
  }
91
106
 
92
107
  /** one git call that MUST succeed. Lock contention is retried (three agents in
93
108
  * one checkout is normal); anything else throws with git's own words. */
94
- function gitOrThrow(root: string, args: string[], indexFile: string): string {
109
+ function gitOrThrow(root: string, args: string[], env: GitEnv): string {
95
110
  let last = { code: -1, out: '' }
96
111
  for (let attempt = 0; attempt < RETRIES; attempt++) {
97
- last = git(root, args, indexFile)
112
+ last = git(root, args, env)
98
113
  if (last.code === 0) return last.out
99
114
  if (!LOCK_RE.test(last.out)) break
100
115
  Bun.sleepSync(10 + attempt * 10)
@@ -200,10 +215,6 @@ export function sweepScanIndexes(dir: string, now: number): void {
200
215
  } catch { /* no dir: nothing to sweep */ }
201
216
  }
202
217
 
203
- const pidAlive = (pid: number): boolean => {
204
- try { process.kill(pid, 0); return true } catch (e) { return (e as { code?: string }).code === 'EPERM' }
205
- }
206
-
207
218
  /** the whole work tree as one input. A rule that walks the repo (SK001's test
208
219
  * file probe, SK010's `git ls-files`) genuinely reads all of it, and saying so
209
220
  * is more honest than naming three of the files it happens to open. Its object
@@ -245,11 +256,23 @@ export function scanPaths(root: string, rawPaths: string[], prior?: ScanResult,
245
256
  const started = performance.now()
246
257
  if (o.treeOnly === true && (rawPaths.length !== 1 || normalizeInput(rawPaths[0]!) !== WHOLE_TREE))
247
258
  throw new GitScanError(`treeOnly scans the whole tree and nothing else, asked for: ${rawPaths.join(', ')}`)
248
- const { scratch: indexFile, ignored: ignoredIndex, real: realIndex } = indexPaths(root)
259
+ const idx = indexPaths(root)
249
260
  const wanted = [...new Set(rawPaths.map(normalizeInput))].sort()
250
261
  // nothing asked for: the repo is still validated above, and no tree is
251
262
  // written that nobody reads (a run of read checks declares no path)
252
263
  if (wanted.length === 0) return { treeOid: '', oidByPath: new Map(), missing: [], excluded: new Map(), ignored: [], ignoredTreeOid: null, ms: performance.now() - started }
264
+ const objects = scratchObjects(root, dirname(idx.scratch))
265
+ try {
266
+ return stage(root, wanted, prior, o, idx, objects.env, started)
267
+ } finally {
268
+ objects.drop()
269
+ }
270
+ }
271
+
272
+ /** the adds, the trees and every id read off them, under one scratch object dir */
273
+ function stage(root: string, wanted: string[], prior: ScanResult | undefined, o: ScanOpts, idx: { scratch: string; ignored: string; real: string }, objects: GitEnv, started: number): ScanResult {
274
+ const { scratch: indexFile, ignored: ignoredIndex, real: realIndex } = idx
275
+ const on = (index: string): GitEnv => ({ ...objects, GIT_INDEX_FILE: index })
253
276
  const missing = wanted.filter((p) => !existsSync(join(root, p)))
254
277
  const present = wanted.filter((p) => existsSync(join(root, p)))
255
278
  const toAdd = dropCovered(present)
@@ -271,7 +294,7 @@ export function scanPaths(root: string, rawPaths: string[], prior?: ScanResult,
271
294
  ? prior.ignored
272
295
  : toAdd.length === 0
273
296
  ? []
274
- : gitOrThrow(root, ['ls-files', '--others', '-i', '--exclude-standard', '--directory', '--', ...toAdd], realIndex)
297
+ : gitOrThrow(root, ['ls-files', '--others', '-i', '--exclude-standard', '--directory', '--', ...toAdd], on(realIndex))
275
298
  .split('\n')
276
299
  .map((l) => l.trim().replace(/\/+$/, ''))
277
300
  .filter((l) => l !== '')
@@ -298,30 +321,33 @@ export function scanPaths(root: string, rawPaths: string[], prior?: ScanResult,
298
321
  // <ignored>` exits 1 and takes the whole scan down with it
299
322
  const ignoredSet = new Set([...ignored, ...underIgnored])
300
323
  const plainAdds = toAdd.filter((p) => !ignoredSet.has(p))
301
- if (plainAdds.length > 0) gitOrThrow(root, ['add', '--', ...plainAdds], indexFile)
324
+ if (plainAdds.length > 0) gitOrThrow(root, ['add', '--', ...plainAdds], on(indexFile))
302
325
  // force-adds land in their OWN index, so a path one check named can never
303
326
  // ride inside the whole-tree id another check is keyed on
304
- if (forceAdd.length > 0) gitOrThrow(root, ['add', '-Af', '--', ...forceAdd], ignoredIndex)
327
+ if (forceAdd.length > 0) gitOrThrow(root, ['add', '-Af', '--', ...forceAdd], on(ignoredIndex))
305
328
 
306
329
  const excluded = excludedBy(wanted, ignored, new Set(forceAdd))
307
330
  // write-tree and every `<tree>:<path>` answer are pure functions of the
308
331
  // index bytes, so staged bytes this process already derived need no git.
309
332
  // the post-run re-hash of an untouched tree is the common hit
310
- const memoKey = derivedKey(root, indexFile, forceAdd.length > 0 ? ignoredIndex : null, wanted, missing)
333
+ const memoKey = derivedKey(root, indexFile, forceAdd.length > 0 ? ignoredIndex : null, wanted, missing, o.treeOnly === true)
311
334
  const hit = memoKey == null ? undefined : derived.get(memoKey)
312
335
  if (hit != null)
313
336
  return { ...hit, oidByPath: new Map(hit.oidByPath), missing: [...hit.missing], excluded, ignored, ms: performance.now() - started }
314
- const treeOid = gitOrThrow(root, ['write-tree'], indexFile).trim()
315
- const ignoredTreeOid = forceAdd.length > 0 ? gitOrThrow(root, ['write-tree'], ignoredIndex).trim() : null
316
- const done = (oidByPath: Map<string, string>): ScanResult => {
317
- const r: ScanResult = { treeOid, oidByPath, missing: [...new Set(missing)].sort(), excluded, ignored, ignoredTreeOid, ms: performance.now() - started }
337
+ const treeOid = gitOrThrow(root, ['write-tree'], on(indexFile)).trim()
338
+ // the force-add index stays warm across scans, so its entries name blobs
339
+ // an earlier scan's object dir held and dropped: their ids are right, and
340
+ // `--missing-ok` lets the tree be written from the ids alone
341
+ const ignoredTreeOid = forceAdd.length > 0 ? gitOrThrow(root, ['write-tree', '--missing-ok'], on(ignoredIndex)).trim() : null
342
+ const done = (oidByPath: Map<string, string>, files?: readonly string[]): ScanResult => {
343
+ const r: ScanResult = { treeOid, oidByPath, missing: [...new Set(missing)].sort(), excluded, ignored, ignoredTreeOid, ...(files == null ? {} : { files }), ms: performance.now() - started }
318
344
  if (memoKey != null) remember(memoKey, { ...r, oidByPath: new Map(oidByPath), missing: [...r.missing] })
319
345
  return r
320
346
  }
321
347
  // both root trees unchanged and the same paths on disk: every path under
322
348
  // them names the same object, so the per path answer is the prior one
323
- if (prior != null && prior.treeOid === treeOid && prior.ignoredTreeOid === ignoredTreeOid && prior.missing.join('\n') === [...new Set(missing)].sort().join('\n'))
324
- return done(new Map(prior.oidByPath))
349
+ if (prior != null && prior.treeOid === treeOid && prior.ignoredTreeOid === ignoredTreeOid && prior.missing.join('\n') === [...new Set(missing)].sort().join('\n') && (o.treeOnly !== true || prior.files != null))
350
+ return done(new Map(prior.oidByPath), prior.files)
325
351
  const oidByPath = new Map<string, string>()
326
352
  // a declared path is relative to root, and `<tree>:<path>` reads from the
327
353
  // work tree root. In a nested repo the two differ, so every query carries
@@ -342,7 +368,7 @@ export function scanPaths(root: string, rawPaths: string[], prior?: ScanResult,
342
368
  stdin: Buffer.from(`${query}\n`),
343
369
  stdout: 'pipe',
344
370
  stderr: 'pipe',
345
- env: { ...process.env, GIT_INDEX_FILE: index },
371
+ env: { ...process.env, ...on(index) },
346
372
  })
347
373
  if (p.exitCode !== 0) throw new GitScanError(`git cat-file --batch-check exited ${p.exitCode}: ${p.stderr.toString().trim()}`)
348
374
  const lines = p.stdout.toString().split('\n').filter((l) => l !== '')
@@ -357,19 +383,41 @@ export function scanPaths(root: string, rawPaths: string[], prior?: ScanResult,
357
383
  })
358
384
  }
359
385
 
360
- return done(oidByPath)
386
+ if (o.treeOnly !== true) return done(oidByPath)
387
+ const whole = oidByPath.get(WHOLE_TREE)
388
+ if (whole == null) throw new GitScanError('git could not name the work tree')
389
+ return done(oidByPath, filesOf(root, whole, on(indexFile)))
390
+ }
391
+
392
+ /** a tree id names its content, so its file list is a pure function of the
393
+ * id and one listing serves every scan of that tree. `--full-tree` keeps it
394
+ * so: without it git filters the listing by the cwd's path under the work
395
+ * tree, and a nested folder's own subtree lists nothing */
396
+ const listed = new Map<string, readonly string[]>()
397
+ const LISTED_MAX = 64
398
+
399
+ function filesOf(root: string, tree: string, env: GitEnv): readonly string[] {
400
+ const hit = listed.get(tree)
401
+ if (hit != null) return hit
402
+ const p = Bun.spawnSync([gitBin(), 'ls-tree', '--full-tree', '-r', '-z', '--name-only', tree], { cwd: root, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, ...env } })
403
+ if (p.exitCode !== 0) throw new GitScanError(`git ls-tree exited ${p.exitCode}: ${p.stderr.toString().trim()}`)
404
+ const files = p.stdout.toString().split('\0').filter((f) => f !== '').sort()
405
+ if (listed.size >= LISTED_MAX) listed.delete(listed.keys().next().value!)
406
+ listed.set(tree, files)
407
+ return files
361
408
  }
362
409
 
363
410
  /** scans already derived in this process, by the exact bytes they staged */
364
411
  const derived = new Map<string, ScanResult>()
365
412
  const DERIVED_MAX = 64
366
413
 
367
- /** the repo, both staged index files byte for byte, and the question asked.
414
+ /** the repo, both staged index files byte for byte, and the question asked
415
+ * (a listing is part of the question).
368
416
  * null when an index cannot be read: no key, so no reuse */
369
- function derivedKey(root: string, index: string, ignoredIndex: string | null, wanted: string[], missing: string[]): string | null {
417
+ function derivedKey(root: string, index: string, ignoredIndex: string | null, wanted: string[], missing: string[], listing: boolean): string | null {
370
418
  try {
371
419
  const bytes = (f: string | null): string => (f == null ? '-' : Bun.hash(readFileSync(f)).toString(36))
372
- return [resolve(root), bytes(index), bytes(ignoredIndex), wanted.join('\n'), [...new Set(missing)].sort().join('\n')].join('\0')
420
+ return [resolve(root), bytes(index), bytes(ignoredIndex), wanted.join('\n'), [...new Set(missing)].sort().join('\n'), listing ? 'files' : ''].join('\0')
373
421
  } catch {
374
422
  return null
375
423
  }
@@ -12,7 +12,6 @@
12
12
  // its glob names a path inside one: a check never mistakes third party code
13
13
  // for the repo's own, and the replay check lists through the same filter.
14
14
  import { relative } from 'path'
15
- import { gitBin } from '../core/git-bin.ts'
16
15
  import { listingWithoutVendored } from '../core/vendored.ts'
17
16
  import { readVendored } from '../core/vendored-read.ts'
18
17
  import { GitScanError, scanPaths, WHOLE_TREE, type ScanResult } from './git-scan.ts'
@@ -38,9 +37,8 @@ export class RepoView {
38
37
  const vendored = readVendored(root)
39
38
  try {
40
39
  const scan = scanPaths(root, [WHOLE_TREE], prior?.scan ?? undefined, { treeOnly: true })
41
- const tree = scan.oidByPath.get(WHOLE_TREE)
42
- if (tree == null) throw new GitScanError('git could not name the work tree')
43
- return new RepoView(filesOf(root, tree), null, scan, vendored)
40
+ if (scan.files == null) throw new GitScanError('git could not list the work tree')
41
+ return new RepoView(scan.files, null, scan, vendored)
44
42
  } catch (e) {
45
43
  return new RepoView(walk(root), e instanceof Error ? e.message : String(e), null, vendored)
46
44
  }
@@ -54,24 +52,6 @@ export class RepoView {
54
52
  }
55
53
  }
56
54
 
57
- /** a tree id names its content, so its file list is a pure function of the
58
- * id and one listing serves every view of that tree. `--full-tree` keeps it
59
- * so: without it git filters the listing by the cwd's path under the work
60
- * tree, and a nested folder's own subtree lists nothing */
61
- const listed = new Map<string, string[]>()
62
- const LISTED_MAX = 64
63
-
64
- function filesOf(root: string, tree: string): string[] {
65
- const hit = listed.get(tree)
66
- if (hit != null) return hit
67
- const p = Bun.spawnSync([gitBin(), 'ls-tree', '--full-tree', '-r', '-z', '--name-only', tree], { cwd: root, stdout: 'pipe', stderr: 'pipe' })
68
- if (p.exitCode !== 0) throw new GitScanError(`git ls-tree exited ${p.exitCode}: ${p.stderr.toString().trim()}`)
69
- const files = p.stdout.toString().split('\0').filter((f) => f !== '').sort()
70
- if (listed.size >= LISTED_MAX) listed.delete(listed.keys().next().value!)
71
- listed.set(tree, files)
72
- return files
73
- }
74
-
75
55
  /** no git: every file under the root, installs and dot dirs left out */
76
56
  function walk(root: string): string[] {
77
57
  try {
@@ -0,0 +1,14 @@
1
+ // every kind the machine's media store holds (wiki build/shipkit/media-store.md, A kind): the daemon and `sk media` read
2
+ // this list. A new caller writes its kind beside its own code and adds its line here
3
+ import type { MediaKind } from './media-store/kind.ts'
4
+ import { handKind, labelsInIndex } from './media-store/hand.ts'
5
+ import { reviewMedia } from './review/media-kind.ts'
6
+ import { trailerMedia } from './review/trailer-media.ts'
7
+
8
+ export const MEDIA_KINDS: readonly MediaKind[] = [reviewMedia, trailerMedia]
9
+
10
+ /** the kinds of the code, then the generic kind of every other label the index holds (`sk media put`) */
11
+ export function mediaKinds(): MediaKind[] {
12
+ const code = new Set(MEDIA_KINDS.map((k) => k.kind))
13
+ return [...MEDIA_KINDS, ...labelsInIndex().filter((l) => !code.has(l)).map(handKind)]
14
+ }
@@ -0,0 +1,61 @@
1
+ // a media file by its content (wiki build/shipkit/media-store.md): its sha256, size and type, and the one key the Space
2
+ // keeps it under, `<kind>/<sha256>.<ext>`, the same for every caller and repo that names it
3
+ import { existsSync, statSync } from 'node:fs'
4
+ import { extname, join } from 'node:path'
5
+ import type { MediaFact } from './fact.ts'
6
+
7
+ const TYPES: Record<string, string> = {
8
+ '.png': 'image/png',
9
+ '.jpg': 'image/jpeg',
10
+ '.jpeg': 'image/jpeg',
11
+ '.webp': 'image/webp',
12
+ '.mp4': 'video/mp4',
13
+ '.webm': 'video/webm',
14
+ '.wav': 'audio/wav',
15
+ '.mp3': 'audio/mpeg',
16
+ '.flac': 'audio/flac',
17
+ '.ogg': 'audio/ogg',
18
+ '.opus': 'audio/opus',
19
+ '.m4a': 'audio/mp4',
20
+ '.gif': 'image/gif',
21
+ '.pdf': 'application/pdf',
22
+ '.zip': 'application/zip',
23
+ '.gz': 'application/gzip',
24
+ '.tar': 'application/x-tar',
25
+ '.dmg': 'application/x-apple-diskimage',
26
+ '.json': 'application/json',
27
+ '.txt': 'text/plain; charset=utf-8',
28
+ '.md': 'text/markdown; charset=utf-8',
29
+ '.csv': 'text/csv; charset=utf-8',
30
+ }
31
+
32
+ export const typeOf = (name: string): string => TYPES[extname(name).toLowerCase()] ?? 'application/octet-stream'
33
+
34
+ /** a file's sha256, read as a stream: a clip is never held whole */
35
+ export async function shaOf(file: string): Promise<string> {
36
+ const h = new Bun.CryptoHasher('sha256')
37
+ for await (const chunk of Bun.file(file).stream()) h.update(chunk)
38
+ return h.digest('hex')
39
+ }
40
+
41
+ export async function factOf(file: string): Promise<MediaFact> {
42
+ return { sha: await shaOf(file), size: statSync(file).size, type: typeOf(file) }
43
+ }
44
+
45
+ /** the facts of `names` in a folder: a fact `keep` holds is kept unless its name is in `fresh` (a file this write
46
+ * replaced), every other file present is hashed; a name with no file and no fact is left out */
47
+ export async function factsOf(folder: string, names: readonly string[], keep: Record<string, MediaFact> = {}, fresh: ReadonlySet<string> = new Set()): Promise<Record<string, MediaFact>> {
48
+ const out: Record<string, MediaFact> = {}
49
+ for (const n of [...new Set(names)].sort()) {
50
+ const held = keep[n]
51
+ if (held && !fresh.has(n)) out[n] = held
52
+ else if (existsSync(join(folder, n))) out[n] = await factOf(join(folder, n))
53
+ }
54
+ return out
55
+ }
56
+
57
+ /** where the Space keeps a file of a kind: its content's sha and the extension of its name */
58
+ export const mediaKey = (kind: string, f: Pick<MediaFact, 'sha'>, name: string): string => `${kind}/${f.sha}${extname(name).toLowerCase()}`
59
+
60
+ /** the sha a key names, null when it is no content key */
61
+ export const shaOfKey = (key: string): string | null => /^[a-z0-9-]+\/([0-9a-f]{64})(?:\.|$)/.exec(key)?.[1] ?? null
@@ -0,0 +1,91 @@
1
+ // the daemon's media loop (wiki build/shipkit/media-store.md, The daemon): every kind of every house repo scanned into
2
+ // the machine index once its store moved, what waits sent up, and (when the owner turned it on) the disk purged under
3
+ // 40 GB free. Each failure is one line in the daemon's log
4
+ import { existsSync } from 'node:fs'
5
+ import { machineGet, machineSet } from '../core/machine-db.ts'
6
+ import type { MediaKind } from './kind.ts'
7
+ import { FREE_MIN_BYTES, freeBytes, purge, purgeCandidates } from './purge.ts'
8
+ import { machineSpace } from './space.ts'
9
+ import { syncKind } from './sync.ts'
10
+ import { mb, uploadWaiting } from './upload.ts'
11
+
12
+ const TICK_MS = 30_000
13
+ const PURGE_EVERY_MS = 10 * 60_000
14
+ const AUTO_KEY = 'media-purge-auto'
15
+
16
+ /** the owner's switch: the daemon purges on its own only once he turned it on */
17
+ export const autoPurgeOn = (): boolean => machineGet<boolean>(AUTO_KEY) === true
18
+ export const setAutoPurge = (on: boolean): boolean => machineSet(AUTO_KEY, on)
19
+
20
+ export interface MediaLoop {
21
+ stop(): void
22
+ /** one pass now, for a test */
23
+ once(): Promise<void>
24
+ }
25
+
26
+ export function startMediaStore(o: { roots: () => string[]; kinds: () => readonly MediaKind[]; print: (l: string) => void; printErr: (l: string) => void; tickMs?: number }): MediaLoop {
27
+ const synced = new Map<string, string>()
28
+ let busy = false
29
+ let lastPurge = 0
30
+ let toldNoSpace = false
31
+ const stores = (): { kind: MediaKind; root: string; dir: string }[] =>
32
+ o.roots().flatMap((root) =>
33
+ o.kinds().flatMap((kind) => {
34
+ const dir = kind.storeOf(root)
35
+ return dir && existsSync(dir) ? [{ kind, root, dir }] : []
36
+ }),
37
+ )
38
+ const once = async (): Promise<void> => {
39
+ if (busy) return
40
+ busy = true
41
+ try {
42
+ for (const { kind, root, dir } of stores()) {
43
+ const id = `${kind.kind}\0${dir}`
44
+ try {
45
+ const stamp = kind.stamp(dir)
46
+ if (synced.get(id) === stamp) continue
47
+ const r = await syncKind(kind, dir, { fill: 50 })
48
+ // files left to hash: the next tick goes on with them
49
+ synced.set(id, r.left > 0 ? '' : stamp)
50
+ if (r.filled > 0) o.print(`ok: media store: ${r.filled} ${kind.kind} files of ${root} hashed${r.left > 0 ? `, ${r.left} to go` : ''}`)
51
+ } catch (e) {
52
+ o.printErr(`WARN media store: the ${kind.kind} files of ${root} did not sync: ${(e as Error).message}`)
53
+ }
54
+ }
55
+ const { space, why } = await machineSpace()
56
+ if (!space) {
57
+ if (!toldNoSpace) o.printErr(`WARN media store: nothing goes up: ${why}`)
58
+ toldNoSpace = true
59
+ return
60
+ }
61
+ const up = await uploadWaiting(space, { limit: 200, jobs: 3 })
62
+ if (up.up + up.there > 0) o.print(`ok: media store: ${up.up} up (${mb(up.bytes)})${up.there > 0 ? `, ${up.there} already there` : ''}`)
63
+ if (up.failed.length > 0) o.printErr(`WARN media store: ${up.failed.length} uploads failed, tried again later; first: ${up.failed[0]?.key}: ${up.failed[0]?.error}`)
64
+ if (autoPurgeOn() && Date.now() - lastPurge > PURGE_EVERY_MS) {
65
+ lastPurge = Date.now()
66
+ for (const { kind, root, dir } of stores()) {
67
+ if (freeBytes(dir) >= FREE_MIN_BYTES) continue
68
+ const { candidates } = await purgeCandidates(kind, dir)
69
+ const r = await purge(kind, dir, space, candidates, { enough: () => freeBytes(dir) >= FREE_MIN_BYTES })
70
+ if (r.files > 0) o.print(`ok: media store: the disk under ${mb(FREE_MIN_BYTES)} free, ${r.files} ${kind.kind} files of ${root} purged (${mb(r.freed)})`)
71
+ if (r.refused.length > 0) o.printErr(`WARN media store: ${r.refused.length} ${kind.kind} files of ${root} kept: ${r.refused[0]?.key}: ${r.refused[0]?.why}`)
72
+ }
73
+ }
74
+ } catch (e) {
75
+ o.printErr(`WARN media store: the pass broke: ${(e as Error).message}`)
76
+ } finally {
77
+ busy = false
78
+ }
79
+ }
80
+ const every = setInterval(() => void once(), o.tickMs ?? TICK_MS)
81
+ every.unref()
82
+ const boot = setTimeout(() => void once(), 15_000)
83
+ boot.unref()
84
+ return {
85
+ stop: () => {
86
+ clearInterval(every)
87
+ clearTimeout(boot)
88
+ },
89
+ once,
90
+ }
91
+ }
@@ -0,0 +1,74 @@
1
+ // THE MACHINE'S MEDIA INDEX (wiki build/shipkit/media-store.md, The index): one sqlite file in the home's state folder,
2
+ // never in a repo, for every media file of this machine, whatever kind holds it. It is DERIVED: each kind's files stay
3
+ // the truth, and a deleted index builds again from them (a file's place in the Space is found again by a HEAD). It holds
4
+ // each file a kind names (local or not), each Space object (up or waiting, its retries), and the review store's item
5
+ // reads by the code that read them
6
+ import { Database } from 'bun:sqlite'
7
+ import { mkdirSync } from 'node:fs'
8
+ import { dirname, join } from 'node:path'
9
+ import { homeDir } from '../home/home-paths.ts'
10
+ import { ensureWal } from '../ledger/db.ts'
11
+
12
+ export const MEDIA_DB_ENV = 'SHIPKIT_MEDIA_DB'
13
+ export const mediaDbPath = (): string => process.env[MEDIA_DB_ENV] || join(homeDir(), 'media.sqlite')
14
+
15
+ const BUSY_MS = 3_000
16
+
17
+ const SCHEMA = `
18
+ create table if not exists codes (store text not null, code text not null, used integer not null, primary key (store, code)) without rowid;
19
+ create table if not exists items (store text not null, code text not null, id text not null, stamp text not null, read text not null, primary key (store, code, id)) without rowid;
20
+ create table if not exists files (store text not null, item text not null, name text not null, key text not null, size integer not null, local integer not null, purged integer, primary key (store, item, name)) without rowid;
21
+ create index if not exists files_key on files (key);
22
+ create table if not exists objects (key text primary key, size integer not null, up integer, tries integer not null default 0, next integer not null default 0, error text) without rowid;
23
+ `
24
+
25
+ let open: { path: string; db: Database } | null = null
26
+ let warned = false
27
+
28
+ /** the index of this process, opened once; null (said once on stderr) when it does not open: every caller then reads
29
+ * the files alone */
30
+ export function mediaDb(): Database | null {
31
+ const path = mediaDbPath()
32
+ if (open?.path === path) return open.db
33
+ try {
34
+ open?.db.close()
35
+ } catch {
36
+ // already gone
37
+ }
38
+ open = null
39
+ try {
40
+ mkdirSync(dirname(path), { recursive: true })
41
+ const db = new Database(path, { create: true, readwrite: true })
42
+ db.exec(`pragma busy_timeout = ${BUSY_MS}`)
43
+ ensureWal(db, BUSY_MS)
44
+ db.exec('pragma synchronous = NORMAL')
45
+ db.exec(SCHEMA)
46
+ open = { path, db }
47
+ return db
48
+ } catch (e) {
49
+ if (!warned) console.error(`WARN media index ${path} does not open, so every read goes to the files: ${(e as Error).message}`)
50
+ warned = true
51
+ return null
52
+ }
53
+ }
54
+
55
+ /** closes this process's index (a test that moves it) */
56
+ export function closeMediaDb(): void {
57
+ try {
58
+ open?.db.close()
59
+ } catch {
60
+ // already gone
61
+ }
62
+ open = null
63
+ }
64
+
65
+ /** a write that fails is one line, never a throw: the index is derived, the next read writes it again */
66
+ export function tryWrite(what: string, body: (db: Database) => void): void {
67
+ const db = mediaDb()
68
+ if (!db) return
69
+ try {
70
+ db.transaction(() => body(db))()
71
+ } catch (e) {
72
+ console.error(`WARN media index: ${what} not written: ${(e as Error).message}`)
73
+ }
74
+ }
@@ -0,0 +1,9 @@
1
+ // a media file known by its content (wiki build/shipkit/media-store.md): the shape every caller records beside its file
2
+ // name. Pure, so a page's types read it too
3
+ export interface MediaFact {
4
+ /** sha256, hex */
5
+ sha: string
6
+ size: number
7
+ /** its MIME type */
8
+ type: string
9
+ }
@@ -0,0 +1,58 @@
1
+ // the generic kind (wiki build/shipkit/media-store.md, Put a file from any repo): a label no `MediaKind` of the code
2
+ // owns, its files named by hand through `sk media put`. The index is its only record, so its scan reads the index's
3
+ // own rows back and asks the disk whether each file still holds the bytes of its key; nothing else names them
4
+ import { statSync } from 'node:fs'
5
+ import { join, resolve } from 'node:path'
6
+ import { shaOf, shaOfKey, typeOf } from './content.ts'
7
+ import { mediaDb } from './db.ts'
8
+ import type { MediaKind, MediaRow } from './kind.ts'
9
+
10
+ /** a label `sk media put` takes: the key prefix in the Space */
11
+ export const LABEL = /^[a-z0-9-]+$/
12
+ export const DEFAULT_LABEL = 'files'
13
+
14
+ /** the stores the index holds rows of under this label */
15
+ function storesOf(label: string): string[] {
16
+ const db = mediaDb()
17
+ if (!db) return []
18
+ const p = `${label}/`
19
+ return (db.query('select distinct store from files where substr(key, 1, ?) = ?').all(p.length, p) as { store: string }[]).map((r) => r.store)
20
+ }
21
+
22
+ /** every label the index holds rows of */
23
+ export function labelsInIndex(): string[] {
24
+ const db = mediaDb()
25
+ if (!db) return []
26
+ return (db.query(`select distinct substr(key, 1, instr(key, '/') - 1) as label from files`).all() as { label: string }[]).map((r) => r.label).filter((l) => LABEL.test(l))
27
+ }
28
+
29
+ const rowsOf = (label: string, store: string): { item: string; name: string; key: string; size: number }[] => {
30
+ const p = `${label}/`
31
+ return (mediaDb()?.query('select item, name, key, size from files where store = ? and substr(key, 1, ?) = ?').all(store, p.length, p) ?? []) as { item: string; name: string; key: string; size: number }[]
32
+ }
33
+
34
+ export function handKind(label: string): MediaKind {
35
+ return {
36
+ kind: label,
37
+ storeOf: (root) => (storesOf(label).includes(resolve(root)) ? resolve(root) : null),
38
+ // the index is the record: read it again every 10 min, to see a file the disk let go
39
+ stamp: () => String(Math.floor(Date.now() / 600_000)),
40
+ async scan(store) {
41
+ const rows: MediaRow[] = []
42
+ for (const r of rowsOf(label, store)) {
43
+ const sha = shaOfKey(r.key)
44
+ if (!sha) continue
45
+ const size = statSync(join(store, r.item, r.name), { throwIfNoEntry: false })?.size
46
+ rows.push({ item: r.item, name: r.name, fact: { sha, size: r.size, type: typeOf(r.name) }, local: size === r.size })
47
+ }
48
+ return { rows, filled: 0, left: 0 }
49
+ },
50
+ async holds(store) {
51
+ return (row) => ({ pinned: false, used: statSync(join(store, row.item, row.name), { throwIfNoEntry: false })?.mtimeMs })
52
+ },
53
+ async beforePurge(store, _space, row) {
54
+ const sha = await shaOf(join(store, row.item, row.name))
55
+ if (sha !== shaOfKey(row.key)) throw new Error(`${join(row.item, row.name)} changed since it was put: its bytes hash to ${sha.slice(0, 12)}, the key says ${row.key}`)
56
+ },
57
+ }
58
+ }
@@ -0,0 +1,44 @@
1
+ // what a caller of the media store plugs in (wiki build/shipkit/media-store.md, A kind): where its files live in a repo,
2
+ // what they are, and what must stay on the disk. The store does the rest: the index, the upload, the signed URL, the
3
+ // fetch back, the purge. A row's path is always `join(store, item, name)`, the one form every scan, pin and delete uses
4
+ import type { MediaFact } from './fact.ts'
5
+ import type { Space } from './space.ts'
6
+
7
+ /** one file a kind names: its folder relative to the store, its name, its content when known, whether the disk holds it */
8
+ export interface MediaRow {
9
+ item: string
10
+ name: string
11
+ /** null: never hashed, and the disk lacks it (lost before it went up) */
12
+ fact: MediaFact | null
13
+ local: boolean
14
+ }
15
+
16
+ export interface Scan {
17
+ rows: MediaRow[]
18
+ /** files hashed this pass */
19
+ filled: number
20
+ /** files left to hash: the budget ran out */
21
+ left: number
22
+ }
23
+
24
+ /** what the purge reads of one row: pinned rows stay, the rest go once quiet for the window */
25
+ export interface Hold {
26
+ pinned: boolean
27
+ /** the row's last use (ms), the window's clock; undefined keeps the row (nothing names it, so nothing is sure) */
28
+ used: number | undefined
29
+ }
30
+
31
+ export interface MediaKind {
32
+ /** the key prefix in the Space and the name in every report: `review`, `trailer` */
33
+ readonly kind: string
34
+ /** the folder of a repo the kind's rows are relative to; null when the repo holds none */
35
+ storeOf(root: string): string | null
36
+ /** a cheap stamp of the store: the daemon scans again only once it moved */
37
+ stamp(store: string): string
38
+ /** every file the kind names in the store; at most `fill` files hashed this pass (Infinity: all) */
39
+ scan(store: string, o: { fill: number }): Promise<Scan>
40
+ /** the purge's judge of each row, read once per purge */
41
+ holds(store: string, now: number): Promise<(row: Pick<MediaRow, 'item' | 'name'>) => Hold>
42
+ /** run before a file leaves the disk; a throw keeps it (review sends an image's previews up, trailer checks the sha) */
43
+ beforePurge?(store: string, space: Space, row: { item: string; name: string; key: string; size: number }): Promise<void>
44
+ }