@huaqiu/hardware-artifacts 0.7.18 → 0.7.20

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,430 @@
1
+ /**
2
+ * Download → verify → extract → validate → promote, as one cancellable job.
3
+ *
4
+ * The order of the stages *is* the safety property (§8.5): nothing is reported
5
+ * installed until a checksum matched the manifest entry and the extracted
6
+ * executables answered a version probe, and a failure at any stage removes what
7
+ * that stage wrote. Every stage is host-side and asynchronous, so the browser
8
+ * only ever polls progress (§7.5).
9
+ *
10
+ * @module @huaqiu/hardware-artifacts/toolchain/install
11
+ */
12
+ import { createHash } from 'node:crypto'
13
+ import { createWriteStream, existsSync } from 'node:fs'
14
+ import { mkdir, rename, rm, stat } from 'node:fs/promises'
15
+ import { join } from 'node:path'
16
+ import { Readable, Transform } from 'node:stream'
17
+ import { pipeline } from 'node:stream/promises'
18
+ import type { ManifestEntry } from './manifest.js'
19
+ import { label, type ToolchainId } from './resolve.js'
20
+ import { commonDirectory, extractZip, readZipDirectory, ZipError } from './zip.js'
21
+
22
+ /** Stage a job is in; the first five are transient, the last three terminal. */
23
+ export type InstallPhase =
24
+ | 'download'
25
+ | 'verify'
26
+ | 'extract'
27
+ | 'layout'
28
+ | 'promote'
29
+ | 'done'
30
+ | 'failed'
31
+ | 'cancelled'
32
+
33
+ /** A stable error vocabulary for the UI, independent of Node's error text. */
34
+ export type InstallErrorCode =
35
+ | 'http'
36
+ | 'network'
37
+ | 'checksum-mismatch'
38
+ | 'invalid-zip'
39
+ | 'unsafe-entry'
40
+ | 'archive-too-large'
41
+ | 'unsupported-compression'
42
+ | 'unsupported-zip64'
43
+ | 'duplicate-entry'
44
+ | 'layout'
45
+ | 'validation'
46
+ | 'disk'
47
+ | 'cancelled'
48
+ | 'internal'
49
+
50
+ /** One job's observable state, as the UI polls it. */
51
+ export interface InstallJobSnapshot {
52
+ readonly id: string
53
+ readonly tool: ToolchainId
54
+ readonly version: string
55
+ readonly phase: InstallPhase
56
+ /** Bytes received so far (download), or written so far (extract). */
57
+ readonly received: number
58
+ /** Total bytes when the server or the archive declared a reliable one. */
59
+ readonly total?: number
60
+ /** Whole-percent progress, present only when `total` is known. */
61
+ readonly percent?: number
62
+ /** Operator-facing line for the current stage. */
63
+ readonly message: string
64
+ readonly errorCode?: InstallErrorCode
65
+ readonly error?: string
66
+ /** Installation root the job registered, on success only. */
67
+ readonly installPath?: string
68
+ readonly startedAt: number
69
+ readonly finishedAt?: number
70
+ }
71
+
72
+ /** How one job ended. */
73
+ export interface InstallOutcome {
74
+ readonly ok: boolean
75
+ /** Installation root promoted (or reused) on success. */
76
+ readonly installPath?: string
77
+ /** Version the manifest asked for. */
78
+ readonly version: string
79
+ /** True when an already-installed, valid copy satisfied the request (§8.6). */
80
+ readonly reused: boolean
81
+ readonly errorCode?: InstallErrorCode
82
+ readonly error?: string
83
+ }
84
+
85
+ /** What the manager supplies to one run. */
86
+ export interface InstallHooks {
87
+ /**
88
+ * Validate the extracted/promoted installation before it may be registered.
89
+ * @param installPath - candidate installation root.
90
+ * @returns whether it is usable, with the reason when it is not.
91
+ */
92
+ readonly validate: (installPath: string) => Promise<{ readonly ok: boolean; readonly error?: string }>
93
+ /** Receive each progress step (the manager fans it out to its status cache). */
94
+ readonly onProgress?: (snapshot: InstallJobSnapshot) => void
95
+ }
96
+
97
+ /** Injectable boundaries, so the whole stage machine is testable. */
98
+ export interface InstallerOptions {
99
+ /** Per-user toolchain root (`<DSH home>/toolchains`). */
100
+ readonly root: string
101
+ readonly fetchImpl?: typeof fetch
102
+ /** Abort the download stage after this long without a byte. */
103
+ readonly idleTimeoutMs?: number
104
+ readonly now?: () => number
105
+ readonly idPrefix?: string
106
+ }
107
+
108
+ /** The primary file an installation must contain, per distribution (§8.2/§8.3). */
109
+ export function expectedLayout(tool: ToolchainId, platform: NodeJS.Platform = process.platform): string[] {
110
+ const exe = platform === 'win32' ? '.exe' : ''
111
+ if (tool === 'kicad') {
112
+ return platform === 'darwin'
113
+ ? ['KiCad.app/Contents/MacOS/kicad-cli']
114
+ : [join('bin', `kicad-cli${exe}`)]
115
+ }
116
+ return [`solidcraft${exe}`]
117
+ }
118
+
119
+ /** The stable vocabulary, as a runtime list so a thrown code can be recognised. */
120
+ const INSTALL_ERROR_CODES: readonly InstallErrorCode[] = [
121
+ 'http', 'network', 'checksum-mismatch', 'invalid-zip', 'unsafe-entry', 'archive-too-large',
122
+ 'unsupported-compression', 'unsupported-zip64', 'duplicate-entry', 'layout', 'validation',
123
+ 'disk', 'cancelled', 'internal',
124
+ ]
125
+
126
+ /** Wrap a Node/unknown failure into the job's stable vocabulary. */
127
+ function classify(error: unknown): { code: InstallErrorCode; message: string } {
128
+ const declared = (error as { code?: unknown } | null)?.code
129
+ if (typeof declared === 'string' && INSTALL_ERROR_CODES.includes(declared as InstallErrorCode)) {
130
+ return { code: declared as InstallErrorCode, message: error instanceof Error ? error.message : String(error) }
131
+ }
132
+ if (error instanceof ZipError) {
133
+ return { code: 'invalid-zip', message: error.message }
134
+ }
135
+ if (typeof declared === 'string') {
136
+ if (declared === 'ENOSPC' || declared === 'EDQUOT') return { code: 'disk', message: 'not enough free disk space' }
137
+ if (declared === 'ABORT_ERR') return { code: 'cancelled', message: 'the download was cancelled' }
138
+ }
139
+ return { code: 'internal', message: error instanceof Error ? error.message : String(error) }
140
+ }
141
+
142
+ /**
143
+ * Runs one download/install at a time per tool, and reports it as a snapshot.
144
+ *
145
+ * Job identity is the tool: a second request while one is running joins the
146
+ * running job instead of starting a competing one (§14.4).
147
+ */
148
+ export class ToolchainInstaller {
149
+ private readonly jobs = new Map<string, InstallJobSnapshot>()
150
+ private readonly running = new Map<ToolchainId, { id: string; controller: AbortController }>()
151
+ private readonly root: string
152
+ private readonly fetchImpl: typeof fetch
153
+ private readonly idleTimeoutMs: number
154
+ private readonly now: () => number
155
+ private sequence = 0
156
+
157
+ constructor(private readonly options: InstallerOptions) {
158
+ this.root = options.root
159
+ this.fetchImpl = options.fetchImpl ?? fetch
160
+ this.idleTimeoutMs = options.idleTimeoutMs ?? 30_000
161
+ this.now = options.now ?? (() => Date.now())
162
+ }
163
+
164
+ /** One job's current snapshot. */
165
+ snapshot(id: string): InstallJobSnapshot | undefined {
166
+ return this.jobs.get(id)
167
+ }
168
+
169
+ /** The job currently running for one tool, if any. */
170
+ activeFor(tool: ToolchainId): InstallJobSnapshot | undefined {
171
+ const entry = this.running.get(tool)
172
+ return entry === undefined ? undefined : this.jobs.get(entry.id)
173
+ }
174
+
175
+ /**
176
+ * Cancel one job.
177
+ * @param id - job to cancel.
178
+ * @returns true when a running job was signalled.
179
+ */
180
+ cancel(id: string): boolean {
181
+ for (const [tool, entry] of this.running) {
182
+ if (entry.id !== id) continue
183
+ entry.controller.abort()
184
+ this.running.delete(tool)
185
+ return true
186
+ }
187
+ return false
188
+ }
189
+
190
+ /**
191
+ * Start (or join) the install of one manifest entry.
192
+ * @param tool - which toolchain.
193
+ * @param entry - validated manifest entry to install.
194
+ * @param hooks - validation and progress callbacks.
195
+ * @returns the job's initial snapshot and the promise that settles it.
196
+ */
197
+ start(
198
+ tool: ToolchainId,
199
+ entry: ManifestEntry,
200
+ hooks: InstallHooks,
201
+ ): { readonly snapshot: InstallJobSnapshot; readonly done: Promise<InstallOutcome> } {
202
+ const active = this.running.get(tool)
203
+ if (active !== undefined) {
204
+ const snapshot = this.jobs.get(active.id) as InstallJobSnapshot
205
+ return { snapshot, done: Promise.resolve({ ok: false, version: snapshot.version, reused: false, errorCode: 'internal', error: 'another installation is already running' }) }
206
+ }
207
+ this.sequence += 1
208
+ const id = `${tool}-${this.now()}-${this.sequence}`
209
+ const controller = new AbortController()
210
+ this.running.set(tool, { id, controller })
211
+ const initial: InstallJobSnapshot = {
212
+ id, tool, version: entry.version, phase: 'download', received: 0,
213
+ message: `Downloading ${label(tool)} ${entry.version}`, startedAt: this.now(),
214
+ }
215
+ this.jobs.set(id, initial)
216
+ const done = this.run(id, tool, entry, controller, hooks)
217
+ return { snapshot: this.jobs.get(id) as InstallJobSnapshot, done }
218
+ }
219
+
220
+ /** Emit one snapshot and keep it as the job's latest state. */
221
+ private publish(snapshot: InstallJobSnapshot, hooks: InstallHooks): void {
222
+ this.jobs.set(snapshot.id, snapshot)
223
+ hooks.onProgress?.(snapshot)
224
+ }
225
+
226
+ /** Advance one job to a transient stage. */
227
+ private stage(
228
+ id: string,
229
+ tool: ToolchainId,
230
+ version: string,
231
+ phase: InstallPhase,
232
+ message: string,
233
+ progress: { received?: number; total?: number } = {},
234
+ hooks?: InstallHooks,
235
+ ): InstallJobSnapshot {
236
+ const startedAt = this.jobs.get(id)?.startedAt ?? this.now()
237
+ const received = progress.received ?? 0
238
+ const total = progress.total
239
+ const snapshot: InstallJobSnapshot = {
240
+ id, tool, version, phase, received, message, startedAt,
241
+ ...(total === undefined ? {} : { total, percent: total === 0 ? 100 : Math.min(100, Math.round((received / total) * 100)) }),
242
+ }
243
+ this.jobs.set(id, snapshot)
244
+ if (hooks !== undefined) hooks.onProgress?.(snapshot)
245
+ return snapshot
246
+ }
247
+
248
+ /** The whole stage machine for one job. */
249
+ private async run(
250
+ id: string,
251
+ tool: ToolchainId,
252
+ entry: ManifestEntry,
253
+ controller: AbortController,
254
+ hooks: InstallHooks,
255
+ ): Promise<InstallOutcome> {
256
+ const tempRoot = join(this.root, '.tmp')
257
+ const stagingRoot = join(this.root, '.staging')
258
+ const trashRoot = join(this.root, '.trash')
259
+ const archivePath = join(tempRoot, `${tool}-${entry.version}-${id}.zip`)
260
+ const stagingPath = join(stagingRoot, `${tool}-${entry.version}-${id}`)
261
+ const finalPath = join(this.root, tool, entry.version)
262
+ let promoted = false
263
+ try {
264
+ await mkdir(tempRoot, { recursive: true })
265
+ await mkdir(stagingRoot, { recursive: true })
266
+ await mkdir(join(this.root, tool), { recursive: true })
267
+
268
+ // §8.6: an already-installed, valid copy of the requested version is
269
+ // reused rather than downloaded again.
270
+ if (existsSync(finalPath) && (await hooks.validate(finalPath)).ok) {
271
+ this.stage(id, tool, entry.version, 'done', `${label(tool)} ${entry.version} is already installed`, {}, hooks)
272
+ this.jobs.set(id, { ...(this.jobs.get(id) as InstallJobSnapshot), installPath: finalPath })
273
+ return { ok: true, installPath: finalPath, version: entry.version, reused: true }
274
+ }
275
+
276
+ this.stage(id, tool, entry.version, 'download', `Downloading ${label(tool)} ${entry.version}`, {}, hooks)
277
+ const digest = await this.download(id, tool, entry, archivePath, controller, hooks)
278
+
279
+ this.stage(id, tool, entry.version, 'verify', 'Verifying the download', {}, hooks)
280
+ if (digest !== entry.sha256.toLowerCase()) {
281
+ throw Object.assign(new Error('the download does not match the published SHA-256'), { code: 'checksum-mismatch' })
282
+ }
283
+ // The manifest's size is not declared, so the archive's own size is the
284
+ // only "complete download" signal available (§7.5).
285
+ const archiveBytes = (await stat(archivePath)).size
286
+ if (archiveBytes === 0) throw Object.assign(new Error('the downloaded archive is empty'), { code: 'invalid-zip' })
287
+
288
+ this.stage(id, tool, entry.version, 'extract', 'Extracting', { received: 0 }, hooks)
289
+ const directory = await readZipDirectory(archivePath)
290
+ await rm(stagingPath, { recursive: true, force: true })
291
+ await mkdir(stagingPath, { recursive: true })
292
+ const prefix = commonDirectory(directory)
293
+ await extractZip(archivePath, stagingPath, {
294
+ ...(prefix === undefined ? {} : { stripPrefix: prefix }),
295
+ directory,
296
+ signal: controller.signal,
297
+ ...(hooks.onProgress === undefined ? {} : {
298
+ onProgress: (progress) => {
299
+ this.stage(
300
+ id, tool, entry.version, 'extract',
301
+ `Extracting ${String(progress.entries)}/${String(progress.totalEntries)} files`,
302
+ { received: progress.written, total: directory.totalUncompressed },
303
+ hooks,
304
+ )
305
+ },
306
+ }),
307
+ })
308
+
309
+ this.stage(id, tool, entry.version, 'layout', 'Checking the installation layout', {}, hooks)
310
+ for (const relative of expectedLayout(tool)) {
311
+ if (!existsSync(join(stagingPath, relative))) {
312
+ throw Object.assign(new Error(`the archive is missing ${relative}`), { code: 'layout' })
313
+ }
314
+ }
315
+
316
+ this.stage(id, tool, entry.version, 'promote', 'Installing', {}, hooks)
317
+ if (existsSync(finalPath)) {
318
+ // A previously promoted copy exists but did not validate above: move it
319
+ // aside instead of overwriting it in place (§8.4).
320
+ await mkdir(trashRoot, { recursive: true })
321
+ await rename(finalPath, join(trashRoot, `${tool}-${entry.version}-${id}`))
322
+ }
323
+ await rename(stagingPath, finalPath)
324
+ promoted = true
325
+
326
+ const validation = await hooks.validate(finalPath)
327
+ if (!validation.ok) {
328
+ throw Object.assign(new Error(validation.error ?? 'the installed executables did not validate'), { code: 'validation' })
329
+ }
330
+
331
+ await rm(archivePath, { force: true }).catch(() => {})
332
+ this.jobs.set(id, { ...(this.jobs.get(id) as InstallJobSnapshot), phase: 'done', message: `${label(tool)} ${entry.version} installed`, installPath: finalPath, received: 1, total: 1 })
333
+ hooks.onProgress?.(this.jobs.get(id) as InstallJobSnapshot)
334
+ return { ok: true, installPath: finalPath, version: entry.version, reused: false }
335
+ } catch (error) {
336
+ const cancelled = controller.signal.aborted || (error as { code?: unknown } | null)?.code === 'cancelled'
337
+ const failure = classify(error)
338
+ // An unvalidated promotion is not an installation: take it back out.
339
+ if (promoted) {
340
+ await mkdir(trashRoot, { recursive: true }).catch(() => {})
341
+ await rename(finalPath, join(trashRoot, `${tool}-${entry.version}-${id}-rejected`)).catch(() => {})
342
+ }
343
+ await rm(stagingPath, { recursive: true, force: true }).catch(() => {})
344
+ await rm(archivePath, { force: true, maxRetries: 2 }).catch(() => {})
345
+ const phase: InstallPhase = cancelled ? 'cancelled' : 'failed'
346
+ const message = cancelled ? 'Installation cancelled' : `${label(tool)} could not be installed: ${failure.message}`
347
+ this.jobs.set(id, {
348
+ id, tool, version: entry.version, phase, received: 0, message,
349
+ errorCode: cancelled ? 'cancelled' : failure.code, error: message,
350
+ startedAt: this.jobs.get(id)?.startedAt ?? this.now(), finishedAt: this.now(),
351
+ })
352
+ hooks.onProgress?.(this.jobs.get(id) as InstallJobSnapshot)
353
+ return {
354
+ ok: false, version: entry.version, reused: false,
355
+ errorCode: cancelled ? 'cancelled' : failure.code, error: message,
356
+ }
357
+ } finally {
358
+ this.running.delete(tool)
359
+ const snapshot = this.jobs.get(id)
360
+ if (snapshot !== undefined && (snapshot.phase === 'done' || snapshot.phase === 'failed' || snapshot.phase === 'cancelled')) {
361
+ this.jobs.set(id, { ...snapshot, finishedAt: snapshot.finishedAt ?? this.now() })
362
+ }
363
+ }
364
+ }
365
+
366
+ /** Stream one archive to disk, hashing as it arrives. */
367
+ private async download(
368
+ id: string,
369
+ tool: ToolchainId,
370
+ entry: ManifestEntry,
371
+ archivePath: string,
372
+ controller: AbortController,
373
+ hooks: InstallHooks,
374
+ ): Promise<string> {
375
+ const signal = controller.signal
376
+ let response: Response
377
+ try {
378
+ response = await this.fetchImpl(entry.url, { signal, redirect: 'follow' })
379
+ } catch (error) {
380
+ throw Object.assign(new Error(`the download could not start: ${error instanceof Error ? error.message : String(error)}`), { code: 'network' })
381
+ }
382
+ if (!response.ok || response.body === null) {
383
+ throw Object.assign(new Error(`the download answered HTTP ${String(response.status)}`), { code: 'http' })
384
+ }
385
+ const declared = Number(response.headers.get('content-length') ?? '')
386
+ const total = Number.isFinite(declared) && declared > 0 ? declared : undefined
387
+ const digest = createHash('sha256')
388
+ let received = 0
389
+ let lastEmit = 0
390
+ let idle = setTimeout(() => { controller.abort() }, this.idleTimeoutMs)
391
+ idle.unref?.()
392
+ const counter = new Transform({
393
+ transform: (chunk: Buffer, _encoding, callback) => {
394
+ received += chunk.length
395
+ digest.update(chunk)
396
+ clearTimeout(idle)
397
+ idle = setTimeout(() => { controller.abort() }, this.idleTimeoutMs)
398
+ idle.unref?.()
399
+ const now = this.now()
400
+ // Progress is throttled: one snapshot per quarter second is enough for a
401
+ // 840 MB transfer, and a per-chunk update would flood the poll.
402
+ const percent = total === undefined ? 0 : Math.round((received / total) * 100)
403
+ if (now - lastEmit >= 250 || percent === 100) {
404
+ lastEmit = now
405
+ this.stage(
406
+ id, tool, entry.version, 'download',
407
+ total === undefined ? `Downloading (${String(received)} bytes)` : `Downloading ${String(percent)}%`,
408
+ { received, ...(total === undefined ? {} : { total }) },
409
+ hooks,
410
+ )
411
+ }
412
+ callback(null, chunk)
413
+ },
414
+ })
415
+ const source = Readable.fromWeb(response.body as Parameters<typeof Readable.fromWeb>[0])
416
+ const sink = createWriteStream(archivePath)
417
+ try {
418
+ await pipeline(source, counter, sink)
419
+ } finally {
420
+ clearTimeout(idle)
421
+ }
422
+ if (total !== undefined && received !== total) {
423
+ throw Object.assign(
424
+ new Error(`the download stopped at ${String(received)} of ${String(total)} bytes`),
425
+ { code: 'network' },
426
+ )
427
+ }
428
+ return digest.digest('hex')
429
+ }
430
+ }