plantr 2.1.0 → 2.3.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.
@@ -1,8 +1,11 @@
1
1
  import { resolveDependencyOrder, UnknownSeederError } from './dependency-resolver.js'
2
+ import { SeedUsageError } from './errors.js'
2
3
  import {
4
+ printCleanupErrors,
3
5
  printConcurrentComplete,
4
6
  printConcurrentSkipped,
5
7
  printErrors,
8
+ printFreshReset,
6
9
  printResultsTable,
7
10
  printSeederComplete,
8
11
  printSeederHeader,
@@ -11,6 +14,7 @@ import {
11
14
  printSummary,
12
15
  } from './formatting.js'
13
16
  import { enterSeeding, exitSeeding } from './seeding-state.js'
17
+ import { onTerminationSignal } from './signals.js'
14
18
  import type { StepRecord } from './step.js'
15
19
  import type {
16
20
  MaybePromise,
@@ -33,16 +37,48 @@ export type SeederScopeHandle = {
33
37
  run: <T>(fn: () => Promise<T>) => Promise<T>
34
38
  }
35
39
 
40
+ /** Passed to `setup`, for resources it acquires one at a time */
41
+ export type SetupHelpers = {
42
+ /**
43
+ * Register the cleanup for a resource right after acquiring it. Deferred cleanups run
44
+ * after `teardown`, last registered first, and also when `setup` throws after
45
+ * registering them (when `teardown` does not run, because there are no resources).
46
+ */
47
+ defer: (cleanup: () => MaybePromise<void>) => void
48
+ }
49
+
50
+ /** Passed to `onFresh`: which seeders of this run ignore their cached steps */
51
+ export type FreshRun<TResources = undefined> = {
52
+ /** What `setup` returned */
53
+ resources: TResources
54
+ /** Names of the seeders in this run that run fresh, in run order (never empty) */
55
+ seeders: readonly string[]
56
+ /**
57
+ * Whether every registered seeder runs, and runs fresh (`fresh: true` without `only`,
58
+ * or CLI `--fresh` without seeder names). Only then is wiping the whole target safe:
59
+ * otherwise seeders outside `seeders` keep replaying cached ids of what they created.
60
+ */
61
+ all: boolean
62
+ }
63
+
36
64
  /**
37
65
  * Internal configuration used by the runner.
38
66
  * This is created by `createSeederInstance` and includes the wrapped context factory.
39
67
  */
40
- export type InternalSeederConfig<TContext> = {
41
- /** Factory function that creates the full context; called once, after onBeforeAll */
42
- context: () => MaybePromise<TContext>
43
- /** Called once after onBeforeAll to preload step cache entries (when cache.getAll is configured) */
68
+ export type InternalSeederConfig<TContext, TResources = undefined> = {
69
+ /** Factory function that creates the full context; called once, after setup */
70
+ context: (resources: TResources) => MaybePromise<TContext>
71
+ /** Acquires the run's resources, after onBeforeAll; its return value reaches context and teardown */
72
+ setup?: ((helpers: SetupHelpers) => MaybePromise<TResources>) | undefined
73
+ /** Releases what setup returned; runs whenever setup returned, also on failure and SIGINT/SIGTERM */
74
+ teardown?: ((resources: TResources) => MaybePromise<void>) | undefined
75
+ /** Called once after setup, before the cache preload (createSeederInstance builds its cache here) */
76
+ prepare?: ((resources: TResources) => MaybePromise<void>) | undefined
77
+ /** Called after prepare and before the cache preload when at least one seeder of the run is fresh */
78
+ onFresh?: ((run: FreshRun<TResources>) => MaybePromise<void>) | undefined
79
+ /** Called once after setup and onFresh to preload step cache entries */
44
80
  preloadCache?: (() => MaybePromise<void>) | undefined
45
- /** Called once before onAfterAll to flush buffered step cache writes (when cache.setMany is configured) */
81
+ /** Called once before onAfterAll to flush buffered step cache writes */
46
82
  flushCache?: (() => MaybePromise<void>) | undefined
47
83
  /** Called before each seeder runs (legacy sequential hook); may return the record its steps fill */
48
84
  beforeSeeder?: ((name: string, options: { fresh: boolean }) => StepRecord | undefined) | undefined
@@ -54,7 +90,7 @@ export type InternalSeederConfig<TContext> = {
54
90
  bannerName?: string | undefined
55
91
  /** Database URL the run writes to; non-local hosts are refused unless allowRemote */
56
92
  target?: (() => string | undefined) | undefined
57
- /** Called before the context is created */
93
+ /** Called before setup and the context */
58
94
  onBeforeAll?: (() => MaybePromise<void>) | undefined
59
95
  /** Called after all seeders complete, also when a seeder or the context factory throws */
60
96
  onAfterAll?: ((ctx: TContext | undefined) => MaybePromise<void>) | undefined
@@ -63,7 +99,7 @@ export type InternalSeederConfig<TContext> = {
63
99
  /**
64
100
  * Error thrown when a run would write to a database that is not local
65
101
  */
66
- export class SeedTargetError extends Error {
102
+ export class SeedTargetError extends SeedUsageError {
67
103
  constructor(label: string) {
68
104
  super(
69
105
  `Refusing to seed ${label}: it is not a local database. Pass allowRemote (CLI: --allow-remote) to seed it on purpose.`,
@@ -76,23 +112,28 @@ const isLocalHost = (hostPort: string): boolean => {
76
112
  if (hostPort.startsWith('/')) return true // socket directory
77
113
  const lower = hostPort.toLowerCase()
78
114
  const bracketed = /^\[([^\]]*)\]/.exec(lower)
115
+ const hasPort = bracketed ? /:\d+$/.test(lower.slice(bracketed[0].length)) : /:\d+$/.test(lower)
79
116
  const host = bracketed ? (bracketed[1] ?? '') : lower.replace(/:\d+$/, '')
80
117
  return (
118
+ host === 'localhost' ||
81
119
  host === '::1' ||
82
120
  host === '0.0.0.0' ||
83
121
  host === 'host.docker.internal' ||
84
122
  host.endsWith('.localhost') ||
85
123
  /^127\./.test(host) ||
86
- !/[.:]/.test(host)
124
+ (hasPort && host.length > 0 && !/[.:]/.test(host))
87
125
  )
88
126
  }
89
127
 
90
128
  /**
91
129
  * Describe a database URL without its credentials and say whether every host it names
92
- * is local: loopback, `*.localhost`, `host.docker.internal`, a socket or `file:` path,
93
- * or a name without a dot (a compose service). A `host=` parameter overrides the
94
- * URL's host, as libpq does. Hand-parsed so driver formats `URL` rejects still work
95
- * (several hosts, `sqlserver://host;key=value`, sockets with credentials).
130
+ * is local: loopback (`localhost`, `127.*`, `::1`, `0.0.0.0`), `*.localhost`,
131
+ * `host.docker.internal`, a socket or `file:` path, or a single-label hostname with an
132
+ * explicit port (such as a compose service like `postgres:5432`). A bare name without a
133
+ * port (such as a cloud project URL like `firestore://my-prod-project`) is treated as
134
+ * remote. A `host=` parameter overrides the URL's host, as libpq does. Hand-parsed so
135
+ * driver formats `URL` rejects still work (several hosts, `sqlserver://host;key=value`,
136
+ * sockets with credentials).
96
137
  */
97
138
  export function describeTarget(target: string): TargetDescription {
98
139
  if (/^file:/i.test(target)) return { label: target.replace(/[?#].*$/, ''), local: true }
@@ -105,7 +146,9 @@ export function describeTarget(target: string): TargetDescription {
105
146
  const query = queryStart === -1 ? '' : rest.slice(queryStart)
106
147
  // Drop credentials: everything up to the last @ before the query
107
148
  const authorityAndPath = beforeQuery.slice(beforeQuery.lastIndexOf('@') + 1)
108
- const [authority = '', path = ''] = authorityAndPath.split(/(?=[/;])/, 2)
149
+ const pathStart = authorityAndPath.search(/[/;]/)
150
+ const authority = pathStart === -1 ? authorityAndPath : authorityAndPath.slice(0, pathStart)
151
+ const path = pathStart === -1 ? '' : authorityAndPath.slice(pathStart)
109
152
  let hosts = authority.split(',').filter(Boolean)
110
153
  const hostParam = /[?&;]host=([^&;#]*)/i.exec(`${query}${path.startsWith(';') ? path : ''}`)?.[1]
111
154
  if (hostParam) {
@@ -116,7 +159,9 @@ export function describeTarget(target: string): TargetDescription {
116
159
  }
117
160
  }
118
161
 
119
- const label = `${hosts.join(',') || 'local socket'}${path.startsWith('/') ? path : ''}`
162
+ const pathWithoutParams = path.startsWith('/') ? (path.split(';', 1)[0] ?? '') : ''
163
+ const pathLabel = pathWithoutParams.length > 1 ? pathWithoutParams : ''
164
+ const label = `${hosts.join(',') || 'local socket'}${pathLabel}`
120
165
  return { label, local: hosts.every(isLocalHost) }
121
166
  }
122
167
 
@@ -131,11 +176,12 @@ export function describeTarget(target: string): TargetDescription {
131
176
  */
132
177
  export async function runSeedersCore<
133
178
  TContext,
179
+ TResources = undefined,
134
180
  const TSeeders extends readonly SeederAny[] = readonly SeederAny[],
135
181
  const TOptions extends RunSeedersOptions = RunSeedersOptions,
136
182
  >(
137
183
  seeders: TSeeders,
138
- config: InternalSeederConfig<TContext>,
184
+ config: InternalSeederConfig<TContext, TResources>,
139
185
  options: TOptions = {} as TOptions,
140
186
  ): Promise<RunSeedersResult<TSeeders, TOptions>> {
141
187
  const {
@@ -146,6 +192,7 @@ export async function runSeedersCore<
146
192
  fresh = false,
147
193
  allowRemote = false,
148
194
  concurrency = 1,
195
+ handleSignals = true,
149
196
  } = options
150
197
 
151
198
  if (
@@ -198,7 +245,50 @@ export async function runSeedersCore<
198
245
  const failedSeeders = new Set<string>()
199
246
  const concurrent = concurrency > 1
200
247
 
248
+ // Lifecycle state, read by the cleanup that runs on success, failure and SIGINT/SIGTERM
249
+ let beforeAllDone = false
250
+ let acquired: { resources: TResources } | undefined
251
+ let prepared = false
252
+ let ctx: TContext | undefined
253
+ let interrupted = false
254
+ const deferred: (() => MaybePromise<void>)[] = []
255
+
256
+ let cleanup: Promise<unknown[]> | undefined
257
+ const runCleanup = (): Promise<unknown[]> => {
258
+ cleanup ??= (async () => {
259
+ const errors: unknown[] = []
260
+ const attempt = async (fn: () => MaybePromise<void>) => {
261
+ try {
262
+ await fn()
263
+ } catch (error) {
264
+ errors.push(error)
265
+ }
266
+ }
267
+ if (prepared && config.flushCache) await attempt(config.flushCache)
268
+ if (beforeAllDone && config.onAfterAll) {
269
+ const onAfterAll = config.onAfterAll
270
+ await attempt(() => onAfterAll(ctx))
271
+ }
272
+ if (acquired && config.teardown) {
273
+ const { teardown } = config
274
+ const { resources } = acquired
275
+ await attempt(() => teardown(resources))
276
+ }
277
+ for (const release of deferred.splice(0).reverse()) await attempt(release)
278
+ return errors
279
+ })()
280
+ return cleanup
281
+ }
282
+
201
283
  enterSeeding()
284
+ const unregisterSignals = handleSignals
285
+ ? onTerminationSignal(async () => {
286
+ interrupted = true
287
+ printCleanupErrors(await runCleanup())
288
+ })
289
+ : () => {}
290
+
291
+ let bodyError: { error: unknown } | undefined
202
292
  try {
203
293
  if (verbose) {
204
294
  printStartBanner({
@@ -214,247 +304,265 @@ export async function runSeedersCore<
214
304
  if (config.onBeforeAll) {
215
305
  await config.onBeforeAll()
216
306
  }
307
+ beforeAllDone = true
217
308
 
218
- let ctx: TContext | undefined
219
- try {
220
- if (config.preloadCache) {
221
- await config.preloadCache()
222
- }
309
+ const resources = config.setup
310
+ ? await config.setup({ defer: (release) => deferred.push(release) })
311
+ : (undefined as TResources)
312
+ acquired = { resources }
223
313
 
224
- // Create context once for all seeders
225
- ctx = await config.context()
226
- const activeCtx = ctx
314
+ if (config.prepare) {
315
+ await config.prepare(resources)
316
+ }
317
+ prepared = true
227
318
 
228
- const executeSeeder = async (name: string): Promise<boolean> => {
229
- const idx = resultIndex.get(name)
230
- const seeder = seederMap.get(name)
231
- if (idx === undefined || !seeder) return true
319
+ const freshSeeders = orderedNames.filter(isFresh)
320
+ if (config.onFresh && freshSeeders.length > 0) {
321
+ const all = freshSeeders.length === seederMap.size
322
+ if (verbose) printFreshReset(freshSeeders, all)
323
+ await config.onFresh({ resources, seeders: freshSeeders, all })
324
+ }
232
325
 
233
- const scopeHandle: SeederScopeHandle = config.createSeederScope
234
- ? config.createSeederScope({ name, fresh: isFresh(name), concurrent })
235
- : {
236
- record: config.beforeSeeder?.(name, { fresh: isFresh(name) }),
237
- run: (fn) => fn(),
238
- }
326
+ if (config.preloadCache) {
327
+ await config.preloadCache()
328
+ }
239
329
 
240
- const deps: Record<string, unknown> = {}
241
- for (const depName of seeder.dependsOn) {
242
- deps[depName] = outputs[depName]
243
- }
330
+ // Create context once for all seeders
331
+ ctx = await config.context(resources)
332
+ const activeCtx = ctx
244
333
 
245
- const startTime = performance.now()
334
+ const executeSeeder = async (name: string): Promise<boolean> => {
335
+ const idx = resultIndex.get(name)
336
+ const seeder = seederMap.get(name)
337
+ if (idx === undefined || !seeder) return true
246
338
 
247
- try {
248
- const output = await scopeHandle.run(async () => seeder.run(activeCtx, deps))
249
- const durationMs = Math.round(performance.now() - startTime)
250
-
251
- outputs[name] = output
252
- results[idx] = {
253
- name,
254
- status: 'completed',
255
- durationMs,
256
- output,
257
- cachedSteps: scopeHandle.record?.cachedSteps ?? [],
339
+ const scopeHandle: SeederScopeHandle = config.createSeederScope
340
+ ? config.createSeederScope({ name, fresh: isFresh(name), concurrent })
341
+ : {
342
+ record: config.beforeSeeder?.(name, { fresh: isFresh(name) }),
343
+ run: (fn) => fn(),
258
344
  }
259
345
 
260
- if (verbose) {
261
- if (concurrent) {
262
- printConcurrentComplete(name, durationMs, true)
263
- } else {
264
- printSeederComplete(durationMs, true)
265
- }
266
- }
267
- return true
268
- } catch (error) {
269
- const durationMs = Math.round(performance.now() - startTime)
270
- const err = error instanceof Error ? error : new Error(String(error))
271
- const failedStep =
272
- scopeHandle.record?.failed && scopeHandle.record.failed.error === error
273
- ? scopeHandle.record.failed.step
274
- : undefined
275
-
276
- results[idx] = {
277
- name,
278
- status: 'failed',
279
- durationMs,
280
- error: err,
281
- ...(failedStep !== undefined ? { failedStep } : {}),
282
- cachedSteps: scopeHandle.record?.cachedSteps ?? [],
346
+ const deps: Record<string, unknown> = {}
347
+ for (const depName of seeder.dependsOn) {
348
+ deps[depName] = outputs[depName]
349
+ }
350
+
351
+ const startTime = performance.now()
352
+
353
+ try {
354
+ const output = await scopeHandle.run(async () => seeder.run(activeCtx, deps))
355
+ const durationMs = Math.round(performance.now() - startTime)
356
+
357
+ outputs[name] = output
358
+ results[idx] = {
359
+ name,
360
+ status: 'completed',
361
+ durationMs,
362
+ output,
363
+ cachedSteps: scopeHandle.record?.cachedSteps ?? [],
364
+ }
365
+
366
+ if (verbose) {
367
+ if (concurrent) {
368
+ printConcurrentComplete(name, durationMs, true)
369
+ } else {
370
+ printSeederComplete(durationMs, true)
283
371
  }
284
- failedSeeders.add(name)
372
+ }
373
+ return true
374
+ } catch (error) {
375
+ const durationMs = Math.round(performance.now() - startTime)
376
+ const err = error instanceof Error ? error : new Error(String(error))
377
+ const failedStep =
378
+ scopeHandle.record?.failed && scopeHandle.record.failed.error === error
379
+ ? scopeHandle.record.failed.step
380
+ : undefined
381
+
382
+ results[idx] = {
383
+ name,
384
+ status: 'failed',
385
+ durationMs,
386
+ error: err,
387
+ ...(failedStep !== undefined ? { failedStep } : {}),
388
+ cachedSteps: scopeHandle.record?.cachedSteps ?? [],
389
+ }
390
+ failedSeeders.add(name)
285
391
 
286
- if (verbose) {
287
- if (concurrent) {
288
- printConcurrentComplete(name, durationMs, false)
289
- } else {
290
- printSeederComplete(durationMs, false)
291
- }
392
+ if (verbose) {
393
+ if (concurrent) {
394
+ printConcurrentComplete(name, durationMs, false)
395
+ } else {
396
+ printSeederComplete(durationMs, false)
292
397
  }
293
- return false
294
398
  }
399
+ return false
295
400
  }
401
+ }
296
402
 
297
- if (!concurrent) {
298
- // Sequential execution in topological order
299
- for (let i = 0; i < orderedNames.length; i++) {
300
- const name = orderedNames[i]
301
- if (!name) continue
302
- const seeder = seederMap.get(name)
303
- if (!seeder) continue
304
-
305
- if (continueOnFailure) {
306
- const failedDeps = seeder.dependsOn.filter((dep) => failedSeeders.has(dep))
307
- if (failedDeps.length > 0) {
308
- results[i] = { name, status: 'skipped', failedDeps }
309
- failedSeeders.add(name)
310
- if (verbose) {
311
- printSeederHeader(name, i, orderedNames.length, seeder.description)
312
- printSeederSkipped(failedDeps)
313
- }
314
- continue
403
+ if (!concurrent) {
404
+ // Sequential execution in topological order
405
+ for (let i = 0; i < orderedNames.length; i++) {
406
+ // After SIGINT/SIGTERM, start nothing new while teardown runs
407
+ if (interrupted) break
408
+ const name = orderedNames[i]
409
+ if (!name) continue
410
+ const seeder = seederMap.get(name)
411
+ if (!seeder) continue
412
+
413
+ if (continueOnFailure) {
414
+ const failedDeps = seeder.dependsOn.filter((dep) => failedSeeders.has(dep))
415
+ if (failedDeps.length > 0) {
416
+ results[i] = { name, status: 'skipped', failedDeps }
417
+ failedSeeders.add(name)
418
+ if (verbose) {
419
+ printSeederHeader(name, i, orderedNames.length, seeder.description)
420
+ printSeederSkipped(failedDeps)
315
421
  }
422
+ continue
316
423
  }
424
+ }
317
425
 
318
- if (verbose) {
319
- printSeederHeader(name, i, orderedNames.length, seeder.description)
320
- }
426
+ if (verbose) {
427
+ printSeederHeader(name, i, orderedNames.length, seeder.description)
428
+ }
321
429
 
322
- const ok = await executeSeeder(name)
323
- if (!ok && !continueOnFailure) {
324
- break
325
- }
430
+ const ok = await executeSeeder(name)
431
+ if (!ok && !continueOnFailure) {
432
+ break
326
433
  }
327
- } else if (orderedNames.length > 0) {
328
- // Parallel DAG worker pool with critical-path (longest-downstream-chain-first) scheduling
329
- const remainingDeps = new Map<string, number>()
330
- const dependents = new Map<string, string[]>()
331
-
332
- for (const name of orderedNames) {
333
- remainingDeps.set(name, 0)
334
- dependents.set(name, [])
434
+ }
435
+ } else if (orderedNames.length > 0) {
436
+ // Parallel DAG worker pool with critical-path (longest-downstream-chain-first) scheduling
437
+ const remainingDeps = new Map<string, number>()
438
+ const dependents = new Map<string, string[]>()
439
+
440
+ for (const name of orderedNames) {
441
+ remainingDeps.set(name, 0)
442
+ dependents.set(name, [])
443
+ }
444
+
445
+ for (const name of orderedNames) {
446
+ const seeder = seederMap.get(name)
447
+ if (!seeder) continue
448
+ const uniqueDeps = new Set(seeder.dependsOn)
449
+ remainingDeps.set(name, uniqueDeps.size)
450
+ for (const dep of uniqueDeps) {
451
+ dependents.get(dep)?.push(name)
335
452
  }
453
+ }
336
454
 
337
- for (const name of orderedNames) {
338
- const seeder = seederMap.get(name)
339
- if (!seeder) continue
340
- const uniqueDeps = new Set(seeder.dependsOn)
341
- remainingDeps.set(name, uniqueDeps.size)
342
- for (const dep of uniqueDeps) {
343
- dependents.get(dep)?.push(name)
344
- }
455
+ // Compute critical-path height (longest chain of downstream dependents) in reverse topo order
456
+ const criticalHeight = new Map<string, number>()
457
+ for (let i = orderedNames.length - 1; i >= 0; i--) {
458
+ const name = orderedNames[i]!
459
+ let maxHeight = 0
460
+ for (const dependent of dependents.get(name) ?? []) {
461
+ const h = (criticalHeight.get(dependent) ?? 0) + 1
462
+ if (h > maxHeight) maxHeight = h
345
463
  }
464
+ criticalHeight.set(name, maxHeight)
465
+ }
346
466
 
347
- // Compute critical-path height (longest chain of downstream dependents) in reverse topo order
348
- const criticalHeight = new Map<string, number>()
349
- for (let i = orderedNames.length - 1; i >= 0; i--) {
350
- const name = orderedNames[i]!
351
- let maxHeight = 0
352
- for (const dependent of dependents.get(name) ?? []) {
353
- const h = (criticalHeight.get(dependent) ?? 0) + 1
354
- if (h > maxHeight) maxHeight = h
355
- }
356
- criticalHeight.set(name, maxHeight)
467
+ const ready: string[] = []
468
+ for (const name of orderedNames) {
469
+ if (remainingDeps.get(name) === 0) {
470
+ ready.push(name)
357
471
  }
472
+ }
358
473
 
359
- const ready: string[] = []
360
- for (const name of orderedNames) {
361
- if (remainingDeps.get(name) === 0) {
362
- ready.push(name)
474
+ const popHighestPriority = (): string => {
475
+ let bestIdx = 0
476
+ let bestHeight = criticalHeight.get(ready[0]!) ?? 0
477
+ let bestOrder = resultIndex.get(ready[0]!) ?? 0
478
+ for (let i = 1; i < ready.length; i++) {
479
+ const candidate = ready[i]!
480
+ const h = criticalHeight.get(candidate) ?? 0
481
+ const order = resultIndex.get(candidate) ?? 0
482
+ if (h > bestHeight || (h === bestHeight && order < bestOrder)) {
483
+ bestIdx = i
484
+ bestHeight = h
485
+ bestOrder = order
363
486
  }
364
487
  }
488
+ return ready.splice(bestIdx, 1)[0]!
489
+ }
490
+
491
+ await new Promise<void>((resolve) => {
492
+ let inFlight = 0
493
+ let stopped = false
494
+
495
+ const markSettled = (settledName: string) => {
496
+ const deps = dependents.get(settledName)
497
+ if (!deps) return
498
+ for (const dependent of deps) {
499
+ const next = (remainingDeps.get(dependent) ?? 1) - 1
500
+ remainingDeps.set(dependent, next)
501
+ if (next !== 0 || stopped) continue
502
+
503
+ const seeder = seederMap.get(dependent)
504
+ if (!seeder) continue
365
505
 
366
- const popHighestPriority = (): string => {
367
- let bestIdx = 0
368
- let bestHeight = criticalHeight.get(ready[0]!) ?? 0
369
- let bestOrder = resultIndex.get(ready[0]!) ?? 0
370
- for (let i = 1; i < ready.length; i++) {
371
- const candidate = ready[i]!
372
- const h = criticalHeight.get(candidate) ?? 0
373
- const order = resultIndex.get(candidate) ?? 0
374
- if (h > bestHeight || (h === bestHeight && order < bestOrder)) {
375
- bestIdx = i
376
- bestHeight = h
377
- bestOrder = order
506
+ const failedDeps = seeder.dependsOn.filter((d) => failedSeeders.has(d))
507
+ if (failedDeps.length > 0) {
508
+ const idx = resultIndex.get(dependent)
509
+ if (idx !== undefined) {
510
+ results[idx] = { name: dependent, status: 'skipped', failedDeps }
511
+ }
512
+ failedSeeders.add(dependent)
513
+ if (verbose) {
514
+ printConcurrentSkipped(dependent, failedDeps)
515
+ }
516
+ markSettled(dependent)
517
+ } else {
518
+ ready.push(dependent)
378
519
  }
379
520
  }
380
- return ready.splice(bestIdx, 1)[0]!
381
521
  }
382
522
 
383
- await new Promise<void>((resolve) => {
384
- let inFlight = 0
385
- let stopped = false
386
-
387
- const markSettled = (settledName: string) => {
388
- const deps = dependents.get(settledName)
389
- if (!deps) return
390
- for (const dependent of deps) {
391
- const next = (remainingDeps.get(dependent) ?? 1) - 1
392
- remainingDeps.set(dependent, next)
393
- if (next !== 0 || stopped) continue
394
-
395
- const seeder = seederMap.get(dependent)
396
- if (!seeder) continue
397
-
398
- const failedDeps = seeder.dependsOn.filter((d) => failedSeeders.has(d))
399
- if (failedDeps.length > 0) {
400
- const idx = resultIndex.get(dependent)
401
- if (idx !== undefined) {
402
- results[idx] = { name: dependent, status: 'skipped', failedDeps }
403
- }
404
- failedSeeders.add(dependent)
405
- if (verbose) {
406
- printConcurrentSkipped(dependent, failedDeps)
407
- }
408
- markSettled(dependent)
523
+ const schedule = () => {
524
+ while (!stopped && !interrupted && inFlight < concurrency && ready.length > 0) {
525
+ const name = popHighestPriority()
526
+ inFlight++
527
+ void executeSeeder(name).then((ok) => {
528
+ inFlight--
529
+ if (!ok && !continueOnFailure) {
530
+ stopped = true
409
531
  } else {
410
- ready.push(dependent)
532
+ markSettled(name)
411
533
  }
412
- }
534
+ schedule()
535
+ })
413
536
  }
414
537
 
415
- const schedule = () => {
416
- while (!stopped && inFlight < concurrency && ready.length > 0) {
417
- const name = popHighestPriority()
418
- inFlight++
419
- void executeSeeder(name).then((ok) => {
420
- inFlight--
421
- if (!ok && !continueOnFailure) {
422
- stopped = true
423
- } else {
424
- markSettled(name)
425
- }
426
- schedule()
427
- })
428
- }
429
-
430
- if (inFlight === 0 && (stopped || ready.length === 0)) {
431
- resolve()
432
- }
538
+ if (inFlight === 0 && (stopped || interrupted || ready.length === 0)) {
539
+ resolve()
433
540
  }
541
+ }
434
542
 
435
- schedule()
436
- })
437
- }
543
+ schedule()
544
+ })
545
+ }
438
546
 
439
- if (printResults) {
440
- printResultsTable(results)
441
- printErrors(results)
442
- printSummary(results, performance.now() - runStartTime, concurrency)
443
- }
444
- } finally {
445
- try {
446
- if (config.flushCache) {
447
- await config.flushCache()
448
- }
449
- } finally {
450
- if (config.onAfterAll) {
451
- await config.onAfterAll(ctx)
452
- }
453
- }
547
+ if (printResults) {
548
+ printResultsTable(results)
549
+ printErrors(results)
550
+ printSummary(results, performance.now() - runStartTime, concurrency)
454
551
  }
552
+ } catch (error) {
553
+ bodyError = { error }
455
554
  } finally {
555
+ const cleanupErrors = await runCleanup()
556
+ unregisterSignals()
456
557
  exitSeeding()
558
+ if (bodyError) {
559
+ printCleanupErrors(cleanupErrors)
560
+ } else if (cleanupErrors.length > 0) {
561
+ printCleanupErrors(cleanupErrors.slice(1))
562
+ bodyError = { error: cleanupErrors[0] }
563
+ }
457
564
  }
565
+ if (bodyError) throw bodyError.error
458
566
 
459
567
  const hasFailure = results.some((r) => r.status === 'failed')
460
568
  if (hasFailure) {