feat: run nested async workflows (#9119)

This commit is contained in:
Carlos R. L. Rodrigues
2024-09-16 10:06:45 -03:00
committed by GitHub
parent 0bcdcccbe2
commit ef8dc4087e
23 changed files with 295 additions and 100 deletions

View File

@@ -11,6 +11,7 @@ import {
InjectSharedContext,
MedusaContext,
MedusaError,
TransactionState,
isString,
} from "@medusajs/utils"
import {
@@ -97,6 +98,29 @@ export class WorkflowOrchestratorService {
WorkflowScheduler.setStorage(inMemoryDistributedTransactionStorage)
}
private async triggerParentStep(transaction, result) {
const metadata = transaction.flow.metadata
const { parentStepIdempotencyKey } = metadata ?? {}
if (parentStepIdempotencyKey) {
const hasFailed = [
TransactionState.REVERTED,
TransactionState.FAILED,
].includes(transaction.flow.state)
if (hasFailed) {
await this.setStepFailure({
idempotencyKey: parentStepIdempotencyKey,
stepResponse: result,
})
} else {
await this.setStepSuccess({
idempotencyKey: parentStepIdempotencyKey,
stepResponse: result,
})
}
}
}
@InjectSharedContext()
async run<T = unknown>(
workflowIdOrWorkflow: string | ReturnWorkflow<any, any, any>,
@@ -155,14 +179,25 @@ export class WorkflowOrchestratorService {
events,
})
// TODO: temporary
const hasFinished = ret.transaction.hasFinished()
const metadata = ret.transaction.getFlow().metadata
const { parentStepIdempotencyKey } = metadata ?? {}
const hasFailed = [
TransactionState.REVERTED,
TransactionState.FAILED,
].includes(ret.transaction.getFlow().state)
const acknowledgement = {
transactionId: context.transactionId,
workflowId: workflowId,
parentStepIdempotencyKey,
hasFinished,
hasFailed,
}
if (ret.transaction.hasFinished()) {
const { result, errors } = ret
this.notify({
eventType: "onFinish",
workflowId,
@@ -170,6 +205,8 @@ export class WorkflowOrchestratorService {
result,
errors,
})
await this.triggerParentStep(ret.transaction, result)
}
return { acknowledgement, ...ret }
@@ -261,6 +298,7 @@ export class WorkflowOrchestratorService {
if (ret.transaction.hasFinished()) {
const { result, errors } = ret
this.notify({
eventType: "onFinish",
workflowId,
@@ -268,6 +306,8 @@ export class WorkflowOrchestratorService {
result,
errors,
})
await this.triggerParentStep(ret.transaction, result)
}
return ret
@@ -325,6 +365,7 @@ export class WorkflowOrchestratorService {
if (ret.transaction.hasFinished()) {
const { result, errors } = ret
this.notify({
eventType: "onFinish",
workflowId,
@@ -332,6 +373,8 @@ export class WorkflowOrchestratorService {
result,
errors,
})
await this.triggerParentStep(ret.transaction, result)
}
return ret