Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(medusa, orchestration, utils, workflows-sdk): add transaction options support and cleanup #6020

Merged
merged 5 commits into from
Jan 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/mean-lamps-lie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@medusajs/medusa": patch
"@medusajs/orchestration": patch
"@medusajs/utils": patch
"@medusajs/workflows-sdk": patch
---

chore(medusa, orchestration, utils, workflows-sdk): add transaction options support and cleanup
2 changes: 1 addition & 1 deletion packages/medusa/src/loaders/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ async function loadLegacyModulesEntities(configModules, container) {
for (const [moduleName, moduleConfig] of Object.entries(configModules)) {
const definition = ModulesDefinition[moduleName]

if (!definition.isLegacy) {
if (!definition?.isLegacy) {
continue
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import {
TransactionHandlerType,
TransactionModelOptions,
TransactionState,
TransactionStepStatus,
TransactionStepsDefinition,
TransactionStepStatus,
} from "./types"

import { MedusaError, promiseAll } from "@medusajs/utils"
Expand Down Expand Up @@ -61,6 +61,11 @@ export class TransactionOrchestrator extends EventEmitter {
public static getKeyName(...params: string[]): string {
return params.join(this.SEPARATOR)
}

public getOptions(): TransactionModelOptions {
return this.options ?? {}
}

private getPreviousStep(flow: TransactionFlow, step: TransactionStep) {
const id = step.id.split(".")
id.pop()
Expand Down Expand Up @@ -465,7 +470,7 @@ export class TransactionOrchestrator extends EventEmitter {
if (flow.options?.retentionTime == undefined) {
await transaction.deleteCheckpoint()
} else {
await transaction.archiveCheckpoint()
await transaction.saveCheckpoint()
}

this.emit(DistributedTransactionEvent.FINISH, { transaction })
Expand Down
20 changes: 19 additions & 1 deletion packages/orchestration/src/workflow/local-workflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
DistributedTransaction,
DistributedTransactionEvent,
DistributedTransactionEvents,
TransactionModelOptions,
TransactionOrchestrator,
TransactionStepsDefinition,
} from "../transaction"
Expand All @@ -24,6 +25,7 @@ export class LocalWorkflow {
protected container: MedusaContainer
protected workflowId: string
protected flow: OrchestratorBuilder
protected customOptions: Partial<TransactionModelOptions> = {}
protected workflow: WorkflowDefinition
protected handlers: Map<string, StepHandler>

Expand Down Expand Up @@ -64,10 +66,21 @@ export class LocalWorkflow {
protected commit() {
const finalFlow = this.flow.build()

const globalWorkflow = WorkflowManager.getWorkflow(this.workflowId)
const customOptions = {
...globalWorkflow?.options,
...this.customOptions,
}

this.workflow = {
id: this.workflowId,
flow_: finalFlow,
orchestrator: new TransactionOrchestrator(this.workflowId, finalFlow),
orchestrator: new TransactionOrchestrator(
this.workflowId,
finalFlow,
customOptions
),
options: customOptions,
handler: WorkflowManager.buildHandlers(this.handlers),
handlers_: this.handlers,
}
Expand Down Expand Up @@ -361,6 +374,11 @@ export class LocalWorkflow {
return transaction
}

setOptions(options: Partial<TransactionModelOptions>) {
this.customOptions = options
return this
}

addAction(
action: string,
handler: StepHandler,
Expand Down
14 changes: 12 additions & 2 deletions packages/orchestration/src/workflow/workflow-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
OrchestratorBuilder,
TransactionHandlerType,
TransactionMetadata,
TransactionModelOptions,
TransactionOrchestrator,
TransactionStepHandler,
TransactionStepsDefinition,
Expand All @@ -21,6 +22,7 @@ export interface WorkflowDefinition {
string,
{ invoke: WorkflowStepHandler; compensate?: WorkflowStepHandler }
>
options: TransactionModelOptions
requiredModules?: Set<string>
optionalModules?: Set<string>
}
Expand Down Expand Up @@ -72,6 +74,7 @@ export class WorkflowManager {
workflowId: string,
flow: TransactionStepsDefinition | OrchestratorBuilder | undefined,
handlers: WorkflowHandler,
options: TransactionModelOptions = {},
requiredModules?: Set<string>,
optionalModules?: Set<string>
) {
Expand All @@ -93,9 +96,14 @@ export class WorkflowManager {
WorkflowManager.workflows.set(workflowId, {
id: workflowId,
flow_: finalFlow!,
orchestrator: new TransactionOrchestrator(workflowId, finalFlow ?? {}),
orchestrator: new TransactionOrchestrator(
workflowId,
finalFlow ?? {},
options
),
handler: WorkflowManager.buildHandlers(handlers),
handlers_: handlers,
options,
requiredModules,
optionalModules,
})
Expand All @@ -108,6 +116,7 @@ export class WorkflowManager {
string,
{ invoke: WorkflowStepHandler; compensate?: WorkflowStepHandler }
>,
options: TransactionModelOptions = {},
requiredModules?: Set<string>,
optionalModules?: Set<string>
) {
Expand All @@ -126,9 +135,10 @@ export class WorkflowManager {
WorkflowManager.workflows.set(workflowId, {
id: workflowId,
flow_: finalFlow,
orchestrator: new TransactionOrchestrator(workflowId, finalFlow),
orchestrator: new TransactionOrchestrator(workflowId, finalFlow, options),
handler: WorkflowManager.buildHandlers(workflow.handlers_),
handlers_: workflow.handlers_,
options: { ...workflow.options, ...options },
requiredModules,
optionalModules,
})
Expand Down
1 change: 1 addition & 0 deletions packages/utils/src/modules-sdk/decorators/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from "./inject-transaction-manager"
export * from "./inject-manager"
export * from "./inject-shared-context"
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Context, SharedContext } from "@medusajs/types"

export function InjectSharedContext(): MethodDecorator {
return function (
target: any,
propertyKey: string | symbol,
descriptor: any
): void {
if (!target.MedusaContextIndex_) {
throw new Error(
`To apply @InjectSharedContext you have to flag a parameter using @MedusaContext`
)
}

const originalMethod = descriptor.value
const argIndex = target.MedusaContextIndex_[propertyKey]

descriptor.value = function (...args: any[]) {
const context: SharedContext | Context = { ...(args[argIndex] ?? {}) }
args[argIndex] = context

return originalMethod.apply(this, args)
}
}
}
23 changes: 15 additions & 8 deletions packages/utils/src/modules-sdk/load-module-database-config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MedusaError } from "../common"
import { ModulesSdkTypes } from "@medusajs/types"
import { MedusaError } from "../common"

function getEnv(key: string, moduleName: string): string {
const value =
Expand Down Expand Up @@ -45,10 +45,12 @@ function getDatabaseUrl(
config: ModulesSdkTypes.ModuleServiceInitializeOptions
): string {
const { clientUrl, host, port, user, password, database } = config.database!
if (clientUrl) {
return clientUrl

if (host) {
return `postgres://${user}:${password}@${host}:${port}/${database}`
}
return `postgres://${user}:${password}@${host}:${port}/${database}`

return clientUrl!
}

/**
Expand All @@ -65,25 +67,30 @@ export function loadDatabaseConfig(
ModulesSdkTypes.ModuleServiceInitializeOptions["database"],
"clientUrl" | "schema" | "driverOptions" | "debug"
> {
const clientUrl = getEnv("POSTGRES_URL", moduleName)

const clientUrl =
options?.database?.clientUrl ?? getEnv("POSTGRES_URL", moduleName)

const database = {
clientUrl,
schema: getEnv("POSTGRES_SCHEMA", moduleName) ?? "public",
driverOptions: JSON.parse(
getEnv("POSTGRES_DRIVER_OPTIONS", moduleName) ||
JSON.stringify(getDefaultDriverOptions(clientUrl))
),
debug: process.env.NODE_ENV?.startsWith("dev") ?? false,
debug: false,
connection: undefined,
}

if (isModuleServiceInitializeOptions(options)) {
database.clientUrl = getDatabaseUrl(options)
database.clientUrl = getDatabaseUrl({
database: { ...options.database, clientUrl },
})
database.schema = options.database!.schema ?? database.schema
database.driverOptions =
options.database!.driverOptions ??
getDefaultDriverOptions(database.clientUrl)
database.debug = options.database!.debug ?? database.debug
database.connection = options.database!.connection
}

if (!database.clientUrl && !silent) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
LocalWorkflow,
TransactionModelOptions,
WorkflowHandler,
WorkflowManager,
} from "@medusajs/orchestration"
Expand Down Expand Up @@ -150,15 +151,16 @@ export function createWorkflow<
[K in keyof TResult]:
| WorkflowData<TResult[K]>
| WorkflowDataProperties<TResult[K]>
}
},
options?: TransactionModelOptions
): ReturnWorkflow<TData, TResult, THooks> {
const handlers: WorkflowHandler = new Map()

if (WorkflowManager.getWorkflow(name)) {
WorkflowManager.unregister(name)
}

WorkflowManager.register(name, undefined, handlers)
WorkflowManager.register(name, undefined, handlers, options)

const context: CreateWorkflowComposerContext = {
workflowId: name,
Expand Down