@tryghost/mg-queue 0.2.0-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/LICENSE +21 -0
- package/README.md +533 -0
- package/build/index.d.ts +9 -0
- package/build/index.js +6 -0
- package/build/index.js.map +1 -0
- package/build/lib/DynamicRenderer.d.ts +14 -0
- package/build/lib/DynamicRenderer.js +245 -0
- package/build/lib/DynamicRenderer.js.map +1 -0
- package/build/lib/Queue.d.ts +46 -0
- package/build/lib/Queue.js +392 -0
- package/build/lib/Queue.js.map +1 -0
- package/build/lib/Renderer.d.ts +22 -0
- package/build/lib/Renderer.js +2 -0
- package/build/lib/Renderer.js.map +1 -0
- package/build/lib/SilentRenderer.d.ts +9 -0
- package/build/lib/SilentRenderer.js +11 -0
- package/build/lib/SilentRenderer.js.map +1 -0
- package/build/lib/SqliteReader.d.ts +50 -0
- package/build/lib/SqliteReader.js +179 -0
- package/build/lib/SqliteReader.js.map +1 -0
- package/build/lib/VerboseRenderer.d.ts +9 -0
- package/build/lib/VerboseRenderer.js +34 -0
- package/build/lib/VerboseRenderer.js.map +1 -0
- package/build/test/DynamicRenderer.test.d.ts +1 -0
- package/build/test/DynamicRenderer.test.js +390 -0
- package/build/test/DynamicRenderer.test.js.map +1 -0
- package/build/test/Queue.test.d.ts +1 -0
- package/build/test/Queue.test.js +1458 -0
- package/build/test/Queue.test.js.map +1 -0
- package/build/test/SqliteReader.test.d.ts +1 -0
- package/build/test/SqliteReader.test.js +402 -0
- package/build/test/SqliteReader.test.js.map +1 -0
- package/build/test/VerboseRenderer.test.d.ts +1 -0
- package/build/test/VerboseRenderer.test.js +118 -0
- package/build/test/VerboseRenderer.test.js.map +1 -0
- package/package.json +46 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2013-2026 Ghost Foundation
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
# mg-queue
|
|
2
|
+
|
|
3
|
+
A concurrent task queue with progress rendering for migrations.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @tryghost/mg-queue
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
`mg-queue` includes SQLite support via `better-sqlite3` (native module).
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
### Basic Example (Silent Mode)
|
|
16
|
+
|
|
17
|
+
No renderer - tasks run silently and stats are returned:
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
import {Queue, Task} from '@tryghost/mg-queue';
|
|
21
|
+
|
|
22
|
+
const tasks: Task[] = [
|
|
23
|
+
{title: 'Task 1', task: async () => { /* ... */ }},
|
|
24
|
+
{title: 'Task 2', task: async () => { /* ... */ }}
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
const queue = new Queue({concurrency: 5});
|
|
28
|
+
const stats = await queue.run(tasks);
|
|
29
|
+
|
|
30
|
+
// stats = {
|
|
31
|
+
// completed: 1,
|
|
32
|
+
// skipped: 0,
|
|
33
|
+
// errors: [{title: 'Task 1', error: Error}]
|
|
34
|
+
// }
|
|
35
|
+
|
|
36
|
+
console.log(`Completed: ${stats.completed}, Skipped: ${stats.skipped}`);
|
|
37
|
+
|
|
38
|
+
if (stats.errors.length > 0) {
|
|
39
|
+
console.log('Failed tasks:');
|
|
40
|
+
for (const err of stats.errors) {
|
|
41
|
+
console.log(` ${err.title}: ${err.error.message}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### Verbose Renderer
|
|
47
|
+
|
|
48
|
+
Logs every task start, complete, skip, and error as they happen:
|
|
49
|
+
|
|
50
|
+
```typescript
|
|
51
|
+
import {Queue, Task} from '@tryghost/mg-queue';
|
|
52
|
+
|
|
53
|
+
const tasks: Task[] = [
|
|
54
|
+
{title: 'Download file', task: async () => { /* ... */ }},
|
|
55
|
+
{title: 'Process data', task: async () => { /* ... */ }}
|
|
56
|
+
];
|
|
57
|
+
|
|
58
|
+
const queue = new Queue({
|
|
59
|
+
concurrency: 2,
|
|
60
|
+
renderer: 'verbose'
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
await queue.run(tasks);
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Output:
|
|
67
|
+
```
|
|
68
|
+
→ Starting: Download file
|
|
69
|
+
→ Starting: Process data
|
|
70
|
+
✓ Completed: Download file
|
|
71
|
+
✓ Completed: Process data
|
|
72
|
+
|
|
73
|
+
Completed: 2 | Failed: 0
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Dynamic Renderer
|
|
77
|
+
|
|
78
|
+
Single updating line with spinner - ideal for many tasks:
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
import {Queue, Task} from '@tryghost/mg-queue';
|
|
82
|
+
|
|
83
|
+
async function* generateTasks(): AsyncGenerator<Task> {
|
|
84
|
+
for (let i = 1; i <= 100; i++) {
|
|
85
|
+
yield {
|
|
86
|
+
title: `Task ${i}`,
|
|
87
|
+
task: async () => { /* ... */ }
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const queue = new Queue({
|
|
93
|
+
concurrency: 5,
|
|
94
|
+
renderer: 'dynamic'
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
await queue.run(generateTasks());
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Keep completed tasks visible while new tasks continue:
|
|
101
|
+
|
|
102
|
+
```typescript
|
|
103
|
+
const queue = new Queue({
|
|
104
|
+
concurrency: 5,
|
|
105
|
+
renderer: new DynamicRenderer({keepOnScreen: true})
|
|
106
|
+
});
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
`keepOnScreen` is applied only when the source passed to `queue.run(...)` is a plain array.
|
|
110
|
+
In this mode, only depth-0 tasks persist on screen; subtasks are shown while active and collapse after completion.
|
|
111
|
+
|
|
112
|
+
Example live output:
|
|
113
|
+
```
|
|
114
|
+
✓ Uppercasing titles
|
|
115
|
+
⠹ Adding content
|
|
116
|
+
⠹ Processing Post 1
|
|
117
|
+
⠹ Processing Post 2
|
|
118
|
+
- Saving files
|
|
119
|
+
✓ 42
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
When the queue source is an array, upcoming root tasks are shown as `- Task` until they start.
|
|
123
|
+
When the source is a generator/async generator, upcoming tasks are not pre-rendered.
|
|
124
|
+
|
|
125
|
+
Output (updates in place):
|
|
126
|
+
```
|
|
127
|
+
⠋ Task 42
|
|
128
|
+
⠋ Task 43
|
|
129
|
+
⠋ Task 44
|
|
130
|
+
✓ 41 | ⊘ 2 | ✗ 1
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Final output:
|
|
134
|
+
```
|
|
135
|
+
✓ 97 | ⊘ 2 | ✗ 1 failed
|
|
136
|
+
|
|
137
|
+
✗ Task 25
|
|
138
|
+
Error: Something went wrong
|
|
139
|
+
|
|
140
|
+
✗ Task 50
|
|
141
|
+
Error: Connection timeout
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## SQLite Reader
|
|
145
|
+
|
|
146
|
+
Use `SqliteReader` when you iterate SQLite rows to create queue tasks and/or need to write progress back to those rows.
|
|
147
|
+
|
|
148
|
+
### Stream Rows as Queue Tasks
|
|
149
|
+
|
|
150
|
+
```typescript
|
|
151
|
+
import {Queue, SqliteReader, Task} from '@tryghost/mg-queue';
|
|
152
|
+
|
|
153
|
+
const reader = new SqliteReader({dbPath: './posts.db'});
|
|
154
|
+
await reader.configureForConcurrentAccess();
|
|
155
|
+
|
|
156
|
+
async function* rowsToTasks(batchSize = 1000): AsyncGenerator<Task> {
|
|
157
|
+
for await (const row of reader.streamRowsById({
|
|
158
|
+
table: 'posts',
|
|
159
|
+
columns: ['title', 'body'], // id is auto-selected for paging
|
|
160
|
+
batchSize
|
|
161
|
+
})) {
|
|
162
|
+
const id = Number(row.id);
|
|
163
|
+
|
|
164
|
+
yield {
|
|
165
|
+
title: `Row ${id}: ${row.title}`,
|
|
166
|
+
task: async () => {
|
|
167
|
+
// ... process row ...
|
|
168
|
+
|
|
169
|
+
await reader.updateRowById({
|
|
170
|
+
table: 'posts',
|
|
171
|
+
id,
|
|
172
|
+
values: {
|
|
173
|
+
title: row.title.toUpperCase()
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const queue = new Queue({
|
|
182
|
+
concurrency: 2,
|
|
183
|
+
// Optional: defaults to 250
|
|
184
|
+
yieldEvery: 250,
|
|
185
|
+
renderer: 'dynamic'
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
try {
|
|
189
|
+
const stats = await queue.run(rowsToTasks(2000));
|
|
190
|
+
console.log(`Done: ${stats.completed} completed, ${stats.errors.length} failed`);
|
|
191
|
+
} finally {
|
|
192
|
+
reader.close();
|
|
193
|
+
}
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
### Batch Row Updates (Single Transaction)
|
|
197
|
+
|
|
198
|
+
```typescript
|
|
199
|
+
await reader.updateRowsById({
|
|
200
|
+
table: 'posts',
|
|
201
|
+
rows: [
|
|
202
|
+
{id: 1, values: {status: 'processed', attempts: 1}},
|
|
203
|
+
{id: 2, values: {status: 'processed', attempts: 1}}
|
|
204
|
+
]
|
|
205
|
+
});
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
`updateRowsById` wraps updates in `BEGIN`/`COMMIT` and rolls back on failure.
|
|
209
|
+
|
|
210
|
+
## Skipping Tasks
|
|
211
|
+
|
|
212
|
+
### Pre-execution Skip
|
|
213
|
+
|
|
214
|
+
Skip tasks before they run using a boolean or function:
|
|
215
|
+
|
|
216
|
+
```typescript
|
|
217
|
+
const tasks: Task[] = [
|
|
218
|
+
{
|
|
219
|
+
title: 'Already done',
|
|
220
|
+
skip: true, // Always skip
|
|
221
|
+
task: async () => { /* ... */ }
|
|
222
|
+
},
|
|
223
|
+
{
|
|
224
|
+
title: 'Conditional',
|
|
225
|
+
skip: () => fs.existsSync('output.json'), // Skip if file exists
|
|
226
|
+
task: async () => { /* ... */ }
|
|
227
|
+
},
|
|
228
|
+
{
|
|
229
|
+
title: 'Async check',
|
|
230
|
+
skip: async () => {
|
|
231
|
+
const resp = await fetch('...');
|
|
232
|
+
return resp.status === 200;
|
|
233
|
+
},
|
|
234
|
+
task: async () => { /* ... */ }
|
|
235
|
+
}
|
|
236
|
+
];
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
### In-execution Skip
|
|
240
|
+
|
|
241
|
+
Skip during task execution using the context:
|
|
242
|
+
|
|
243
|
+
```typescript
|
|
244
|
+
const tasks: Task[] = [
|
|
245
|
+
{
|
|
246
|
+
title: 'Process file',
|
|
247
|
+
task: async (ctx) => {
|
|
248
|
+
const data = await readFile('input.json');
|
|
249
|
+
if (data.alreadyProcessed) {
|
|
250
|
+
ctx.skip(); // Marks task as skipped, stops execution
|
|
251
|
+
}
|
|
252
|
+
// ... process data
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
];
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
## Task Timeout
|
|
259
|
+
|
|
260
|
+
Configure a timeout for all tasks in the queue. Tasks that exceed the timeout will fail with a `TimeoutError`:
|
|
261
|
+
|
|
262
|
+
```typescript
|
|
263
|
+
import {Queue, Task, TimeoutError} from '@tryghost/mg-queue';
|
|
264
|
+
|
|
265
|
+
const tasks: Task[] = [
|
|
266
|
+
{title: 'Fast task', task: async () => { /* completes in 100ms */ }},
|
|
267
|
+
{title: 'Slow task', task: async () => { /* takes 10 seconds */ }}
|
|
268
|
+
];
|
|
269
|
+
|
|
270
|
+
const queue = new Queue({
|
|
271
|
+
concurrency: 5,
|
|
272
|
+
timeout: 5000, // 5 second timeout
|
|
273
|
+
renderer: 'verbose'
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
try {
|
|
277
|
+
await queue.run(tasks);
|
|
278
|
+
} catch (err) {
|
|
279
|
+
if (err instanceof AggregateError) {
|
|
280
|
+
for (const taskErr of err.errors) {
|
|
281
|
+
if (taskErr.cause instanceof TimeoutError) {
|
|
282
|
+
console.log(`${taskErr.task} timed out after ${taskErr.cause.timeout}ms`);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
## Cooperative Cancellation with AbortSignal
|
|
290
|
+
|
|
291
|
+
When a task times out, the `ctx.signal` is aborted, allowing tasks to clean up or stop work early. This is especially useful for long-running operations like network requests:
|
|
292
|
+
|
|
293
|
+
```typescript
|
|
294
|
+
const tasks: Task[] = [
|
|
295
|
+
{
|
|
296
|
+
title: 'Fetch data',
|
|
297
|
+
task: async (ctx) => {
|
|
298
|
+
// fetch() automatically aborts when signal is triggered
|
|
299
|
+
const response = await fetch('https://api.example.com/data', {
|
|
300
|
+
signal: ctx.signal
|
|
301
|
+
});
|
|
302
|
+
return response.json();
|
|
303
|
+
}
|
|
304
|
+
},
|
|
305
|
+
{
|
|
306
|
+
title: 'Long polling',
|
|
307
|
+
task: async (ctx) => {
|
|
308
|
+
// Check signal in loops for cooperative cancellation
|
|
309
|
+
while (!ctx.signal.aborted) {
|
|
310
|
+
const data = await pollOnce();
|
|
311
|
+
if (data.complete) break;
|
|
312
|
+
await delay(1000);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
},
|
|
316
|
+
{
|
|
317
|
+
title: 'Custom cleanup',
|
|
318
|
+
task: async (ctx) => {
|
|
319
|
+
const connection = await openConnection();
|
|
320
|
+
|
|
321
|
+
// Register cleanup handler
|
|
322
|
+
ctx.signal.addEventListener('abort', () => {
|
|
323
|
+
connection.close();
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
await processData(connection);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
];
|
|
330
|
+
|
|
331
|
+
const queue = new Queue({
|
|
332
|
+
concurrency: 3,
|
|
333
|
+
timeout: 30000 // 30 second timeout
|
|
334
|
+
});
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
The signal is also available when no timeout is set - it simply won't be aborted automatically.
|
|
338
|
+
|
|
339
|
+
## Subtasks
|
|
340
|
+
|
|
341
|
+
Tasks can dynamically generate subtasks by returning a `Subtasks` instance:
|
|
342
|
+
|
|
343
|
+
```typescript
|
|
344
|
+
import {Queue, Task, Subtasks} from '@tryghost/mg-queue';
|
|
345
|
+
|
|
346
|
+
const tasks: Task[] = [
|
|
347
|
+
{
|
|
348
|
+
title: 'Download files (parallel)',
|
|
349
|
+
task: async () => {
|
|
350
|
+
const files = await fetchFileList();
|
|
351
|
+
// Parallel execution using queue's concurrency
|
|
352
|
+
return new Subtasks(files.map(f => ({
|
|
353
|
+
title: `Download ${f.name}`,
|
|
354
|
+
task: async () => { await download(f); }
|
|
355
|
+
})));
|
|
356
|
+
}
|
|
357
|
+
},
|
|
358
|
+
{
|
|
359
|
+
title: 'Process files (sequential)',
|
|
360
|
+
task: async () => {
|
|
361
|
+
// Sequential execution
|
|
362
|
+
return new Subtasks([
|
|
363
|
+
{title: 'Step 1: Validate', task: async () => { /* ... */ }},
|
|
364
|
+
{title: 'Step 2: Transform', task: async () => { /* ... */ }},
|
|
365
|
+
{title: 'Step 3: Save', task: async () => { /* ... */ }}
|
|
366
|
+
], {sequential: true});
|
|
367
|
+
}
|
|
368
|
+
},
|
|
369
|
+
{
|
|
370
|
+
title: 'API calls (rate limited)',
|
|
371
|
+
task: async () => {
|
|
372
|
+
// Custom concurrency and timeout for subtasks
|
|
373
|
+
return new Subtasks(
|
|
374
|
+
apiEndpoints.map(url => ({
|
|
375
|
+
title: `Fetch ${url}`,
|
|
376
|
+
task: async () => { await fetch(url); }
|
|
377
|
+
})),
|
|
378
|
+
{concurrency: 2, timeout: 5000}
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
];
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
Output with VerboseRenderer:
|
|
386
|
+
```
|
|
387
|
+
[STARTING] Download files (parallel)
|
|
388
|
+
[STARTING] Download image1.jpg
|
|
389
|
+
[STARTING] Download image2.jpg
|
|
390
|
+
[COMPLETED] Download image1.jpg
|
|
391
|
+
[COMPLETED] Download image2.jpg
|
|
392
|
+
[COMPLETED] Download files (parallel)
|
|
393
|
+
[STARTING] Process files (sequential)
|
|
394
|
+
[STARTING] Step 1: Validate
|
|
395
|
+
[COMPLETED] Step 1: Validate
|
|
396
|
+
[STARTING] Step 2: Transform
|
|
397
|
+
[COMPLETED] Step 2: Transform
|
|
398
|
+
[STARTING] Step 3: Save
|
|
399
|
+
[COMPLETED] Step 3: Save
|
|
400
|
+
[COMPLETED] Process files (sequential)
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
Subtasks can be nested to any depth. If any subtask fails, the parent task is marked as failed, but other subtasks continue processing.
|
|
404
|
+
|
|
405
|
+
## API
|
|
406
|
+
|
|
407
|
+
### Queue
|
|
408
|
+
|
|
409
|
+
```typescript
|
|
410
|
+
new Queue(options: QueueOptions)
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
| Option | Type | Required | Default | Description |
|
|
414
|
+
|---|---|---|---|---|
|
|
415
|
+
| `concurrency` | `number` | Yes | — | Maximum number of tasks to run concurrently |
|
|
416
|
+
| `renderer` | `BuiltInRenderer \| Renderer` | No | `'silent'` | A built-in renderer name (`'silent'`, `'verbose'`, `'dynamic'`) or a custom `Renderer` instance |
|
|
417
|
+
| `timeout` | `number` | No | No timeout | Timeout in milliseconds for each task. Tasks exceeding this fail with `TimeoutError` |
|
|
418
|
+
| `yieldEvery` | `number` | No | `250` | Yield to the event loop every N settled tasks. Useful for smooth rendering with synchronous work |
|
|
419
|
+
|
|
420
|
+
Methods:
|
|
421
|
+
- `run(tasks): Promise<QueueStats>` - Execute tasks and return stats (never throws on task errors)
|
|
422
|
+
|
|
423
|
+
### Task
|
|
424
|
+
|
|
425
|
+
```typescript
|
|
426
|
+
interface Task {
|
|
427
|
+
title: string;
|
|
428
|
+
skip?: boolean | (() => boolean | Promise<boolean>);
|
|
429
|
+
task: (ctx: TaskContext) => Promise<void | Subtasks>;
|
|
430
|
+
}
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
| Property | Type | Required | Description |
|
|
434
|
+
|---|---|---|---|
|
|
435
|
+
| `title` | `string` | Yes | Display name for the task, shown in renderer output and error reports |
|
|
436
|
+
| `skip` | `boolean \| () => boolean \| Promise<boolean>` | No | Skip this task. `true` always skips; a function is evaluated before the task runs |
|
|
437
|
+
| `task` | `(ctx: TaskContext) => Promise<void \| Subtasks>` | Yes | The async function to execute. Receives a `TaskContext` for skipping and abort signalling. Return a `Subtasks` instance to spawn child tasks |
|
|
438
|
+
|
|
439
|
+
### Subtasks
|
|
440
|
+
|
|
441
|
+
Wrapper for returning subtasks with execution options:
|
|
442
|
+
|
|
443
|
+
```typescript
|
|
444
|
+
new Subtasks(tasks: Task[], options?: SubtasksOptions)
|
|
445
|
+
|
|
446
|
+
interface SubtasksOptions {
|
|
447
|
+
sequential?: boolean; // Run subtasks one at a time (shorthand for concurrency: 1)
|
|
448
|
+
concurrency?: number; // Max concurrent subtasks (default: inherits from queue)
|
|
449
|
+
timeout?: number; // Timeout per subtask in ms (default: inherits from queue)
|
|
450
|
+
}
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
### TaskContext
|
|
454
|
+
|
|
455
|
+
```typescript
|
|
456
|
+
interface TaskContext {
|
|
457
|
+
skip(): void; // Call to skip the current task
|
|
458
|
+
signal: AbortSignal; // Aborted when task times out
|
|
459
|
+
}
|
|
460
|
+
```
|
|
461
|
+
|
|
462
|
+
### TaskInfo
|
|
463
|
+
|
|
464
|
+
Passed to renderer callbacks:
|
|
465
|
+
|
|
466
|
+
```typescript
|
|
467
|
+
interface TaskInfo {
|
|
468
|
+
title: string;
|
|
469
|
+
depth: number; // 0 = root, 1 = subtask, 2 = nested subtask, etc.
|
|
470
|
+
}
|
|
471
|
+
```
|
|
472
|
+
|
|
473
|
+
### QueueStats
|
|
474
|
+
|
|
475
|
+
Returned from `queue.run()` and passed to renderer's `onQueueEnd`:
|
|
476
|
+
|
|
477
|
+
```typescript
|
|
478
|
+
interface QueueStats {
|
|
479
|
+
completed: number;
|
|
480
|
+
skipped: number;
|
|
481
|
+
errors: Array<{title: string; error: Error}>;
|
|
482
|
+
}
|
|
483
|
+
```
|
|
484
|
+
|
|
485
|
+
### SqliteReader
|
|
486
|
+
|
|
487
|
+
```typescript
|
|
488
|
+
new SqliteReader(options: SqliteReaderOptions)
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
Options:
|
|
492
|
+
- `dbPath: string` - Path to SQLite database file
|
|
493
|
+
- `timeoutMs?: number` - SQLite busy timeout in milliseconds (default: `5000`)
|
|
494
|
+
- `readonly?: boolean` - Open connection in readonly mode
|
|
495
|
+
- `database?: SqliteDatabase` - Inject existing DB instance (useful for tests)
|
|
496
|
+
|
|
497
|
+
Methods:
|
|
498
|
+
- `configureForConcurrentAccess(): Promise<void>` - Sets `journal_mode=WAL` and `synchronous=NORMAL`
|
|
499
|
+
- `streamRowsById(options): AsyncGenerator<SqliteRow>` - Streams rows in `id` order using batched pagination
|
|
500
|
+
- `updateRowById(options): Promise<void>` - Updates one row by ID with bound parameters
|
|
501
|
+
- `updateRowsById(options): Promise<void>` - Updates many rows in one transaction
|
|
502
|
+
- `execute(sql): Promise<void>` - Execute raw SQL
|
|
503
|
+
- `close(): void` - Close owned DB connection
|
|
504
|
+
|
|
505
|
+
## Examples
|
|
506
|
+
|
|
507
|
+
The [examples/](examples/) directory contains runnable scripts, each demonstrating a single feature:
|
|
508
|
+
|
|
509
|
+
- **verbose-renderer.ts** — Concurrent tasks with the verbose renderer
|
|
510
|
+
- **dynamic-renderer.ts** — 20k tasks with the live-updating dynamic renderer
|
|
511
|
+
- **silent-mode.ts** — No renderer, inspecting `QueueStats` directly
|
|
512
|
+
- **skip.ts** — Boolean, sync/async, and in-execution skip patterns
|
|
513
|
+
- **timeout.ts** — Queue-wide timeout with `TimeoutError`
|
|
514
|
+
- **subtasks.ts** — Parallel and sequential child tasks via `Subtasks`
|
|
515
|
+
- **abort-signal.ts** — Cooperative cancellation with `ctx.signal`
|
|
516
|
+
- **sqlite-reader.ts** — Streaming SQLite rows as queue tasks
|
|
517
|
+
- **mg-context.ts** — Reading from an mg-context database with SqliteReader
|
|
518
|
+
- **other.ts** — Minimal end-to-end with dynamic renderer and task hierarchy
|
|
519
|
+
|
|
520
|
+
Run any example from the package directory:
|
|
521
|
+
|
|
522
|
+
```bash
|
|
523
|
+
npx tsx examples/verbose-renderer.ts
|
|
524
|
+
```
|
|
525
|
+
|
|
526
|
+
## Test
|
|
527
|
+
|
|
528
|
+
- `pnpm lint` run just eslint
|
|
529
|
+
- `pnpm test` run lint and tests
|
|
530
|
+
|
|
531
|
+
# Copyright & License
|
|
532
|
+
|
|
533
|
+
Copyright (c) 2013-2026 Ghost Foundation - Released under the [MIT license](LICENSE).
|
package/build/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { Queue, TaskError, SkipError, TimeoutError, Subtasks } from './lib/Queue.js';
|
|
2
|
+
export type { Task, TaskContext, TaskSource, QueueOptions, BuiltInRenderer, SubtasksOptions } from './lib/Queue.js';
|
|
3
|
+
export type { Renderer, QueueStats, TaskInfo } from './lib/Renderer.js';
|
|
4
|
+
export { SilentRenderer } from './lib/SilentRenderer.js';
|
|
5
|
+
export { VerboseRenderer } from './lib/VerboseRenderer.js';
|
|
6
|
+
export { DynamicRenderer } from './lib/DynamicRenderer.js';
|
|
7
|
+
export type { DynamicRendererOptions } from './lib/DynamicRenderer.js';
|
|
8
|
+
export { SqliteReader } from './lib/SqliteReader.js';
|
|
9
|
+
export type { SqliteBatchUpdateRow, SqliteBatchUpdateRowsOptions, SqliteDatabase, SqliteReaderOptions, SqliteStatement, SqliteStreamRowsOptions, SqliteUpdateRowOptions, SqliteRow, SqliteValue } from './lib/SqliteReader.js';
|
package/build/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { Queue, TaskError, SkipError, TimeoutError, Subtasks } from './lib/Queue.js';
|
|
2
|
+
export { SilentRenderer } from './lib/SilentRenderer.js';
|
|
3
|
+
export { VerboseRenderer } from './lib/VerboseRenderer.js';
|
|
4
|
+
export { DynamicRenderer } from './lib/DynamicRenderer.js';
|
|
5
|
+
export { SqliteReader } from './lib/SqliteReader.js';
|
|
6
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,YAAY,EAAE,QAAQ,EAAC,MAAM,gBAAgB,CAAC;AAInF,OAAO,EAAC,cAAc,EAAC,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAC,eAAe,EAAC,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAC,eAAe,EAAC,MAAM,0BAA0B,CAAC;AAEzD,OAAO,EAAC,YAAY,EAAC,MAAM,uBAAuB,CAAC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Renderer, QueueStats, TaskInfo } from './Renderer.js';
|
|
2
|
+
export interface DynamicRendererOptions {
|
|
3
|
+
keepOnScreen?: boolean;
|
|
4
|
+
}
|
|
5
|
+
export declare class DynamicRenderer implements Renderer {
|
|
6
|
+
#private;
|
|
7
|
+
constructor(options?: DynamicRendererOptions);
|
|
8
|
+
onTaskPending(info: TaskInfo): void;
|
|
9
|
+
onTaskStart(info: TaskInfo): void;
|
|
10
|
+
onTaskComplete(info: TaskInfo): void;
|
|
11
|
+
onTaskError(info: TaskInfo, _error: Error): void;
|
|
12
|
+
onTaskSkip(info: TaskInfo): void;
|
|
13
|
+
onQueueEnd(stats: QueueStats): void;
|
|
14
|
+
}
|