-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathdbos-executor.ts
1475 lines (1337 loc) · 59 KB
/
dbos-executor.ts
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
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Span } from "@opentelemetry/sdk-trace-base";
import { DBOSError, DBOSInitializationError, DBOSWorkflowConflictUUIDError, DBOSNotRegisteredError, DBOSDebuggerError, DBOSConfigKeyTypeError, DBOSFailedSqlTransactionError } from "./error";
import {
InvokedHandle,
Workflow,
WorkflowConfig,
WorkflowContext,
WorkflowHandle,
WorkflowParams,
RetrievedHandle,
WorkflowContextImpl,
WorkflowStatus,
StatusString,
BufferedResult,
ContextFreeFunction,
GetWorkflowQueueInput,
GetWorkflowQueueOutput,
} from './workflow';
import { IsolationLevel, Transaction, TransactionConfig, TransactionContextImpl } from './transaction';
import { StepConfig, StepContextImpl, StepFunction } from './step';
import { TelemetryCollector } from './telemetry/collector';
import { Tracer } from './telemetry/traces';
import { GlobalLogger as Logger } from './telemetry/logs';
import { TelemetryExporter } from './telemetry/exporters';
import { TelemetryConfig } from './telemetry';
import { Pool, PoolClient, PoolConfig, QueryResultRow } from 'pg';
import { SystemDatabase, PostgresSystemDatabase, WorkflowStatusInternal } from './system_database';
import { v4 as uuidv4 } from 'uuid';
import {
PGNodeUserDatabase,
PrismaUserDatabase,
UserDatabase,
TypeORMDatabase,
UserDatabaseName,
KnexUserDatabase,
DrizzleUserDatabase,
UserDatabaseClient,
} from './user_database';
import { MethodRegistrationBase, getRegisteredOperations, getOrCreateClassRegistration, MethodRegistration, getRegisteredMethodClassName, getRegisteredMethodName, getConfiguredInstance, ConfiguredInstance, getAllRegisteredClasses } from './decorators';
import { SpanStatusCode } from '@opentelemetry/api';
import knex, { Knex } from 'knex';
import { DBOSContextImpl, InitContext, runWithWorkflowContext, runWithTransactionContext, runWithStepContext } from './context';
import { HandlerRegistrationBase } from './httpServer/handler';
import { WorkflowContextDebug } from './debugger/debug_workflow';
import { serializeError } from 'serialize-error';
import { DBOSJSON, sleepms } from './utils';
import path from 'node:path';
import { StoredProcedure, StoredProcedureConfig } from './procedure';
import { NoticeMessage } from "pg-protocol/dist/messages";
import { DBOSEventReceiver, DBOSExecutorContext, GetWorkflowsInput, GetWorkflowsOutput} from ".";
import { get } from "lodash";
import { wfQueueRunner, WorkflowQueue } from "./wfqueue";
import { debugTriggerPoint, DEBUG_TRIGGER_WORKFLOW_ENQUEUE } from "./debugpoint";
import { DBOSScheduler } from './scheduler/scheduler';
import { DBOSEventReceiverState, DBOSEventReceiverQuery, DBNotificationCallback, DBNotificationListener } from "./eventreceiver";
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface DBOSNull { }
export const dbosNull: DBOSNull = {};
/* Interface for DBOS configuration */
export interface DBOSConfig {
readonly poolConfig: PoolConfig;
readonly userDbclient?: UserDatabaseName;
readonly telemetry?: TelemetryConfig;
readonly system_database: string;
readonly env?: Record<string, string>;
readonly application?: object;
readonly debugProxy?: string;
readonly debugMode?: boolean;
readonly appVersion?: string;
readonly http?: {
readonly cors_middleware?: boolean;
readonly credentials?: boolean;
readonly allowed_origins?: string[];
};
}
interface WorkflowRegInfo {
workflow: Workflow<unknown[], unknown>;
config: WorkflowConfig;
registration?: MethodRegistrationBase; // Always set except for temp WF...
}
interface TransactionRegInfo {
transaction: Transaction<unknown[], unknown>;
config: TransactionConfig;
registration: MethodRegistrationBase;
}
interface StepRegInfo {
step: StepFunction<unknown[], unknown>;
config: StepConfig;
registration: MethodRegistrationBase;
}
interface ProcedureRegInfo {
procedure: StoredProcedure<unknown>;
config: StoredProcedureConfig;
registration: MethodRegistrationBase;
}
export interface InternalWorkflowParams extends WorkflowParams {
readonly tempWfType?: string;
readonly tempWfName?: string;
readonly tempWfClass?: string;
}
export const OperationType = {
HANDLER: "handler",
WORKFLOW: "workflow",
TRANSACTION: "transaction",
COMMUNICATOR: "communicator",
PROCEDURE: "procedure",
} as const;
const TempWorkflowType = {
transaction: "transaction",
procedure: "procedure",
external: "external",
send: "send",
} as const;
export class DBOSExecutor implements DBOSExecutorContext {
initialized: boolean;
// User Database
userDatabase: UserDatabase = null as unknown as UserDatabase;
// System Database
readonly systemDatabase: SystemDatabase;
readonly procedurePool: Pool;
// Temporary workflows are created by calling transaction/send/recv directly from the executor class
static readonly tempWorkflowName = "temp_workflow";
readonly workflowInfoMap: Map<string, WorkflowRegInfo> = new Map([
// We initialize the map with an entry for temporary workflows.
[
DBOSExecutor.tempWorkflowName,
{
workflow: async () => {
this.logger.error("UNREACHABLE: Indirect invoke of temp workflow");
return Promise.resolve();
},
config: {},
},
],
]);
readonly transactionInfoMap: Map<string, TransactionRegInfo> = new Map();
readonly stepInfoMap: Map<string, StepRegInfo> = new Map();
readonly procedureInfoMap: Map<string, ProcedureRegInfo> = new Map();
readonly registeredOperations: Array<MethodRegistrationBase> = [];
readonly pendingWorkflowMap: Map<string, Promise<unknown>> = new Map(); // Map from workflowUUID to workflow promise
readonly workflowResultBuffer: Map<string, Map<number, BufferedResult>> = new Map(); // Map from workflowUUID to its remaining result buffer.
readonly telemetryCollector: TelemetryCollector;
readonly flushBufferIntervalMs: number = 1000;
readonly flushBufferID: NodeJS.Timeout;
isFlushingBuffers = false;
static readonly defaultNotificationTimeoutSec = 60;
readonly debugMode: boolean;
readonly debugProxy: string | undefined;
static systemDBSchemaName = "dbos";
readonly logger: Logger;
readonly tracer: Tracer;
// eslint-disable-next-line @typescript-eslint/ban-types
typeormEntities: Function[] = [];
drizzleEntities: { [key: string]: object } = {};
eventReceivers: DBOSEventReceiver[] = [];
scheduler?: DBOSScheduler = undefined;
wfqEnded?: Promise<void> = undefined;
static globalInstance: DBOSExecutor | undefined = undefined;
/* WORKFLOW EXECUTOR LIFE CYCLE MANAGEMENT */
constructor(readonly config: DBOSConfig, systemDatabase?: SystemDatabase) {
this.debugMode = config.debugMode ?? false;
this.debugProxy = config.debugProxy;
// Set configured environment variables
if (config.env) {
for (const [key, value] of Object.entries(config.env)) {
if (typeof value === "string") {
process.env[key] = value;
} else {
console.warn(`Invalid value type for environment variable ${key}: ${typeof value}`);
}
}
}
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 Logger(this.telemetryCollector, this.config.telemetry?.logs);
this.tracer = new Tracer(this.telemetryCollector);
if (this.debugMode) {
this.logger.info("Running in debug mode!");
if (this.debugProxy) {
try {
const url = new URL(this.config.debugProxy!);
this.config.poolConfig.host = url.hostname;
this.config.poolConfig.port = parseInt(url.port, 10);
this.logger.info(`Debugging mode proxy: ${this.config.poolConfig.host}:${this.config.poolConfig.port}`);
} catch (err) {
this.logger.error(err);
throw err;
}
}
}
this.procedurePool = new Pool(this.config.poolConfig);
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 PostgresSystemDatabase(this.config.poolConfig, this.config.system_database, this.logger);
}
this.flushBufferID = setInterval(() => {
if (!this.debugMode && !this.isFlushingBuffers) {
this.isFlushingBuffers = true;
void this.flushWorkflowBuffers();
}
}, this.flushBufferIntervalMs);
this.logger.debug("Started workflow status buffer worker");
this.initialized = false;
DBOSExecutor.globalInstance = this;
}
configureDbClient() {
const userDbClient = this.config.userDbclient;
const userDBConfig = this.config.poolConfig;
if (userDbClient === UserDatabaseName.PRISMA) {
// TODO: make Prisma work with debugger proxy.
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-require-imports
const { PrismaClient } = require(path.join(process.cwd(), "node_modules", "@prisma", "client")); // Find the prisma client in the node_modules of the current project
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-call
this.userDatabase = new PrismaUserDatabase(new PrismaClient(
{
datasources: {
db: {
url: `postgresql://${userDBConfig.user}:${userDBConfig.password as string}@${userDBConfig.host}:${userDBConfig.port}/${userDBConfig.database}`,
},
}
}
));
this.logger.debug("Loaded Prisma user database");
} else if (userDbClient === UserDatabaseName.TYPEORM) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-require-imports
const DataSourceExports = require("typeorm");
try {
this.userDatabase = new TypeORMDatabase(
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
new DataSourceExports.DataSource({
type: "postgres", // perhaps should move to config file
host: userDBConfig.host,
port: userDBConfig.port,
username: userDBConfig.user,
password: userDBConfig.password,
database: userDBConfig.database,
entities: this.typeormEntities,
ssl: userDBConfig.ssl,
})
);
} catch (s) {
(s as Error).message = `Error loading TypeORM user database: ${(s as Error).message}`;
this.logger.error(s);
}
this.logger.debug("Loaded TypeORM user database");
} else if (userDbClient === UserDatabaseName.KNEX) {
const knexConfig: Knex.Config = {
client: "postgres",
connection: {
host: userDBConfig.host,
port: userDBConfig.port,
user: userDBConfig.user,
password: userDBConfig.password,
database: userDBConfig.database,
ssl: userDBConfig.ssl,
},
};
this.userDatabase = new KnexUserDatabase(knex(knexConfig));
this.logger.debug("Loaded Knex user database");
} else if (userDbClient === UserDatabaseName.DRIZZLE) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-require-imports
const DrizzleExports = require("drizzle-orm/node-postgres");
const drizzlePool = new Pool(userDBConfig);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
const drizzle = DrizzleExports.drizzle(drizzlePool, { schema: this.drizzleEntities });
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
this.userDatabase = new DrizzleUserDatabase(drizzlePool, drizzle);
this.logger.debug("Loaded Drizzle user database");
} else {
this.userDatabase = new PGNodeUserDatabase(userDBConfig);
this.logger.debug("Loaded Postgres user database");
}
}
#registerClass(cls: object) {
const registeredClassOperations = getRegisteredOperations(cls);
this.registeredOperations.push(...registeredClassOperations);
for (const ro of registeredClassOperations) {
if (ro.workflowConfig) {
this.#registerWorkflow(ro);
} else if (ro.txnConfig) {
this.#registerTransaction(ro);
} else if (ro.commConfig) {
this.#registerStep(ro);
} else if (ro.procConfig) {
this.#registerProcedure(ro);
}
for (const [evtRcvr, _cfg] of ro.eventReceiverInfo) {
if (!this.eventReceivers.includes(evtRcvr)) this.eventReceivers.push(evtRcvr);
}
}
}
getRegistrationsFor(obj: DBOSEventReceiver) {
const res: { methodConfig: unknown, classConfig: unknown, methodReg: MethodRegistrationBase }[] = [];
for (const r of this.registeredOperations) {
if (!r.eventReceiverInfo.has(obj)) continue;
const methodConfig = r.eventReceiverInfo.get(obj)!;
const classConfig = r.defaults?.eventReceiverInfo.get(obj) ?? {};
res.push({ methodReg: r, methodConfig, classConfig })
}
return res;
}
async init(classes?: object[]): Promise<void> {
if (this.initialized) {
this.logger.error("Workflow executor already initialized!");
return;
}
if (!classes || !classes.length) {
classes = getAllRegisteredClasses();
}
type AnyConstructor = new (...args: unknown[]) => object;
try {
let length; // Track the length of the array (or number of keys of the object)
for (const cls of classes) {
const reg = getOrCreateClassRegistration(cls as AnyConstructor);
/**
* With TSORM, we take an array of entities (Function[]) and add them to this.entities:
*/
if (Array.isArray(reg.ormEntities)) {
this.typeormEntities = (this.typeormEntities).concat(reg.ormEntities as any[]);
length = reg.ormEntities.length;
} else {
/**
* With Drizzle, we need to take an object of entities, since the object keys are used to access the entities from ctx.client.query:
*/
this.drizzleEntities = { ...this.drizzleEntities, ...reg.ormEntities };
length = Object.keys(reg.ormEntities).length;
}
this.logger.debug(`Loaded ${length} ORM entities`);
}
this.configureDbClient();
if (!this.userDatabase) {
this.logger.error("No user database configured!");
throw new DBOSInitializationError("No user database configured!");
}
for (const cls of classes) {
this.#registerClass(cls);
}
// Debug mode doesn't need to initialize the DBs. Everything should appear to be read-only.
await this.userDatabase.init(this.debugMode);
if (!this.debugMode) {
await this.systemDatabase.init();
}
} catch (err) {
if (err instanceof AggregateError) {
let combinedMessage = 'Failed to initialize workflow executor: ';
for (const error of err.errors) {
combinedMessage += `${(error as Error).message}; `;
}
throw new DBOSInitializationError(combinedMessage);
} else if (err instanceof Error) {
const errorMessage = `Failed to initialize workflow executor: ${err.message}`;
throw new DBOSInitializationError(errorMessage);
} else {
const errorMessage = `Failed to initialize workflow executor: ${String(err)}`;
throw new DBOSInitializationError(errorMessage);
}
}
this.initialized = true;
// Only execute init code if under non-debug mode
if (!this.debugMode) {
for (const cls of classes) {
// Init its configurations
const creg = getOrCreateClassRegistration(cls as AnyConstructor);
for (const [_cfgname, cfg] of creg.configuredInstances) {
await cfg.initialize(new InitContext(this));
}
}
for (const v of this.registeredOperations) {
const m = v as MethodRegistration<unknown, unknown[], unknown>;
if (m.init === true) {
this.logger.debug("Executing init method: " + m.name);
await m.origFunction(new InitContext(this));
}
}
await this.recoverPendingWorkflows();
}
this.logger.info("Workflow executor initialized");
}
#logNotice(msg: NoticeMessage) {
switch (msg.severity) {
case "INFO":
case "LOG":
case "NOTICE":
this.logger.info(msg.message);
break;
case "WARNING":
this.logger.warn(msg.message);
break;
case "DEBUG":
this.logger.debug(msg.message);
break;
case "ERROR":
case "FATAL":
case "PANIC":
this.logger.error(msg.message);
break;
default:
this.logger.error(`Unknown notice severity: ${msg.severity} - ${msg.message}`);
}
}
async callProcedure<R extends QueryResultRow = any>(proc: StoredProcedure<unknown>, args: unknown[]): Promise<R[]> {
const client = await this.procedurePool.connect();
const log = (msg: NoticeMessage) => this.#logNotice(msg);
const procClassName = this.getProcedureClassName(proc);
const plainProcName = `${procClassName}_${proc.name}_p`;
const procName = this.config.appVersion
? `v${this.config.appVersion}_${plainProcName}`
: plainProcName;
const sql = `CALL "${procName}"(${args.map((_v, i) => `$${i + 1}`).join()});`;
try {
client.on('notice', log);
return await client.query<R>(sql, args).then(value => value.rows);
} finally {
client.off('notice', log);
client.release();
}
}
async destroy() {
if (this.pendingWorkflowMap.size > 0) {
this.logger.info("Waiting for pending workflows to finish.");
await Promise.allSettled(this.pendingWorkflowMap.values());
}
clearInterval(this.flushBufferID);
if (!this.debugMode && !this.isFlushingBuffers) {
// Don't flush the buffers if we're already flushing them in the background.
await this.flushWorkflowBuffers();
}
while (this.isFlushingBuffers) {
this.logger.info("Waiting for result buffers to be exported.");
await sleepms(1000);
}
await this.systemDatabase.destroy();
if (this.userDatabase) {
await this.userDatabase.destroy();
}
await this.procedurePool.end();
await this.logger.destroy();
if (DBOSExecutor.globalInstance === this) {
DBOSExecutor.globalInstance = undefined;
}
}
/* WORKFLOW OPERATIONS */
#registerWorkflow(ro: MethodRegistrationBase) {
const wf = ro.registeredFunction as Workflow<unknown[], unknown>;
if (wf.name === DBOSExecutor.tempWorkflowName) {
throw new DBOSError(`Unexpected use of reserved workflow name: ${wf.name}`);
}
const wfn = ro.className + '.' + ro.name;
if (this.workflowInfoMap.has(wfn)) {
throw new DBOSError(`Repeated workflow name: ${wfn}`);
}
const workflowInfo: WorkflowRegInfo = {
workflow: wf,
config: { ...ro.workflowConfig },
registration: ro,
};
this.workflowInfoMap.set(wfn, workflowInfo);
this.logger.debug(`Registered workflow ${wfn}`);
}
#registerTransaction(ro: MethodRegistrationBase) {
const txf = ro.registeredFunction as Transaction<unknown[], unknown>;
const tfn = ro.className + '.' + ro.name;
if (this.transactionInfoMap.has(tfn)) {
throw new DBOSError(`Repeated Transaction name: ${tfn}`);
}
const txnInfo: TransactionRegInfo = {
transaction: txf,
config: { ...ro.txnConfig },
registration: ro,
};
this.transactionInfoMap.set(tfn, txnInfo);
this.logger.debug(`Registered transaction ${tfn}`);
}
#registerStep(ro: MethodRegistrationBase) {
const comm = ro.registeredFunction as StepFunction<unknown[], unknown>;
const cfn = ro.className + '.' + ro.name;
if (this.stepInfoMap.has(cfn)) {
throw new DBOSError(`Repeated Commmunicator name: ${cfn}`);
}
const stepInfo: StepRegInfo = {
step: comm,
config: { ...ro.commConfig },
registration: ro,
};
this.stepInfoMap.set(cfn, stepInfo);
this.logger.debug(`Registered step ${cfn}`);
}
#registerProcedure(ro: MethodRegistrationBase) {
const proc = ro.registeredFunction as StoredProcedure<unknown>;
const cfn = ro.className + '.' + ro.name;
if (this.procedureInfoMap.has(cfn)) {
throw new DBOSError(`Repeated Procedure name: ${cfn}`);
}
const procInfo: ProcedureRegInfo = {
procedure: proc,
config: { ...ro.procConfig },
registration: ro,
};
this.procedureInfoMap.set(cfn, procInfo);
this.logger.debug(`Registered stored proc ${cfn}`);
}
getWorkflowInfo(wf: Workflow<unknown[], unknown>) {
const wfname = (wf.name === DBOSExecutor.tempWorkflowName)
? wf.name
: getRegisteredMethodClassName(wf) + '.' + wf.name;
return this.workflowInfoMap.get(wfname);
}
getWorkflowInfoByStatus(wf: WorkflowStatus) {
const wfname = wf.workflowClassName + '.' + wf.workflowName;
let wfInfo = this.workflowInfoMap.get(wfname);
if (!wfInfo && !wf.workflowClassName) {
for (const [_wfn, wfr] of this.workflowInfoMap) {
if (wf.workflowName === wfr.workflow.name) {
if (wfInfo) {
throw new DBOSError(`Recovered workflow function name '${wf.workflowName}' is ambiguous. The ambiguous name was recently added; remove it and recover pending workflows before re-adding the new function.`);
}
else {
wfInfo = wfr;
}
}
}
}
return { wfInfo, configuredInst: getConfiguredInstance(wf.workflowClassName, wf.workflowConfigName) };
}
getTransactionInfo(tf: Transaction<unknown[], unknown>) {
const tfname = getRegisteredMethodClassName(tf) + '.' + tf.name;
return this.transactionInfoMap.get(tfname);
}
getTransactionInfoByNames(className: string, functionName: string, cfgName: string) {
const tfname = className + '.' + functionName;
let txnInfo: TransactionRegInfo | undefined = this.transactionInfoMap.get(tfname);
if (!txnInfo && !className) {
for (const [_wfn, tfr] of this.transactionInfoMap) {
if (functionName === tfr.transaction.name) {
if (txnInfo) {
throw new DBOSError(`Recovered transaction function name '${functionName}' is ambiguous. The ambiguous name was recently added; remove it and recover pending workflows before re-adding the new function.`);
}
else {
txnInfo = tfr;
}
}
}
}
return { txnInfo, clsInst: getConfiguredInstance(className, cfgName) };
}
getStepInfo(cf: StepFunction<unknown[], unknown>) {
const cfname = getRegisteredMethodClassName(cf) + '.' + cf.name;
return this.stepInfoMap.get(cfname);
}
getStepInfoByNames(className: string, functionName: string, cfgName: string) {
const cfname = className + '.' + functionName;
let commInfo: StepRegInfo | undefined = this.stepInfoMap.get(cfname);
if (!commInfo && !className) {
for (const [_wfn, cfr] of this.stepInfoMap) {
if (functionName === cfr.step.name) {
if (commInfo) {
throw new DBOSError(`Recovered step function name '${functionName}' is ambiguous. The ambiguous name was recently added; remove it and recover pending workflows before re-adding the new function.`);
}
else {
commInfo = cfr;
}
}
}
}
return {commInfo, clsInst: getConfiguredInstance(className, cfgName)};
}
getProcedureClassName(pf: StoredProcedure<unknown>) {
return getRegisteredMethodClassName(pf);
}
getProcedureInfo(pf: StoredProcedure<unknown>) {
const pfName = getRegisteredMethodClassName(pf) + '.' + pf.name;
return this.procedureInfoMap.get(pfName);
}
// TODO: getProcedureInfoByNames??
async workflow<T extends unknown[], R>(wf: Workflow<T, R>, params: InternalWorkflowParams, ...args: T): Promise<WorkflowHandle<R>> {
if (this.debugMode) {
return this.debugWorkflow(wf, params, undefined, undefined, ...args);
}
return this.internalWorkflow(wf, params, undefined, undefined, ...args);
}
// If callerUUID and functionID are set, it means the workflow is invoked from within a workflow.
async internalWorkflow<T extends unknown[], R>(wf: Workflow<T, R>, params: InternalWorkflowParams, callerUUID?: string, callerFunctionID?: number, ...args: T): Promise<WorkflowHandle<R>> {
const workflowUUID: string = params.workflowUUID ? params.workflowUUID : this.#generateUUID();
const presetUUID: boolean = params.workflowUUID ? true : false;
const wInfo = this.getWorkflowInfo(wf as Workflow<unknown[], unknown>);
if (wInfo === undefined) {
throw new DBOSNotRegisteredError(wf.name);
}
const wConfig = wInfo.config;
const passContext = wInfo.registration?.passContext ?? true;
const wCtxt: WorkflowContextImpl = new WorkflowContextImpl(this, params.parentCtx, workflowUUID, wConfig, wf.name, presetUUID, params.tempWfType, params.tempWfName);
const internalStatus: WorkflowStatusInternal = {
workflowUUID: workflowUUID,
status: (params.queueName !== undefined) ? StatusString.ENQUEUED : StatusString.PENDING,
name: wf.name,
className: wCtxt.isTempWorkflow ? "" : getRegisteredMethodClassName(wf),
configName: params.configuredInstance?.name || "",
queueName: params.queueName,
authenticatedUser: wCtxt.authenticatedUser,
output: undefined,
error: "",
assumedRole: wCtxt.assumedRole,
authenticatedRoles: wCtxt.authenticatedRoles,
request: wCtxt.request,
executorID: wCtxt.executorID,
applicationVersion: wCtxt.applicationVersion,
applicationID: wCtxt.applicationID,
createdAt: Date.now(), // Remember the start time of this workflow
maxRetries: wCtxt.maxRecoveryAttempts,
recovery: params.recovery === true,
};
if (wCtxt.isTempWorkflow) {
internalStatus.name = `${DBOSExecutor.tempWorkflowName}-${wCtxt.tempWfOperationType}-${wCtxt.tempWfOperationName}`;
internalStatus.className = params.tempWfClass ?? "";
}
// Synchronously set the workflow's status to PENDING and record workflow inputs (for non single-transaction workflows).
// We have to do it for all types of workflows because operation_outputs table has a foreign key constraint on workflow status table.
if ((wCtxt.tempWfOperationType !== TempWorkflowType.transaction
&& wCtxt.tempWfOperationType !== TempWorkflowType.procedure)
|| params.queueName !== undefined
) {
// TODO: Make this transactional (and with the queue step below)
args = await this.systemDatabase.initWorkflowStatus(internalStatus, args);
await debugTriggerPoint(DEBUG_TRIGGER_WORKFLOW_ENQUEUE);
}
const runWorkflow = async () => {
let result: R;
// Execute the workflow.
try {
let cresult: R | undefined;
await runWithWorkflowContext(wCtxt, async () => {
if (passContext) {
cresult = await wf.call(params.configuredInstance, wCtxt, ...args);
}
else {
cresult = await (wf as unknown as ContextFreeFunction<T, R>).call(params.configuredInstance, ...args);
}
});
result = cresult!
internalStatus.output = result;
internalStatus.status = StatusString.SUCCESS;
if (internalStatus.queueName) {
// Now... the workflow isn't certainly done.
// But waiting this long is for concurrency control anyway,
// so it is probably done enough.
await this.systemDatabase.dequeueWorkflow(workflowUUID, this.#getQueueByName(internalStatus.queueName));
}
this.systemDatabase.bufferWorkflowOutput(workflowUUID, internalStatus);
wCtxt.span.setStatus({ code: SpanStatusCode.OK });
} catch (err) {
if (err instanceof DBOSWorkflowConflictUUIDError) {
// Retrieve the handle and wait for the result.
const retrievedHandle = this.retrieveWorkflow<R>(workflowUUID);
result = await retrievedHandle.getResult();
wCtxt.span.setAttribute("cached", true);
wCtxt.span.setStatus({ code: SpanStatusCode.OK });
} else {
// Record the error.
const e = err as Error & { dbos_already_logged?: boolean };
this.logger.error(e);
e.dbos_already_logged = true
if (wCtxt.isTempWorkflow) {
internalStatus.name = `${DBOSExecutor.tempWorkflowName}-${wCtxt.tempWfOperationType}-${wCtxt.tempWfOperationName}`;
}
internalStatus.error = DBOSJSON.stringify(serializeError(e));
internalStatus.status = StatusString.ERROR;
if (internalStatus.queueName) {
await this.systemDatabase.dequeueWorkflow(workflowUUID, this.#getQueueByName(internalStatus.queueName));
}
await this.systemDatabase.recordWorkflowError(workflowUUID, internalStatus);
// TODO: Log errors, but not in the tests when they're expected.
wCtxt.span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });
throw err;
}
} finally {
this.tracer.endSpan(wCtxt.span);
if (wCtxt.tempWfOperationType === TempWorkflowType.transaction
|| wCtxt.tempWfOperationType === TempWorkflowType.procedure
) {
// For single-transaction workflows, asynchronously record inputs.
// We must buffer inputs after workflow status is buffered/flushed because workflow_inputs table has a foreign key reference to the workflow_status table.
this.systemDatabase.bufferWorkflowInputs(workflowUUID, args);
}
}
// Asynchronously flush the result buffer.
if (wCtxt.resultBuffer.size > 0) {
this.workflowResultBuffer.set(wCtxt.workflowUUID, wCtxt.resultBuffer);
}
return result;
};
if (params.queueName === undefined || params.executeWorkflow) {
const workflowPromise: Promise<R> = runWorkflow();
// Need to await for the workflow and capture errors.
const awaitWorkflowPromise = workflowPromise
.catch((error) => {
this.logger.debug("Captured error in awaitWorkflowPromise: " + error);
})
.finally(() => {
// Remove itself from pending workflow map.
this.pendingWorkflowMap.delete(workflowUUID);
});
this.pendingWorkflowMap.set(workflowUUID, awaitWorkflowPromise);
// Return the normal handle that doesn't capture errors.
return new InvokedHandle(this.systemDatabase, workflowPromise, workflowUUID, wf.name, callerUUID, callerFunctionID);
}
else {
await this.systemDatabase.enqueueWorkflow(workflowUUID, this.#getQueueByName(params.queueName));
return new RetrievedHandle(this.systemDatabase, workflowUUID, callerUUID, callerFunctionID);
}
}
#getQueueByName(name: string): WorkflowQueue {
const q = wfQueueRunner.wfQueuesByName.get(name);
if (!q) throw new DBOSNotRegisteredError(`Workflow queue '${name}' does is not defined.`);
return q;
}
/**
* DEBUG MODE workflow execution, skipping all the recording
*/
async debugWorkflow<T extends unknown[], R>(wf: Workflow<T, R>, params: WorkflowParams, callerUUID?: string, callerFunctionID?: number, ...args: T): Promise<WorkflowHandle<R>> {
// In debug mode, we must have a specific workflow UUID.
if (!params.workflowUUID) {
throw new DBOSDebuggerError("Workflow UUID not found!");
}
const workflowUUID = params.workflowUUID;
const wInfo = this.getWorkflowInfo(wf as Workflow<unknown[], unknown>);
if (wInfo === undefined) {
throw new DBOSDebuggerError("Workflow unregistered! " + wf.name);
}
const wConfig = wInfo.config;
const wCtxt = new WorkflowContextDebug(this, params.parentCtx, workflowUUID, wConfig, wf.name);
// A workflow must have run before.
const wfStatus = await this.systemDatabase.getWorkflowStatus(workflowUUID);
const recordedInputs = await this.systemDatabase.getWorkflowInputs(workflowUUID);
if (!wfStatus || !recordedInputs) {
throw new DBOSDebuggerError("Workflow status or inputs not found! UUID: " + workflowUUID);
}
// Make sure we use the same input.
if (DBOSJSON.stringify(args) !== DBOSJSON.stringify(recordedInputs)) {
throw new DBOSDebuggerError(`Detect different input for the workflow UUID ${workflowUUID}!\n Received: ${DBOSJSON.stringify(args)}\n Original: ${DBOSJSON.stringify(recordedInputs)}`);
}
const workflowPromise: Promise<R> = runWithWorkflowContext(wCtxt, async () => {
return await wf.call(params.configuredInstance, wCtxt, ...args)
.then(async (result) => {
// Check if the result is the same.
const recordedResult = await this.systemDatabase.getWorkflowResult<R>(workflowUUID);
if (result === undefined && !recordedResult) {
return result;
}
if (DBOSJSON.stringify(result) !== DBOSJSON.stringify(recordedResult)) {
this.logger.error(`Detect different output for the workflow UUID ${workflowUUID}!\n Received: ${DBOSJSON.stringify(result)}\n Original: ${DBOSJSON.stringify(recordedResult)}`);
}
return recordedResult; // Always return the recorded result.
});
});
return new InvokedHandle(this.systemDatabase, workflowPromise, workflowUUID, wf.name, callerUUID, callerFunctionID);
}
async transaction<T extends unknown[], R>(txn: Transaction<T, R>, params: WorkflowParams, ...args: T): Promise<R> {
// Create a workflow and call transaction.
const temp_workflow = async (ctxt: WorkflowContext, ...args: T) => {
const ctxtImpl = ctxt as WorkflowContextImpl;
return await ctxtImpl.transaction(txn, params.configuredInstance ?? null, ...args);
};
return (await this.workflow(temp_workflow, {
...params,
tempWfType: TempWorkflowType.transaction,
tempWfName: getRegisteredMethodName(txn),
tempWfClass: getRegisteredMethodClassName(txn),
}, ...args)).getResult();
}
async callTransactionFunction<T extends unknown[], R>(
txn: Transaction<T, R>, clsinst: ConfiguredInstance | null, wfCtx: WorkflowContextImpl, ...args: T
): Promise<R> {
const txnInfo = this.getTransactionInfo(txn as Transaction<unknown[], unknown>);
if (txnInfo === undefined) {
throw new DBOSNotRegisteredError(txn.name);
}
const readOnly = txnInfo.config.readOnly ?? false;
let retryWaitMillis = 1;
const backoffFactor = 1.5;
const maxRetryWaitMs = 2000; // Maximum wait 2 seconds.
const funcId = wfCtx.functionIDGetIncrement();
const span: Span = this.tracer.startSpan(
txn.name,
{
operationUUID: wfCtx.workflowUUID,
operationType: OperationType.TRANSACTION,
authenticatedUser: wfCtx.authenticatedUser,
assumedRole: wfCtx.assumedRole,
authenticatedRoles: wfCtx.authenticatedRoles,
readOnly: readOnly,
isolationLevel: txnInfo.config.isolationLevel,
},
wfCtx.span,
);
while (true) {
let txn_snapshot = "invalid";
const workflowUUID = wfCtx.workflowUUID;
const wrappedTransaction = async (client: UserDatabaseClient): Promise<R> => {
const tCtxt = new TransactionContextImpl(
this.userDatabase.getName(), client, wfCtx,
span, this.logger, funcId, txn.name);
// If the UUID is preset, it is possible this execution previously happened. Check, and return its original result if it did.
// Note: It is possible to retrieve a generated ID from a workflow handle, run a concurrent execution, and cause trouble for yourself. We recommend against this.
if (wfCtx.presetUUID) {
const check: BufferedResult = await wfCtx.checkTxExecution<R>(client, funcId);
txn_snapshot = check.txn_snapshot;
if (check.output !== dbosNull) {
tCtxt.span.setAttribute("cached", true);
tCtxt.span.setStatus({ code: SpanStatusCode.OK });
this.tracer.endSpan(tCtxt.span);
return check.output as R;
}
} else {
// Collect snapshot information for read-only transactions and non-preset UUID transactions, if not already collected above
txn_snapshot = await wfCtx.retrieveTxSnapshot(client);
}
// For non-read-only transactions, flush the result buffer.
if (!readOnly) {
await wfCtx.flushResultBuffer(client);
}
// Execute the user's transaction.
let cresult: R | undefined;
if (txnInfo.registration.passContext) {
await runWithTransactionContext(tCtxt, async ()=> {
cresult = await txn.call(clsinst, tCtxt, ...args);
});
}
else {
await runWithTransactionContext(tCtxt, async ()=> {
const tf = txn as unknown as (...args: T)=>Promise<R>;
cresult = await tf.call(clsinst, ...args);
});
}
const result = cresult!
// Record the execution, commit, and return.
if (readOnly) {
// Buffer the output of read-only transactions instead of synchronously writing it.
const readOutput: BufferedResult = {
output: result,
txn_snapshot: txn_snapshot,
created_at: Date.now(),
}
wfCtx.resultBuffer.set(funcId, readOutput);
} else {
try {
// Synchronously record the output of write transactions and obtain the transaction ID.
const pg_txn_id = await wfCtx.recordOutputTx<R>(client, funcId, txn_snapshot, result);
tCtxt.span.setAttribute("pg_txn_id", pg_txn_id);
wfCtx.resultBuffer.clear();
} catch (error) {
if (this.userDatabase.isFailedSqlTransactionError(error)) {
this.logger.error(`Postgres aborted the ${txn.name} @Transaction of Workflow ${workflowUUID}, but the function did not raise an exception. Please ensure that the @Transaction method raises an exception if the database transaction is aborted.`);
throw new DBOSFailedSqlTransactionError(workflowUUID, txn.name)
} else {
throw error;
}
}
}
return result;
};
try {
const result = await this.userDatabase.transaction(wrappedTransaction, txnInfo.config);
span.setStatus({ code: SpanStatusCode.OK });
this.tracer.endSpan(span);
return result;
} catch (err) {
if (this.userDatabase.isRetriableTransactionError(err)) {
// serialization_failure in PostgreSQL
span.addEvent("TXN SERIALIZATION FAILURE", { "retryWaitMillis": retryWaitMillis }, performance.now());
// Retry serialization failures.
await sleepms(retryWaitMillis);
retryWaitMillis *= backoffFactor;
retryWaitMillis = retryWaitMillis < maxRetryWaitMs ? retryWaitMillis : maxRetryWaitMs;
continue;
}
// Record and throw other errors.
const e: Error = err as Error;
await this.userDatabase.transaction(async (client: UserDatabaseClient) => {
await wfCtx.flushResultBuffer(client);
await wfCtx.recordErrorTx(client, funcId, txn_snapshot, e);
}, { isolationLevel: IsolationLevel.ReadCommitted });
wfCtx.resultBuffer.clear();
span.setStatus({ code: SpanStatusCode.ERROR, message: e.message });
this.tracer.endSpan(span);
throw err;
}
}
}
async procedure<R>(proc: StoredProcedure<R>, params: WorkflowParams, ...args: unknown[]): Promise<R> {
// Create a workflow and call procedure.
const temp_workflow = async (ctxt: WorkflowContext, ...args: unknown[]) => {
const ctxtImpl = ctxt as WorkflowContextImpl;