-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathdbos-executor.ts
More file actions
1204 lines (1085 loc) · 43 KB
/
dbos-executor.ts
File metadata and controls
1204 lines (1085 loc) · 43 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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
DBOSError,
DBOSInitializationError,
DBOSWorkflowConflictError,
DBOSNotRegisteredError,
DBOSMaxStepRetriesError,
DBOSWorkflowCancelledError,
DBOSUnexpectedStepError,
DBOSInvalidQueuePriorityError,
DBOSAwaitedWorkflowCancelledError,
DBOSQueueDuplicatedError,
} from './error';
import {
InvokedHandle,
type WorkflowHandle,
type WorkflowParams,
RetrievedHandle,
StatusString,
type WorkflowStatus,
type StepInfo,
WorkflowConfig,
DEFAULT_MAX_RECOVERY_ATTEMPTS,
WorkflowSerializationFormat,
} from './workflow';
import { type StepConfig } from './step';
import { TelemetryCollector } from './telemetry/collector';
import { getActiveSpan, runWithTrace, SpanStatusCode, Tracer } from './telemetry/traces';
import { DBOSContextualLogger, GlobalLogger } from './telemetry/logs';
import { TelemetryExporter } from './telemetry/exporters';
import { SystemDatabase, type WorkflowStatusInternal, type SystemDatabaseStoredResult } from './system_database';
import { randomUUID } from 'node:crypto';
import {
getRegisteredFunctionClassName,
getRegisteredFunctionName,
getConfiguredInstance,
getLifecycleListeners,
UntypedAsyncFunction,
TypedAsyncFunction,
getFunctionRegistrationByName,
getAllRegisteredFunctions,
getFunctionRegistration,
getAllRegisteredClassNames,
getClassRegistrationByName,
getRegisteredFunctionFullName,
} from './decorators';
import { JsonWorkflowArgs, type step_info } from '../schemas/system_db_schema';
import {
runInStepContext,
getNextWFID,
functionIDGetIncrement,
runWithParentContext,
getCurrentContextStore,
DBOSLocalCtx,
runWithTopContext,
} from './context';
import { deserializeError, serializeError } from 'serialize-error';
import { globalParams, sleepms, INTERNAL_QUEUE_NAME, DEBOUNCER_WORKLOW_NAME as DEBOUNCER_WORKLOW_NAME } from './utils';
import {
DBOSPortableJSON,
DBOSSerializer,
deserializePositionalArgs,
deserializeResError,
deserializeValue,
serializeFunctionInputOutput,
serializeFunctionInputOutputWithSerializer,
serializeResError,
serializeResErrorWithSerializer,
serializeValue,
} from './serialization';
import { DBOS, GetWorkflowsInput } from '.';
import { wfQueueRunner, WorkflowQueue } from './wfqueue';
import { debugTriggerPoint, DEBUG_TRIGGER_WORKFLOW_ENQUEUE } from './debugpoint';
import { ScheduledReceiver } from './scheduler/scheduler_decorator';
import { DynamicSchedulerLoop } from './scheduler/scheduler';
import * as crypto from 'crypto';
import {
forkWorkflow,
listQueuedWorkflows,
listWorkflows,
listWorkflowSteps,
toWorkflowStatus,
} from './workflow_management';
import { maskDatabaseUrl } from './database_utils';
import { debouncerWorkflowFunction } from './debouncer';
import { Pool } from 'pg';
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface DBOSNull {}
const dbosNull: DBOSNull = {};
export const DBOS_QUEUE_MIN_PRIORITY = 1;
export const DBOS_QUEUE_MAX_PRIORITY = 2 ** 31 - 1; // 2,147,483,647
/* Interface for DBOS configuration */
export interface DBOSConfig {
name?: string;
systemDatabaseUrl?: string;
systemDatabasePoolSize?: number;
systemDatabasePool?: Pool;
systemDatabaseSchemaName?: string;
enableOTLP?: boolean;
tracingEnabled?: boolean;
logLevel?: string;
addContextMetadata?: boolean;
otlpTracesEndpoints?: string[];
otlpLogsEndpoints?: string[];
adminPort?: number;
runAdminServer?: boolean;
applicationVersion?: string;
executorID?: string;
serializer?: DBOSSerializer;
enablePatching?: boolean;
listenQueues?: WorkflowQueue[];
schedulerPollingIntervalMs?: number;
useListenNotify?: boolean;
}
export interface DBOSRuntimeConfig {
admin_port: number;
runAdminServer: boolean;
start: string[];
setup: string[];
}
export interface TelemetryConfig {
logs?: LoggerConfig;
OTLPExporter?: OTLPExporterConfig;
}
export interface OTLPExporterConfig {
logsEndpoint?: string[];
tracesEndpoint?: string[];
}
export interface LoggerConfig {
logLevel?: string;
silent?: boolean;
addContextMetadata?: boolean;
forceConsole?: boolean;
}
export type DBOSConfigInternal = {
name?: string;
systemDatabaseUrl: string;
sysDbPoolSize?: number;
systemDatabasePool?: Pool;
systemDatabaseSchemaName: string;
serializer: DBOSSerializer;
telemetry: TelemetryConfig;
schedulerPollingIntervalMs?: number;
useListenNotify: boolean;
http?: {
cors_middleware?: boolean;
credentials?: boolean;
allowed_origins?: string[];
};
};
export interface InternalWorkflowParams extends WorkflowParams {
readonly tempWfType?: string;
readonly tempWfName?: string;
readonly tempWfClass?: string;
readonly isRecoveryDispatch?: boolean;
readonly isQueueDispatch?: boolean;
}
export const OperationType = {
HANDLER: 'handler',
WORKFLOW: 'workflow',
TRANSACTION: 'transaction',
STEP: 'step',
} as const;
export const TempWorkflowType = {
step: 'step',
send: 'send',
} as const;
/**
* State item to be kept in the DBOS system database on behalf of clients
*/
export interface DBOSExternalState {
/** Name of event receiver service */
service: string;
/** Fully qualified function name for which state is kept */
workflowFnName: string;
/** subkey within the service+workflowFnName */
key: string;
/** Value kept for the service+workflowFnName+key combination */
value?: string;
/** Updated time (used to version the value) */
updateTime?: number;
/** Updated sequence number (used to version the value) */
updateSeq?: bigint;
}
export interface DBOSExecutorOptions {
systemDatabase?: SystemDatabase;
}
export class DBOSExecutor {
initialized: boolean;
// System Database
readonly systemDatabase: SystemDatabase;
// Temporary workflows are created by calling transaction/send/recv directly from the executor class
static readonly #tempWorkflowName = 'temp_workflow';
readonly telemetryCollector: TelemetryCollector;
static readonly defaultNotificationTimeoutSec = 60;
readonly systemDBSchemaName: string;
readonly logger: GlobalLogger;
readonly ctxLogger: DBOSContextualLogger;
readonly tracer: Tracer;
readonly serializer: DBOSSerializer;
#wfqEnded?: Promise<void> = undefined;
readonly executorID: string = globalParams.executorID;
static globalInstance: DBOSExecutor | undefined = undefined;
/* WORKFLOW EXECUTOR LIFE CYCLE MANAGEMENT */
constructor(
readonly config: DBOSConfigInternal,
{ systemDatabase }: DBOSExecutorOptions = {},
) {
this.systemDBSchemaName = config.systemDatabaseSchemaName;
if (config.telemetry.OTLPExporter) {
const OTLPExporter = new TelemetryExporter(config.telemetry.OTLPExporter);
this.telemetryCollector = new TelemetryCollector(OTLPExporter);
} else {
// We always setup a collector to drain the signals queue, even if we don't have an exporter.
this.telemetryCollector = new TelemetryCollector();
}
this.logger = new GlobalLogger(this.telemetryCollector, this.config.telemetry.logs, this.appName);
this.ctxLogger = new DBOSContextualLogger(this.logger, () => getActiveSpan());
this.tracer = new Tracer(this.telemetryCollector);
this.serializer = config.serializer;
if (systemDatabase) {
this.logger.debug('Using provided system database'); // XXX print the name or something
this.systemDatabase = systemDatabase;
} else {
this.logger.debug('Using Postgres system database');
this.systemDatabase = new SystemDatabase(
this.config.systemDatabaseUrl,
this.logger,
this.serializer,
this.config.sysDbPoolSize,
this.config.systemDatabasePool,
this.systemDBSchemaName,
this.config.useListenNotify,
);
}
new ScheduledReceiver(); // Create the scheduler, which registers itself.
new DynamicSchedulerLoop(config.schedulerPollingIntervalMs); // Create the dynamic scheduler, which registers itself.
this.initialized = false;
DBOSExecutor.globalInstance = this;
}
get appName(): string | undefined {
return this.config.name;
}
async init(): Promise<void> {
if (this.initialized) {
this.logger.error('Workflow executor already initialized!');
return;
}
try {
await this.systemDatabase.init();
} catch (err) {
if (err instanceof DBOSInitializationError) {
throw err;
}
this.logger.error(err);
let message = 'Failed to initialize workflow executor: ';
if (err instanceof AggregateError) {
for (const error of err.errors as Error[]) {
message += `${error.message}; `;
}
} else if (err instanceof Error) {
message += err.message;
} else {
message += String(err);
}
throw new DBOSInitializationError(message, err instanceof Error ? err : undefined);
}
this.initialized = true;
// Compute the application version if not provided
if (globalParams.appVersion === '') {
globalParams.appVersion = this.computeAppVersion();
globalParams.wasComputed = true;
}
// Any initialization hooks
const classnames = getAllRegisteredClassNames();
for (const cls of classnames) {
// Init its configurations
const creg = getClassRegistrationByName(cls);
for (const [_cfgname, cfg] of creg.configuredInstances) {
await cfg.initialize();
}
}
this.logger.info(`Initializing DBOS (v${globalParams.dbosVersion})`);
this.logger.info(`System Database URL: ${maskDatabaseUrl(this.config.systemDatabaseUrl)}`);
this.logger.info(`Executor ID: ${this.executorID}`);
this.logger.info(`Application version: ${globalParams.appVersion}`);
await this.recoverPendingWorkflows([this.executorID]);
this.logger.info('DBOS launched!');
}
async destroy() {
try {
await this.systemDatabase.awaitRunningWorkflows();
await this.systemDatabase.destroy();
await this.logger.destroy();
} catch (err) {
const e = err as Error;
this.logger.error(e);
throw err;
}
}
// This could return WF, or the function underlying a temp wf
#getFunctionInfoFromWFStatus(wf: WorkflowStatusInternal) {
const methReg = getFunctionRegistrationByName(wf.workflowClassName, wf.workflowName);
return { methReg, configuredInst: getConfiguredInstance(wf.workflowClassName, wf.workflowConfigName) };
}
static reviveResultOrError<R = unknown>(r: SystemDatabaseStoredResult, serializer: DBOSSerializer): R {
if (r.error) {
throw deserializeResError(r.error, r.serialization ?? null, serializer);
}
return deserializeValue(r.output ?? null, r.serialization ?? null, serializer) as R;
}
async workflow<T extends unknown[], R>(
wf: TypedAsyncFunction<T, R>,
params: InternalWorkflowParams,
...args: T
): Promise<WorkflowHandle<R>> {
return this.internalWorkflow(wf, params, undefined, undefined, ...args);
}
// If callerWFID and functionID are set, it means the workflow is invoked from within a workflow.
async internalWorkflow<T extends unknown[], R>(
wf: TypedAsyncFunction<T, R>,
params: InternalWorkflowParams,
callerID?: string,
callerFunctionID?: number,
...args: T
): Promise<WorkflowHandle<R>> {
const workflowID: string = params.workflowUUID ? params.workflowUUID : randomUUID();
const presetID: boolean = params.workflowUUID ? true : false;
const timeoutMS = params.timeoutMS ?? undefined;
// If a timeout is explicitly specified, use it over any propagated deadline
const deadlineEpochMS = params.timeoutMS
? // Queued workflows are assigned a deadline on dequeue. Otherwise, compute the deadline immediately
params.queueName
? undefined
: Date.now() + params.timeoutMS
: // if no timeout is specified, use the propagated deadline (if any)
params.deadlineEpochMS;
const priority = params?.enqueueOptions?.priority;
if (priority !== undefined && (priority < DBOS_QUEUE_MIN_PRIORITY || priority > DBOS_QUEUE_MAX_PRIORITY)) {
throw new DBOSInvalidQueuePriorityError(priority, DBOS_QUEUE_MIN_PRIORITY, DBOS_QUEUE_MAX_PRIORITY);
}
// If the workflow is called on a queue with a priority but the queue is not configured with a priority, print a warning.
if (params.queueName) {
const wfqueue = this.getQueueByName(params.queueName);
if (!wfqueue.priorityEnabled && priority !== undefined) {
throw Error(
`Priority is not enabled for queue ${params.queueName}. Setting priority will not have any effect.`,
);
}
}
const pctx = { ...getCurrentContextStore() }; // function ID was already incremented...
let wConfig: WorkflowConfig = {};
const wInfo = getFunctionRegistration(wf);
const wfNames = getRegisteredFunctionFullName(wf);
let wfname = wfNames.name;
let wfclassname = wfNames.className;
const isTempWorkflow = DBOSExecutor.#tempWorkflowName === wfname || !!params.tempWfType;
if (!isTempWorkflow) {
if (!wInfo || !wInfo.workflowConfig) {
throw new DBOSNotRegisteredError(wf.name);
}
wConfig = wInfo.workflowConfig;
} else if (params.tempWfName) {
wfname = params.tempWfName;
wfclassname = params.tempWfClass ?? '';
}
const maxRecoveryAttempts = wConfig.maxRecoveryAttempts
? wConfig.maxRecoveryAttempts
: DEFAULT_MAX_RECOVERY_ATTEMPTS;
const span = this.tracer.startSpan(wfname, {
status: StatusString.PENDING,
operationUUID: workflowID,
operationType: OperationType.WORKFLOW,
operationName: wInfo?.name ?? wf.name,
authenticatedUser: pctx?.authenticatedUser ?? '',
authenticatedRoles: pctx?.authenticatedRoles ?? [],
assumedRole: pctx?.assumedRole ?? '',
});
let serializationType = wInfo?.workflowConfig?.serialization;
const funcArgs = serializeFunctionInputOutput(
serializationType === 'portable' ? ({ positionalArgs: args } as JsonWorkflowArgs) : args,
[wfname, '<arguments>'],
this.serializer,
serializationType,
);
args =
serializationType === 'portable'
? ((funcArgs.deserialized as JsonWorkflowArgs).positionalArgs! as T)
: (funcArgs.deserialized as T);
const internalStatus: WorkflowStatusInternal = {
workflowUUID: workflowID,
status: params.queueName !== undefined ? StatusString.ENQUEUED : StatusString.PENDING,
workflowName: wfname,
workflowClassName: wfclassname,
workflowConfigName: params.configuredInstance?.name || '',
queueName: params.queueName,
output: null,
error: null,
authenticatedUser: pctx?.authenticatedUser || '',
assumedRole: pctx?.assumedRole || '',
authenticatedRoles: pctx?.authenticatedRoles || [],
request: pctx?.request || {},
executorId: globalParams.executorID,
applicationVersion: params.enqueueOptions?.applicationVersion ?? globalParams.appVersion,
applicationID: globalParams.appID,
createdAt: Date.now(), // Remember the start time of this workflow,
timeoutMS: timeoutMS,
deadlineEpochMS: deadlineEpochMS,
input: funcArgs.stringified,
deduplicationID: params.enqueueOptions?.deduplicationID,
priority: priority ?? 0,
queuePartitionKey: params.enqueueOptions?.queuePartitionKey,
parentWorkflowID: callerID,
serialization: funcArgs.sername,
};
if (isTempWorkflow) {
internalStatus.workflowName = `${DBOSExecutor.#tempWorkflowName}-${params.tempWfType}-${params.tempWfName}`;
}
let $deadlineEpochMS: number | undefined = undefined;
let shouldExecute: boolean | undefined = undefined;
// Synchronously set the workflow's status to PENDING and record workflow inputs.
// We have to do it for all types of workflows because operation_outputs table has a foreign key constraint on workflow status table.
if (callerFunctionID !== undefined && callerID !== undefined) {
const result = await this.systemDatabase.getOperationResultAndThrowIfCancelled(callerID, callerFunctionID);
if (result) {
if (result.error) {
throw deserializeResError(result.error, result.serialization ?? null, this.serializer);
}
return new RetrievedHandle(this.systemDatabase, result.childWorkflowID!);
}
}
let ires: Awaited<ReturnType<SystemDatabase['initWorkflowStatus']>>;
try {
ires = await this.systemDatabase.initWorkflowStatus(internalStatus, randomUUID(), {
maxRetries: maxRecoveryAttempts,
isDequeuedRequest: params.isQueueDispatch,
isRecoveryRequest: params.isRecoveryDispatch,
});
serializationType = ires.serialization === DBOSPortableJSON.name() ? 'portable' : undefined;
} catch (e) {
if (e instanceof DBOSQueueDuplicatedError && callerID && callerFunctionID) {
const sererr = serializeResError(e, this.serializer, undefined); // This is a step result
await this.systemDatabase.recordOperationResult(
callerID,
callerFunctionID,
internalStatus.workflowName,
true,
Date.now(),
{ error: sererr.serializedValue, serialization: sererr.serialization },
);
}
throw e;
}
if (callerFunctionID !== undefined && callerID !== undefined) {
await this.systemDatabase.recordOperationResult(
callerID,
callerFunctionID,
internalStatus.workflowName,
true,
Date.now(),
{
childWorkflowID: workflowID,
},
);
}
$deadlineEpochMS = ires.deadlineEpochMS;
shouldExecute = ires.shouldExecuteOnThisExecutor;
await debugTriggerPoint(DEBUG_TRIGGER_WORKFLOW_ENQUEUE);
async function callPromiseWithTimeout(
callPromise: Promise<R>,
deadlineEpochMS: number,
sysdb: SystemDatabase,
): Promise<R> {
let timeoutID: ReturnType<typeof setTimeout> | undefined = undefined;
const timeoutResult = {};
const timeoutPromise = new Promise<R>((_, reject) => {
timeoutID = setTimeout(reject, deadlineEpochMS - Date.now(), timeoutResult);
});
try {
return await Promise.race([callPromise, timeoutPromise]);
} catch (err) {
if (err === timeoutResult) {
await sysdb.cancelWorkflows([workflowID]);
await callPromise.catch(() => {});
throw new DBOSWorkflowCancelledError(workflowID);
}
throw err;
} finally {
clearTimeout(timeoutID);
}
}
const eserializer = this.serializer;
async function handleWorkflowError(err: Error, exec: DBOSExecutor) {
// Record the error.
const e = err as Error & { dbos_already_logged?: boolean };
exec.logger.error(e);
e.dbos_already_logged = true;
const sererr = serializeResErrorWithSerializer(e, eserializer, ires.serialization ?? null);
internalStatus.error = sererr.serializedValue;
internalStatus.status = StatusString.ERROR;
await exec.systemDatabase.recordWorkflowError(workflowID, internalStatus);
span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });
return deserializeResError(sererr.serializedValue, sererr.serialization, eserializer);
}
const runWorkflow = async () => {
let result: R;
// Execute the workflow.
try {
const callResult = await runWithTrace(span, async () => {
return await runWithParentContext(
pctx,
{
presetID,
workflowTimeoutMS: undefined, // Becomes deadline
deadlineEpochMS,
workflowId: workflowID,
logger: this.ctxLogger,
curWFFunctionId: undefined,
serializationType,
},
() => {
const callPromise = wf.call(params.configuredInstance, ...args);
if ($deadlineEpochMS === undefined) {
return callPromise;
} else {
return callPromiseWithTimeout(callPromise, $deadlineEpochMS, this.systemDatabase);
}
},
);
});
result = callResult!;
const funcResult = serializeFunctionInputOutputWithSerializer(
result,
[wfname, '<result>'],
this.serializer,
ires.serialization,
);
result = funcResult.deserialized;
internalStatus.output = funcResult.stringified;
internalStatus.status = StatusString.SUCCESS;
await this.systemDatabase.recordWorkflowOutput(workflowID, internalStatus);
span.setStatus({ code: SpanStatusCode.OK });
} catch (err) {
if (err instanceof DBOSWorkflowConflictError) {
// Retrieve the handle and wait for the result.
const retrievedHandle = this.retrieveWorkflow<R>(workflowID);
result = await retrievedHandle.getResult();
span.setAttribute('cached', true);
span.setStatus({ code: SpanStatusCode.OK });
} else if (err instanceof DBOSWorkflowCancelledError) {
span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
internalStatus.error = err.message;
if (err.workflowID === workflowID) {
internalStatus.status = StatusString.CANCELLED;
throw err;
} else {
const e = new DBOSAwaitedWorkflowCancelledError(err.workflowID);
await handleWorkflowError(e as Error, this);
throw e;
}
} else {
// If we want to be consistent about what is thrown (stored result vs live)
// we would have to do this. It is a breaking change in the sense that it
// is a behavior change, but it would "break" things that are already broken
if (serializationType === 'portable') {
throw await handleWorkflowError(err as Error, this);
}
await handleWorkflowError(err as Error, this);
throw err;
}
} finally {
this.tracer.endSpan(span);
}
return result;
};
if (
shouldExecute &&
(params.queueName === undefined || params.executeWorkflow) &&
!this.systemDatabase.checkForRunningWorkflow(workflowID)
) {
const workflowPromise: Promise<R> = runWorkflow();
this.systemDatabase.registerRunningWorkflow(workflowID, workflowPromise);
// Return the normal handle that doesn't capture errors.
return new InvokedHandle(this.systemDatabase, workflowPromise, workflowID, wf.name);
} else {
return new RetrievedHandle(this.systemDatabase, workflowID);
}
}
getQueueByName(name: string): WorkflowQueue {
const q = wfQueueRunner.wfQueuesByName.get(name);
if (!q) throw new DBOSNotRegisteredError(name, `Workflow queue '${name}' is not defined.`);
return q;
}
async runStepTempWF<T extends unknown[], R>(
stepFn: TypedAsyncFunction<T, R>,
params: WorkflowParams,
...args: T
): Promise<R> {
return await (await this.startStepTempWF(stepFn, params, undefined, undefined, ...args)).getResult();
}
async startStepTempWF<T extends unknown[], R>(
stepFn: TypedAsyncFunction<T, R>,
params: InternalWorkflowParams,
callerWFID?: string,
callerFunctionID?: number,
...args: T
): Promise<WorkflowHandle<R>> {
// Create a workflow and call external.
const temp_workflow = async (...args: T) => {
return await this.callStepFunction(stepFn, undefined, undefined, params.configuredInstance ?? null, ...args);
};
return await this.internalWorkflow(
temp_workflow,
{
...params,
tempWfType: TempWorkflowType.step,
tempWfName: getRegisteredFunctionName(stepFn),
tempWfClass: getRegisteredFunctionClassName(stepFn),
},
callerWFID,
callerFunctionID,
...args,
);
}
/**
* Execute a step function.
* If it encounters any error, retry according to its configured retry policy until the maximum number of attempts is reached, then throw an DBOSError.
* The step may execute many times, but once it is complete, it will not re-execute.
*/
async callStepFunction<T extends unknown[], R>(
stepFn: TypedAsyncFunction<T, R>,
stepFnName: string | undefined,
stepConfig: StepConfig | undefined,
clsInst: object | null,
...args: T
): Promise<R> {
stepFnName = stepFnName ?? stepFn.name ?? '<unnamed>';
const startTime = Date.now();
if (!stepConfig) {
const stepReg = getFunctionRegistration(stepFn);
stepConfig = stepReg?.stepConfig;
}
if (stepConfig === undefined) {
throw new DBOSNotRegisteredError(stepFnName);
}
// Intentionally advance the function ID before any awaits, then work with a copy of the context.
const funcID = functionIDGetIncrement();
const lctx = { ...getCurrentContextStore()! };
const wfid = lctx.workflowId!;
await this.systemDatabase.checkIfCanceled(wfid);
const maxRetryIntervalSec = 3600; // Maximum retry interval: 1 hour
const span = this.tracer.startSpan(stepFnName, {
operationUUID: wfid,
operationType: OperationType.STEP,
operationName: stepFnName,
authenticatedUser: lctx.authenticatedUser ?? '',
assumedRole: lctx.assumedRole ?? '',
authenticatedRoles: lctx.authenticatedRoles ?? [],
retriesAllowed: stepConfig.retriesAllowed,
intervalSeconds: stepConfig.intervalSeconds,
maxAttempts: stepConfig.maxAttempts,
backoffRate: stepConfig.backoffRate,
});
// Check if this execution previously happened, returning its original result if it did.
const checkr = await this.systemDatabase.getOperationResultAndThrowIfCancelled(wfid, funcID);
if (checkr) {
if (checkr.functionName !== stepFnName) {
throw new DBOSUnexpectedStepError(wfid, funcID, stepFnName, checkr.functionName ?? '?');
}
const check = DBOSExecutor.reviveResultOrError<R>(checkr, this.serializer);
span.setAttribute('cached', true);
span.setStatus({ code: SpanStatusCode.OK });
this.tracer.endSpan(span);
return check;
}
const maxAttempts = stepConfig.maxAttempts ?? 3;
// Execute the step function. If it throws an exception, retry with exponential backoff.
// After reaching the maximum number of retries, throw an DBOSError.
let result: R | DBOSNull = dbosNull;
let err: Error | DBOSNull = dbosNull;
const errors: Error[] = [];
if (stepConfig.retriesAllowed) {
let attemptNum = 0;
let intervalSeconds: number = stepConfig.intervalSeconds ?? 1;
if (intervalSeconds > maxRetryIntervalSec) {
this.logger.warn(
`Step config interval exceeds maximum allowed interval, capped to ${maxRetryIntervalSec} seconds!`,
);
}
while (result === dbosNull && attemptNum++ < (maxAttempts ?? 3)) {
try {
await this.systemDatabase.checkIfCanceled(wfid);
let cresult: R | undefined;
await runWithTrace(span, async () => {
await runInStepContext(lctx, funcID, maxAttempts, attemptNum, async () => {
const sf = stepFn as unknown as (...args: T) => Promise<R>;
cresult = await sf.call(clsInst, ...args);
});
});
result = cresult!;
} catch (error) {
const e = error as Error;
errors.push(e);
this.logger.warn(
`Error in step being automatically retried. Attempt ${attemptNum} of ${maxAttempts}. ${e.stack}`,
);
span.addEvent(
`Step attempt ${attemptNum + 1} failed`,
{ retryIntervalSeconds: intervalSeconds, error: (error as Error).message },
performance.now(),
);
if (attemptNum < maxAttempts) {
// Sleep for an interval, then increase the interval by backoffRate.
// Cap at the maximum allowed retry interval.
await sleepms(intervalSeconds * 1000);
intervalSeconds *= stepConfig.backoffRate ?? 2;
intervalSeconds = intervalSeconds < maxRetryIntervalSec ? intervalSeconds : maxRetryIntervalSec;
}
}
}
} else {
try {
let cresult: R | undefined;
await runWithTrace(span, async () => {
await runInStepContext(lctx, funcID, maxAttempts, undefined, async () => {
const sf = stepFn as unknown as (...args: T) => Promise<R>;
cresult = await sf.call(clsInst, ...args);
});
});
result = cresult!;
} catch (error) {
err = error as Error;
}
}
// `result` can only be dbosNull when the step timed out
if (result === dbosNull) {
// Record the error, then throw it.
err = err === dbosNull ? new DBOSMaxStepRetriesError(stepFnName, maxAttempts, errors) : err;
await this.systemDatabase.recordOperationResult(wfid, funcID, stepFnName, true, startTime, {
error: this.serializer.stringify(serializeError(err)),
serialization: this.serializer.name(),
});
span.setStatus({ code: SpanStatusCode.ERROR, message: (err as Error).message });
this.tracer.endSpan(span);
throw err as Error;
} else {
// Record the execution and return.
const funcResult = serializeFunctionInputOutput(result, [stepFnName, '<result>'], this.serializer);
await this.systemDatabase.recordOperationResult(wfid, funcID, stepFnName, true, startTime, {
output: funcResult.stringified,
serialization: funcResult.sername,
});
span.setStatus({ code: SpanStatusCode.OK });
this.tracer.endSpan(span);
return funcResult.deserialized as R;
}
}
/**
* Wait for a workflow to emit an event, then return its value.
*/
async getEvent<T>(
workflowUUID: string,
key: string,
timeoutSeconds: number = DBOSExecutor.defaultNotificationTimeoutSec,
): Promise<T | null> {
const evt = await this.systemDatabase.getEvent(workflowUUID, key, timeoutSeconds);
return deserializeValue(evt.serializedValue, evt.serialization, this.serializer) as T;
}
/**
* Fork a workflow.
* The forked workflow will be assigned a new ID.
*/
forkWorkflow(
workflowID: string,
startStep: number,
options: { newWorkflowID?: string; applicationVersion?: string; timeoutMS?: number } = {},
): Promise<string> {
const newWorkflowID = options.newWorkflowID ?? getNextWFID(undefined);
return forkWorkflow(this.systemDatabase, workflowID, startStep, { ...options, newWorkflowID });
}
/**
* Retrieve a handle for a workflow UUID.
*/
retrieveWorkflow<R>(workflowID: string): WorkflowHandle<R> {
return new RetrievedHandle(this.systemDatabase, workflowID);
}
async runInternalStep<T>(
callback: () => Promise<T>,
functionName: string,
workflowID: string,
functionID: number,
childWfId?: string,
): Promise<T> {
const startTime = Date.now();
const result = await this.systemDatabase.getOperationResultAndThrowIfCancelled(workflowID, functionID);
if (result) {
if (result.functionName !== functionName) {
throw new DBOSUnexpectedStepError(workflowID, functionID, functionName, result.functionName!);
}
return DBOSExecutor.reviveResultOrError<T>(result, this.serializer);
}
try {
const output: T = await callback();
const funcOutput = serializeFunctionInputOutput(output, [functionName, '<result>'], this.serializer);
await this.systemDatabase.recordOperationResult(workflowID, functionID, functionName, true, startTime, {
output: funcOutput.stringified,
childWorkflowID: childWfId,
});
return funcOutput.deserialized;
} catch (e) {
await this.systemDatabase.recordOperationResult(workflowID, functionID, functionName, false, startTime, {
error: this.serializer.stringify(serializeError(e)),
childWorkflowID: childWfId,
});
throw e;
}
}
async getWorkflowStatus(workflowID: string, callerID?: string, callerFN?: number): Promise<WorkflowStatus | null> {
// use sysdb getWorkflowStatus directly in order to support caller ID/FN params
const status = await this.systemDatabase.getWorkflowStatus(workflowID, callerID, callerFN);
return status ? toWorkflowStatus(status, this.serializer) : null;
}
async listWorkflows(input: GetWorkflowsInput): Promise<WorkflowStatus[]> {
return listWorkflows(this.systemDatabase, input);
}
async listQueuedWorkflows(input: GetWorkflowsInput): Promise<WorkflowStatus[]> {
return listQueuedWorkflows(this.systemDatabase, input);
}
async listWorkflowSteps(workflowID: string): Promise<StepInfo[] | undefined> {
return listWorkflowSteps(this.systemDatabase, workflowID);
}
/* INTERNAL HELPERS */
/**
* A recovery process that by default runs during executor init time.
* It runs to completion all pending workflows that were executing when the previous executor failed.
*/
async recoverPendingWorkflows(executorIDs: string[] = ['local']): Promise<WorkflowHandle<unknown>[]> {
const handlerArray: WorkflowHandle<unknown>[] = [];
for (const execID of executorIDs) {
this.logger.debug(`Recovering workflows assigned to executor: ${execID}`);
const pendingWorkflows = await this.systemDatabase.getPendingWorkflows(execID, globalParams.appVersion);
if (pendingWorkflows.length > 0) {
this.logger.info(
`Recovering ${pendingWorkflows.length} workflows from application version ${globalParams.appVersion}`,
);
} else {
this.logger.info(`No workflows to recover from application version ${globalParams.appVersion}`);
}
for (const pendingWorkflow of pendingWorkflows) {
this.logger.debug(
`Recovering workflow: ${pendingWorkflow.workflowUUID}. Queue name: ${pendingWorkflow.queueName}`,
);
try {
// If the workflow is member of a queue, re-enqueue it.
if (pendingWorkflow.queueName) {
const cleared = await this.systemDatabase.clearQueueAssignment(pendingWorkflow.workflowUUID);
if (cleared) {
handlerArray.push(this.retrieveWorkflow(pendingWorkflow.workflowUUID));
} else {
handlerArray.push(
await this.executeWorkflowId(pendingWorkflow.workflowUUID, { isRecoveryDispatch: true }),
);
}
} else {
handlerArray.push(await this.executeWorkflowId(pendingWorkflow.workflowUUID, { isRecoveryDispatch: true }));
}
} catch (e) {
this.logger.warn(`Recovery of workflow ${pendingWorkflow.workflowUUID} failed: ${(e as Error).message}`);
}
}
}
return handlerArray;
}
async initEventReceivers(listenQueues: WorkflowQueue[] | null) {
this.#wfqEnded = wfQueueRunner.dispatchLoop(this, listenQueues);
for (const lcl of getLifecycleListeners()) {
await lcl.initialize?.();
}
}
async deactivateEventReceivers(stopQueueThread: boolean = true) {
this.logger.debug('Deactivating lifecycle listeners');
for (const lcl of getLifecycleListeners()) {
try {
await lcl.destroy?.();
} catch (err) {
const e = err as Error;
this.logger.warn(`Error destroying lifecycle listener: ${e.message}`);
}
}
this.logger.debug('Deactivating queue runner');
if (stopQueueThread) {
try {
wfQueueRunner.stop();
await this.#wfqEnded;
} catch (err) {
const e = err as Error;
this.logger.warn(`Error destroying wf queue runner: ${e.message}`);