dsh-dl-server 0.1.0 → 0.2.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.
package/lib/queue.js CHANGED
@@ -1,591 +1,800 @@
1
- import { createHash } from 'node:crypto'
2
- import { createReadStream } from 'node:fs'
3
- import fs from 'node:fs/promises'
4
- import path from 'node:path'
5
- import { formatJobId, isTerminal, parseJobId } from './types.js'
6
-
7
- /** How many times one job may fail before it is parked as `failed`. */
8
- export const MAX_ATTEMPTS = 3
9
-
10
- /** Safe default for `download_cleanup`. */
11
- export const DEFAULT_SCOPE = 'allWithoutFiles'
12
-
13
- export const CLEANUP_SCOPES = ['records', 'cache', 'allWithoutFiles', 'all']
14
-
15
- /** Drop undefined properties: the tool registry requires lossless JSON. */
16
- function compact(object) {
17
- const out = {}
18
- for (const [key, value] of Object.entries(object)) {
19
- if (value !== undefined) out[key] = value
20
- }
21
- return out
22
- }
23
-
24
- /** `J#1042` → `j1042`: the path-safe key used by the per-record storage layout. */
25
- function storageKeyOf(id) {
26
- const seq = parseJobId(id)
27
- return seq === undefined ? id : `j${seq}`
28
- }
29
-
30
- export class QueueError extends Error {
31
- /** @param {string} code @param {string} message */
32
- constructor(code, message) {
33
- super(message)
34
- this.code = code
35
- }
36
- }
37
-
38
- /**
39
- * @typedef {object} Caller
40
- * @property {string} workspace WorkspaceId
41
- * @property {string} session SessionId of the parent session
42
- * @property {string} [origin] subagent name, when the call came from one
43
- */
44
-
45
- /**
46
- * The queue engine. Owns scheduling, state transitions and checkpoints; the
47
- * transport owns bytes and the domain owns durability.
48
- */
49
- export class Queue {
50
- /**
51
- * @param {object} deps
52
- * @param {any} deps.domain opened DLS domain
53
- * @param {import('./transport.js').Transport} deps.transport
54
- * @param {object} deps.config
55
- * @param {(level: string, message: string) => void} [deps.log]
56
- * @param {() => number} [deps.now]
57
- * @param {(sessionId: string) => boolean | Promise<boolean>} [deps.isOwnerAlive]
58
- */
59
- constructor({ domain, transport, config, log = () => {}, now = Date.now, isOwnerAlive }) {
60
- // Per-record keys must match /^[a-zA-Z0-9_-]+$/ while the public id is
61
- // `J#1042`; translate at the storage boundary so callers stay on job ids.
62
- const rawJobs = domain.table('jobs')
63
- this.jobs = {
64
- entries: () => rawJobs.entries(),
65
- get: (id) => rawJobs.get(storageKeyOf(id)),
66
- put: (id, record) => rawJobs.put(storageKeyOf(id), record),
67
- // `deleteMany` only exists from 0.2.2; loop over `delete` so the plugin
68
- // also runs on 0.2.1 profiles.
69
- deleteMany: async (ids) => {
70
- let removed = 0
71
- for (const id of ids) {
72
- if (await rawJobs.delete(storageKeyOf(id))) removed += 1
73
- }
74
- return removed
75
- },
76
- }
77
- this.domain = domain
78
- this.transport = transport
79
- this.config = config
80
- this.log = log
81
- this.now = now
82
- this.isOwnerAlive = isOwnerAlive
83
-
84
- /** @type {Map<string, { controller: AbortController, startedAt: number }>} */
85
- this.active = new Map()
86
- /** @type {Map<string, { done: number, total: number, speed: number, lastDone: number, lastAt: number }>} */
87
- this.progress = new Map()
88
- this.closed = false
89
- this.timer = undefined
90
- this.checkpointTimer = undefined
91
- }
92
-
93
- // ---------------------------------------------------------------- lifecycle
94
-
95
- /** Reconcile persisted state with reality. Call once before serving. */
96
- async recover() {
97
- const resumable = []
98
-
99
- for (const [, record] of this.jobs.entries()) {
100
- if (record.state === 'running') {
101
- record.state = 'paused'
102
- record.pauseReason = 'host_restart'
103
- record.updatedAt = this.now()
104
- await this.jobs.put(record.id, record)
105
- resumable.push(record)
106
- } else if (record.state === 'paused' && record.pauseReason === 'host_restart') {
107
- // A previous shutdown may persist the pause before the process exits; such a
108
- // record still deserves the same resume treatment as a freshly paused one.
109
- resumable.push(record)
110
- }
111
- }
112
-
113
- if (resumable.length > 0) {
114
- this.log('info', `${resumable.length} job(s) interrupted by a restart -> paused(host_restart)`)
115
- }
116
-
117
- if (this.config.autoResumeOnHostRestart) {
118
- for (const record of resumable) {
119
- await this.resume(record.id, { workspace: record.ownerWorkspace, session: record.ownerSession }, { internal: true })
120
- }
121
- }
122
-
123
- await this.#cancelOrphans()
124
-
125
- this.checkpointTimer = setInterval(() => void this.#checkpointAll(), this.config.checkpointSeconds * 1000)
126
- this.checkpointTimer.unref?.()
127
- this.#schedule()
128
- }
129
-
130
- async close() {
131
- this.closed = true
132
- clearTimeout(this.timer)
133
- if (this.checkpointTimer) clearInterval(this.checkpointTimer)
134
-
135
- const pending = []
136
- for (const [id, entry] of this.active) {
137
- entry.controller.abort()
138
- pending.push(this.#stopAs(id, 'host_restart'))
139
- }
140
- await Promise.allSettled(pending)
141
- }
142
-
143
- // ------------------------------------------------------------------- reading
144
-
145
- /** Every session sees every job. */
146
- list() {
147
- return [...this.jobs.entries()].map(([, record]) => this.#view(record))
148
- }
149
-
150
- /** @param {string} id */
151
- get(id) {
152
- const record = this.jobs.get(id)
153
- return record ? this.#view(record) : undefined
154
- }
155
-
156
- /**
157
- * Block until a job reaches a terminal state or the timeout expires.
158
- * @param {string} id
159
- * @param {number} timeoutMs
160
- */
161
- async wait(id, timeoutMs = 60_000) {
162
- const deadline = this.now() + timeoutMs
163
- for (;;) {
164
- const record = this.jobs.get(id)
165
- if (!record) throw new QueueError('not-found', `job ${id} does not exist`)
166
- if (isTerminal(record.state)) return this.#view(record)
167
- if (this.now() >= deadline) return this.#view(record)
168
- await new Promise((resolve) => setTimeout(resolve, 200))
169
- }
170
- }
171
-
172
- // ------------------------------------------------------------------- writing
173
-
174
- /**
175
- * Add a job. Returns immediately; the scheduler picks it up.
176
- * @param {{ urls: string[], destPath: string, expectSha256?: string }} spec
177
- * @param {Caller} caller
178
- */
179
- async enqueue(spec, caller) {
180
- if (!Array.isArray(spec.urls) || spec.urls.length === 0) {
181
- throw new QueueError('url-invalid', 'at least one URL is required')
182
- }
183
- for (const url of spec.urls) {
184
- try {
185
- const parsed = new URL(url)
186
- if (!/^https?:$/.test(parsed.protocol)) throw new Error('scheme')
187
- } catch {
188
- throw new QueueError('url-invalid', `not an http(s) URL: ${url}`)
189
- }
190
- }
191
-
192
- await this.#assertDiskSpace(spec.destPath)
193
-
194
- const seq = await this.#nextSeq()
195
- const id = formatJobId(seq)
196
- const stamp = this.now()
197
-
198
- /** @type {import('./types.js').JobRecord} */
199
- const record = {
200
- id,
201
- seq,
202
- ownerWorkspace: caller.workspace,
203
- ownerSession: caller.session,
204
- origin: caller.origin,
205
- urls: [...spec.urls],
206
- destPath: spec.destPath,
207
- state: 'queued',
208
- createdAt: stamp,
209
- updatedAt: stamp,
210
- bytesTotal: -1,
211
- bytesCheckpoint: 0,
212
- attempts: 0,
213
- expectSha256: spec.expectSha256,
214
- }
215
-
216
- await this.jobs.put(id, record)
217
- this.log('info', `${id} enqueued by ${caller.workspace}#${caller.session.slice(0, 8)}`)
218
- this.#schedule()
219
- return this.#view(record)
220
- }
221
-
222
- /** @param {string} id @param {Caller} caller */
223
- async pause(id, caller) {
224
- const record = this.#writable(id, caller)
225
- if (record.state !== 'running' && record.state !== 'queued') {
226
- throw new QueueError('bad-state', `${id} is ${record.state}, cannot pause`)
227
- }
228
- if (record.state === 'queued') {
229
- record.state = 'paused'
230
- record.pauseReason = 'user'
231
- record.updatedAt = this.now()
232
- await this.jobs.put(id, record)
233
- return this.#view(record)
234
- }
235
- this.active.get(id)?.controller.abort()
236
- await this.#stopAs(id, 'user')
237
- return this.#view(this.jobs.get(id))
238
- }
239
-
240
- /** @param {string} id @param {Caller} caller @param {{ internal?: boolean }} [options] */
241
- async resume(id, caller, options = {}) {
242
- const record = options.internal ? this.#must(id) : this.#writable(id, caller)
243
- if (record.state !== 'paused' && record.state !== 'queued') {
244
- throw new QueueError('bad-state', `${id} is ${record.state}, cannot resume`)
245
- }
246
- record.state = 'queued'
247
- delete record.pauseReason
248
- record.updatedAt = this.now()
249
- await this.jobs.put(id, record)
250
- this.#schedule()
251
- return this.#view(record)
252
- }
253
-
254
- /** @param {string} id @param {Caller} caller */
255
- async cancel(id, caller) {
256
- const record = this.#must(id)
257
- if (!this.#canWrite(record, caller)) {
258
- throw new QueueError('not-owner', `${id} belongs to another session`)
259
- }
260
- if (isTerminal(record.state)) {
261
- throw new QueueError('bad-state', `${id} is already ${record.state}`)
262
- }
263
-
264
- const controller = this.active.get(id)?.controller
265
- controller?.abort()
266
-
267
- record.state = 'canceled'
268
- record.updatedAt = this.now()
269
- await this.jobs.put(id, record)
270
- this.progress.delete(id)
271
-
272
- await this.#dropPartialFiles(record)
273
- this.log('info', `${id} canceled`)
274
- return this.#view(record)
275
- }
276
-
277
- /**
278
- * @param {string} scope
279
- * @param {Caller} caller
280
- */
281
- async cleanup(scope, caller) {
282
- if (!CLEANUP_SCOPES.includes(scope)) {
283
- throw new QueueError('bad-state', `unknown scope: ${scope}`)
284
- }
285
-
286
- const mine = [...this.jobs.entries()]
287
- .map(([, record]) => record)
288
- .filter((record) => record.ownerWorkspace === caller.workspace && record.ownerSession === caller.session)
289
-
290
- let removedRecords = 0
291
- let removedCacheFiles = 0
292
- let removedFiles = 0
293
- let freedBytes = 0
294
-
295
- const touch = async (file) => {
296
- try {
297
- const info = await fs.stat(file)
298
- await fs.rm(file, { force: true })
299
- return info.size
300
- } catch {
301
- return undefined
302
- }
303
- }
304
-
305
- if (scope === 'records' || scope === 'allWithoutFiles' || scope === 'all') {
306
- const removable = mine.filter((record) => isTerminal(record.state)).map((record) => record.id)
307
- if (removable.length > 0) {
308
- removedRecords = await this.jobs.deleteMany(removable)
309
- }
310
- }
311
-
312
- if (scope === 'cache' || scope === 'allWithoutFiles' || scope === 'all') {
313
- for (const record of mine) {
314
- for (const file of [`${record.destPath}.part`, `${record.destPath}.aria2`]) {
315
- const freed = await touch(file)
316
- if (freed !== undefined) removedCacheFiles += 1
317
- freedBytes += freed ?? 0
318
- }
319
- }
320
- }
321
-
322
- if (scope === 'all') {
323
- for (const record of mine) {
324
- if (!isTerminal(record.state)) continue
325
- const freed = await touch(record.destPath)
326
- if (freed !== undefined) removedFiles += 1
327
- freedBytes += freed ?? 0
328
- }
329
- }
330
-
331
- return { scope, removedRecords, removedCacheFiles, removedFiles, freedBytes }
332
- }
333
-
334
- // ------------------------------------------------------------------ internals
335
-
336
- /** @param {string} id */
337
- #must(id) {
338
- const record = this.jobs.get(id)
339
- if (!record) throw new QueueError('not-found', `job ${id} does not exist`)
340
- return record
341
- }
342
-
343
- /** @param {string} id @param {Caller} caller */
344
- #writable(id, caller) {
345
- const record = this.#must(id)
346
- if (!this.#canWrite(record, caller)) {
347
- throw new QueueError('not-owner', `${id} belongs to another session`)
348
- }
349
- return record
350
- }
351
-
352
- /** @param {import('./types.js').JobRecord} record @param {Caller} caller */
353
- #canWrite(record, caller) {
354
- if (isTerminal(record.state)) return true
355
- return record.ownerWorkspace === caller.workspace && record.ownerSession === caller.session
356
- }
357
-
358
- async #nextSeq() {
359
- const state = this.domain.global.get()
360
- const seq = state.nextSeq
361
- await this.domain.global.set({ nextSeq: seq + 1 })
362
- return seq
363
- }
364
-
365
- /** @param {import('./types.js').JobRecord} record */
366
- #view(record) {
367
- const live = this.progress.get(record.id)
368
- const total = live?.total && live.total > 0 ? live.total : record.bytesTotal
369
- const done = isTerminal(record.state)
370
- ? (record.finalBytes ?? record.bytesCheckpoint)
371
- : (live?.done ?? record.bytesCheckpoint)
372
-
373
- return compact({
374
- id: record.id,
375
- state: record.state,
376
- pauseReason: record.pauseReason,
377
- owner: { workspace: record.ownerWorkspace, session: record.ownerSession },
378
- origin: record.origin,
379
- urls: record.urls,
380
- dest: record.destPath,
381
- bytesTotal: total,
382
- bytesDone: done,
383
- speedBps: live?.speed ?? 0,
384
- etaSeconds: live && live.speed > 0 && total > 0 ? Math.max(0, Math.round((total - done) / live.speed)) : undefined,
385
- attempts: record.attempts,
386
- lastError: record.lastError,
387
- createdAt: record.createdAt,
388
- updatedAt: record.updatedAt,
389
- })
390
- }
391
-
392
- #schedule() {
393
- if (this.closed || this.timer) return
394
- this.timer = setTimeout(() => {
395
- this.timer = undefined
396
- void this.#pump()
397
- }, 0)
398
- this.timer.unref?.()
399
- }
400
-
401
- async #pump() {
402
- if (this.closed) return
403
- const queued = [...this.jobs.entries()]
404
- .map(([, record]) => record)
405
- .filter((record) => record.state === 'queued')
406
- .sort((a, b) => a.seq - b.seq)
407
-
408
- for (const record of queued) {
409
- if (this.active.size >= this.config.maxConcurrentJobs) break
410
- if (this.active.has(record.id)) continue
411
- void this.#run(record)
412
- }
413
- }
414
-
415
- /** @param {import('./types.js').JobRecord} record */
416
- async #run(record) {
417
- const id = record.id
418
- const controller = new AbortController()
419
- this.active.set(id, { controller, startedAt: this.now() })
420
-
421
- record.state = 'running'
422
- record.updatedAt = this.now()
423
- await this.jobs.put(id, record)
424
-
425
- const stats = { done: record.bytesCheckpoint, total: record.bytesTotal, speed: 0, lastDone: record.bytesCheckpoint, lastAt: this.now() }
426
- this.progress.set(id, stats)
427
-
428
- try {
429
- const result = await this.transport.transfer({
430
- urls: record.urls,
431
- destPath: record.destPath,
432
- connections: this.config.connectionsPerJob,
433
- speedLimitKbps: this.config.speedLimitKbps,
434
- bytesDone: record.bytesCheckpoint,
435
- signal: controller.signal,
436
- onProgress: (done, total) => {
437
- const stamp = this.now()
438
- const elapsed = (stamp - stats.lastAt) / 1000
439
- if (elapsed >= 0.4) {
440
- stats.speed = Math.max(0, (done - stats.lastDone) / elapsed)
441
- stats.lastDone = done
442
- stats.lastAt = stamp
443
- }
444
- stats.done = done
445
- if (total > 0) stats.total = total
446
- },
447
- })
448
-
449
- if (record.expectSha256) {
450
- const actual = await sha256File(record.destPath)
451
- if (actual.toLowerCase() !== record.expectSha256.toLowerCase()) {
452
- throw new Error(`sha256 mismatch: expected ${record.expectSha256}, got ${actual}`)
453
- }
454
- }
455
-
456
- await this.#finish(id, 'completed', {
457
- bytesTotal: result.total > 0 ? result.total : stats.total,
458
- bytesCheckpoint: result.bytes,
459
- finalBytes: result.bytes,
460
- })
461
- } catch (error) {
462
- const aborted = controller.signal.aborted
463
- if (aborted) {
464
- // pause / cancel / close already recorded the target state
465
- if (!isTerminal(record.state)) {
466
- await this.#stopAs(id, 'host_restart')
467
- }
468
- } else {
469
- await this.#fail(id, error)
470
- }
471
- } finally {
472
- this.active.delete(id)
473
- this.progress.delete(id)
474
- this.#schedule()
475
- }
476
- }
477
-
478
- /** @param {string} id @param {Error} error */
479
- async #fail(id, error) {
480
- const record = this.jobs.get(id)
481
- if (!record || isTerminal(record.state)) return
482
-
483
- record.attempts += 1
484
- record.lastError = error?.message ?? String(error)
485
- record.updatedAt = this.now()
486
-
487
- if (record.attempts < MAX_ATTEMPTS) {
488
- record.state = 'queued'
489
- record.pauseReason = undefined
490
- this.log('warn', `${id} failed (attempt ${record.attempts}/${MAX_ATTEMPTS}), retrying: ${record.lastError}`)
491
- } else {
492
- record.state = 'failed'
493
- this.log('warn', `${id} failed permanently: ${record.lastError}`)
494
- }
495
- await this.jobs.put(id, record)
496
- }
497
-
498
- /** @param {string} id @param {'user'|'session_closed'|'host_restart'} reason */
499
- async #stopAs(id, reason) {
500
- const record = this.jobs.get(id)
501
- if (!record || isTerminal(record.state)) return
502
- const stats = this.progress.get(id)
503
- record.state = 'paused'
504
- record.pauseReason = reason
505
- if (stats) record.bytesCheckpoint = stats.done
506
- record.updatedAt = this.now()
507
- await this.jobs.put(id, record)
508
- }
509
-
510
- /**
511
- * @param {string} id
512
- * @param {'completed'} state
513
- * @param {Partial<import('./types.js').JobRecord>} patch
514
- */
515
- async #finish(id, state, patch) {
516
- const record = this.jobs.get(id)
517
- if (!record) return
518
- Object.assign(record, patch, { state, updatedAt: this.now() })
519
- delete record.pauseReason
520
- await this.jobs.put(id, record)
521
- this.log('info', `${id} ${state} (${record.finalBytes ?? record.bytesCheckpoint} bytes)`)
522
- }
523
-
524
- async #checkpointAll() {
525
- for (const [id] of this.active) {
526
- const stats = this.progress.get(id)
527
- const record = this.jobs.get(id)
528
- if (!stats || !record || record.state !== 'running') continue
529
- if (stats.done <= record.bytesCheckpoint) continue
530
- record.bytesCheckpoint = stats.done
531
- record.bytesTotal = stats.total > 0 ? stats.total : record.bytesTotal
532
- record.updatedAt = this.now()
533
- await this.jobs.put(id, record).catch(() => {})
534
- }
535
- }
536
-
537
- /** @param {import('./types.js').JobRecord} record */
538
- async #dropPartialFiles(record) {
539
- for (const file of [`${record.destPath}.part`, `${record.destPath}.aria2`]) {
540
- await fs.rm(file, { force: true }).catch(() => {})
541
- }
542
- }
543
-
544
- async #cancelOrphans() {
545
- if (!this.isOwnerAlive) {
546
- this.log('info', 'orphan scan skipped (no session probe wired in yet)')
547
- return
548
- }
549
- for (const [, record] of [...this.jobs.entries()]) {
550
- if (isTerminal(record.state)) continue
551
- if (await this.isOwnerAlive(record.ownerSession)) continue
552
- record.state = 'canceled'
553
- record.lastError = 'owner session no longer exists'
554
- record.updatedAt = this.now()
555
- await this.jobs.put(record.id, record)
556
- await this.#dropPartialFiles(record)
557
- this.log('info', `${record.id} canceled: owner session is gone`)
558
- }
559
- }
560
-
561
- /**
562
- * Cheap guard against enqueueing onto a full disk. The real file size is not
563
- * known yet, so this only catches the obvious case.
564
- * @param {string} destPath
565
- */
566
- async #assertDiskSpace(destPath) {
567
- const minimumFree = 512 * 1024 * 1024
568
- try {
569
- const stats = await fs.statfs(path.dirname(destPath))
570
- const free = Number(stats.bavail) * Number(stats.bsize)
571
- if (Number.isFinite(free) && free < minimumFree) {
572
- throw new QueueError('disk-full', `less than 512 MB free for ${path.dirname(destPath)}`)
573
- }
574
- } catch (error) {
575
- if (error instanceof QueueError) throw error
576
- /* statfs is unavailable on some platforms; do not block the enqueue */
577
- }
578
- }
579
- }
580
-
581
- /** @param {string} file */
582
- async function sha256File(file) {
583
- const hash = createHash('sha256')
584
- await new Promise((resolve, reject) => {
585
- createReadStream(file)
586
- .on('data', (chunk) => hash.update(chunk))
587
- .on('end', resolve)
588
- .on('error', reject)
589
- })
590
- return hash.digest('hex')
591
- }
1
+ import { createHash } from 'node:crypto'
2
+ import { createReadStream } from 'node:fs'
3
+ import fs from 'node:fs/promises'
4
+ import path from 'node:path'
5
+ import { expandMirrors, hostOf } from './mirrors.js'
6
+ import { formatJobId, isTerminal, parseJobId } from './types.js'
7
+
8
+ /** How many times one job may fail before it is parked as `failed`. */
9
+ export const MAX_ATTEMPTS = 3
10
+
11
+ /** Safe default for `download_cleanup`. */
12
+ export const DEFAULT_SCOPE = 'allWithoutFiles'
13
+
14
+ export const CLEANUP_SCOPES = ['records', 'cache', 'allWithoutFiles', 'all']
15
+
16
+ /** Free space always kept in reserve, on top of what queued jobs will consume. */
17
+ const MIN_FREE_BYTES = 512 * 1024 * 1024
18
+
19
+ /** Assumed size of a queued job whose total is not known yet. */
20
+ const UNKNOWN_SIZE_RESERVE = 256 * 1024 * 1024
21
+
22
+ /** A mirror host that fails this many times in a row is skipped for COOLDOWN_MS. */
23
+ const MIRROR_FAIL_THRESHOLD = 2
24
+ const MIRROR_COOLDOWN_MS = 10 * 60 * 1000
25
+
26
+ /** Drop undefined properties: the tool registry requires lossless JSON. */
27
+ function compact(object) {
28
+ const out = {}
29
+ for (const [key, value] of Object.entries(object)) {
30
+ if (value !== undefined) out[key] = value
31
+ }
32
+ return out
33
+ }
34
+
35
+ /** `J#1042` → `j1042`: the path-safe key used by the per-record storage layout. */
36
+ function storageKeyOf(id) {
37
+ const seq = parseJobId(id)
38
+ return seq === undefined ? id : `j${seq}`
39
+ }
40
+
41
+ export class QueueError extends Error {
42
+ /** @param {string} code @param {string} message */
43
+ constructor(code, message) {
44
+ super(message)
45
+ this.code = code
46
+ }
47
+ }
48
+
49
+ /**
50
+ * @typedef {object} Caller
51
+ * @property {string} workspace WorkspaceId
52
+ * @property {string} session SessionId of the parent session
53
+ * @property {string} [origin] subagent name, when the call came from one
54
+ */
55
+
56
+ /**
57
+ * The queue engine. Owns scheduling, state transitions and checkpoints; the
58
+ * transport owns bytes and the domain owns durability.
59
+ */
60
+ export class Queue {
61
+ /**
62
+ * @param {object} deps
63
+ * @param {any} deps.domain opened DLS domain
64
+ * @param {import('./transport.js').Transport} deps.transport
65
+ * @param {object} deps.config
66
+ * @param {(level: string, message: string) => void} [deps.log]
67
+ * @param {() => number} [deps.now]
68
+ * @param {(sessionId: string) => boolean | Promise<boolean>} [deps.isOwnerAlive]
69
+ */
70
+ constructor({ domain, transport, config, log = () => {}, now = Date.now, isOwnerAlive }) {
71
+ // Per-record keys must match /^[a-zA-Z0-9_-]+$/ while the public id is
72
+ // `J#1042`; translate at the storage boundary so callers stay on job ids.
73
+ const rawJobs = domain.table('jobs')
74
+ this.jobs = {
75
+ entries: () => rawJobs.entries(),
76
+ get: (id) => rawJobs.get(storageKeyOf(id)),
77
+ put: (id, record) => rawJobs.put(storageKeyOf(id), record),
78
+ // `deleteMany` only exists from 0.2.2; loop over `delete` so the plugin
79
+ // also runs on 0.2.1 profiles.
80
+ deleteMany: async (ids) => {
81
+ let removed = 0
82
+ for (const id of ids) {
83
+ if (await rawJobs.delete(storageKeyOf(id))) removed += 1
84
+ }
85
+ return removed
86
+ },
87
+ }
88
+ this.domain = domain
89
+ this.transport = transport
90
+ this.config = config
91
+ this.log = log
92
+ this.now = now
93
+ this.isOwnerAlive = isOwnerAlive
94
+
95
+ /** @type {Map<string, { controller: AbortController, startedAt: number }>} */
96
+ this.active = new Map()
97
+ /** @type {Map<string, { done: number, total: number, speed: number, lastDone: number, lastAt: number }>} */
98
+ this.progress = new Map()
99
+ this.closed = false
100
+ this.timer = undefined
101
+ this.checkpointTimer = undefined
102
+
103
+ /** @type {{ errors: number, lastError?: string, lastAt?: number }} */
104
+ this.storage = { errors: 0 }
105
+ /** @type {Map<string, { fails: number, cooldownUntil: number }>} */
106
+ this.mirrorHealth = new Map()
107
+ }
108
+
109
+ // ---------------------------------------------------------------- lifecycle
110
+
111
+ /** Reconcile persisted state with reality. Call once before serving. */
112
+ async recover() {
113
+ const resumable = []
114
+
115
+ for (const [, record] of this.jobs.entries()) {
116
+ if (record.state === 'running') {
117
+ record.state = 'paused'
118
+ record.pauseReason = 'host_restart'
119
+ record.updatedAt = this.now()
120
+ await this.jobs.put(record.id, record)
121
+ resumable.push(record)
122
+ } else if (record.state === 'paused' && record.pauseReason === 'host_restart') {
123
+ // A previous shutdown may persist the pause before the process exits; such a
124
+ // record still deserves the same resume treatment as a freshly paused one.
125
+ resumable.push(record)
126
+ }
127
+ }
128
+
129
+ if (resumable.length > 0) {
130
+ this.log('info', `${resumable.length} job(s) interrupted by a restart -> paused(host_restart)`)
131
+ }
132
+
133
+ if (this.config.autoResumeOnHostRestart) {
134
+ for (const record of resumable) {
135
+ await this.resume(record.id, { workspace: record.ownerWorkspace, session: record.ownerSession }, { internal: true })
136
+ }
137
+ }
138
+
139
+ await this.#cancelOrphans()
140
+
141
+ this.checkpointTimer = setInterval(() => void this.#checkpointAll(), this.config.checkpointSeconds * 1000)
142
+ this.checkpointTimer.unref?.()
143
+ this.#schedule()
144
+ }
145
+
146
+ async close() {
147
+ this.closed = true
148
+ clearTimeout(this.timer)
149
+ if (this.checkpointTimer) clearInterval(this.checkpointTimer)
150
+
151
+ const pending = []
152
+ for (const [id, entry] of this.active) {
153
+ entry.controller.abort()
154
+ pending.push(this.#stopAs(id, 'host_restart'))
155
+ }
156
+ await Promise.allSettled(pending)
157
+ }
158
+
159
+ // ------------------------------------------------------------------- reading
160
+
161
+ /** Every session sees every job. */
162
+ list() {
163
+ return [...this.jobs.entries()].map(([, record]) => this.#view(record))
164
+ }
165
+
166
+ /** @param {string} id */
167
+ get(id) {
168
+ const record = this.jobs.get(id)
169
+ return record ? this.#view(record) : undefined
170
+ }
171
+
172
+ /**
173
+ * Block until a job reaches a terminal state or the timeout expires.
174
+ * @param {string} id
175
+ * @param {number} timeoutMs
176
+ */
177
+ async wait(id, timeoutMs = 60_000) {
178
+ const deadline = this.now() + timeoutMs
179
+ for (;;) {
180
+ const record = this.jobs.get(id)
181
+ if (!record) throw new QueueError('not-found', `job ${id} does not exist`)
182
+ if (isTerminal(record.state)) return this.#view(record)
183
+ if (this.now() >= deadline) return this.#view(record)
184
+ await new Promise((resolve) => setTimeout(resolve, 200))
185
+ }
186
+ }
187
+
188
+ // ------------------------------------------------------------------- writing
189
+
190
+ /**
191
+ * Add a job. Returns immediately; the scheduler picks it up.
192
+ * @param {{ urls: string[], destPath: string, expectSha256?: string, expectedBytes?: number }} spec
193
+ * @param {Caller} caller
194
+ */
195
+ async enqueue(spec, caller) {
196
+ if (!Array.isArray(spec.urls) || spec.urls.length === 0) {
197
+ throw new QueueError('url-invalid', 'at least one URL is required')
198
+ }
199
+ for (const url of spec.urls) {
200
+ try {
201
+ const parsed = new URL(url)
202
+ if (!/^https?:$/.test(parsed.protocol)) throw new Error('scheme')
203
+ } catch {
204
+ throw new QueueError('url-invalid', `not an http(s) URL: ${url}`)
205
+ }
206
+ }
207
+
208
+ const expanded = expandMirrors(spec.urls)
209
+
210
+ await this.#assertDestWritable(spec.destPath)
211
+ await this.#assertDiskSpace(spec.destPath, spec.expectedBytes)
212
+
213
+ const seq = await this.#nextSeq()
214
+ const id = formatJobId(seq)
215
+ const stamp = this.now()
216
+
217
+ /** @type {import('./types.js').JobRecord} */
218
+ const record = {
219
+ id,
220
+ seq,
221
+ ownerWorkspace: caller.workspace,
222
+ ownerSession: caller.session,
223
+ origin: caller.origin,
224
+ urls: expanded.urls,
225
+ mirrors: expanded.applied.length > 0 ? expanded.applied : undefined,
226
+ destPath: spec.destPath,
227
+ state: 'queued',
228
+ createdAt: stamp,
229
+ updatedAt: stamp,
230
+ bytesTotal: -1,
231
+ bytesCheckpoint: 0,
232
+ attempts: 0,
233
+ expectSha256: spec.expectSha256,
234
+ }
235
+
236
+ await this.jobs.put(id, record)
237
+ this.log('info', `${id} enqueued by ${caller.workspace}#${caller.session.slice(0, 8)}`)
238
+ this.#schedule()
239
+ return this.#view(record)
240
+ }
241
+
242
+ /** @param {string} id @param {Caller} caller */
243
+ async pause(id, caller) {
244
+ const record = this.#writable(id, caller)
245
+ if (record.state !== 'running' && record.state !== 'queued') {
246
+ throw new QueueError('bad-state', `${id} is ${record.state}, cannot pause`)
247
+ }
248
+ if (record.state === 'queued') {
249
+ record.state = 'paused'
250
+ record.pauseReason = 'user'
251
+ record.updatedAt = this.now()
252
+ await this.jobs.put(id, record)
253
+ return this.#view(record)
254
+ }
255
+ this.active.get(id)?.controller.abort()
256
+ await this.#stopAs(id, 'user')
257
+ return this.#view(this.jobs.get(id))
258
+ }
259
+
260
+ /** @param {string} id @param {Caller} caller @param {{ internal?: boolean }} [options] */
261
+ async resume(id, caller, options = {}) {
262
+ const record = options.internal ? this.#must(id) : this.#writable(id, caller)
263
+ if (record.state !== 'paused' && record.state !== 'queued') {
264
+ throw new QueueError('bad-state', `${id} is ${record.state}, cannot resume`)
265
+ }
266
+ record.state = 'queued'
267
+ delete record.pauseReason
268
+ record.updatedAt = this.now()
269
+ await this.jobs.put(id, record)
270
+ this.#schedule()
271
+ return this.#view(record)
272
+ }
273
+
274
+ /** @param {string} id @param {Caller} caller */
275
+ async cancel(id, caller) {
276
+ const record = this.#must(id)
277
+ if (!this.#canWrite(record, caller)) {
278
+ throw new QueueError('not-owner', `${id} belongs to another session`)
279
+ }
280
+ if (isTerminal(record.state)) {
281
+ throw new QueueError('bad-state', `${id} is already ${record.state}`)
282
+ }
283
+
284
+ const controller = this.active.get(id)?.controller
285
+ controller?.abort()
286
+
287
+ record.state = 'canceled'
288
+ record.updatedAt = this.now()
289
+ await this.jobs.put(id, record)
290
+ this.progress.delete(id)
291
+
292
+ await this.#dropPartialFiles(record)
293
+ this.log('info', `${id} canceled`)
294
+ return this.#view(record)
295
+ }
296
+
297
+ /**
298
+ * @param {string} scope
299
+ * @param {Caller} caller
300
+ */
301
+ async cleanup(scope, caller) {
302
+ if (!CLEANUP_SCOPES.includes(scope)) {
303
+ throw new QueueError('bad-state', `unknown scope: ${scope}`)
304
+ }
305
+
306
+ const mine = [...this.jobs.entries()]
307
+ .map(([, record]) => record)
308
+ .filter((record) => record.ownerWorkspace === caller.workspace && record.ownerSession === caller.session)
309
+
310
+ let removedRecords = 0
311
+ let removedCacheFiles = 0
312
+ let removedFiles = 0
313
+ let freedBytes = 0
314
+
315
+ const touch = async (file) => {
316
+ try {
317
+ const info = await fs.stat(file)
318
+ await fs.rm(file, { force: true })
319
+ return info.size
320
+ } catch {
321
+ return undefined
322
+ }
323
+ }
324
+
325
+ if (scope === 'records' || scope === 'allWithoutFiles' || scope === 'all') {
326
+ const removable = mine.filter((record) => isTerminal(record.state)).map((record) => record.id)
327
+ if (removable.length > 0) {
328
+ removedRecords = await this.jobs.deleteMany(removable)
329
+ }
330
+ }
331
+
332
+ if (scope === 'cache' || scope === 'allWithoutFiles' || scope === 'all') {
333
+ for (const record of mine) {
334
+ for (const file of [`${record.destPath}.part`, `${record.destPath}.aria2`]) {
335
+ const freed = await touch(file)
336
+ if (freed !== undefined) removedCacheFiles += 1
337
+ freedBytes += freed ?? 0
338
+ }
339
+ }
340
+ }
341
+
342
+ if (scope === 'all') {
343
+ for (const record of mine) {
344
+ if (!isTerminal(record.state)) continue
345
+ const freed = await touch(record.destPath)
346
+ if (freed !== undefined) removedFiles += 1
347
+ freedBytes += freed ?? 0
348
+ }
349
+ }
350
+
351
+ return { scope, removedRecords, removedCacheFiles, removedFiles, freedBytes }
352
+ }
353
+
354
+ // ------------------------------------------------------------------ internals
355
+
356
+ /** @param {string} id */
357
+ #must(id) {
358
+ const record = this.jobs.get(id)
359
+ if (!record) throw new QueueError('not-found', `job ${id} does not exist`)
360
+ return record
361
+ }
362
+
363
+ /** @param {string} id @param {Caller} caller */
364
+ #writable(id, caller) {
365
+ const record = this.#must(id)
366
+ if (!this.#canWrite(record, caller)) {
367
+ throw new QueueError('not-owner', `${id} belongs to another session`)
368
+ }
369
+ return record
370
+ }
371
+
372
+ /** @param {import('./types.js').JobRecord} record @param {Caller} caller */
373
+ #canWrite(record, caller) {
374
+ if (isTerminal(record.state)) return true
375
+ return record.ownerWorkspace === caller.workspace && record.ownerSession === caller.session
376
+ }
377
+
378
+ async #nextSeq() {
379
+ const state = this.domain.global.get()
380
+ const seq = state.nextSeq
381
+ await this.domain.global.set({ nextSeq: seq + 1 })
382
+ return seq
383
+ }
384
+
385
+ /** @param {import('./types.js').JobRecord} record */
386
+ #view(record) {
387
+ const live = this.progress.get(record.id)
388
+ const total = live?.total && live.total > 0 ? live.total : record.bytesTotal
389
+ const done = isTerminal(record.state)
390
+ ? (record.finalBytes ?? record.bytesCheckpoint)
391
+ : (live?.done ?? record.bytesCheckpoint)
392
+
393
+ return compact({
394
+ id: record.id,
395
+ state: record.state,
396
+ pauseReason: record.pauseReason,
397
+ owner: { workspace: record.ownerWorkspace, session: record.ownerSession },
398
+ origin: record.origin,
399
+ urls: record.urls,
400
+ mirrors: record.mirrors,
401
+ dest: record.destPath,
402
+ bytesTotal: total,
403
+ bytesDone: done,
404
+ speedBps: live?.speed ?? 0,
405
+ etaSeconds: live && live.speed > 0 && total > 0 ? Math.max(0, Math.round((total - done) / live.speed)) : undefined,
406
+ attempts: record.attempts,
407
+ lastError: record.lastError,
408
+ createdAt: record.createdAt,
409
+ updatedAt: record.updatedAt,
410
+ })
411
+ }
412
+
413
+ /** Storage-write and mirror health, surfaced through `download_status`. */
414
+ health() {
415
+ const mirrors = this.mirrorStatus()
416
+ return compact({
417
+ storage: this.storage.errors > 0 ? { ...this.storage } : { errors: 0 },
418
+ mirrorHealth: mirrors.length > 0 ? mirrors : undefined,
419
+ })
420
+ }
421
+
422
+ #schedule() {
423
+ if (this.closed || this.timer) return
424
+ this.timer = setTimeout(() => {
425
+ this.timer = undefined
426
+ void this.#pump()
427
+ }, 0)
428
+ this.timer.unref?.()
429
+ }
430
+
431
+ async #pump() {
432
+ if (this.closed) return
433
+ const queued = [...this.jobs.entries()]
434
+ .map(([, record]) => record)
435
+ .filter((record) => record.state === 'queued')
436
+ .sort((a, b) => a.seq - b.seq)
437
+
438
+ if (queued.length === 0) return
439
+
440
+ // One session hogging every slot starves the others. Only enforce a cap
441
+ // when at least two sessions are actually competing: a lone session keeps
442
+ // the full concurrency it would get anyway.
443
+ const sessionKeyOf = (record) => `${record.ownerWorkspace}::${record.ownerSession}`
444
+ const sessions = new Set(queued.map(sessionKeyOf))
445
+ const cap = sessions.size >= 2 ? Math.max(1, Math.floor(this.config.maxConcurrentJobs / 2)) : Infinity
446
+
447
+ /** @type {Map<string, number>} */
448
+ const running = new Map()
449
+ for (const [id] of this.active) {
450
+ const record = this.jobs.get(id)
451
+ if (!record) continue
452
+ const key = sessionKeyOf(record)
453
+ running.set(key, (running.get(key) ?? 0) + 1)
454
+ }
455
+
456
+ /** @type {Map<string, import('./types.js').JobRecord[]>} */
457
+ const bySession = new Map()
458
+ for (const record of queued) {
459
+ const key = sessionKeyOf(record)
460
+ const list = bySession.get(key)
461
+ if (list) list.push(record)
462
+ else bySession.set(key, [record])
463
+ }
464
+
465
+ // Round-robin across sessions, so a session that queued ten jobs cannot run
466
+ // ahead of one that queued a single job.
467
+ let progressed = true
468
+ while (progressed && this.active.size < this.config.maxConcurrentJobs) {
469
+ progressed = false
470
+ for (const key of bySession.keys()) {
471
+ if (this.active.size >= this.config.maxConcurrentJobs) break
472
+ const list = bySession.get(key)
473
+ if (!list || list.length === 0) continue
474
+ if ((running.get(key) ?? 0) >= cap) continue
475
+ const record = list.shift()
476
+ if (this.active.has(record.id)) continue
477
+ running.set(key, (running.get(key) ?? 0) + 1)
478
+ void this.#run(record)
479
+ progressed = true
480
+ }
481
+ }
482
+ }
483
+
484
+ /** @param {import('./types.js').JobRecord} record */
485
+ async #run(record) {
486
+ const id = record.id
487
+ const controller = new AbortController()
488
+ this.active.set(id, { controller, startedAt: this.now() })
489
+
490
+ record.state = 'running'
491
+ record.updatedAt = this.now()
492
+ await this.#persist(id, record)
493
+
494
+ const stats = { done: record.bytesCheckpoint, total: record.bytesTotal, speed: 0, lastDone: record.bytesCheckpoint, lastAt: this.now() }
495
+ this.progress.set(id, stats)
496
+
497
+ const urls = this.#orderUrls(record.urls)
498
+
499
+ try {
500
+ const result = await this.transport.transfer({
501
+ urls,
502
+ destPath: record.destPath,
503
+ connectionsCap: this.config.connectionsPerJob,
504
+ speedLimitKbps: this.config.speedLimitKbps,
505
+ bytesDone: record.bytesCheckpoint,
506
+ signal: controller.signal,
507
+ onUrlResult: (url, ok) => {
508
+ if (ok) this.noteUrlSuccess(url)
509
+ else this.noteUrlFailure(url)
510
+ },
511
+ onProgress: (done, total) => {
512
+ const stamp = this.now()
513
+ const elapsed = (stamp - stats.lastAt) / 1000
514
+ if (elapsed >= 0.4) {
515
+ stats.speed = Math.max(0, (done - stats.lastDone) / elapsed)
516
+ stats.lastDone = done
517
+ stats.lastAt = stamp
518
+ }
519
+ stats.done = done
520
+ if (total > 0) stats.total = total
521
+ },
522
+ })
523
+
524
+ if (record.expectSha256) {
525
+ const actual = await sha256File(record.destPath)
526
+ if (actual.toLowerCase() !== record.expectSha256.toLowerCase()) {
527
+ throw new Error(`sha256 mismatch: expected ${record.expectSha256}, got ${actual}`)
528
+ }
529
+ }
530
+
531
+ await this.#finish(id, 'completed', {
532
+ bytesTotal: result.total > 0 ? result.total : stats.total,
533
+ bytesCheckpoint: result.bytes,
534
+ finalBytes: result.bytes,
535
+ })
536
+ } catch (error) {
537
+ const aborted = controller.signal.aborted
538
+ if (aborted) {
539
+ // pause / cancel / close already recorded the target state
540
+ if (!isTerminal(record.state)) {
541
+ await this.#stopAs(id, 'host_restart')
542
+ }
543
+ } else {
544
+ await this.#fail(id, error)
545
+ }
546
+ } finally {
547
+ this.active.delete(id)
548
+ this.progress.delete(id)
549
+ this.#schedule()
550
+ }
551
+ }
552
+
553
+ /** @param {string} id @param {Error} error */
554
+ async #fail(id, error) {
555
+ const record = this.jobs.get(id)
556
+ if (!record || isTerminal(record.state)) return
557
+
558
+ record.attempts += 1
559
+ record.lastError = error?.message ?? String(error)
560
+ record.updatedAt = this.now()
561
+
562
+ if (record.attempts < MAX_ATTEMPTS) {
563
+ record.state = 'queued'
564
+ record.pauseReason = undefined
565
+ this.log('warn', `${id} failed (attempt ${record.attempts}/${MAX_ATTEMPTS}), retrying: ${record.lastError}`)
566
+ } else {
567
+ record.state = 'failed'
568
+ this.log('warn', `${id} failed permanently: ${record.lastError}`)
569
+ }
570
+ await this.#persist(id, record)
571
+ }
572
+
573
+ /** @param {string} id @param {'user'|'session_closed'|'host_restart'} reason */
574
+ async #stopAs(id, reason) {
575
+ const record = this.jobs.get(id)
576
+ if (!record || isTerminal(record.state)) return
577
+ const stats = this.progress.get(id)
578
+ record.state = 'paused'
579
+ record.pauseReason = reason
580
+ if (stats) record.bytesCheckpoint = stats.done
581
+ record.updatedAt = this.now()
582
+ await this.#persist(id, record)
583
+ }
584
+
585
+ /**
586
+ * @param {string} id
587
+ * @param {'completed'} state
588
+ * @param {Partial<import('./types.js').JobRecord>} patch
589
+ */
590
+ async #finish(id, state, patch) {
591
+ const record = this.jobs.get(id)
592
+ if (!record) return
593
+ Object.assign(record, patch, { state, updatedAt: this.now() })
594
+ delete record.pauseReason
595
+ await this.#persist(id, record)
596
+ this.log('info', `${id} ${state} (${record.finalBytes ?? record.bytesCheckpoint} bytes)`)
597
+ }
598
+
599
+ async #checkpointAll() {
600
+ for (const [id] of this.active) {
601
+ const stats = this.progress.get(id)
602
+ const record = this.jobs.get(id)
603
+ if (!stats || !record || record.state !== 'running') continue
604
+ if (stats.done <= record.bytesCheckpoint) continue
605
+ record.bytesCheckpoint = stats.done
606
+ record.bytesTotal = stats.total > 0 ? stats.total : record.bytesTotal
607
+ record.updatedAt = this.now()
608
+ try {
609
+ await this.#persist(id, record)
610
+ } catch (error) {
611
+ // A failed checkpoint means the next resume restarts from a stale
612
+ // offset, which corrupts the file. Report it instead of swallowing it.
613
+ this.#noteStorageFailure(id, error)
614
+ }
615
+ }
616
+ }
617
+
618
+ /** @param {string} id @param {unknown} error */
619
+ #noteStorageFailure(id, error) {
620
+ const message = error instanceof Error ? error.message : String(error)
621
+ this.storage.errors += 1
622
+ this.storage.lastError = `${id}: ${message}`
623
+ this.storage.lastAt = this.now()
624
+ if (this.storage.errors === 3) {
625
+ this.log('error', `checkpoint writes are failing (${message}); resume offsets may be stale`)
626
+ }
627
+ }
628
+
629
+ /**
630
+ * Persist a lifecycle transition. Unlike the user-facing mutations, these run
631
+ * on the scheduler and during shutdown: a broken storage must not turn into an
632
+ * unhandled rejection that takes the whole plugin down with it.
633
+ * @param {string} id @param {import('./types.js').JobRecord} record
634
+ */
635
+ async #persist(id, record) {
636
+ try {
637
+ await this.jobs.put(id, record)
638
+ return true
639
+ } catch (error) {
640
+ this.#noteStorageFailure(id, error)
641
+ return false
642
+ }
643
+ }
644
+
645
+ /** @param {import('./types.js').JobRecord} record */
646
+ async #dropPartialFiles(record) {
647
+ for (const file of [`${record.destPath}.part`, `${record.destPath}.aria2`]) {
648
+ await fs.rm(file, { force: true }).catch(() => {})
649
+ }
650
+ }
651
+
652
+ async #cancelOrphans() {
653
+ if (!this.isOwnerAlive) {
654
+ this.log('info', 'orphan scan skipped (no session probe wired in yet)')
655
+ return
656
+ }
657
+ for (const [, record] of [...this.jobs.entries()]) {
658
+ if (isTerminal(record.state)) continue
659
+ if (await this.isOwnerAlive(record.ownerSession)) continue
660
+ record.state = 'canceled'
661
+ record.lastError = 'owner session no longer exists'
662
+ record.updatedAt = this.now()
663
+ await this.#persist(record.id, record)
664
+ await this.#dropPartialFiles(record)
665
+ this.log('info', `${record.id} canceled: owner session is gone`)
666
+ }
667
+ }
668
+
669
+ /**
670
+ * Refuse a destination whose directory we cannot write to, before the download
671
+ * starts. A sandbox can make a path readable but not writable; discovering that
672
+ * at the first byte wastes the whole queue slot.
673
+ * @param {string} destPath
674
+ */
675
+ async #assertDestWritable(destPath) {
676
+ let dir = path.dirname(destPath)
677
+ // Walk up to the nearest directory that exists: an absent leaf is fine,
678
+ // it gets created at transfer time.
679
+ for (;;) {
680
+ try {
681
+ await fs.access(dir, fs.constants?.W_OK ?? 2)
682
+ return
683
+ } catch (error) {
684
+ const code = error?.code
685
+ if (code === 'ENOENT') {
686
+ const parent = path.dirname(dir)
687
+ if (parent === dir) return
688
+ dir = parent
689
+ continue
690
+ }
691
+ if (code === 'EACCES' || code === 'EPERM') {
692
+ throw new QueueError('permission-denied', `cannot write to ${path.dirname(destPath)} (${code})`)
693
+ }
694
+ // Anything else (e.g. an exotic filesystem) is not a reason to block.
695
+ return
696
+ }
697
+ }
698
+ }
699
+
700
+ /**
701
+ * Cheap guard against enqueueing onto a full disk. Sums what already-queued
702
+ * jobs are expected to consume, so twenty small enqueues cannot add up to a
703
+ * full disk one "looks fine" at a time.
704
+ * @param {string} destPath
705
+ * @param {number} [expectedBytes]
706
+ */
707
+ async #assertDiskSpace(destPath, expectedBytes) {
708
+ const committed = [...this.jobs.entries()]
709
+ .map(([, record]) => record)
710
+ .filter((record) => !isTerminal(record.state))
711
+ .reduce((sum, record) => {
712
+ const remaining = record.bytesTotal > 0 ? record.bytesTotal - record.bytesCheckpoint : UNKNOWN_SIZE_RESERVE
713
+ return sum + Math.max(0, remaining)
714
+ }, 0)
715
+
716
+ const reserve = Number.isFinite(expectedBytes) && expectedBytes > 0 ? expectedBytes : UNKNOWN_SIZE_RESERVE
717
+ const needed = MIN_FREE_BYTES + committed + reserve
718
+
719
+ try {
720
+ const stats = await fs.statfs(path.dirname(destPath))
721
+ const free = Number(stats.bavail) * Number(stats.bsize)
722
+ if (Number.isFinite(free) && free < needed) {
723
+ const shortfall = needed - free
724
+ throw new QueueError(
725
+ 'disk-full',
726
+ `need ${Math.ceil(needed / 1048576)} MB free for ${path.dirname(destPath)} ` +
727
+ `(512 MB reserve + ${Math.ceil(committed / 1048576)} MB queued + ${Math.ceil(reserve / 1048576)} MB this job), ` +
728
+ `only ${Math.floor(free / 1048576)} MB available, short by ${Math.ceil(shortfall / 1048576)} MB`,
729
+ )
730
+ }
731
+ } catch (error) {
732
+ if (error instanceof QueueError) throw error
733
+ /* statfs is unavailable on some platforms; do not block the enqueue */
734
+ }
735
+ }
736
+
737
+ // ------------------------------------------------------------------- mirrors
738
+
739
+ /**
740
+ * Mark a URL host as failed. Two consecutive failures park it for a while so a
741
+ * dead mirror is not retried on every job; the cooldown is in memory only, so
742
+ * a restart clears it rather than turning a blip into a permanent ban.
743
+ * @param {string} url
744
+ */
745
+ noteUrlFailure(url) {
746
+ const host = hostOf(url)
747
+ if (!host) return
748
+ const entry = this.mirrorHealth.get(host) ?? { fails: 0, cooldownUntil: 0 }
749
+ entry.fails += 1
750
+ if (entry.fails >= MIRROR_FAIL_THRESHOLD) {
751
+ entry.cooldownUntil = this.now() + MIRROR_COOLDOWN_MS
752
+ this.log('warn', `mirror ${host} cooling down for ${MIRROR_COOLDOWN_MS / 60000} min after ${entry.fails} failures`)
753
+ }
754
+ this.mirrorHealth.set(host, entry)
755
+ }
756
+
757
+ /** @param {string} url */
758
+ noteUrlSuccess(url) {
759
+ const host = hostOf(url)
760
+ if (!host) return
761
+ this.mirrorHealth.delete(host)
762
+ }
763
+
764
+ /** Hosts currently in cooldown, for `download_status`. */
765
+ mirrorStatus() {
766
+ const out = []
767
+ for (const [host, entry] of this.mirrorHealth) {
768
+ if (entry.cooldownUntil > this.now()) {
769
+ out.push({ host, fails: entry.fails, cooldownUntil: entry.cooldownUntil })
770
+ }
771
+ }
772
+ return out
773
+ }
774
+
775
+ /** Reorder URLs so cooling hosts are tried last. @param {string[]} urls */
776
+ #orderUrls(urls) {
777
+ const stamp = this.now()
778
+ const warm = []
779
+ const cold = []
780
+ for (const url of urls) {
781
+ const host = hostOf(url)
782
+ const entry = host ? this.mirrorHealth.get(host) : undefined
783
+ if (entry && entry.cooldownUntil > stamp) cold.push(url)
784
+ else warm.push(url)
785
+ }
786
+ return cold.length === 0 ? urls : [...warm, ...cold]
787
+ }
788
+ }
789
+
790
+ /** @param {string} file */
791
+ async function sha256File(file) {
792
+ const hash = createHash('sha256')
793
+ await new Promise((resolve, reject) => {
794
+ createReadStream(file)
795
+ .on('data', (chunk) => hash.update(chunk))
796
+ .on('end', resolve)
797
+ .on('error', reject)
798
+ })
799
+ return hash.digest('hex')
800
+ }