-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathdev-run-worker.ts
More file actions
684 lines (569 loc) · 19.6 KB
/
dev-run-worker.ts
File metadata and controls
684 lines (569 loc) · 19.6 KB
1
2
3
4
5
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
89
90
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
import type { Tracer } from "@opentelemetry/api";
import type { Logger } from "@opentelemetry/api-logs";
import {
AnyOnCatchErrorHookFunction,
AnyOnFailureHookFunction,
AnyOnInitHookFunction,
AnyOnStartHookFunction,
AnyOnSuccessHookFunction,
apiClientManager,
attemptKey,
clock,
ExecutorToWorkerMessageCatalog,
type HandleErrorFunction,
lifecycleHooks,
localsAPI,
logger,
LogLevel,
OTEL_LOG_ATTRIBUTE_COUNT_LIMIT,
resourceCatalog,
runMetadata,
runtime,
runTimelineMetrics,
taskContext,
TaskRunErrorCodes,
TaskRunExecution,
timeout,
TriggerConfig,
UsageMeasurement,
waitUntil,
WorkerManifest,
WorkerToExecutorMessageCatalog,
} from "@trigger.dev/core/v3";
import { TriggerTracer } from "@trigger.dev/core/v3/tracer";
import {
ConsoleInterceptor,
DevUsageManager,
DurableClock,
getEnvVar,
getNumberEnvVar,
logLevels,
SharedRuntimeManager,
OtelTaskLogger,
populateEnv,
StandardLifecycleHooksManager,
StandardLocalsManager,
StandardMetadataManager,
StandardResourceCatalog,
StandardRunTimelineMetricsManager,
StandardWaitUntilManager,
TaskExecutor,
TracingDiagnosticLogLevel,
TracingSDK,
usage,
UsageTimeoutManager,
} from "@trigger.dev/core/v3/workers";
import { ZodIpcConnection } from "@trigger.dev/core/v3/zodIpc";
import { readFile } from "node:fs/promises";
import { setInterval, setTimeout } from "node:timers/promises";
import sourceMapSupport from "source-map-support";
import { env } from "std-env";
import { normalizeImportPath } from "../utilities/normalizeImportPath.js";
import { VERSION } from "../version.js";
import { promiseWithResolvers } from "@trigger.dev/core/utils";
sourceMapSupport.install({
handleUncaughtExceptions: false,
environment: "node",
hookRequire: false,
});
process.on("uncaughtException", function (error, origin) {
logError("Uncaught exception", { error, origin });
if (error instanceof Error) {
process.send &&
process.send({
type: "EVENT",
message: {
type: "UNCAUGHT_EXCEPTION",
payload: {
error: { name: error.name, message: error.message, stack: error.stack },
origin,
},
version: "v1",
},
});
} else {
process.send &&
process.send({
type: "EVENT",
message: {
type: "UNCAUGHT_EXCEPTION",
payload: {
error: {
name: "Error",
message: typeof error === "string" ? error : JSON.stringify(error),
},
origin,
},
version: "v1",
},
});
}
});
process.title = `trigger-dev-run-worker (${
getEnvVar("TRIGGER_WORKER_VERSION") ?? "unknown version"
})`;
const heartbeatIntervalMs = getEnvVar("HEARTBEAT_INTERVAL_MS");
const standardLocalsManager = new StandardLocalsManager();
localsAPI.setGlobalLocalsManager(standardLocalsManager);
const standardLifecycleHooksManager = new StandardLifecycleHooksManager();
lifecycleHooks.setGlobalLifecycleHooksManager(standardLifecycleHooksManager);
const standardRunTimelineMetricsManager = new StandardRunTimelineMetricsManager();
runTimelineMetrics.setGlobalManager(standardRunTimelineMetricsManager);
const devUsageManager = new DevUsageManager();
usage.setGlobalUsageManager(devUsageManager);
const usageTimeoutManager = new UsageTimeoutManager(devUsageManager);
timeout.setGlobalManager(usageTimeoutManager);
const standardResourceCatalog = new StandardResourceCatalog();
resourceCatalog.setGlobalResourceCatalog(standardResourceCatalog);
const durableClock = new DurableClock();
clock.setGlobalClock(durableClock);
const runMetadataManager = new StandardMetadataManager(
apiClientManager.clientOrThrow(),
getEnvVar("TRIGGER_STREAM_URL", getEnvVar("TRIGGER_API_URL")) ?? "https://api.trigger.dev"
);
runMetadata.setGlobalManager(runMetadataManager);
const waitUntilManager = new StandardWaitUntilManager();
waitUntil.setGlobalManager(waitUntilManager);
// Wait for all streams to finish before completing the run
waitUntil.register({
requiresResolving: () => runMetadataManager.hasActiveStreams(),
promise: () => runMetadataManager.waitForAllStreams(),
});
const triggerLogLevel = getEnvVar("TRIGGER_LOG_LEVEL");
const showInternalLogs = getEnvVar("RUN_WORKER_SHOW_LOGS") === "true";
async function importConfig(
configPath: string
): Promise<{ config: TriggerConfig; handleError?: HandleErrorFunction }> {
const configModule = await import(normalizeImportPath(configPath));
const config = configModule?.default ?? configModule?.config;
return {
config,
handleError: configModule?.handleError,
};
}
async function loadWorkerManifest() {
const manifestContents = await readFile(env.TRIGGER_WORKER_MANIFEST_PATH!, "utf-8");
const raw = JSON.parse(manifestContents);
return WorkerManifest.parse(raw);
}
async function doBootstrap() {
return await runTimelineMetrics.measureMetric("trigger.dev/start", "bootstrap", {}, async () => {
log("Bootstrapping worker");
const workerManifest = await loadWorkerManifest();
resourceCatalog.registerWorkerManifest(workerManifest);
const { config, handleError } = await importConfig(workerManifest.configPath);
const tracingSDK = new TracingSDK({
url: env.OTEL_EXPORTER_OTLP_ENDPOINT ?? "http://0.0.0.0:4318",
instrumentations: config.telemetry?.instrumentations ?? config.instrumentations ?? [],
exporters: config.telemetry?.exporters ?? [],
logExporters: config.telemetry?.logExporters ?? [],
diagLogLevel: (env.OTEL_LOG_LEVEL as TracingDiagnosticLogLevel) ?? "none",
forceFlushTimeoutMillis: 30_000,
});
const otelTracer: Tracer = tracingSDK.getTracer("trigger-dev-worker", VERSION);
const otelLogger: Logger = tracingSDK.getLogger("trigger-dev-worker", VERSION);
const tracer = new TriggerTracer({ tracer: otelTracer, logger: otelLogger });
const consoleInterceptor = new ConsoleInterceptor(
otelLogger,
typeof config.enableConsoleLogging === "boolean" ? config.enableConsoleLogging : true,
typeof config.disableConsoleInterceptor === "boolean"
? config.disableConsoleInterceptor
: false,
OTEL_LOG_ATTRIBUTE_COUNT_LIMIT
);
const configLogLevel = triggerLogLevel ?? config.logLevel ?? "info";
const otelTaskLogger = new OtelTaskLogger({
logger: otelLogger,
tracer: tracer,
level: logLevels.includes(configLogLevel as any) ? (configLogLevel as LogLevel) : "info",
maxAttributeCount: OTEL_LOG_ATTRIBUTE_COUNT_LIMIT,
});
logger.setGlobalTaskLogger(otelTaskLogger);
if (config.init) {
lifecycleHooks.registerGlobalInitHook({
id: "config",
fn: config.init as AnyOnInitHookFunction,
});
}
if (config.onStart) {
lifecycleHooks.registerGlobalStartHook({
id: "config",
fn: config.onStart as AnyOnStartHookFunction,
});
}
if (config.onSuccess) {
lifecycleHooks.registerGlobalSuccessHook({
id: "config",
fn: config.onSuccess as AnyOnSuccessHookFunction,
});
}
if (config.onFailure) {
lifecycleHooks.registerGlobalFailureHook({
id: "config",
fn: config.onFailure as AnyOnFailureHookFunction,
});
}
if (handleError) {
lifecycleHooks.registerGlobalCatchErrorHook({
id: "config",
fn: handleError as AnyOnCatchErrorHookFunction,
});
}
log("Bootstrapped worker");
return {
tracer,
tracingSDK,
consoleInterceptor,
config,
workerManifest,
};
});
}
let bootstrapCache:
| {
tracer: TriggerTracer;
tracingSDK: TracingSDK;
consoleInterceptor: ConsoleInterceptor;
config: TriggerConfig;
workerManifest: WorkerManifest;
}
| undefined;
async function bootstrap() {
if (!bootstrapCache) {
bootstrapCache = await doBootstrap();
}
return bootstrapCache;
}
let _execution: TaskRunExecution | undefined;
let _isRunning = false;
let _isCancelled = false;
let _tracingSDK: TracingSDK | undefined;
let _executionMeasurement: UsageMeasurement | undefined;
let _cancelController = new AbortController();
let _lastFlushPromise: Promise<void> | undefined;
let _sharedWorkerRuntime: SharedRuntimeManager | undefined;
let _lastEnv: Record<string, string> | undefined;
let _executionCount = 0;
function resetExecutionEnvironment() {
_execution = undefined;
_isRunning = false;
_isCancelled = false;
_executionMeasurement = undefined;
_cancelController = new AbortController();
standardLocalsManager.reset();
standardLifecycleHooksManager.reset();
standardRunTimelineMetricsManager.reset();
devUsageManager.reset();
usageTimeoutManager.reset();
runMetadataManager.reset();
waitUntilManager.reset();
_sharedWorkerRuntime?.reset();
durableClock.reset();
taskContext.disable();
log(`[${new Date().toISOString()}] Reset execution environment`);
}
const zodIpc = new ZodIpcConnection({
listenSchema: WorkerToExecutorMessageCatalog,
emitSchema: ExecutorToWorkerMessageCatalog,
process,
handlers: {
EXECUTE_TASK_RUN: async (
{ execution, traceContext, metadata, metrics, env, isWarmStart },
sender
) => {
if (env) {
populateEnv(env, {
override: true,
previousEnv: _lastEnv,
});
_lastEnv = env;
}
log(`[${new Date().toISOString()}] Received EXECUTE_TASK_RUN`, execution);
if (_lastFlushPromise) {
const now = performance.now();
await _lastFlushPromise;
const duration = performance.now() - now;
log(`[${new Date().toISOString()}] Awaited last flush in ${duration}ms`);
}
resetExecutionEnvironment();
standardRunTimelineMetricsManager.registerMetricsFromExecution(metrics, isWarmStart);
if (_isRunning) {
logError("Worker is already running a task");
await sender.send("TASK_RUN_COMPLETED", {
execution,
result: {
ok: false,
id: execution.run.id,
error: {
type: "INTERNAL_ERROR",
code: TaskRunErrorCodes.TASK_ALREADY_RUNNING,
},
usage: {
durationMs: 0,
},
flushedMetadata: await runMetadataManager.stopAndReturnLastFlush(),
},
});
return;
}
try {
const { tracer, tracingSDK, consoleInterceptor, config, workerManifest } =
await bootstrap();
_tracingSDK = tracingSDK;
const taskManifest = workerManifest.tasks.find((t) => t.id === execution.task.id);
if (!taskManifest) {
logError(`Could not find task ${execution.task.id}`);
await sender.send("TASK_RUN_COMPLETED", {
execution,
result: {
ok: false,
id: execution.run.id,
error: {
type: "INTERNAL_ERROR",
code: TaskRunErrorCodes.COULD_NOT_FIND_TASK,
message: `Could not find task ${execution.task.id}. Make sure the task is exported and the ID is correct.`,
},
usage: {
durationMs: 0,
},
flushedMetadata: await runMetadataManager.stopAndReturnLastFlush(),
},
});
return;
}
// First attempt to get the task from the resource catalog
let task = resourceCatalog.getTask(execution.task.id);
if (!task) {
log(`Could not find task ${execution.task.id} in resource catalog, importing...`);
try {
await runTimelineMetrics.measureMetric(
"trigger.dev/start",
"import",
{
entryPoint: taskManifest.entryPoint,
file: taskManifest.filePath,
},
async () => {
const beforeImport = performance.now();
resourceCatalog.setCurrentFileContext(
taskManifest.entryPoint,
taskManifest.filePath
);
// Load init file if it exists
if (workerManifest.initEntryPoint) {
try {
await import(normalizeImportPath(workerManifest.initEntryPoint));
log(`Loaded init file from ${workerManifest.initEntryPoint}`);
} catch (err) {
logError(`Failed to load init file`, err);
throw err;
}
}
await import(normalizeImportPath(taskManifest.entryPoint));
resourceCatalog.clearCurrentFileContext();
const durationMs = performance.now() - beforeImport;
log(
`Imported task ${execution.task.id} [${taskManifest.entryPoint}] in ${durationMs}ms`
);
}
);
} catch (err) {
logError(`Failed to import task ${execution.task.id}`, err);
await sender.send("TASK_RUN_COMPLETED", {
execution,
result: {
ok: false,
id: execution.run.id,
error: {
type: "INTERNAL_ERROR",
code: TaskRunErrorCodes.COULD_NOT_IMPORT_TASK,
message: err instanceof Error ? err.message : String(err),
stackTrace: err instanceof Error ? err.stack : undefined,
},
usage: {
durationMs: 0,
},
flushedMetadata: await runMetadataManager.stopAndReturnLastFlush(),
},
});
return;
}
// Now try and get the task again
task = resourceCatalog.getTask(execution.task.id);
}
if (!task) {
logError(`Could not find task ${execution.task.id}`);
await sender.send("TASK_RUN_COMPLETED", {
execution,
result: {
ok: false,
id: execution.run.id,
error: {
type: "INTERNAL_ERROR",
code: TaskRunErrorCodes.COULD_NOT_FIND_EXECUTOR,
},
usage: {
durationMs: 0,
},
flushedMetadata: await runMetadataManager.stopAndReturnLastFlush(),
},
});
return;
}
runMetadataManager.runId = execution.run.id;
_executionCount++;
const executor = new TaskExecutor(task, {
tracer,
tracingSDK,
consoleInterceptor,
retries: config.retries,
isWarmStart,
executionCount: _executionCount,
});
try {
_execution = execution;
_isRunning = true;
runMetadataManager.startPeriodicFlush(
getNumberEnvVar("TRIGGER_RUN_METADATA_FLUSH_INTERVAL", 1000)
);
_executionMeasurement = usage.start();
const timeoutController = timeout.abortAfterTimeout(execution.run.maxDuration);
const signal = AbortSignal.any([_cancelController.signal, timeoutController.signal]);
const { result } = await executor.execute(execution, metadata, traceContext, signal);
if (_isRunning && !_isCancelled) {
const usageSample = usage.stop(_executionMeasurement);
return sender.send("TASK_RUN_COMPLETED", {
execution,
result: {
...result,
usage: {
durationMs: usageSample.cpuTime,
},
flushedMetadata: await runMetadataManager.stopAndReturnLastFlush(),
},
});
}
} finally {
_execution = undefined;
_isRunning = false;
log(`[${new Date().toISOString()}] Task run completed`);
}
} catch (err) {
logError("Failed to execute task", err);
await sender.send("TASK_RUN_COMPLETED", {
execution,
result: {
ok: false,
id: execution.run.id,
error: {
type: "INTERNAL_ERROR",
code: TaskRunErrorCodes.CONFIGURED_INCORRECTLY,
message: err instanceof Error ? err.message : String(err),
stackTrace: err instanceof Error ? err.stack : undefined,
},
usage: {
durationMs: 0,
},
flushedMetadata: await runMetadataManager.stopAndReturnLastFlush(),
},
});
}
},
CANCEL: async ({ timeoutInMs }) => {
_isCancelled = true;
_cancelController.abort("run cancelled");
await callCancelHooks(timeoutInMs);
if (_executionMeasurement) {
usage.stop(_executionMeasurement);
}
await flushAll(timeoutInMs);
},
FLUSH: async ({ timeoutInMs }) => {
await flushAll(timeoutInMs);
},
RESOLVE_WAITPOINT: async ({ waitpoint }) => {
_sharedWorkerRuntime?.resolveWaitpoints([waitpoint]);
},
},
});
async function callCancelHooks(timeoutInMs: number = 10_000) {
const now = performance.now();
try {
await Promise.race([lifecycleHooks.callOnCancelHookListeners(), setTimeout(timeoutInMs)]);
} finally {
const duration = performance.now() - now;
log(`Called cancel hooks in ${duration}ms`);
}
}
async function flushAll(timeoutInMs: number = 10_000) {
const now = performance.now();
const { promise, resolve } = promiseWithResolvers<void>();
_lastFlushPromise = promise;
const results = await Promise.allSettled([
flushTracingSDK(timeoutInMs),
flushMetadata(timeoutInMs),
]);
const successfulFlushes = results
.filter((result) => result.status === "fulfilled")
.map((result) => result.value.flushed);
const failedFlushes = ["tracingSDK", "runMetadata"].filter(
(flushed) => !successfulFlushes.includes(flushed)
);
if (failedFlushes.length > 0) {
logError(`Failed to flush ${failedFlushes.join(", ")}`);
}
const errorMessages = results
.filter((result) => result.status === "rejected")
.map((result) => result.reason);
if (errorMessages.length > 0) {
logError(errorMessages.join("\n"));
}
for (const flushed of successfulFlushes) {
log(`Flushed ${flushed} successfully`);
}
const duration = performance.now() - now;
log(`Flushed all in ${duration}ms`);
// Resolve the last flush promise
resolve();
}
async function flushTracingSDK(timeoutInMs: number = 10_000) {
const now = performance.now();
await Promise.race([_tracingSDK?.flush(), setTimeout(timeoutInMs)]);
const duration = performance.now() - now;
log(`Flushed tracingSDK in ${duration}ms`);
return {
flushed: "tracingSDK",
durationMs: duration,
};
}
async function flushMetadata(timeoutInMs: number = 10_000) {
const now = performance.now();
await Promise.race([runMetadataManager.flush(), setTimeout(timeoutInMs)]);
const duration = performance.now() - now;
log(`Flushed runMetadata in ${duration}ms`);
return {
flushed: "runMetadata",
durationMs: duration,
};
}
_sharedWorkerRuntime = new SharedRuntimeManager(zodIpc, showInternalLogs);
runtime.setGlobalRuntimeManager(_sharedWorkerRuntime);
const heartbeatInterval = parseInt(heartbeatIntervalMs ?? "30000", 10);
for await (const _ of setInterval(heartbeatInterval)) {
if (_isRunning && _execution) {
try {
await zodIpc.send("TASK_HEARTBEAT", { id: attemptKey(_execution) });
} catch (err) {
logError("Failed to send HEARTBEAT message", err);
}
}
}
function log(message: string, ...args: any[]) {
if (!showInternalLogs) return;
console.log(`[${new Date().toISOString()}] ${message}`, args);
}
function logError(message: string, error?: any) {
if (!showInternalLogs) return;
console.error(`[${new Date().toISOString()}] ${message}`, error);
}
log(`Executor started`);