-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathdbos.ts
More file actions
2184 lines (1994 loc) · 80.3 KB
/
dbos.ts
File metadata and controls
2184 lines (1994 loc) · 80.3 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 {
getCurrentContextStore,
HTTPRequest,
runWithTopContext,
getNextWFID,
StepStatus,
DBOSContextOptions,
functionIDGetIncrement,
functionIDGet,
} from './context';
import { DBOSConfig, DBOSExecutor, DBOSExternalState, InternalWorkflowParams } from './dbos-executor';
import { DBOSSpan, getActiveSpan, installTraceContextManager, isTraceContextWorking, Tracer } from './telemetry/traces';
import {
GetWorkflowsInput,
InternalWFHandle,
isWorkflowActive,
RetrievedHandle,
StepInfo,
WorkflowConfig,
WorkflowHandle,
WorkflowParams,
WorkflowSerializationFormat,
WorkflowStatus,
} from './workflow';
import { DLogger, GlobalLogger } from './telemetry/logs';
import {
DBOSError,
DBOSExecutorNotInitializedError,
DBOSInvalidWorkflowTransitionError,
DBOSNotRegisteredError,
DBOSAwaitedWorkflowCancelledError,
DBOSConflictingRegistrationError,
DBOSAwaitedWorkflowExceededMaxRecoveryAttempts,
DBOSUnexpectedStepError,
} from './error';
import {
getDbosConfig,
getRuntimeConfig,
overwriteConfigForDBOSCloud,
readConfigFile,
translateDbosConfig,
translateRuntimeConfig,
} from './config';
import { ScheduledArgs, ScheduledReceiver, SchedulerConfig } from './scheduler/scheduler_decorator';
import {
AlertHandler,
associateClassWithExternal,
associateMethodWithExternal,
ClassAuthDefaults,
DBOS_AUTH,
ExternalRegistration,
getAlertHandler,
getLifecycleListeners,
getRegisteredOperations,
getFunctionRegistration,
getRegistrationsForExternal,
insertAllMiddleware,
MethodAuth,
MethodRegistration,
recordDBOSLaunch,
recordDBOSShutdown,
registerFunctionWrapper,
registerLifecycleCallback,
setAlertHandler,
transactionalDataSources,
registerMiddlewareInstaller,
MethodRegistrationBase,
TypedAsyncFunction,
UntypedAsyncFunction,
FunctionName,
wrapDBOSFunctionAndRegisterByUniqueName,
wrapDBOSFunctionAndRegisterByTarget,
wrapDBOSFunctionAndRegister,
ensureDBOSIsLaunched,
ConfiguredInstance,
DBOSMethodMiddlewareInstaller,
DBOSLifecycleCallback,
associateParameterWithExternal,
finalizeClassRegistrations,
getClassRegistration,
clearAllRegistrations,
getRegisteredFunctionFullName,
} from './decorators';
import { defaultEnableOTLP, globalParams, sleepConfig, sleepms } from './utils';
import {
deserializeValue,
JSONValue,
registerSerializationRecipe,
SerializationRecipe,
serializeValue,
} from './serialization';
import { DBOSAdminServer } from './adminserver';
import { Server } from 'http';
import { randomUUID } from 'node:crypto';
import { StepConfig } from './step';
import { Conductor } from './conductor/conductor';
import {
EnqueueOptions,
DBOS_STREAM_CLOSED_SENTINEL,
DBOS_FUNCNAME_WRITESTREAM,
WorkflowScheduleInternal,
VersionInfo,
} from './system_database';
import { PoolClient } from 'pg';
import {
WorkflowSchedule,
ScheduledWorkflowFn,
ScheduleOptions,
toWorkflowSchedule,
createScheduleId,
triggerSchedule as triggerScheduleImpl,
backfillSchedule as backfillScheduleImpl,
} from './scheduler/scheduler';
import { validateCrontab, validateTimezone } from './scheduler/crontab';
import { wfQueueRunner } from './wfqueue';
import { registerAuthChecker } from './authdecorators';
import assert from 'node:assert';
type AnyConstructor = new (...args: unknown[]) => object;
// Declare all the options a user can pass to the DBOS object during launch()
export interface DBOSLaunchOptions {
// For DBOS Conductor
conductorURL?: string;
conductorKey?: string;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type PossiblyWFFunc = (...args: any[]) => Promise<unknown>;
type InvokeFunctionsAsync<T> =
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
T extends Function
? {
[P in keyof T]: T[P] extends PossiblyWFFunc
? (...args: Parameters<T[P]>) => Promise<WorkflowHandle<Awaited<ReturnType<T[P]>>>>
: never;
}
: never;
type InvokeFunctionsAsyncInst<T> = T extends ConfiguredInstance
? {
[P in keyof T]: T[P] extends PossiblyWFFunc
? (...args: Parameters<T[P]>) => Promise<WorkflowHandle<Awaited<ReturnType<T[P]>>>>
: never;
}
: never;
export interface StartWorkflowParams {
workflowID?: string;
queueName?: string;
timeoutMS?: number | null;
enqueueOptions?: EnqueueOptions;
}
/**
* Options for `DBOS.send`
*/
export interface SendOptions {
/** Serialization format override, allows cross-language send/recv */
serializationType?: WorkflowSerializationFormat;
}
/**
* Options for `DBOS.writeStream`
*/
export interface WriteStreamOptions {
/** Serialization format override, allows cross-language writeStream / readStream */
serializationType?: WorkflowSerializationFormat;
}
/**
* Options for `DBOS.setEvent`
*/
export interface SetEventOptions {
/**
* Serialization format override, allows event to be read by
* workflows or clients written in other languages
*/
serializationType?: WorkflowSerializationFormat;
}
export function getExecutor() {
if (!DBOSExecutor.globalInstance) {
throw new DBOSExecutorNotInitializedError();
}
return DBOSExecutor.globalInstance;
}
export function runInternalStep<T>(
callback: () => Promise<T>,
funcName: string,
childWFID?: string,
assignedFuncID?: number,
): Promise<T> {
if (DBOS.isWithinWorkflow()) {
if (DBOS.isInStep()) {
// OK to use directly
return callback();
} else if (DBOS.isInWorkflow()) {
return DBOSExecutor.globalInstance!.runInternalStep<T>(
callback,
funcName,
DBOS.workflowID!,
assignedFuncID ?? functionIDGetIncrement(),
childWFID,
);
} else {
throw new DBOSInvalidWorkflowTransitionError(`Invalid call to \`${funcName}\` inside a \`transaction\``);
}
}
return callback();
}
/**
* Like runInternalStep, but when called from within a workflow, the callback and the step
* result recording run in the same database transaction (via runTransactionalStep).
* The callback receives a PoolClient that should be passed to any SystemDatabase
* methods so they participate in the same transaction.
* Outside a workflow, the callback is called directly with `undefined` as the client.
*/
async function runTransactionalInternalStep<T>(
callback: (client: PoolClient | undefined) => Promise<T>,
funcName: string,
): Promise<T> {
if (DBOS.isWithinWorkflow()) {
if (DBOS.isInStep()) {
return callback(undefined);
} else if (DBOS.isInWorkflow()) {
const executor = DBOSExecutor.globalInstance!;
const functionID = functionIDGetIncrement();
let freshResult: T;
const stored = await executor.systemDatabase.runTransactionalStep(
DBOS.workflowID!,
functionID,
funcName,
async (client) => {
freshResult = await callback(client);
return executor.serializer.stringify(freshResult !== undefined ? freshResult : null);
},
);
if (stored !== undefined) {
if (stored.functionName !== funcName) {
throw new DBOSUnexpectedStepError(DBOS.workflowID!, functionID, funcName, stored.functionName!);
}
return DBOSExecutor.reviveResultOrError<T>(stored, executor.serializer);
}
return freshResult!;
} else {
throw new DBOSInvalidWorkflowTransitionError(`Invalid call to \`${funcName}\` inside a \`transaction\``);
}
}
return callback(undefined);
}
export class DBOS {
///////
// Lifecycle
///////
static adminServer: Server | undefined = undefined;
static conductor: Conductor | undefined = undefined;
/**
* Set configuration of `DBOS` prior to `launch`
* @param config - configuration of services needed by DBOS
*/
static setConfig(config: DBOSConfig) {
assert(!DBOS.isInitialized(), 'Cannot call DBOS.setConfig after DBOS.launch');
DBOS.#dbosConfig = config;
}
/**
* Check if DBOS has been `launch`ed (and not `shutdown`)
* @returns `true` if DBOS has been launched, or `false` otherwise
*/
static isInitialized(): boolean {
return !!DBOSExecutor.globalInstance?.initialized;
}
/**
* Launch DBOS, starting recovery and request handling
* @param options - Launch options for connecting to DBOS Conductor
*/
static async launch(options?: DBOSLaunchOptions): Promise<void> {
const configFile = await readConfigFile();
let internalConfig = DBOS.#dbosConfig ? translateDbosConfig(DBOS.#dbosConfig) : getDbosConfig(configFile);
let runtimeConfig = DBOS.#dbosConfig ? translateRuntimeConfig(DBOS.#dbosConfig) : getRuntimeConfig(configFile);
if (process.env.DBOS__CLOUD === 'true') {
[internalConfig, runtimeConfig] = overwriteConfigForDBOSCloud(internalConfig, runtimeConfig, configFile);
}
globalParams.enableOTLP = DBOS.#dbosConfig?.enableOTLP ?? defaultEnableOTLP();
globalParams.tracingEnabled = DBOS.#dbosConfig?.tracingEnabled || globalParams.enableOTLP;
if (!isTraceContextWorking()) installTraceContextManager(internalConfig.name);
// Do nothing if DBOS is already initialized
if (DBOS.isInitialized()) {
return;
}
finalizeClassRegistrations();
insertAllMiddleware();
// Globally set the application version and executor ID.
// In DBOS Cloud, instead use the value supplied through environment variables.
if (process.env.DBOS__CLOUD !== 'true') {
if (DBOS.#dbosConfig?.applicationVersion) {
globalParams.appVersion = DBOS.#dbosConfig.applicationVersion;
} else if (DBOS.#dbosConfig?.enablePatching) {
globalParams.appVersion = 'PATCHING_ENABLED';
}
if (DBOS.#dbosConfig?.executorID) {
globalParams.executorID = DBOS.#dbosConfig.executorID;
}
}
if (options?.conductorKey) {
// Always use a generated executor ID in Conductor.
globalParams.executorID = randomUUID();
}
DBOSExecutor.createDebouncerWorkflow();
DBOSExecutor.createInternalQueue();
DBOSExecutor.globalInstance = new DBOSExecutor(internalConfig);
recordDBOSLaunch();
const executor: DBOSExecutor = DBOSExecutor.globalInstance;
await executor.init();
// Register the current application version
await executor.systemDatabase.createApplicationVersion(globalParams.appVersion);
const latest = await executor.systemDatabase.getLatestApplicationVersion();
if (latest.versionName !== globalParams.appVersion) {
executor.logger.warn(
`Current version '${globalParams.appVersion}' is not the latest version. Latest version is '${latest.versionName}'.`,
);
}
await DBOSExecutor.globalInstance.initEventReceivers(this.#dbosConfig?.listenQueues || null);
for (const [_n, ds] of transactionalDataSources) {
await ds.initialize();
}
if (options?.conductorKey) {
if (!options.conductorURL) {
const dbosDomain = process.env.DBOS_DOMAIN || 'cloud.dbos.dev';
options.conductorURL = `wss://${dbosDomain}/conductor/v1alpha1`;
}
DBOS.conductor = new Conductor(DBOSExecutor.globalInstance, options.conductorKey, options.conductorURL);
DBOS.conductor.dispatchLoop();
}
// Start the DBOS admin server
const logger = DBOS.logger;
if (runtimeConfig.runAdminServer) {
const adminApp = DBOSAdminServer.setupAdminApp(executor);
try {
await DBOSAdminServer.checkPortAvailabilityIPv4Ipv6(runtimeConfig.admin_port, logger as GlobalLogger);
// Wrap the listen call in a promise to properly catch errors
DBOS.adminServer = await new Promise((resolve, reject) => {
const server = adminApp.listen(runtimeConfig?.admin_port, () => {
DBOS.logger.debug(`DBOS Admin Server is running at http://localhost:${runtimeConfig?.admin_port}`);
resolve(server);
});
server.on('error', (err) => {
reject(err);
});
});
} catch (e) {
logger.warn(`Unable to start DBOS admin server on port ${runtimeConfig.admin_port}`);
}
}
}
/**
* Logs all workflows that can be invoked externally, rather than directly by the applicaton.
* This includes:
* All DBOS event receiver entrypoints (message queues, URLs, etc.)
* Scheduled workflows
* Queues
*/
static logRegisteredEndpoints(): void {
if (!DBOSExecutor.globalInstance) return;
wfQueueRunner.logRegisteredEndpoints(DBOSExecutor.globalInstance);
for (const lcl of getLifecycleListeners()) {
lcl.logRegisteredEndpoints?.();
}
}
/**
* Shut down DBOS processing:
* Stops receiving external workflow requests
* Disconnects from administration / Conductor
* Stops workflow processing and disconnects from databases
* @param options Optional shutdown options.
* @param options.deregister
* If true, clear the DBOS workflow, queue, instance, data source, listener, and other registries.
* This is available for testing and development purposes only.
* Functions may then be registered before the next call to DBOS.launch().
* Decorated / registered functions created prior to `clearRegistry` may no longer be used.
* Fresh wrappers may be created from the original functions.
*/
static async shutdown(options?: { deregister?: boolean }) {
// Stop the admin server
if (DBOS.adminServer) {
DBOS.adminServer.close();
DBOS.adminServer = undefined;
}
// Stop the conductor
if (DBOS.conductor) {
DBOS.conductor.stop();
while (!DBOS.conductor.isClosed) {
await sleepms(500);
}
DBOS.conductor = undefined;
}
// Stop the executor
if (DBOSExecutor.globalInstance) {
await DBOSExecutor.globalInstance.deactivateEventReceivers();
await DBOSExecutor.globalInstance.destroy();
DBOSExecutor.globalInstance = undefined;
}
for (const [_n, ds] of transactionalDataSources) {
await ds.destroy();
}
// Reset the global app version and executor ID
globalParams.appVersion = process.env.DBOS__APPVERSION || '';
globalParams.wasComputed = false;
globalParams.appID = process.env.DBOS__APPID || '';
globalParams.executorID = process.env.DBOS__VMID || 'local';
recordDBOSShutdown();
if (options?.deregister) {
DBOS.clearRegistry();
}
}
/**
* Clear the DBOS workflow, queue, instance, data source, listener, and other registries.
* This is available for testing and development purposes only.
* This may only be done while DBOS is not launch()ed.
* Decorated / registered functions created prior to `clearRegistry` may no longer be used.
* Fresh wrappers may be created from the original functions.
*/
private static clearRegistry() {
assert(!DBOS.isInitialized(), 'Cannot call DBOS.clearRegistry after DBOS.launch');
clearAllRegistrations();
wfQueueRunner.clearRegistrations();
DBOSExecutor.debouncerWorkflow = undefined;
DBOSExecutor.internalQueue = undefined;
}
/** Stop listening for external events (for testing) */
static async deactivateEventReceivers() {
return DBOSExecutor.globalInstance?.deactivateEventReceivers();
}
/** Start listening for external events (for testing) */
static async initEventReceivers() {
return DBOSExecutor.globalInstance?.initEventReceivers(this.#dbosConfig?.listenQueues || null);
}
// Global DBOS executor instance
static get #executor() {
return getExecutor();
}
//////
// Globals
//////
static #dbosConfig?: DBOSConfig;
//////
// Context
//////
/** Get the current DBOS Logger, appropriate to the current context */
static get logger(): DLogger {
const lctx = getCurrentContextStore();
if (lctx?.logger) return lctx.logger;
const executor = DBOSExecutor.globalInstance;
if (executor) return executor.logger;
return new GlobalLogger();
}
/** Get the current DBOS Tracer, for starting spans */
static get tracer(): Tracer | undefined {
const executor = DBOSExecutor.globalInstance;
if (executor) return executor.tracer;
}
/** Get the current DBOS tracing span, appropriate to the current context */
static get span(): DBOSSpan | undefined {
return getActiveSpan();
}
/**
* Get the current request object (such as an HTTP request)
* This is intended for use in event libraries that know the type of the current request,
* and set it using `withTracedContext` or `runWithContext`
*/
static requestObject(): object | undefined {
return getCurrentContextStore()?.request;
}
/** Get the current HTTP request (within `@DBOS.getApi` et al) */
static getRequest(): HTTPRequest | undefined {
return this.requestObject() as HTTPRequest | undefined;
}
/** Get the current HTTP request (within `@DBOS.getApi` et al) */
static get request(): HTTPRequest {
const r = DBOS.getRequest();
if (!r) throw new DBOSError('`DBOS.request` accessed from outside of HTTP requests');
return r;
}
/** Get the current application version */
static get applicationVersion(): string {
return globalParams.appVersion;
}
/** Get the current executor ID */
static get executorID(): string {
return globalParams.executorID;
}
/** Get the current workflow ID */
static get workflowID(): string | undefined {
return getCurrentContextStore()?.workflowId;
}
/** Use portable serialization by default? */
static get defaultSerializationType(): WorkflowSerializationFormat | undefined {
return getCurrentContextStore()?.serializationType;
}
/** Get the current step number, within the current workflow */
static get stepID(): number | undefined {
if (DBOS.isInStep()) {
return getCurrentContextStore()?.curStepFunctionId;
} else if (DBOS.isInTransaction()) {
return getCurrentContextStore()?.curTxFunctionId;
} else {
return undefined;
}
}
static get stepStatus(): StepStatus | undefined {
return getCurrentContextStore()?.stepStatus;
}
/** Get the current authenticated user */
static get authenticatedUser(): string {
return getCurrentContextStore()?.authenticatedUser ?? '';
}
/** Get the roles granted to the current authenticated user */
static get authenticatedRoles(): string[] {
return getCurrentContextStore()?.authenticatedRoles ?? [];
}
/** Get the role assumed by the current user giving authorization to execute the current function */
static get assumedRole(): string {
return getCurrentContextStore()?.assumedRole ?? '';
}
/** @returns true if called from within a transaction, false otherwise */
static isInTransaction(): boolean {
return getCurrentContextStore()?.curTxFunctionId !== undefined;
}
/** @returns true if called from within a step, false otherwise */
static isInStep(): boolean {
return getCurrentContextStore()?.curStepFunctionId !== undefined;
}
/**
* @returns true if called from within a workflow
* (regardless of whether the workflow is currently executing a step
* or transaction), false otherwise
*/
static isWithinWorkflow(): boolean {
return getCurrentContextStore()?.workflowId !== undefined;
}
/**
* @returns true if called from within a workflow that is not currently executing
* a step or transaction, or false otherwise
*/
static isInWorkflow(): boolean {
return DBOS.isWithinWorkflow() && !DBOS.isInTransaction() && !DBOS.isInStep();
}
//////
// Access to system DB, for event receivers etc.
//////
/**
* Get a state item from the system database, which provides a key/value store interface for event dispatchers.
* The full key for the database state should include the service, function, and item.
* Values are versioned. A version can either be a sequence number (long integer), or a time (high precision floating point).
* If versions are in use, any upsert is discarded if the version field is less than what is already stored.
*
* Examples of state that could be kept:
* Offsets into kafka topics, per topic partition
* Last time for which a scheduling service completed schedule dispatch
*
* @param service - should be unique to the event receiver keeping state, to separate from others
* @param workflowFnName - function name; should be the fully qualified / unique function name dispatched
* @param key - The subitem kept by event receiver service for the function, allowing multiple values to be stored per function
* @returns The latest system database state for the specified service+workflow+item
*/
static async getEventDispatchState(svc: string, wfn: string, key: string): Promise<DBOSExternalState | undefined> {
ensureDBOSIsLaunched('getEventDispatchState');
return await DBOS.#executor.getEventDispatchState(svc, wfn, key);
}
/**
* Set a state item into the system database, which provides a key/value store interface for event dispatchers.
* The full key for the database state should include the service, function, and item; these fields are part of `state`.
* Values are versioned. A version can either be a sequence number (long integer), or a time (high precision floating point).
* If versions are in use, any upsert is discarded if the version field is less than what is already stored.
*
* @param state - the service, workflow, item, version, and value to write to the database
* @returns The upsert returns the current record, which may be useful if it is more recent than the `state` provided.
*/
static async upsertEventDispatchState(state: DBOSExternalState): Promise<DBOSExternalState> {
ensureDBOSIsLaunched('upsertEventDispatchState');
return await DBOS.#executor.upsertEventDispatchState(state);
}
//////
// Workflow and other operations
//////
/**
* Get the workflow status given a workflow ID
* @param workflowID - ID of the workflow
* @returns status of the workflow as `WorkflowStatus`, or `null` if there is no workflow with `workflowID`
*/
static getWorkflowStatus(workflowID: string): Promise<WorkflowStatus | null> {
ensureDBOSIsLaunched('getWorkflowStatus');
if (DBOS.isWithinWorkflow()) {
if (DBOS.isInStep()) {
// OK to use directly
return DBOS.#executor.getWorkflowStatus(workflowID);
} else if (DBOS.isInWorkflow()) {
return DBOS.#executor.getWorkflowStatus(workflowID, DBOS.workflowID, functionIDGetIncrement());
} else {
throw new DBOSInvalidWorkflowTransitionError('Invalid call to `getWorkflowStatus` inside a `transaction`');
}
}
return DBOS.#executor.getWorkflowStatus(workflowID);
}
/**
* Get the workflow result, given a workflow ID
* @param workflowID - ID of the workflow
* @param timeoutSeconds - Maximum time to wait for result; if not provided, the operation does not time out
* @returns The return value of the workflow, or throws the exception thrown by the workflow, or `null` if times out
*/
static async getResult<T>(workflowID: string, timeoutSeconds?: number): Promise<T | null> {
ensureDBOSIsLaunched('getResult');
let timerFuncID: number | undefined = undefined;
if (DBOS.isWithinWorkflow() && timeoutSeconds !== undefined) {
timerFuncID = functionIDGetIncrement();
}
return await DBOS.getResultInternal(workflowID, timeoutSeconds, timerFuncID, undefined);
}
static async getResultInternal<T>(
workflowID: string,
timeoutSeconds?: number,
timerFuncID?: number,
assignedFuncID?: number,
): Promise<T | null> {
return await runInternalStep(
async () => {
const rres = await DBOSExecutor.globalInstance!.systemDatabase.awaitWorkflowResult(
workflowID,
timeoutSeconds,
DBOS.workflowID,
timerFuncID,
);
if (!rres) return null;
if (rres?.cancelled) {
throw new DBOSAwaitedWorkflowCancelledError(workflowID);
}
if (rres?.maxRecoveryAttemptsExceeded) {
throw new DBOSAwaitedWorkflowExceededMaxRecoveryAttempts(workflowID);
}
return DBOSExecutor.reviveResultOrError<T>(rres, DBOS.#executor.serializer);
},
'DBOS.getResult',
workflowID,
assignedFuncID,
);
}
/**
* Wait for any one of the given workflow handles to complete and return it.
* Polls the database until at least one workflow's status is no longer PENDING or ENQUEUED,
* then returns the corresponding handle.
* @param handles - Non-empty array of workflow handles to wait on
* @returns The first handle whose workflow has completed
*/
static async waitFirst(handles: WorkflowHandle<unknown>[]): Promise<WorkflowHandle<unknown>> {
ensureDBOSIsLaunched('waitFirst');
if (handles.length === 0) {
throw new Error('handles must not be empty');
}
// Build a map from workflow ID to handle, disallowing duplicates.
const handleMap = new Map<string, WorkflowHandle<unknown>>();
for (const handle of handles) {
if (handleMap.has(handle.workflowID)) {
throw new Error(`Duplicate workflow ID in waitFirst: ${handle.workflowID}`);
}
handleMap.set(handle.workflowID, handle);
}
const workflowIds = [...handleMap.keys()];
const completedId = await runInternalStep(async () => {
return await DBOSExecutor.globalInstance!.systemDatabase.awaitFirstWorkflowId(workflowIds, DBOS.workflowID);
}, 'DBOS.waitFirst');
return handleMap.get(completedId)!;
}
/**
* Create a workflow handle with a given workflow ID.
* This call always returns a handle, even if the workflow does not exist.
* The resulting handle will check the database to provide any workflow information.
* @param workflowID - ID of the workflow
* @returns `WorkflowHandle` that can be used to poll for the status or result of any workflow with `workflowID`
*/
static retrieveWorkflow<T = unknown>(workflowID: string): WorkflowHandle<Awaited<T>> {
ensureDBOSIsLaunched('retrieveWorkflow');
if (DBOS.isWithinWorkflow()) {
if (!DBOS.isInWorkflow()) {
throw new DBOSInvalidWorkflowTransitionError(
'Invalid call to `retrieveWorkflow` inside a `transaction` or `step`',
);
}
return new RetrievedHandle(DBOSExecutor.globalInstance!.systemDatabase, workflowID);
}
return DBOS.#executor.retrieveWorkflow(workflowID);
}
/**
* Query the system database for all workflows matching the provided predicate
* @param input - `GetWorkflowsInput` predicate for filtering returned workflows
* @returns `WorkflowStatus` array containing details of the matching workflows
*/
static async listWorkflows(input: GetWorkflowsInput): Promise<WorkflowStatus[]> {
ensureDBOSIsLaunched('listWorkflows');
return await runInternalStep(async () => {
return await DBOS.#executor.listWorkflows(input);
}, 'DBOS.listWorkflows');
}
/**
* Query the system database for all queued workflows matching the provided predicate
* @param input - `GetQueuedWorkflowsInput` predicate for filtering returned workflows
* @returns `WorkflowStatus` array containing details of the matching workflows
*/
static async listQueuedWorkflows(input: GetWorkflowsInput): Promise<WorkflowStatus[]> {
ensureDBOSIsLaunched('listQueuedWorkflows');
return await runInternalStep(async () => {
return await DBOS.#executor.listQueuedWorkflows(input);
}, 'DBOS.listQueuedWorkflows');
}
/**
* Retrieve the steps of a workflow
* @param workflowID - ID of the workflow
* @returns `StepInfo` array listing the executed steps of the workflow. If the workflow is not found, `undefined` is returned.
*/
static async listWorkflowSteps(workflowID: string): Promise<StepInfo[] | undefined> {
ensureDBOSIsLaunched('listWorkflowSteps');
return await runInternalStep(async () => {
return await DBOS.#executor.listWorkflowSteps(workflowID);
}, 'DBOS.listWorkflowSteps');
}
/**
* Cancel a workflow given its ID.
* If the workflow is currently running, `DBOSWorkflowCancelledError` will be
* thrown from its next DBOS call.
* @param workflowID - ID of the workflow
*/
static async cancelWorkflow(workflowID: string): Promise<void> {
return this.cancelWorkflows([workflowID]);
}
/**
* Cancel multiple workflows given their IDs.
* @param workflowIDs - IDs of the workflows to cancel
*/
static async cancelWorkflows(workflowIDs: string[]): Promise<void> {
ensureDBOSIsLaunched('cancelWorkflows');
return runInternalStep(async () => {
return DBOSExecutor.globalInstance!.systemDatabase.cancelWorkflows(workflowIDs);
}, 'DBOS.cancelWorkflow');
}
/**
* Resume a workflow given its ID.
* @param workflowID - ID of the workflow
*/
static async resumeWorkflow<T>(workflowID: string): Promise<WorkflowHandle<Awaited<T>>> {
const handles = await this.resumeWorkflows<T>([workflowID]);
return handles[0];
}
/**
* Resume multiple workflows given their IDs.
* @param workflowIDs - IDs of the workflows to resume
* @returns An array of workflow handles
*/
static async resumeWorkflows<T>(workflowIDs: string[]): Promise<WorkflowHandle<Awaited<T>>[]> {
ensureDBOSIsLaunched('resumeWorkflows');
await runInternalStep(async () => {
return DBOSExecutor.globalInstance!.systemDatabase.resumeWorkflows(workflowIDs);
}, 'DBOS.resumeWorkflow');
return workflowIDs.map((wfid) => this.retrieveWorkflow(wfid));
}
/**
* Delete a workflow and optionally all its child workflows.
* This permanently removes the workflow from the system database.
*
* WARNING: This operation is irreversible.
*
* @param workflowID - ID of the workflow to delete
* @param deleteChildren - If true, also delete all child workflows recursively (default: false)
*/
static async deleteWorkflow(workflowID: string, deleteChildren: boolean = false): Promise<void> {
return this.deleteWorkflows([workflowID], deleteChildren);
}
/**
* Delete multiple workflows and optionally all their child workflows.
*
* WARNING: This operation is irreversible.
*
* @param workflowIDs - IDs of the workflows to delete
* @param deleteChildren - If true, also delete all child workflows recursively (default: false)
*/
static async deleteWorkflows(workflowIDs: string[], deleteChildren: boolean = false): Promise<void> {
ensureDBOSIsLaunched('deleteWorkflows');
return runInternalStep(async () => {
return DBOSExecutor.globalInstance!.systemDatabase.deleteWorkflows(workflowIDs, deleteChildren);
}, 'DBOS.deleteWorkflow');
}
/**
* Fork a workflow given its ID.
* @param workflowID - ID of the workflow
* @param startStep - Step ID to start the forked workflow from
* @param applicationVersion - Version of the application to use for the forked workflow
* @returns A handle to the forked workflow
* @throws DBOSInvalidStepIDError if the `startStep` is greater than the maximum step ID of the workflow
*/
static async forkWorkflow<T>(
workflowID: string,
startStep: number,
options?: { newWorkflowID?: string; applicationVersion?: string; timeoutMS?: number },
): Promise<WorkflowHandle<Awaited<T>>> {
ensureDBOSIsLaunched('forkWorkflow');
const forkedID = await runInternalStep(async () => {
return await DBOS.#executor.forkWorkflow(workflowID, startStep, options);
}, 'DBOS.forkWorkflow');
return this.retrieveWorkflow(forkedID);
}
/**
* Sleep for the specified amount of time.
* If called from within a workflow, the sleep is "durable",
* meaning that the workflow will sleep until the wakeup time
* (calculated by adding `durationMS` to the original invocation time),
* regardless of workflow recovery.
* @param durationMS - Length of sleep, in milliseconds.
*/
static async sleepms(durationMS: number): Promise<void> {
if (DBOS.isWithinWorkflow() && !DBOS.isInStep()) {
if (DBOS.isInTransaction()) {
throw new DBOSInvalidWorkflowTransitionError('Invalid call to `DBOS.sleep` inside a `transaction`');
}
const functionID = functionIDGetIncrement();
if (durationMS <= 0) {
return;
}
return await DBOSExecutor.globalInstance!.systemDatabase.durableSleepms(DBOS.workflowID!, functionID, durationMS);
}
const endTime = Date.now() + durationMS;
while (Date.now() < endTime) {
await sleepms(Math.min(endTime - Date.now(), sleepConfig.maxTimeoutMS));
}
}
/** @see sleepms */
static async sleepSeconds(durationSec: number): Promise<void> {
return DBOS.sleepms(durationSec * 1000);
}
/** @see sleepms */
static async sleep(durationMS: number): Promise<void> {
return DBOS.sleepms(durationMS);
}
/**
* Get the current time in milliseconds, similar to `Date.now()`.
* This function is deterministic and can be used within workflows.
*/
static async now(): Promise<number> {
if (DBOS.isInWorkflow()) {
return runInternalStep(async () => Promise.resolve(Date.now()), 'DBOS.now');
}
return Date.now();
}
/**
* Generate a random (v4) UUUID, similar to `node:crypto.randomUUID`.
* This function is deterministic and can be used within workflows.
*/
static async randomUUID(): Promise<string> {
if (DBOS.isInWorkflow()) {
return runInternalStep(async () => Promise.resolve(randomUUID()), 'DBOS.randomUUID');
}
return randomUUID();
}
/**
* Use the provided `workflowID` as the identifier for first workflow started
* within the `callback` function.
* @param workflowID - ID to assign to the first workflow started
* @param callback - Function to run, which would start a workflow
* @returns - Return value from `callback`
*/
static async withNextWorkflowID<R>(workflowID: string, callback: () => Promise<R>): Promise<R> {
ensureDBOSIsLaunched('workflows');
return DBOS.#withTopContext({ idAssignedForNextWorkflow: workflowID }, callback);
}
/**
* Use the provided `authedUser` and `authedRoles` as the authenticated user for
* any security checks or calls to `DBOS.authenticatedUser`
* or `DBOS.authenticatedRoles` placed within the `callback` function.
* @param authedUser - Authenticated user
* @param authedRoles - Authenticated roles
* @param callback - Function to run with authentication context in place
* @returns - Return value from `callback`
*/
static async withAuthedContext<R>(authedUser: string, authedRoles: string[], callback: () => Promise<R>): Promise<R> {
ensureDBOSIsLaunched('auth');
return DBOS.#withTopContext(
{
authenticatedUser: authedUser,
authenticatedRoles: authedRoles,
},
callback,
);
}
/**
* This generic setter helps users calling DBOS operation to pass a name,
* later used in seeding a parent OTel span for the operation.
* @param callerName - Tracing caller name
* @param callback - Function to run with tracing context in place
* @returns - Return value from `callback`
*/
static async withNamedContext<R>(callerName: string, callback: () => Promise<R>): Promise<R> {
ensureDBOSIsLaunched('tracing');
return DBOS.#withTopContext({ operationCaller: callerName }, callback);
}
/**
* Use queue named `queueName` for any workflows started within the `callback`.
* @param queueName - Name of queue upon which all workflows called or started within `callback` will be run
* @param callback - Function to run, which would call or start workflows
* @returns - Return value from `callback`
*/
static async withWorkflowQueue<R>(queueName: string, callback: () => Promise<R>): Promise<R> {
ensureDBOSIsLaunched('workflows');
return DBOS.#withTopContext({ queueAssignedForWorkflows: queueName }, callback);
}
/**
* Specify workflow timeout for any workflows started within the `callback`.
* @param timeoutMS - timeout length for all workflows started within `callback` will be run
* @param callback - Function to run, which would call or start workflows
* @returns - Return value from `callback`
*/
static async withWorkflowTimeout<R>(timeoutMS: number | null, callback: () => Promise<R>): Promise<R> {