plantr 1.0.1 → 2.1.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/dist/index.d.ts +23 -20
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +906 -235
- package/dist/src/cli.d.ts +23 -0
- package/dist/src/cli.d.ts.map +1 -0
- package/dist/src/create-seeder-instance.d.ts +73 -83
- package/dist/src/create-seeder-instance.d.ts.map +1 -0
- package/dist/src/define-seeder.d.ts +4 -3
- package/dist/src/define-seeder.d.ts.map +1 -0
- package/dist/src/dependency-resolver.d.ts +18 -2
- package/dist/src/dependency-resolver.d.ts.map +1 -0
- package/dist/src/formatting.d.ts +31 -12
- package/dist/src/formatting.d.ts.map +1 -0
- package/dist/src/lazy-faker.d.ts +12 -0
- package/dist/src/lazy-faker.d.ts.map +1 -0
- package/dist/src/run-seeders.d.ts +57 -17
- package/dist/src/run-seeders.d.ts.map +1 -0
- package/dist/src/seeding-state.d.ts +17 -2
- package/dist/src/seeding-state.d.ts.map +1 -0
- package/dist/src/step.d.ts +97 -15
- package/dist/src/step.d.ts.map +1 -0
- package/dist/src/types.d.ts +132 -29
- package/dist/src/types.d.ts.map +1 -0
- package/dist/state.d.ts +12 -0
- package/dist/state.d.ts.map +1 -0
- package/dist/state.js +20 -0
- package/index.ts +60 -24
- package/package.json +20 -10
- package/readme.md +169 -49
- package/src/cli.ts +251 -0
- package/src/create-seeder-instance.ts +254 -173
- package/src/define-seeder.ts +14 -7
- package/src/dependency-resolver.ts +59 -30
- package/src/formatting.ts +142 -39
- package/src/lazy-faker.ts +46 -0
- package/src/run-seeders.ts +413 -123
- package/src/seeding-state.ts +32 -5
- package/src/step.ts +247 -46
- package/src/types.ts +184 -32
- package/state.ts +11 -0
- package/dist/cli.d.ts +0 -17
- package/dist/cli.js +0 -59
- package/dist/index-a1s5r901.js +0 -4
package/src/run-seeders.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { resolveDependencyOrder } from './dependency-resolver'
|
|
1
|
+
import { resolveDependencyOrder, UnknownSeederError } from './dependency-resolver.js'
|
|
2
2
|
import {
|
|
3
|
+
printConcurrentComplete,
|
|
4
|
+
printConcurrentSkipped,
|
|
3
5
|
printErrors,
|
|
4
6
|
printResultsTable,
|
|
5
7
|
printSeederComplete,
|
|
@@ -7,176 +9,464 @@ import {
|
|
|
7
9
|
printSeederSkipped,
|
|
8
10
|
printStartBanner,
|
|
9
11
|
printSummary,
|
|
10
|
-
} from './formatting'
|
|
11
|
-
import
|
|
12
|
+
} from './formatting.js'
|
|
13
|
+
import { enterSeeding, exitSeeding } from './seeding-state.js'
|
|
14
|
+
import type { StepRecord } from './step.js'
|
|
15
|
+
import type {
|
|
16
|
+
MaybePromise,
|
|
17
|
+
RunSeedersOptions,
|
|
18
|
+
RunSeedersResult,
|
|
19
|
+
SeederAny,
|
|
20
|
+
SeederResult,
|
|
21
|
+
SeederResultFor,
|
|
22
|
+
} from './types.js'
|
|
23
|
+
|
|
24
|
+
/** Parsed description of a database target URL (without credentials) */
|
|
25
|
+
export type TargetDescription = {
|
|
26
|
+
label: string
|
|
27
|
+
local: boolean
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Per-seeder scope handle returned by `InternalSeederConfig.runSeederScope` */
|
|
31
|
+
export type SeederScopeHandle = {
|
|
32
|
+
record?: StepRecord | undefined
|
|
33
|
+
run: <T>(fn: () => Promise<T>) => Promise<T>
|
|
34
|
+
}
|
|
12
35
|
|
|
13
36
|
/**
|
|
14
37
|
* Internal configuration used by the runner.
|
|
15
|
-
* This is created by createSeederInstance and includes the wrapped context factory.
|
|
38
|
+
* This is created by `createSeederInstance` and includes the wrapped context factory.
|
|
16
39
|
*/
|
|
17
40
|
export type InternalSeederConfig<TContext> = {
|
|
18
|
-
/** Factory function that creates the full context
|
|
19
|
-
context: () =>
|
|
20
|
-
/** Called
|
|
21
|
-
|
|
22
|
-
/** Called before
|
|
23
|
-
|
|
24
|
-
/** Called
|
|
25
|
-
|
|
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) */
|
|
44
|
+
preloadCache?: (() => MaybePromise<void>) | undefined
|
|
45
|
+
/** Called once before onAfterAll to flush buffered step cache writes (when cache.setMany is configured) */
|
|
46
|
+
flushCache?: (() => MaybePromise<void>) | undefined
|
|
47
|
+
/** Called before each seeder runs (legacy sequential hook); may return the record its steps fill */
|
|
48
|
+
beforeSeeder?: ((name: string, options: { fresh: boolean }) => StepRecord | undefined) | undefined
|
|
49
|
+
/** Concurrency-safe scope wrapper for running a seeder (used by createSeederInstance) */
|
|
50
|
+
createSeederScope?:
|
|
51
|
+
| ((options: { name: string; fresh: boolean; concurrent: boolean }) => SeederScopeHandle)
|
|
52
|
+
| undefined
|
|
53
|
+
/** Banner title (default: `'Seeders'`) */
|
|
54
|
+
bannerName?: string | undefined
|
|
55
|
+
/** Database URL the run writes to; non-local hosts are refused unless allowRemote */
|
|
56
|
+
target?: (() => string | undefined) | undefined
|
|
57
|
+
/** Called before the context is created */
|
|
58
|
+
onBeforeAll?: (() => MaybePromise<void>) | undefined
|
|
59
|
+
/** Called after all seeders complete, also when a seeder or the context factory throws */
|
|
60
|
+
onAfterAll?: ((ctx: TContext | undefined) => MaybePromise<void>) | undefined
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Error thrown when a run would write to a database that is not local
|
|
65
|
+
*/
|
|
66
|
+
export class SeedTargetError extends Error {
|
|
67
|
+
constructor(label: string) {
|
|
68
|
+
super(
|
|
69
|
+
`Refusing to seed ${label}: it is not a local database. Pass allowRemote (CLI: --allow-remote) to seed it on purpose.`,
|
|
70
|
+
)
|
|
71
|
+
this.name = 'SeedTargetError'
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const isLocalHost = (hostPort: string): boolean => {
|
|
76
|
+
if (hostPort.startsWith('/')) return true // socket directory
|
|
77
|
+
const lower = hostPort.toLowerCase()
|
|
78
|
+
const bracketed = /^\[([^\]]*)\]/.exec(lower)
|
|
79
|
+
const host = bracketed ? (bracketed[1] ?? '') : lower.replace(/:\d+$/, '')
|
|
80
|
+
return (
|
|
81
|
+
host === '::1' ||
|
|
82
|
+
host === '0.0.0.0' ||
|
|
83
|
+
host === 'host.docker.internal' ||
|
|
84
|
+
host.endsWith('.localhost') ||
|
|
85
|
+
/^127\./.test(host) ||
|
|
86
|
+
!/[.:]/.test(host)
|
|
87
|
+
)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 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).
|
|
96
|
+
*/
|
|
97
|
+
export function describeTarget(target: string): TargetDescription {
|
|
98
|
+
if (/^file:/i.test(target)) return { label: target.replace(/[?#].*$/, ''), local: true }
|
|
99
|
+
const scheme = /^[a-z][\w+.-]*:\/\//i.exec(target)
|
|
100
|
+
if (!scheme) return { label: 'a target that is not a URL', local: false }
|
|
101
|
+
|
|
102
|
+
const rest = target.slice(scheme[0].length)
|
|
103
|
+
const queryStart = rest.search(/[?#]/)
|
|
104
|
+
const beforeQuery = queryStart === -1 ? rest : rest.slice(0, queryStart)
|
|
105
|
+
const query = queryStart === -1 ? '' : rest.slice(queryStart)
|
|
106
|
+
// Drop credentials: everything up to the last @ before the query
|
|
107
|
+
const authorityAndPath = beforeQuery.slice(beforeQuery.lastIndexOf('@') + 1)
|
|
108
|
+
const [authority = '', path = ''] = authorityAndPath.split(/(?=[/;])/, 2)
|
|
109
|
+
let hosts = authority.split(',').filter(Boolean)
|
|
110
|
+
const hostParam = /[?&;]host=([^&;#]*)/i.exec(`${query}${path.startsWith(';') ? path : ''}`)?.[1]
|
|
111
|
+
if (hostParam) {
|
|
112
|
+
try {
|
|
113
|
+
hosts = decodeURIComponent(hostParam).split(',').filter(Boolean)
|
|
114
|
+
} catch {
|
|
115
|
+
return { label: 'a target with an invalid host parameter', local: false }
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const label = `${hosts.join(',') || 'local socket'}${path.startsWith('/') ? path : ''}`
|
|
120
|
+
return { label, local: hosts.every(isLocalHost) }
|
|
26
121
|
}
|
|
27
122
|
|
|
28
123
|
/**
|
|
29
|
-
* Core seeder runner - executes seeders in dependency order
|
|
124
|
+
* Core seeder runner - executes seeders in dependency order (sequentially or in parallel)
|
|
30
125
|
*
|
|
31
126
|
* @param seeders - Array of seeders to run
|
|
32
127
|
* @param config - Instance configuration (context factory, lifecycle hooks)
|
|
33
|
-
* @param options - Runner options (verbose output, etc.)
|
|
34
|
-
* @returns Object containing results and
|
|
128
|
+
* @param options - Runner options (verbose output, concurrency, etc.)
|
|
129
|
+
* @returns Object containing `success`, `results`, and `outputs`
|
|
130
|
+
* @throws Dependency errors, `UnknownSeederError`, `SeedTargetError`, or `RangeError` (invalid concurrency), before any hook runs
|
|
35
131
|
*/
|
|
36
|
-
export async function runSeedersCore<
|
|
37
|
-
|
|
132
|
+
export async function runSeedersCore<
|
|
133
|
+
TContext,
|
|
134
|
+
const TSeeders extends readonly SeederAny[] = readonly SeederAny[],
|
|
135
|
+
const TOptions extends RunSeedersOptions = RunSeedersOptions,
|
|
136
|
+
>(
|
|
137
|
+
seeders: TSeeders,
|
|
38
138
|
config: InternalSeederConfig<TContext>,
|
|
39
|
-
options:
|
|
40
|
-
): Promise<{
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
}
|
|
139
|
+
options: TOptions = {} as TOptions,
|
|
140
|
+
): Promise<RunSeedersResult<TSeeders, TOptions>> {
|
|
141
|
+
const {
|
|
142
|
+
printResults = true,
|
|
143
|
+
verbose = true,
|
|
144
|
+
continueOnFailure = false,
|
|
145
|
+
only,
|
|
146
|
+
fresh = false,
|
|
147
|
+
allowRemote = false,
|
|
148
|
+
concurrency = 1,
|
|
149
|
+
} = options
|
|
50
150
|
|
|
51
|
-
if (
|
|
52
|
-
|
|
151
|
+
if (
|
|
152
|
+
Number.isNaN(concurrency) ||
|
|
153
|
+
concurrency < 1 ||
|
|
154
|
+
(Number.isFinite(concurrency) && !Number.isInteger(concurrency))
|
|
155
|
+
) {
|
|
156
|
+
throw new RangeError(
|
|
157
|
+
`Invalid concurrency (${String(concurrency)}): expected a positive integer or Infinity`,
|
|
158
|
+
)
|
|
53
159
|
}
|
|
54
160
|
|
|
55
|
-
//
|
|
56
|
-
|
|
57
|
-
try {
|
|
58
|
-
orderedNames = resolveDependencyOrder(seeders)
|
|
59
|
-
} catch (error) {
|
|
60
|
-
console.error('Failed to resolve seeder dependencies:')
|
|
61
|
-
console.error(` ${error instanceof Error ? error.message : String(error)}`)
|
|
62
|
-
if (config.onAfterAll) {
|
|
63
|
-
await config.onAfterAll()
|
|
64
|
-
}
|
|
65
|
-
return { results: [], success: false }
|
|
66
|
-
}
|
|
161
|
+
// Validate everything before setting the seeding flag or touching the database
|
|
162
|
+
const orderedNames = resolveDependencyOrder(seeders, only)
|
|
67
163
|
|
|
68
|
-
// Create a map for quick seeder lookup
|
|
69
164
|
const seederMap = new Map<string, SeederAny>()
|
|
70
165
|
for (const seeder of seeders) {
|
|
71
166
|
seederMap.set(seeder.name, seeder)
|
|
72
167
|
}
|
|
73
168
|
|
|
74
|
-
|
|
169
|
+
const freshSet = Array.isArray(fresh) ? new Set<string>(fresh) : undefined
|
|
170
|
+
if (freshSet) {
|
|
171
|
+
for (const name of freshSet) {
|
|
172
|
+
if (!seederMap.has(name)) throw new UnknownSeederError(name, [...seederMap.keys()])
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const targetUrl = config.target?.()
|
|
177
|
+
const target = targetUrl ? describeTarget(targetUrl) : undefined
|
|
178
|
+
if (target && !target.local && !allowRemote) {
|
|
179
|
+
throw new SeedTargetError(target.label)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const isFresh = (name: string): boolean => fresh === true || (freshSet?.has(name) ?? false)
|
|
183
|
+
|
|
184
|
+
// Initialize results in deterministic topological order
|
|
75
185
|
const results: SeederResult[] = orderedNames.map((name) => ({
|
|
76
186
|
name,
|
|
77
187
|
status: 'pending',
|
|
78
188
|
}))
|
|
189
|
+
const resultIndex = new Map<string, number>()
|
|
190
|
+
for (let i = 0; i < orderedNames.length; i++) {
|
|
191
|
+
resultIndex.set(orderedNames[i]!, i)
|
|
192
|
+
}
|
|
79
193
|
|
|
80
|
-
// Store outputs for dependency injection
|
|
194
|
+
// Store outputs for dependency injection and return value
|
|
81
195
|
const outputs: Record<string, unknown> = {}
|
|
82
196
|
|
|
83
|
-
// Track failed seeders to skip their dependents
|
|
197
|
+
// Track failed (and skipped) seeders to skip their dependents
|
|
84
198
|
const failedSeeders = new Set<string>()
|
|
199
|
+
const concurrent = concurrency > 1
|
|
85
200
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
// Execute seeders in order
|
|
90
|
-
for (let i = 0; i < orderedNames.length; i++) {
|
|
91
|
-
const name = orderedNames[i]
|
|
92
|
-
const result = results[i]
|
|
93
|
-
|
|
94
|
-
// TypeScript safety - should never happen since we iterate within bounds
|
|
95
|
-
if (!name || !result) continue
|
|
96
|
-
|
|
97
|
-
const seeder = seederMap.get(name)
|
|
98
|
-
if (!seeder) continue
|
|
99
|
-
|
|
100
|
-
// Check if any dependencies have failed (only relevant when continueOnFailure is true)
|
|
101
|
-
if (continueOnFailure) {
|
|
102
|
-
const hasFailedDep = seeder.dependsOn.some((dep) => failedSeeders.has(dep))
|
|
103
|
-
if (hasFailedDep) {
|
|
104
|
-
result.status = 'skipped'
|
|
105
|
-
failedSeeders.add(name) // Treat skipped as failed for dependency chain
|
|
106
|
-
if (verbose) {
|
|
107
|
-
printSeederHeader(name, i, orderedNames.length, seeder.description)
|
|
108
|
-
printSeederSkipped(seeder.dependsOn.filter((d) => failedSeeders.has(d)))
|
|
109
|
-
}
|
|
110
|
-
continue
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
// Print seeder header
|
|
201
|
+
enterSeeding()
|
|
202
|
+
try {
|
|
115
203
|
if (verbose) {
|
|
116
|
-
|
|
204
|
+
printStartBanner({
|
|
205
|
+
name: config.bannerName,
|
|
206
|
+
count: orderedNames.length,
|
|
207
|
+
target,
|
|
208
|
+
concurrency,
|
|
209
|
+
})
|
|
117
210
|
}
|
|
118
211
|
|
|
119
|
-
|
|
120
|
-
result.status = 'running'
|
|
212
|
+
const runStartTime = performance.now()
|
|
121
213
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
config.setSeederName(name)
|
|
214
|
+
if (config.onBeforeAll) {
|
|
215
|
+
await config.onBeforeAll()
|
|
125
216
|
}
|
|
126
217
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
218
|
+
let ctx: TContext | undefined
|
|
219
|
+
try {
|
|
220
|
+
if (config.preloadCache) {
|
|
221
|
+
await config.preloadCache()
|
|
222
|
+
}
|
|
132
223
|
|
|
133
|
-
|
|
224
|
+
// Create context once for all seeders
|
|
225
|
+
ctx = await config.context()
|
|
226
|
+
const activeCtx = ctx
|
|
134
227
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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
|
|
232
|
+
|
|
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
|
+
}
|
|
239
|
+
|
|
240
|
+
const deps: Record<string, unknown> = {}
|
|
241
|
+
for (const depName of seeder.dependsOn) {
|
|
242
|
+
deps[depName] = outputs[depName]
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const startTime = performance.now()
|
|
246
|
+
|
|
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 ?? [],
|
|
258
|
+
}
|
|
138
259
|
|
|
139
|
-
|
|
140
|
-
|
|
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
|
|
141
275
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
276
|
+
results[idx] = {
|
|
277
|
+
name,
|
|
278
|
+
status: 'failed',
|
|
279
|
+
durationMs,
|
|
280
|
+
error: err,
|
|
281
|
+
...(failedStep !== undefined ? { failedStep } : {}),
|
|
282
|
+
cachedSteps: scopeHandle.record?.cachedSteps ?? [],
|
|
283
|
+
}
|
|
284
|
+
failedSeeders.add(name)
|
|
146
285
|
|
|
147
|
-
|
|
148
|
-
|
|
286
|
+
if (verbose) {
|
|
287
|
+
if (concurrent) {
|
|
288
|
+
printConcurrentComplete(name, durationMs, false)
|
|
289
|
+
} else {
|
|
290
|
+
printSeederComplete(durationMs, false)
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
return false
|
|
294
|
+
}
|
|
149
295
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
296
|
+
|
|
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
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
if (verbose) {
|
|
319
|
+
printSeederHeader(name, i, orderedNames.length, seeder.description)
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const ok = await executeSeeder(name)
|
|
323
|
+
if (!ok && !continueOnFailure) {
|
|
324
|
+
break
|
|
325
|
+
}
|
|
326
|
+
}
|
|
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, [])
|
|
335
|
+
}
|
|
336
|
+
|
|
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
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
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)
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const ready: string[] = []
|
|
360
|
+
for (const name of orderedNames) {
|
|
361
|
+
if (remainingDeps.get(name) === 0) {
|
|
362
|
+
ready.push(name)
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
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
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return ready.splice(bestIdx, 1)[0]!
|
|
381
|
+
}
|
|
382
|
+
|
|
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)
|
|
409
|
+
} else {
|
|
410
|
+
ready.push(dependent)
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
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
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
schedule()
|
|
436
|
+
})
|
|
159
437
|
}
|
|
160
438
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
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
|
+
}
|
|
164
453
|
}
|
|
165
454
|
}
|
|
455
|
+
} finally {
|
|
456
|
+
exitSeeding()
|
|
166
457
|
}
|
|
167
458
|
|
|
168
|
-
|
|
169
|
-
if (
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
// Call onAfterAll hook
|
|
176
|
-
if (config.onAfterAll) {
|
|
177
|
-
await config.onAfterAll()
|
|
459
|
+
const hasFailure = results.some((r) => r.status === 'failed')
|
|
460
|
+
if (hasFailure) {
|
|
461
|
+
return {
|
|
462
|
+
success: false,
|
|
463
|
+
results: results as SeederResultFor<TSeeders>[],
|
|
464
|
+
outputs: outputs as Partial<Record<string, unknown>>,
|
|
465
|
+
} as RunSeedersResult<TSeeders, TOptions>
|
|
178
466
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
467
|
+
return {
|
|
468
|
+
success: true,
|
|
469
|
+
results: results as SeederResultFor<TSeeders>[],
|
|
470
|
+
outputs,
|
|
471
|
+
} as RunSeedersResult<TSeeders, TOptions>
|
|
182
472
|
}
|
package/src/seeding-state.ts
CHANGED
|
@@ -6,21 +6,48 @@
|
|
|
6
6
|
* - Sending notifications (email, Slack, push)
|
|
7
7
|
* - Creating background jobs
|
|
8
8
|
* - Syncing to external services
|
|
9
|
+
*
|
|
10
|
+
* The flag lives on `globalThis`, so `plantr` and `plantr/state` share it even when
|
|
11
|
+
* they are loaded as separate bundles. Overlapping runs are reference-counted so
|
|
12
|
+
* one finishing run does not clear the flag while another is still active.
|
|
9
13
|
*/
|
|
10
14
|
|
|
11
|
-
|
|
15
|
+
const key = Symbol.for('plantr.seedingActive')
|
|
16
|
+
const countKey = Symbol.for('plantr.seedingCount')
|
|
17
|
+
const state = globalThis as { [key]?: boolean; [countKey]?: number }
|
|
12
18
|
|
|
13
19
|
/**
|
|
14
20
|
* Check if seeding is currently active
|
|
15
21
|
*/
|
|
16
22
|
export function isSeedingActive(): boolean {
|
|
17
|
-
return
|
|
23
|
+
return state[key] === true
|
|
18
24
|
}
|
|
19
25
|
|
|
20
26
|
/**
|
|
21
|
-
* Set the seeding state.
|
|
22
|
-
*
|
|
27
|
+
* Set the seeding state directly.
|
|
28
|
+
* Resets the active run count to 1 (true) or 0 (false).
|
|
23
29
|
*/
|
|
24
30
|
export function setSeedingActive(active: boolean): void {
|
|
25
|
-
|
|
31
|
+
state[countKey] = active ? 1 : 0
|
|
32
|
+
state[key] = active
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Increment the active seeding run counter and mark seeding active.
|
|
37
|
+
* Called automatically by `runSeeders` when execution begins.
|
|
38
|
+
*/
|
|
39
|
+
export function enterSeeding(): void {
|
|
40
|
+
const next = (state[countKey] ?? 0) + 1
|
|
41
|
+
state[countKey] = next
|
|
42
|
+
state[key] = true
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Decrement the active seeding run counter and clear the flag when no runs remain.
|
|
47
|
+
* Called automatically by `runSeeders` when execution finishes.
|
|
48
|
+
*/
|
|
49
|
+
export function exitSeeding(): void {
|
|
50
|
+
const next = Math.max(0, (state[countKey] ?? 0) - 1)
|
|
51
|
+
state[countKey] = next
|
|
52
|
+
state[key] = next > 0
|
|
26
53
|
}
|