dsh-dl-server 0.1.1 → 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/README.md +17 -2
- package/README.zh.md +18 -3
- package/lib/domain.js +4 -0
- package/lib/mirrors.js +102 -0
- package/lib/queue.js +800 -591
- package/lib/tools.js +3 -2
- package/lib/transport.js +68 -4
- package/package.json +1 -1
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 {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
this.
|
|
89
|
-
this.
|
|
90
|
-
this.
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
if (this.
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
const
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
*
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
throw new QueueError('
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
await this
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
record.
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
record.
|
|
268
|
-
record.updatedAt = this.now()
|
|
269
|
-
await this.jobs.put(id, record)
|
|
270
|
-
this
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
.
|
|
406
|
-
.
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
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
|
+
}
|