|
1
|
import { |
|
2
|
DistributedTransaction, |
|
3
|
DistributedTransactionEvents, |
|
4
|
DistributedTransactionType, |
|
5
|
TransactionHandlerType, |
|
6
|
TransactionStep, |
|
7
|
WorkflowScheduler, |
|
8
|
} from "@medusajs/framework/orchestration" |
|
9
|
import { |
|
10
|
ContainerLike, |
|
11
|
Context, |
|
12
|
Logger, |
|
13
|
MedusaContainer, |
|
14
|
} from "@medusajs/framework/types" |
|
15
|
import { |
|
16
|
isString, |
|
17
|
MedusaError, |
|
18
|
promiseAll, |
|
19
|
TransactionState, |
|
20
|
} from "@medusajs/framework/utils" |
|
21
|
import { |
|
22
|
FlowCancelOptions, |
|
23
|
FlowRunOptions, |
|
24
|
MedusaWorkflow, |
|
25
|
resolveValue, |
|
26
|
ReturnWorkflow, |
|
27
|
} from "@medusajs/framework/workflows-sdk" |
|
28
|
import Redis from "ioredis" |
|
29
|
import { ulid } from "ulid" |
|
30
|
import type { RedisDistributedTransactionStorage } from "../utils" |
|
31
|
|
|
32
|
export type WorkflowOrchestratorRunOptions<T> = Omit< |
|
33
|
FlowRunOptions<T>, |
|
34
|
"container" |
|
35
|
> & { |
|
36
|
transactionId?: string |
|
37
|
runId?: string |
|
38
|
container?: ContainerLike |
|
39
|
} |
|
40
|
|
|
41
|
export type WorkflowOrchestratorCancelOptions = Omit< |
|
42
|
FlowCancelOptions, |
|
43
|
"transaction" | "transactionId" | "container" |
|
44
|
> & { |
|
45
|
transactionId: string |
|
46
|
runId?: string |
|
47
|
container?: ContainerLike |
|
48
|
} |
|
49
|
|
|
50
|
type RegisterStepSuccessOptions<T> = Omit< |
|
51
|
WorkflowOrchestratorRunOptions<T>, |
|
52
|
"transactionId" | "input" |
|
53
|
> |
|
54
|
|
|
55
|
type RegisterStepFailureOptions<T> = Omit< |
|
56
|
WorkflowOrchestratorRunOptions<T>, |
|
57
|
"transactionId" | "input" |
|
58
|
> & { |
|
59
|
forcePermanentFailure?: boolean |
|
60
|
} |
|
61
|
|
|
62
|
type RetryStepOptions<T> = Omit< |
|
63
|
WorkflowOrchestratorRunOptions<T>, |
|
64
|
"transactionId" | "input" | "resultFrom" |
|
65
|
> |
|
66
|
|
|
67
|
type IdempotencyKeyParts = { |
|
68
|
workflowId: string |
|
69
|
transactionId: string |
|
70
|
stepId: string |
|
71
|
action: "invoke" | "compensate" |
|
72
|
} |
|
73
|
|
|
74
|
type NotifyOptions = { |
|
75
|
eventType: keyof DistributedTransactionEvents |
|
76
|
isFlowAsync: boolean |
|
77
|
workflowId: string |
|
78
|
transactionId?: string |
|
79
|
step?: TransactionStep |
|
80
|
response?: unknown |
|
81
|
result?: unknown |
|
82
|
errors?: unknown[] |
|
83
|
state?: TransactionState |
|
84
|
} |
|
85
|
|
|
86
|
type WorkflowId = string |
|
87
|
type TransactionId = string |
|
88
|
|
|
89
|
type SubscriberHandler = { |
|
90
|
(input: NotifyOptions): void |
|
91
|
} & { |
|
92
|
_id?: string |
|
93
|
} |
|
94
|
|
|
95
|
type SubscribeOptions = { |
|
96
|
workflowId: string |
|
97
|
transactionId?: string |
|
98
|
subscriber: SubscriberHandler |
|
99
|
subscriberId?: string |
|
100
|
} |
|
101
|
|
|
102
|
type UnsubscribeOptions = { |
|
103
|
workflowId: string |
|
104
|
transactionId?: string |
|
105
|
subscriberOrId: string | SubscriberHandler |
|
106
|
} |
|
107
|
|
|
108
|
type TransactionSubscribers = Map<TransactionId, SubscriberHandler[]> |
|
109
|
type Subscribers = Map<WorkflowId, TransactionSubscribers> |
|
110
|
|
|
111
|
const AnySubscriber = "any" |
|
112
|
|
|
113
|
export class WorkflowOrchestratorService { |
|
114
|
private instanceId = ulid() |
|
115
|
protected redisPublisher: Redis |
|
116
|
protected redisSubscriber: Redis |
|
117
|
protected container_: MedusaContainer |
|
118
|
private static subscribers: Subscribers = new Map() |
|
119
|
|
|
120
|
readonly #logger: Logger |
|
121
|
|
|
122
|
protected redisDistributedTransactionStorage_: RedisDistributedTransactionStorage |
|
123
|
|
|
124
|
constructor({ |
|
125
|
dataLoaderOnly, |
|
126
|
redisDistributedTransactionStorage, |
|
127
|
redisPublisher, |
|
128
|
redisSubscriber, |
|
129
|
sharedContainer, |
|
130
|
}: { |
|
131
|
dataLoaderOnly: boolean |
|
132
|
redisDistributedTransactionStorage: RedisDistributedTransactionStorage |
|
133
|
workflowOrchestratorService: WorkflowOrchestratorService |
|
134
|
redisPublisher: Redis |
|
135
|
redisSubscriber: Redis |
|
136
|
sharedContainer: MedusaContainer |
|
137
|
}) { |
|
138
|
this.container_ = sharedContainer |
|
139
|
this.redisPublisher = redisPublisher |
|
140
|
this.redisSubscriber = redisSubscriber |
|
141
|
|
|
142
|
this.#logger = |
|
143
|
this.container_.resolve("logger", { allowUnregistered: true }) ?? console |
|
144
|
|
|
145
|
redisDistributedTransactionStorage.setWorkflowOrchestratorService(this) |
|
146
|
|
|
147
|
if (!dataLoaderOnly) { |
|
148
|
DistributedTransaction.setStorage(redisDistributedTransactionStorage) |
|
149
|
WorkflowScheduler.setStorage(redisDistributedTransactionStorage) |
|
150
|
} |
|
151
|
|
|
152
|
this.redisDistributedTransactionStorage_ = |
|
153
|
redisDistributedTransactionStorage |
|
154
|
|
|
155
|
this.redisSubscriber.on("message", async (channel, message) => { |
|
156
|
const workflowId = channel.split(":")[1] |
|
157
|
if (!WorkflowOrchestratorService.subscribers.has(workflowId)) return |
|
158
|
|
|
159
|
try { |
|
160
|
const { instanceId, data } = JSON.parse(message) |
|
161
|
await this.notify(data, false, instanceId) |
|
162
|
} catch (error) { |
|
163
|
this.#logger.error(`Failed to process Redis message: ${error}`) |
|
164
|
} |
|
165
|
}) |
|
166
|
} |
|
167
|
|
|
168
|
async onApplicationShutdown() { |
|
169
|
await this.redisDistributedTransactionStorage_.onApplicationShutdown() |
|
170
|
} |
|
171
|
|
|
172
|
async onApplicationPrepareShutdown() { |
|
173
|
// eslint-disable-next-line max-len |
|
174
|
await this.redisDistributedTransactionStorage_.onApplicationPrepareShutdown() |
|
175
|
} |
|
176
|
|
|
177
|
async onApplicationStart() { |
|
178
|
await this.redisDistributedTransactionStorage_.onApplicationStart() |
|
179
|
} |
|
180
|
|
|
181
|
private async triggerParentStep(transaction, result, errors) { |
|
182
|
const metadata = transaction.flow.metadata |
|
183
|
const { parentStepIdempotencyKey, cancelingFromParentStep } = metadata ?? {} |
|
184
|
|
|
185
|
if (cancelingFromParentStep) { |
|
186
|
/** |
|
187
|
* If the sub workflow is cancelling from a parent step, we don't want to trigger the parent |
|
188
|
* step. |
|
189
|
*/ |
|
190
|
return |
|
191
|
} |
|
192
|
|
|
193
|
if (parentStepIdempotencyKey) { |
|
194
|
const hasFailed = [ |
|
195
|
TransactionState.REVERTED, |
|
196
|
TransactionState.FAILED, |
|
197
|
].includes(transaction.flow.state) |
|
198
|
|
|
199
|
if (hasFailed) { |
|
200
|
await this.setStepFailure({ |
|
201
|
idempotencyKey: parentStepIdempotencyKey, |
|
202
|
stepResponse: errors, |
|
203
|
options: { |
|
204
|
logOnError: true, |
|
205
|
}, |
|
206
|
}) |
|
207
|
} else { |
|
208
|
await this.setStepSuccess({ |
|
209
|
idempotencyKey: parentStepIdempotencyKey, |
|
210
|
stepResponse: result, |
|
211
|
options: { |
|
212
|
logOnError: true, |
|
213
|
}, |
|
214
|
}) |
|
215
|
} |
|
216
|
} |
|
217
|
} |
|
218
|
|
|
219
|
async run<T = unknown>( |
|
220
|
workflowIdOrWorkflow: string | ReturnWorkflow<any, any, any>, |
|
221
|
options?: WorkflowOrchestratorRunOptions<T> |
|
222
|
) { |
|
223
|
const { |
|
224
|
input, |
|
225
|
transactionId, |
|
226
|
resultFrom, |
|
227
|
logOnError, |
|
228
|
events: eventHandlers, |
|
229
|
container, |
|
230
|
} = options ?? {} |
|
231
|
|
|
232
|
let { throwOnError, context } = options ?? {} |
|
233
|
|
|
234
|
throwOnError ??= true |
|
235
|
context ??= {} |
|
236
|
context.transactionId = transactionId ?? "auto-" + ulid() |
|
237
|
const workflowId = isString(workflowIdOrWorkflow) |
|
238
|
? workflowIdOrWorkflow |
|
239
|
: workflowIdOrWorkflow.getName() |
|
240
|
|
|
241
|
if (!workflowId) { |
|
242
|
throw new MedusaError( |
|
243
|
MedusaError.Types.NOT_FOUND, |
|
244
|
`Workflow ID is required` |
|
245
|
) |
|
246
|
} |
|
247
|
|
|
248
|
const events: FlowRunOptions["events"] = this.buildWorkflowEvents({ |
|
249
|
customEventHandlers: eventHandlers, |
|
250
|
workflowId, |
|
251
|
transactionId: context.transactionId, |
|
252
|
}) |
|
253
|
|
|
254
|
const exportedWorkflow = MedusaWorkflow.getWorkflow(workflowId) |
|
255
|
if (!exportedWorkflow) { |
|
256
|
throw new MedusaError( |
|
257
|
MedusaError.Types.NOT_FOUND, |
|
258
|
`Workflow with id "${workflowId}" not found.` |
|
259
|
) |
|
260
|
} |
|
261
|
|
|
262
|
const { onFinish, ...restEvents } = events |
|
263
|
const originalOnFinishHandler = events.onFinish! |
|
264
|
|
|
265
|
const ret = await exportedWorkflow.run({ |
|
266
|
input, |
|
267
|
throwOnError: false, |
|
268
|
logOnError, |
|
269
|
resultFrom, |
|
270
|
context, |
|
271
|
events: restEvents, |
|
272
|
container: container ?? this.container_, |
|
273
|
}) |
|
274
|
|
|
275
|
const hasFinished = ret.transaction.hasFinished() |
|
276
|
const metadata = ret.transaction.getFlow().metadata |
|
277
|
const { parentStepIdempotencyKey } = metadata ?? {} |
|
278
|
|
|
279
|
const hasFailed = [ |
|
280
|
TransactionState.REVERTED, |
|
281
|
TransactionState.FAILED, |
|
282
|
].includes(ret.transaction.getFlow().state) |
|
283
|
|
|
284
|
const acknowledgement = { |
|
285
|
transactionId: context.transactionId, |
|
286
|
workflowId: workflowId, |
|
287
|
parentStepIdempotencyKey, |
|
288
|
hasFinished, |
|
289
|
hasFailed, |
|
290
|
} |
|
291
|
|
|
292
|
if (hasFinished) { |
|
293
|
const { result, errors } = ret |
|
294
|
|
|
295
|
await originalOnFinishHandler({ |
|
296
|
transaction: ret.transaction, |
|
297
|
result, |
|
298
|
errors, |
|
299
|
}) |
|
300
|
|
|
301
|
await this.triggerParentStep(ret.transaction, result, errors) |
|
302
|
} |
|
303
|
|
|
304
|
if (throwOnError && (ret.thrownError || ret.errors?.length)) { |
|
305
|
if (ret.thrownError) { |
|
306
|
throw ret.thrownError |
|
307
|
} |
|
308
|
|
|
309
|
throw ret.errors[0].error |
|
310
|
} |
|
311
|
|
|
312
|
return { acknowledgement, ...ret } |
|
313
|
} |
|
314
|
|
|
315
|
async cancel( |
|
316
|
workflowIdOrWorkflow: string | ReturnWorkflow<any, any, any>, |
|
317
|
options?: WorkflowOrchestratorCancelOptions |
|
318
|
) { |
|
319
|
const { |
|
320
|
transactionId, |
|
321
|
logOnError, |
|
322
|
events: eventHandlers, |
|
323
|
container, |
|
324
|
} = options ?? {} |
|
325
|
|
|
326
|
let { throwOnError, context } = options ?? {} |
|
327
|
|
|
328
|
throwOnError ??= true |
|
329
|
context ??= {} |
|
330
|
|
|
331
|
const workflowId = isString(workflowIdOrWorkflow) |
|
332
|
? workflowIdOrWorkflow |
|
333
|
: workflowIdOrWorkflow.getName() |
|
334
|
|
|
335
|
if (!workflowId) { |
|
336
|
throw new Error("Workflow ID is required") |
|
337
|
} |
|
338
|
|
|
339
|
if (!transactionId) { |
|
340
|
throw new Error("Transaction ID is required") |
|
341
|
} |
|
342
|
|
|
343
|
const exportedWorkflow = MedusaWorkflow.getWorkflow(workflowId) |
|
344
|
if (!exportedWorkflow) { |
|
345
|
throw new MedusaError( |
|
346
|
MedusaError.Types.NOT_FOUND, |
|
347
|
`Workflow with id "${workflowId}" not found.` |
|
348
|
) |
|
349
|
} |
|
350
|
|
|
351
|
const transaction = await this.getRunningTransaction( |
|
352
|
workflowId, |
|
353
|
transactionId, |
|
354
|
{ ...options, isCancelling: true } |
|
355
|
) |
|
356
|
if (!transaction) { |
|
357
|
if (!throwOnError) { |
|
358
|
return { |
|
359
|
acknowledgement: { |
|
360
|
transactionId, |
|
361
|
workflowId, |
|
362
|
exists: false, |
|
363
|
}, |
|
364
|
} |
|
365
|
} |
|
366
|
throw new Error("Transaction not found") |
|
367
|
} |
|
368
|
|
|
369
|
const events: FlowRunOptions["events"] = this.buildWorkflowEvents({ |
|
370
|
customEventHandlers: eventHandlers, |
|
371
|
workflowId, |
|
372
|
transactionId: transactionId, |
|
373
|
}) |
|
374
|
|
|
375
|
const { onFinish, ...restEvents } = events |
|
376
|
const originalOnFinishHandler = events.onFinish! |
|
377
|
|
|
378
|
const ret = await exportedWorkflow.cancel({ |
|
379
|
transaction, |
|
380
|
throwOnError: false, |
|
381
|
logOnError, |
|
382
|
context, |
|
383
|
events: restEvents, |
|
384
|
container: container ?? this.container_, |
|
385
|
}) |
|
386
|
|
|
387
|
const hasFinished = ret.transaction.hasFinished() |
|
388
|
const metadata = ret.transaction.getFlow().metadata |
|
389
|
const { parentStepIdempotencyKey } = metadata ?? {} |
|
390
|
|
|
391
|
const transactionState = ret.transaction.getFlow().state |
|
392
|
const hasFailed = [TransactionState.FAILED].includes(transactionState) |
|
393
|
|
|
394
|
const acknowledgement = { |
|
395
|
transactionId: transaction.transactionId, |
|
396
|
workflowId: workflowId, |
|
397
|
parentStepIdempotencyKey, |
|
398
|
hasFinished, |
|
399
|
hasFailed, |
|
400
|
exists: true, |
|
401
|
} |
|
402
|
|
|
403
|
if (hasFinished) { |
|
404
|
const { result, errors } = ret |
|
405
|
|
|
406
|
await originalOnFinishHandler({ |
|
407
|
transaction: ret.transaction, |
|
408
|
result, |
|
409
|
errors, |
|
410
|
}) |
|
411
|
|
|
412
|
await this.triggerParentStep(ret.transaction, result, errors) |
|
413
|
} |
|
414
|
|
|
415
|
if (throwOnError && (ret.thrownError || ret.errors?.length)) { |
|
416
|
if (ret.thrownError) { |
|
417
|
throw ret.thrownError |
|
418
|
} |
|
419
|
|
|
420
|
throw ret.errors[0].error |
|
421
|
} |
|
422
|
|
|
423
|
return { acknowledgement, ...ret } |
|
424
|
} |
|
425
|
|
|
426
|
async getRunningTransaction( |
|
427
|
workflowId: string, |
|
428
|
transactionId: string, |
|
429
|
context?: Context |
|
430
|
): Promise<DistributedTransactionType> { |
|
431
|
if (!workflowId) { |
|
432
|
throw new Error("Workflow ID is required") |
|
433
|
} |
|
434
|
|
|
435
|
if (!transactionId) { |
|
436
|
throw new Error("TransactionId ID is required") |
|
437
|
} |
|
438
|
|
|
439
|
context ??= {} |
|
440
|
|
|
441
|
const exportedWorkflow: any = MedusaWorkflow.getWorkflow(workflowId) |
|
442
|
if (!exportedWorkflow) { |
|
443
|
throw new Error(`Workflow with id "${workflowId}" not found.`) |
|
444
|
} |
|
445
|
|
|
446
|
const flow = exportedWorkflow() |
|
447
|
|
|
448
|
const transaction = await flow.getRunningTransaction(transactionId, context) |
|
449
|
|
|
450
|
return transaction |
|
451
|
} |
|
452
|
|
|
453
|
async retryStep<T = unknown>({ |
|
454
|
idempotencyKey, |
|
455
|
options, |
|
456
|
}: { |
|
457
|
idempotencyKey: string | IdempotencyKeyParts |
|
458
|
options?: RetryStepOptions<T> |
|
459
|
}) { |
|
460
|
const { |
|
461
|
context, |
|
462
|
logOnError, |
|
463
|
container, |
|
464
|
events: eventHandlers, |
|
465
|
} = options ?? {} |
|
466
|
|
|
467
|
let { throwOnError } = options ?? {} |
|
468
|
throwOnError ??= true |
|
469
|
|
|
470
|
const [idempotencyKey_, { workflowId, transactionId }] = |
|
471
|
this.buildIdempotencyKeyAndParts(idempotencyKey) |
|
472
|
|
|
473
|
const exportedWorkflow: any = MedusaWorkflow.getWorkflow(workflowId) |
|
474
|
if (!exportedWorkflow) { |
|
475
|
throw new Error(`Workflow with id "${workflowId}" not found.`) |
|
476
|
} |
|
477
|
|
|
478
|
const events = this.buildWorkflowEvents({ |
|
479
|
customEventHandlers: eventHandlers, |
|
480
|
transactionId, |
|
481
|
workflowId, |
|
482
|
}) |
|
483
|
|
|
484
|
const { onFinish, ...restEvents } = events |
|
485
|
const originalOnFinishHandler = events.onFinish! |
|
486
|
|
|
487
|
const ret = await exportedWorkflow.retryStep({ |
|
488
|
idempotencyKey: idempotencyKey_, |
|
489
|
context, |
|
490
|
throwOnError: false, |
|
491
|
logOnError, |
|
492
|
events: restEvents, |
|
493
|
container: container ?? this.container_, |
|
494
|
}) |
|
495
|
|
|
496
|
if (ret.transaction.hasFinished()) { |
|
497
|
const { result, errors } = ret |
|
498
|
|
|
499
|
await originalOnFinishHandler({ |
|
500
|
transaction: ret.transaction, |
|
501
|
result, |
|
502
|
errors, |
|
503
|
}) |
|
504
|
|
|
505
|
await this.triggerParentStep(ret.transaction, result, errors) |
|
506
|
} |
|
507
|
|
|
508
|
if (throwOnError && (ret.thrownError || ret.errors?.length)) { |
|
509
|
if (ret.thrownError) { |
|
510
|
throw ret.thrownError |
|
511
|
} |
|
512
|
|
|
513
|
throw ret.errors[0].error |
|
514
|
} |
|
515
|
|
|
516
|
return ret |
|
517
|
} |
|
518
|
|
|
519
|
async setStepSuccess<T = unknown>({ |
|
520
|
idempotencyKey, |
|
521
|
stepResponse, |
|
522
|
options, |
|
523
|
}: { |
|
524
|
idempotencyKey: string | IdempotencyKeyParts |
|
525
|
stepResponse: unknown |
|
526
|
options?: RegisterStepSuccessOptions<T> |
|
527
|
}) { |
|
528
|
const { |
|
529
|
context, |
|
530
|
logOnError, |
|
531
|
resultFrom, |
|
532
|
container, |
|
533
|
events: eventHandlers, |
|
534
|
} = options ?? {} |
|
535
|
|
|
536
|
let { throwOnError } = options ?? {} |
|
537
|
throwOnError ??= true |
|
538
|
|
|
539
|
const [idempotencyKey_, { workflowId, transactionId }] = |
|
540
|
this.buildIdempotencyKeyAndParts(idempotencyKey) |
|
541
|
|
|
542
|
const exportedWorkflow: any = MedusaWorkflow.getWorkflow(workflowId) |
|
543
|
if (!exportedWorkflow) { |
|
544
|
throw new Error(`Workflow with id "${workflowId}" not found.`) |
|
545
|
} |
|
546
|
|
|
547
|
const events = this.buildWorkflowEvents({ |
|
548
|
customEventHandlers: eventHandlers, |
|
549
|
transactionId, |
|
550
|
workflowId, |
|
551
|
}) |
|
552
|
|
|
553
|
const { onFinish, ...restEvents } = events |
|
554
|
const originalOnFinishHandler = events.onFinish! |
|
555
|
|
|
556
|
const ret = await exportedWorkflow.registerStepSuccess({ |
|
557
|
idempotencyKey: idempotencyKey_, |
|
558
|
context, |
|
559
|
resultFrom, |
|
560
|
throwOnError: false, |
|
561
|
logOnError, |
|
562
|
events: restEvents, |
|
563
|
response: stepResponse, |
|
564
|
container: container ?? this.container_, |
|
565
|
}) |
|
566
|
|
|
567
|
if (ret.transaction.hasFinished()) { |
|
568
|
const { result, errors } = ret |
|
569
|
|
|
570
|
await originalOnFinishHandler({ |
|
571
|
transaction: ret.transaction, |
|
572
|
result, |
|
573
|
errors, |
|
574
|
}) |
|
575
|
|
|
576
|
await this.triggerParentStep(ret.transaction, result, errors) |
|
577
|
} |
|
578
|
|
|
579
|
if (throwOnError && (ret.thrownError || ret.errors?.length)) { |
|
580
|
if (ret.thrownError) { |
|
581
|
throw ret.thrownError |
|
582
|
} |
|
583
|
|
|
584
|
throw ret.errors[0].error |
|
585
|
} |
|
586
|
|
|
587
|
return ret |
|
588
|
} |
|
589
|
|
|
590
|
async setStepFailure<T = unknown>({ |
|
591
|
idempotencyKey, |
|
592
|
stepResponse, |
|
593
|
options, |
|
594
|
}: { |
|
595
|
idempotencyKey: string | IdempotencyKeyParts |
|
596
|
stepResponse: unknown |
|
597
|
options?: RegisterStepFailureOptions<T> |
|
598
|
}) { |
|
599
|
const { |
|
600
|
context, |
|
601
|
logOnError, |
|
602
|
resultFrom, |
|
603
|
container, |
|
604
|
events: eventHandlers, |
|
605
|
forcePermanentFailure, |
|
606
|
} = options ?? {} |
|
607
|
|
|
608
|
let { throwOnError } = options ?? {} |
|
609
|
throwOnError ??= true |
|
610
|
|
|
611
|
const [idempotencyKey_, { workflowId, transactionId }] = |
|
612
|
this.buildIdempotencyKeyAndParts(idempotencyKey) |
|
613
|
|
|
614
|
const exportedWorkflow: any = MedusaWorkflow.getWorkflow(workflowId) |
|
615
|
if (!exportedWorkflow) { |
|
616
|
throw new Error(`Workflow with id "${workflowId}" not found.`) |
|
617
|
} |
|
618
|
|
|
619
|
const events = this.buildWorkflowEvents({ |
|
620
|
customEventHandlers: eventHandlers, |
|
621
|
transactionId, |
|
622
|
workflowId, |
|
623
|
}) |
|
624
|
|
|
625
|
const { onFinish, ...restEvents } = events |
|
626
|
const originalOnFinishHandler = events.onFinish! |
|
627
|
|
|
628
|
const ret = await exportedWorkflow.registerStepFailure({ |
|
629
|
idempotencyKey: idempotencyKey_, |
|
630
|
context, |
|
631
|
resultFrom, |
|
632
|
throwOnError: false, |
|
633
|
logOnError, |
|
634
|
events: restEvents, |
|
635
|
response: stepResponse, |
|
636
|
container: container ?? this.container_, |
|
637
|
forcePermanentFailure, |
|
638
|
}) |
|
639
|
|
|
640
|
if (ret.transaction.hasFinished()) { |
|
641
|
const { result, errors } = ret |
|
642
|
|
|
643
|
await originalOnFinishHandler({ |
|
644
|
transaction: ret.transaction, |
|
645
|
result, |
|
646
|
errors, |
|
647
|
}) |
|
648
|
|
|
649
|
await this.triggerParentStep(ret.transaction, result, errors) |
|
650
|
} |
|
651
|
|
|
652
|
if (throwOnError && (ret.thrownError || ret.errors?.length)) { |
|
653
|
if (ret.thrownError) { |
|
654
|
throw ret.thrownError |
|
655
|
} |
|
656
|
|
|
657
|
throw ret.errors[0].error |
|
658
|
} |
|
659
|
|
|
660
|
return ret |
|
661
|
} |
|
662
|
|
|
663
|
subscribe({ |
|
664
|
workflowId, |
|
665
|
transactionId, |
|
666
|
subscriber, |
|
667
|
subscriberId, |
|
668
|
}: SubscribeOptions) { |
|
669
|
subscriber._id = subscriberId |
|
670
|
const subscribers = |
|
671
|
WorkflowOrchestratorService.subscribers.get(workflowId) ?? new Map() |
|
672
|
|
|
673
|
// Subscribe instance to redis |
|
674
|
if (!WorkflowOrchestratorService.subscribers.has(workflowId)) { |
|
675
|
void this.redisSubscriber.subscribe(this.getChannelName(workflowId)) |
|
676
|
} |
|
677
|
|
|
678
|
const handlerIndex = (handlers) => { |
|
679
|
return handlers.findIndex( |
|
680
|
(s) => s === subscriber || s._id === subscriberId |
|
681
|
) |
|
682
|
} |
|
683
|
|
|
684
|
if (transactionId) { |
|
685
|
const transactionSubscribers = subscribers.get(transactionId) ?? [] |
|
686
|
const subscriberIndex = handlerIndex(transactionSubscribers) |
|
687
|
if (subscriberIndex !== -1) { |
|
688
|
transactionSubscribers.splice(subscriberIndex, 1) |
|
689
|
} |
|
690
|
|
|
691
|
transactionSubscribers.push(subscriber) |
|
692
|
subscribers.set(transactionId, transactionSubscribers) |
|
693
|
WorkflowOrchestratorService.subscribers.set(workflowId, subscribers) |
|
694
|
return |
|
695
|
} |
|
696
|
|
|
697
|
const workflowSubscribers = subscribers.get(AnySubscriber) ?? [] |
|
698
|
const subscriberIndex = handlerIndex(workflowSubscribers) |
|
699
|
if (subscriberIndex !== -1) { |
|
700
|
workflowSubscribers.splice(subscriberIndex, 1) |
|
701
|
} |
|
702
|
|
|
703
|
workflowSubscribers.push(subscriber) |
|
704
|
subscribers.set(AnySubscriber, workflowSubscribers) |
|
705
|
WorkflowOrchestratorService.subscribers.set(workflowId, subscribers) |
|
706
|
} |
|
707
|
|
|
708
|
unsubscribe({ |
|
709
|
workflowId, |
|
710
|
transactionId, |
|
711
|
subscriberOrId, |
|
712
|
}: UnsubscribeOptions) { |
|
713
|
const subscribers = WorkflowOrchestratorService.subscribers.get(workflowId) |
|
714
|
if (!subscribers) { |
|
715
|
return |
|
716
|
} |
|
717
|
|
|
718
|
const filterSubscribers = (handlers: SubscriberHandler[]) => { |
|
719
|
return handlers.filter((handler) => { |
|
720
|
return handler._id |
|
721
|
? handler._id !== (subscriberOrId as string) |
|
722
|
: handler !== (subscriberOrId as SubscriberHandler) |
|
723
|
}) |
|
724
|
} |
|
725
|
|
|
726
|
if (transactionId) { |
|
727
|
const transactionSubscribers = subscribers.get(transactionId) |
|
728
|
if (transactionSubscribers) { |
|
729
|
const newTransactionSubscribers = filterSubscribers( |
|
730
|
transactionSubscribers |
|
731
|
) |
|
732
|
|
|
733
|
if (newTransactionSubscribers.length) { |
|
734
|
subscribers.set(transactionId, newTransactionSubscribers) |
|
735
|
} else { |
|
736
|
subscribers.delete(transactionId) |
|
737
|
} |
|
738
|
} |
|
739
|
} else { |
|
740
|
const workflowSubscribers = subscribers.get(AnySubscriber) |
|
741
|
if (workflowSubscribers) { |
|
742
|
const newWorkflowSubscribers = filterSubscribers(workflowSubscribers) |
|
743
|
|
|
744
|
if (newWorkflowSubscribers.length) { |
|
745
|
subscribers.set(AnySubscriber, newWorkflowSubscribers) |
|
746
|
} else { |
|
747
|
subscribers.delete(AnySubscriber) |
|
748
|
} |
|
749
|
} |
|
750
|
} |
|
751
|
|
|
752
|
if (subscribers.size === 0) { |
|
753
|
WorkflowOrchestratorService.subscribers.delete(workflowId) |
|
754
|
void this.redisSubscriber.unsubscribe(this.getChannelName(workflowId)) |
|
755
|
} |
|
756
|
} |
|
757
|
|
|
758
|
private async notify( |
|
759
|
options: NotifyOptions, |
|
760
|
publish = true, |
|
761
|
instanceId = this.instanceId |
|
762
|
) { |
|
763
|
if (!publish && instanceId === this.instanceId) { |
|
764
|
return |
|
765
|
} |
|
766
|
|
|
767
|
const { workflowId, isFlowAsync } = options |
|
768
|
|
|
769
|
// Non-blocking Redis publishing |
|
770
|
if (publish && isFlowAsync) { |
|
771
|
setImmediate(async () => { |
|
772
|
try { |
|
773
|
const channel = this.getChannelName(workflowId) |
|
774
|
const message = JSON.stringify({ |
|
775
|
instanceId: this.instanceId, |
|
776
|
data: options, |
|
777
|
}) |
|
778
|
await this.redisPublisher.publish(channel, message) |
|
779
|
} catch (error) { |
|
780
|
this.#logger.error(`Failed to publish to Redis: ${error}`) |
|
781
|
} |
|
782
|
}) |
|
783
|
} |
|
784
|
|
|
785
|
// Process subscribers asynchronously |
|
786
|
setImmediate(() => this.processSubscriberNotifications(options)) |
|
787
|
} |
|
788
|
|
|
789
|
private async processSubscriberNotifications(options: NotifyOptions) { |
|
790
|
const { workflowId, transactionId, eventType } = options |
|
791
|
const subscribers: TransactionSubscribers = |
|
792
|
WorkflowOrchestratorService.subscribers.get(workflowId) ?? new Map() |
|
793
|
|
|
794
|
const notifySubscribersAsync = async (handlers: SubscriberHandler[]) => { |
|
795
|
const promises = handlers.map(async (handler) => { |
|
796
|
try { |
|
797
|
const result = handler(options) as void | Promise<any> |
|
798
|
if (result && typeof result === "object" && "then" in result) { |
|
799
|
await (result as Promise<any>) |
|
800
|
} |
|
801
|
} catch (error) { |
|
802
|
this.#logger.error(`Subscriber error: ${error}`) |
|
803
|
} |
|
804
|
}) |
|
805
|
|
|
806
|
await promiseAll(promises) |
|
807
|
} |
|
808
|
|
|
809
|
const tasks: Promise<void>[] = [] |
|
810
|
|
|
811
|
if (transactionId) { |
|
812
|
const transactionSubscribers = subscribers.get(transactionId) ?? [] |
|
813
|
if (transactionSubscribers.length > 0) { |
|
814
|
tasks.push(notifySubscribersAsync(transactionSubscribers)) |
|
815
|
} |
|
816
|
|
|
817
|
if (eventType === "onFinish") { |
|
818
|
subscribers.delete(transactionId) |
|
819
|
} |
|
820
|
} |
|
821
|
|
|
822
|
const workflowSubscribers = subscribers.get(AnySubscriber) ?? [] |
|
823
|
if (workflowSubscribers.length > 0) { |
|
824
|
tasks.push(notifySubscribersAsync(workflowSubscribers)) |
|
825
|
} |
|
826
|
|
|
827
|
await promiseAll(tasks) |
|
828
|
} |
|
829
|
|
|
830
|
private getChannelName(workflowId: string): string { |
|
831
|
return `orchestrator:${workflowId}` |
|
832
|
} |
|
833
|
|
|
834
|
private buildWorkflowEvents({ |
|
835
|
customEventHandlers, |
|
836
|
workflowId, |
|
837
|
transactionId, |
|
838
|
}): DistributedTransactionEvents { |
|
839
|
const notify = async ({ |
|
840
|
isFlowAsync, |
|
841
|
eventType, |
|
842
|
step, |
|
843
|
result, |
|
844
|
response, |
|
845
|
errors, |
|
846
|
state, |
|
847
|
}: { |
|
848
|
isFlowAsync: boolean |
|
849
|
eventType: keyof DistributedTransactionEvents |
|
850
|
step?: TransactionStep |
|
851
|
response?: unknown |
|
852
|
result?: unknown |
|
853
|
errors?: unknown[] |
|
854
|
state?: TransactionState |
|
855
|
}) => { |
|
856
|
await this.notify({ |
|
857
|
isFlowAsync, |
|
858
|
workflowId, |
|
859
|
transactionId, |
|
860
|
eventType, |
|
861
|
response, |
|
862
|
step, |
|
863
|
result, |
|
864
|
errors, |
|
865
|
state, |
|
866
|
}) |
|
867
|
} |
|
868
|
|
|
869
|
return { |
|
870
|
onTimeout: async ({ transaction }) => { |
|
871
|
customEventHandlers?.onTimeout?.({ transaction }) |
|
872
|
await notify({ |
|
873
|
eventType: "onTimeout", |
|
874
|
isFlowAsync: transaction.getFlow().hasAsyncSteps, |
|
875
|
}) |
|
876
|
}, |
|
877
|
|
|
878
|
onBegin: async ({ transaction }) => { |
|
879
|
customEventHandlers?.onBegin?.({ transaction }) |
|
880
|
await notify({ |
|
881
|
eventType: "onBegin", |
|
882
|
isFlowAsync: transaction.getFlow().hasAsyncSteps, |
|
883
|
}) |
|
884
|
}, |
|
885
|
onResume: async ({ transaction }) => { |
|
886
|
customEventHandlers?.onResume?.({ transaction }) |
|
887
|
await notify({ |
|
888
|
eventType: "onResume", |
|
889
|
isFlowAsync: transaction.getFlow().hasAsyncSteps, |
|
890
|
}) |
|
891
|
}, |
|
892
|
onCompensateBegin: async ({ transaction }) => { |
|
893
|
customEventHandlers?.onCompensateBegin?.({ transaction }) |
|
894
|
await notify({ |
|
895
|
eventType: "onCompensateBegin", |
|
896
|
isFlowAsync: transaction.getFlow().hasAsyncSteps, |
|
897
|
}) |
|
898
|
}, |
|
899
|
onFinish: async ({ transaction, result, errors }) => { |
|
900
|
customEventHandlers?.onFinish?.({ transaction, result, errors }) |
|
901
|
await notify({ |
|
902
|
eventType: "onFinish", |
|
903
|
isFlowAsync: transaction.getFlow().hasAsyncSteps, |
|
904
|
result, |
|
905
|
errors, |
|
906
|
state: transaction.getFlow().state as TransactionState, |
|
907
|
}) |
|
908
|
}, |
|
909
|
|
|
910
|
onStepBegin: async ({ step, transaction }) => { |
|
911
|
customEventHandlers?.onStepBegin?.({ step, transaction }) |
|
912
|
await notify({ |
|
913
|
eventType: "onStepBegin", |
|
914
|
step, |
|
915
|
isFlowAsync: transaction.getFlow().hasAsyncSteps, |
|
916
|
}) |
|
917
|
}, |
|
918
|
onStepSuccess: async ({ step, transaction }) => { |
|
919
|
const stepName = step.definition.action! |
|
920
|
const response = await resolveValue( |
|
921
|
transaction.getContext().invoke[stepName], |
|
922
|
transaction |
|
923
|
) |
|
924
|
customEventHandlers?.onStepSuccess?.({ step, transaction, response }) |
|
925
|
await notify({ |
|
926
|
eventType: "onStepSuccess", |
|
927
|
step, |
|
928
|
response, |
|
929
|
isFlowAsync: transaction.getFlow().hasAsyncSteps, |
|
930
|
}) |
|
931
|
}, |
|
932
|
onStepFailure: async ({ step, transaction }) => { |
|
933
|
const stepName = step.definition.action! |
|
934
|
const errors = transaction |
|
935
|
.getErrors(TransactionHandlerType.INVOKE) |
|
936
|
.filter((err) => err.action === stepName) |
|
937
|
|
|
938
|
customEventHandlers?.onStepFailure?.({ step, transaction, errors }) |
|
939
|
await notify({ |
|
940
|
eventType: "onStepFailure", |
|
941
|
step, |
|
942
|
errors, |
|
943
|
isFlowAsync: transaction.getFlow().hasAsyncSteps, |
|
944
|
}) |
|
945
|
}, |
|
946
|
onStepAwaiting: async ({ step, transaction }) => { |
|
947
|
customEventHandlers?.onStepAwaiting?.({ step, transaction }) |
|
948
|
|
|
949
|
await notify({ |
|
950
|
eventType: "onStepAwaiting", |
|
951
|
step, |
|
952
|
isFlowAsync: transaction.getFlow().hasAsyncSteps, |
|
953
|
}) |
|
954
|
}, |
|
955
|
|
|
956
|
onCompensateStepSuccess: async ({ step, transaction }) => { |
|
957
|
const stepName = step.definition.action! |
|
958
|
const response = transaction.getContext().compensate[stepName] |
|
959
|
customEventHandlers?.onCompensateStepSuccess?.({ |
|
960
|
step, |
|
961
|
transaction, |
|
962
|
response, |
|
963
|
}) |
|
964
|
|
|
965
|
await notify({ |
|
966
|
eventType: "onCompensateStepSuccess", |
|
967
|
step, |
|
968
|
response, |
|
969
|
isFlowAsync: transaction.getFlow().hasAsyncSteps, |
|
970
|
}) |
|
971
|
}, |
|
972
|
onCompensateStepFailure: async ({ step, transaction }) => { |
|
973
|
const stepName = step.definition.action! |
|
974
|
const errors = transaction |
|
975
|
.getErrors(TransactionHandlerType.COMPENSATE) |
|
976
|
.filter((err) => err.action === stepName) |
|
977
|
|
|
978
|
customEventHandlers?.onStepFailure?.({ step, transaction, errors }) |
|
979
|
|
|
980
|
await notify({ |
|
981
|
eventType: "onCompensateStepFailure", |
|
982
|
step, |
|
983
|
errors, |
|
984
|
isFlowAsync: transaction.getFlow().hasAsyncSteps, |
|
985
|
}) |
|
986
|
}, |
|
987
|
} |
|
988
|
} |
|
989
|
|
|
990
|
private buildIdempotencyKeyAndParts( |
|
991
|
idempotencyKey: string | IdempotencyKeyParts |
|
992
|
): [string, IdempotencyKeyParts] { |
|
993
|
const parts: IdempotencyKeyParts = { |
|
994
|
workflowId: "", |
|
995
|
transactionId: "", |
|
996
|
stepId: "", |
|
997
|
action: "invoke", |
|
998
|
} |
|
999
|
let idempotencyKey_ = idempotencyKey as string |
|
1000
|
|
|
1001
|
const setParts = (workflowId, transactionId, stepId, action) => { |
|
1002
|
parts.workflowId = workflowId |
|
1003
|
parts.transactionId = transactionId |
|
1004
|
parts.stepId = stepId |
|
1005
|
parts.action = action |
|
1006
|
} |
|
1007
|
|
|
1008
|
if (!isString(idempotencyKey)) { |
|
1009
|
const { workflowId, transactionId, stepId, action } = |
|
1010
|
idempotencyKey as IdempotencyKeyParts |
|
1011
|
idempotencyKey_ = [workflowId, transactionId, stepId, action].join(":") |
|
1012
|
setParts(workflowId, transactionId, stepId, action) |
|
1013
|
} else { |
|
1014
|
const [workflowId, transactionId, stepId, action] = |
|
1015
|
idempotencyKey_.split(":") |
|
1016
|
setParts(workflowId, transactionId, stepId, action) |
|
1017
|
} |
|
1018
|
|
|
1019
|
return [idempotencyKey_, parts] |
|
1020
|
} |
|
1021
|
} |