@ds-hu/dsh-bvi-local 0.0.0-stage → 0.1.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.
@@ -0,0 +1,427 @@
1
+ /**
2
+ * Variant installation: verify, download, unpack and publish the files one model variant needs.
3
+ *
4
+ * The installation layer is the only writer of the model tree. It reuses already verified files,
5
+ * downloads per-file HuggingFace sources or one release archive, unpacks archive-only variants,
6
+ * installs the shared Silero VAD model when a family segments audio, and finally checks that every
7
+ * pinned file is present with the expected size. Progress is reported as a sequence of small
8
+ * state events (checking / downloading / extracting / verifying) that the provider maps onto the
9
+ * official preparation phases; byte totals always describe the exact amount still to download.
10
+ *
11
+ * One installation per destination runs at a time: concurrent callers join the running task and
12
+ * share its progress, and the underlying work is aborted only when every waiter has gone away.
13
+ *
14
+ * @module @ds-hu/dsh-bvi-local/provision/install
15
+ */
16
+ import { basename, dirname, join } from 'node:path'
17
+ import { mkdir, rm, stat } from 'node:fs/promises'
18
+ import { downloadAsset, verifyAsset } from './download.js'
19
+ import { extractArchive, variantFilePath } from './archive.js'
20
+
21
+ /** Shared VAD asset lives in one place for every family. */
22
+ const SHARED_DIRECTORY = '_shared'
23
+ /** Downloaded release archives are cached by digest until unpacked. */
24
+ const ARCHIVE_DIRECTORY = '_archives'
25
+
26
+ /**
27
+ * One failed installation, carrying a stable machine code.
28
+ */
29
+ export class InstallError extends Error {
30
+ /**
31
+ * @param {'verify'|'archive'|'download'|'layout'} code - stable code.
32
+ * @param {string} message - human-readable explanation.
33
+ * @param {ErrorOptions} [options] - native error options.
34
+ */
35
+ constructor(code, message, options) {
36
+ super(message, options)
37
+ this.name = 'InstallError'
38
+ this.code = code
39
+ }
40
+ }
41
+
42
+ /**
43
+ * @param {AbortSignal|undefined} signal - cancellation signal.
44
+ * @returns {void}
45
+ * @throws {Error} when the signal is already aborted.
46
+ */
47
+ function throwIfAborted(signal) {
48
+ if (signal !== undefined) signal.throwIfAborted()
49
+ }
50
+
51
+ /**
52
+ * @param {AbortSignal} signal - aborted signal.
53
+ * @returns {Error} the abort reason or a plain abort error.
54
+ */
55
+ function abortReasonOf(signal) {
56
+ const reason = signal.reason
57
+ if (reason instanceof Error) return reason
58
+ const error = new Error('The installation was cancelled')
59
+ error.name = 'AbortError'
60
+ return error
61
+ }
62
+
63
+ /**
64
+ * Absolute directory that holds one variant's model files.
65
+ * @param {string} root - model root (`config.dataRoot`).
66
+ * @param {{ family: string }} model - catalog record.
67
+ * @param {{ id: string }} variant - catalog variant.
68
+ * @returns {string} absolute variant directory.
69
+ */
70
+ export function variantDirectory(root, model, variant) {
71
+ return join(root, model.family, variant.id)
72
+ }
73
+
74
+ /**
75
+ * Absolute path of one shared asset (currently only the Silero VAD model).
76
+ * @param {string} root - model root.
77
+ * @param {{ name: string }} asset - shared-asset record.
78
+ * @returns {string} absolute asset path.
79
+ */
80
+ export function sharedAssetPath(root, asset) {
81
+ return join(root, SHARED_DIRECTORY, asset.name)
82
+ }
83
+
84
+ /**
85
+ * Absolute cache path for one release archive, keyed by its pinned digest.
86
+ * @param {string} root - model root.
87
+ * @param {{ sha256: string }} archive - archive identity.
88
+ * @returns {string} absolute archive path.
89
+ */
90
+ export function archiveCachePath(root, archive) {
91
+ return join(root, ARCHIVE_DIRECTORY, `${archive.sha256}.zip`)
92
+ }
93
+
94
+ /**
95
+ * Map every expected catalog file of one variant to its absolute installed path.
96
+ * @param {string} root - model root.
97
+ * @param {{ family: string }} model - catalog record.
98
+ * @param {{ id: string, files: Array<{ relativePath: string }> }} variant - catalog variant.
99
+ * @returns {Map<string, string>} relative catalog path -> absolute path.
100
+ */
101
+ export function installedFilePaths(root, model, variant) {
102
+ const directory = variantDirectory(root, model, variant)
103
+ /** @type {Map<string, string>} */
104
+ const paths = new Map()
105
+ for (const file of variant.files) paths.set(file.relativePath, variantFilePath(directory, file.relativePath))
106
+ return paths
107
+ }
108
+
109
+ /** HuggingFace file URLs are served by either pinned HF host through a path rewrite. */
110
+ const HUGGING_FACE_ORIGINS = new Set(['https://huggingface.co', 'https://hf-mirror.com'])
111
+
112
+ /**
113
+ * Origins that can serve the selected variant.
114
+ *
115
+ * Per-file HuggingFace variants are reachable from both pinned HF hosts (the downloader rewrites
116
+ * the URL path onto the chosen origin), while an archive variant is only reachable from the host
117
+ * that publishes the release asset. The result keeps the catalog order so the UI's source picker
118
+ * is stable.
119
+ * @param {{ downloadSources?: string[] }} model - catalog record.
120
+ * @param {{ files?: Array<{ url?: string }>, archive?: { url: string } }} variant - catalog variant.
121
+ * @returns {string[]} applicable origins in catalog order.
122
+ */
123
+ export function downloadSourcesForVariant(model, variant) {
124
+ /** @type {Set<string>} */
125
+ const fileOrigins = new Set()
126
+ for (const file of variant.files ?? []) {
127
+ if (typeof file.url === 'string' && file.url !== '') fileOrigins.add(new URL(file.url).origin)
128
+ }
129
+ const archiveOrigin = variant.archive === undefined ? undefined : new URL(variant.archive.url).origin
130
+ return (model.downloadSources ?? []).filter((source) => {
131
+ let origin
132
+ try {
133
+ origin = new URL(source).origin
134
+ } catch {
135
+ return false
136
+ }
137
+ if (archiveOrigin !== undefined && origin === archiveOrigin) return true
138
+ if (fileOrigins.has(origin)) return true
139
+ return HUGGING_FACE_ORIGINS.has(origin) && [...fileOrigins].some((fileOrigin) => HUGGING_FACE_ORIGINS.has(fileOrigin))
140
+ })
141
+ }
142
+
143
+ /**
144
+ * @template T
145
+ * @param {string} key - destination key of the single-flight task.
146
+ * @param {(signal: AbortSignal, report: (progress: Record<string, any>) => void) => Promise<T>} run - installation work; `report` forwards progress to every waiting caller.
147
+ * @param {{ signal?: AbortSignal, onProgress?: (progress: Record<string, any>) => void }} options - caller cancellation and progress listener.
148
+ * @returns {Promise<T>} result shared by every caller of the same destination.
149
+ */
150
+ const active = new Map()
151
+
152
+ async function joinSingleFlight(key, run, options = {}) {
153
+ /** @type {{ controller: AbortController, listeners: Set<Function>, waiters: number, promise: Promise<any> }} */
154
+ let entry = active.get(key)
155
+ if (entry === undefined) {
156
+ const created = {
157
+ controller: new AbortController(),
158
+ listeners: new Set(),
159
+ waiters: 0,
160
+ /** @type {Promise<any>} */
161
+ promise: Promise.resolve(),
162
+ }
163
+ /* c8 ignore next 3 -- broadcast runs only while a caller waits on the shared task */
164
+ const report = (progress) => {
165
+ for (const listener of created.listeners) listener(progress)
166
+ }
167
+ created.promise = (async () => {
168
+ try {
169
+ return await run(created.controller.signal, report)
170
+ } finally {
171
+ if (active.get(key) === created) active.delete(key)
172
+ }
173
+ })()
174
+ // A caller may abort before joining; keep the shared task from becoming an unhandled rejection.
175
+ void created.promise.catch(() => undefined)
176
+ active.set(key, created)
177
+ entry = created
178
+ }
179
+ const task = entry
180
+ task.waiters += 1
181
+ const listener = options.onProgress
182
+ if (listener !== undefined) task.listeners.add(listener)
183
+ const signal = options.signal
184
+ const aborted = new Promise((_, reject) => {
185
+ if (signal === undefined) return
186
+ if (signal.aborted) {
187
+ reject(abortReasonOf(signal))
188
+ return
189
+ }
190
+ const onAbort = () => reject(abortReasonOf(/** @type {AbortSignal} */ (signal)))
191
+ signal.addEventListener('abort', onAbort, { once: true })
192
+ })
193
+ try {
194
+ return await Promise.race([task.promise, aborted])
195
+ } finally {
196
+ task.waiters -= 1
197
+ if (listener !== undefined) task.listeners.delete(listener)
198
+ if (task.waiters === 0 && !task.controller.signal.aborted) {
199
+ task.controller.abort(new Error('Model installation cancelled'))
200
+ }
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Make one shared asset available and verified, joining a concurrent installation of the same
206
+ * destination when one is already running.
207
+ * @param {{
208
+ * root: string,
209
+ * asset: { name: string, bytes: number, sha256: string, url?: string, mirrorURL?: string },
210
+ * signal?: AbortSignal,
211
+ * onProgress?: (progress: Record<string, any>) => void,
212
+ * fetchImpl?: typeof fetch,
213
+ * downloadTimeoutMs?: number,
214
+ * }} options - shared asset request.
215
+ * @returns {Promise<string>} verified asset path.
216
+ */
217
+ export async function ensureSharedAsset(options) {
218
+ const { root, asset, signal } = options
219
+ const destination = sharedAssetPath(root, asset)
220
+ throwIfAborted(signal)
221
+ if (await verifyAsset(destination, asset, signal)) return destination
222
+ const key = `shared:${root}:${asset.sha256}`
223
+ return await joinSingleFlight(key, async (installSignal, report) => {
224
+ await mkdir(dirname(destination), { recursive: true })
225
+ if (!(await verifyAsset(destination, asset, installSignal))) {
226
+ await downloadAsset({
227
+ asset,
228
+ destination,
229
+ resource: asset.name,
230
+ signal: installSignal,
231
+ onProgress: report,
232
+ fetchImpl: options.fetchImpl,
233
+ timeoutMs: options.downloadTimeoutMs,
234
+ })
235
+ }
236
+ return destination
237
+ }, { signal, onProgress: options.onProgress })
238
+ }
239
+
240
+ /**
241
+ * Verify every pinned file of a variant and report which ones are missing.
242
+ * @param {{ root: string, model: { family: string }, variant: { id: string, files: Array<{ relativePath: string, bytes: number, sha256: string }> } }} options - variant identity.
243
+ * @param {AbortSignal} [signal] - cancellation signal.
244
+ * @returns {Promise<{ complete: boolean, missing: Array<{ relativePath: string, bytes: number, sha256: string }> }>} verification result.
245
+ */
246
+ export async function verifyVariant({ root, model, variant }, signal) {
247
+ throwIfAborted(signal)
248
+ const paths = installedFilePaths(root, model, variant)
249
+ /** @type {Array<{ relativePath: string, bytes: number, sha256: string }>} */
250
+ const missing = []
251
+ for (const file of variant.files) {
252
+ if (!(await verifyAsset(/** @type {string} */ (paths.get(file.relativePath)), file, signal))) missing.push(file)
253
+ }
254
+ return { complete: missing.length === 0, missing }
255
+ }
256
+
257
+ /**
258
+ * Perform the installation work for one variant.
259
+ * @param {{
260
+ * root: string,
261
+ * model: { family: string, downloadSources?: string[] },
262
+ * variant: { id: string, bytes: number, files: Array<{ relativePath: string, bytes: number, sha256: string, url?: string, mirrorURL?: string }>, archive?: { url: string, bytes: number, sha256: string, innerLayout: Record<string, string> } },
263
+ * vadAsset?: { name: string, bytes: number, sha256: string, url?: string, mirrorURL?: string },
264
+ * sources?: readonly string[],
265
+ * signal: AbortSignal,
266
+ * onProgress: (progress: Record<string, any>) => void,
267
+ * fetchImpl?: typeof fetch,
268
+ * downloadTimeoutMs?: number,
269
+ * }} options - installation request.
270
+ * @returns {Promise<{ variantDir: string, files: Map<string, string>, vadPath: string|undefined }>} installed layout.
271
+ */
272
+ async function performInstall(options) {
273
+ const { root, model, variant, vadAsset, sources, signal, onProgress } = options
274
+ const destination = variantDirectory(root, model, variant)
275
+ const paths = installedFilePaths(root, model, variant)
276
+
277
+ onProgress({ phase: 'checking', step: 'model' })
278
+ /** @type {Array<{ relativePath: string, bytes: number, sha256: string }>} */
279
+ const missing = []
280
+ for (const file of variant.files) {
281
+ if (!(await verifyAsset(/** @type {string} */ (paths.get(file.relativePath)), file, signal))) missing.push(file)
282
+ }
283
+ const vadDestination = vadAsset === undefined ? undefined : sharedAssetPath(root, vadAsset)
284
+ const needVad = vadDestination !== undefined && !(await verifyAsset(vadDestination, /** @type {any} */ (vadAsset), signal))
285
+ if (missing.length === 0 && !needVad) {
286
+ onProgress({ phase: 'verifying', step: 'verify' })
287
+ return { variantDir: destination, files: paths, vadPath: vadDestination }
288
+ }
289
+
290
+ /** @type {Array<{ kind: 'file'|'archive'|'vad', asset: any, destination: string, label: string }>} */
291
+ const actions = []
292
+ if (missing.length > 0) {
293
+ if (variant.archive !== undefined) {
294
+ actions.push({
295
+ kind: 'archive',
296
+ asset: variant.archive,
297
+ destination: archiveCachePath(root, variant.archive),
298
+ label: basename(new URL(variant.archive.url).pathname),
299
+ })
300
+ } else {
301
+ for (const file of missing) {
302
+ actions.push({
303
+ kind: 'file',
304
+ asset: file,
305
+ destination: /** @type {string} */ (paths.get(file.relativePath)),
306
+ label: file.relativePath,
307
+ })
308
+ }
309
+ }
310
+ }
311
+ if (needVad) {
312
+ actions.push({ kind: 'vad', asset: vadAsset, destination: /** @type {string} */ (vadDestination), label: /** @type {any} */ (vadAsset).name })
313
+ }
314
+ const totalBytes = actions.reduce((sum, action) => sum + action.asset.bytes, 0)
315
+ let completedBefore = 0
316
+ for (const action of actions) {
317
+ throwIfAborted(signal)
318
+ const report = (progress) => onProgress({
319
+ phase: 'downloading',
320
+ step: action.kind === 'vad' ? 'vad' : 'model',
321
+ resource: action.label,
322
+ completedBytes: completedBefore + progress.completedBytes,
323
+ totalBytes,
324
+ })
325
+ if (action.kind === 'vad') {
326
+ await ensureSharedAsset({
327
+ root,
328
+ asset: action.asset,
329
+ signal,
330
+ onProgress: report,
331
+ fetchImpl: options.fetchImpl,
332
+ downloadTimeoutMs: options.downloadTimeoutMs,
333
+ })
334
+ } else {
335
+ await downloadAsset({
336
+ asset: action.asset,
337
+ destination: action.destination,
338
+ resource: action.label,
339
+ signal,
340
+ onProgress: report,
341
+ sources: action.kind === 'vad' ? undefined : sources,
342
+ fetchImpl: options.fetchImpl,
343
+ timeoutMs: options.downloadTimeoutMs,
344
+ })
345
+ }
346
+ completedBefore += action.asset.bytes
347
+ onProgress({ phase: 'downloading', step: action.kind === 'vad' ? 'vad' : 'model', resource: action.label, completedBytes: completedBefore, totalBytes })
348
+ }
349
+
350
+ const archiveAction = actions.find((action) => action.kind === 'archive')
351
+ if (variant.archive !== undefined && archiveAction !== undefined) {
352
+ onProgress({ phase: 'extracting', step: 'model', resource: archiveAction.label, completedBytes: 0, totalBytes: variant.bytes })
353
+ await extractArchive({
354
+ archivePath: archiveAction.destination,
355
+ innerLayout: variant.archive.innerLayout,
356
+ files: variant.files,
357
+ destination,
358
+ signal,
359
+ onProgress: (progress) => onProgress({
360
+ phase: 'extracting',
361
+ step: 'model',
362
+ resource: progress.relativePath,
363
+ completedBytes: progress.completedBytes,
364
+ totalBytes: progress.totalBytes,
365
+ }),
366
+ })
367
+ await rm(archiveAction.destination, { force: true })
368
+ }
369
+
370
+ onProgress({ phase: 'verifying', step: 'verify' })
371
+ for (const file of variant.files) {
372
+ const path = /** @type {string} */ (paths.get(file.relativePath))
373
+ let info
374
+ try {
375
+ info = await stat(path)
376
+ } catch (error) {
377
+ throw new InstallError('verify', `Installed file is missing: ${file.relativePath}`, { cause: error })
378
+ }
379
+ if (!info.isFile() || info.size !== file.bytes) {
380
+ throw new InstallError('verify', `Installed file has the wrong size: ${file.relativePath}`)
381
+ }
382
+ }
383
+ if (vadDestination !== undefined && !(await verifyAsset(vadDestination, /** @type {any} */ (vadAsset), signal))) {
384
+ throw new InstallError('verify', `Shared VAD asset failed verification: ${String(/** @type {any} */ (vadAsset).name)}`)
385
+ }
386
+ onProgress({ phase: 'verifying', step: 'verify', completedBytes: 0, totalBytes: 0 })
387
+ return { variantDir: destination, files: paths, vadPath: vadDestination }
388
+ }
389
+
390
+ /**
391
+ * Install one catalog variant (and the shared VAD asset when the family needs it), joining a
392
+ * concurrent installation of the same destination.
393
+ *
394
+ * Reuses verified files; downloads the pinned per-file sources, or the release archive of
395
+ * archive-only variants and unpacks only its whitelisted members. Cancelling all callers aborts
396
+ * the active download; already published files stay valid for the next attempt.
397
+ * @param {{
398
+ * root: string,
399
+ * model: { family: string, downloadSources?: string[] },
400
+ * variant: { id: string, bytes: number, files: Array<{ relativePath: string, bytes: number, sha256: string, url?: string, mirrorURL?: string }>, archive?: { url: string, bytes: number, sha256: string, innerLayout: Record<string, string> } },
401
+ * vadAsset?: { name: string, bytes: number, sha256: string, url?: string, mirrorURL?: string },
402
+ * downloadSource?: string,
403
+ * signal?: AbortSignal,
404
+ * onProgress?: (progress: Record<string, any>) => void,
405
+ * fetchImpl?: typeof fetch,
406
+ * downloadTimeoutMs?: number,
407
+ * }} options - installation request.
408
+ * @returns {Promise<{ variantDir: string, files: Map<string, string>, vadPath: string|undefined }>} installed layout.
409
+ * @throws {InstallError|import('./download').DownloadError|import('./archive').ArchiveError} when installation fails or is cancelled.
410
+ */
411
+ export async function ensureVariantInstalled(options) {
412
+ const { root, model, variant } = options
413
+ throwIfAborted(options.signal)
414
+ const sources = options.downloadSource === undefined ? undefined : [options.downloadSource]
415
+ const key = `variant:${variantDirectory(root, model, variant)}`
416
+ return await joinSingleFlight(key, async (installSignal, report) => performInstall({
417
+ root,
418
+ model,
419
+ variant,
420
+ vadAsset: options.vadAsset,
421
+ sources,
422
+ signal: installSignal,
423
+ onProgress: report,
424
+ fetchImpl: options.fetchImpl,
425
+ downloadTimeoutMs: options.downloadTimeoutMs,
426
+ }), { signal: options.signal, onProgress: options.onProgress })
427
+ }