1 import { asValue } from "@medusajs/framework/awilix"
2 import {
3 defineConfig,
4 MikroORM,
5 SqlEntityManager,
6 } from "@medusajs/framework/mikro-orm/postgresql"
7 import { MedusaModule } from "@medusajs/framework/modules-sdk"
8 import { MedusaContainer } from "@medusajs/framework/types"
9 import {
10 ContainerRegistrationKeys,
11 createMedusaContainer,
12 CustomDBMigrator,
13 Modules,
14 ModulesSdkUtils,
15 toMikroOrmEntities,
16 } from "@medusajs/framework/utils"
17 import { TestDatabaseUtils } from "@medusajs/test-utils"
18 import { IndexData, IndexMetadata, IndexRelation, IndexSync } from "@models"
19 import { IndexModuleService } from "@services"
20 import * as fs from "fs"
21 import * as os from "os"
22 import * as path from "path"
23 import { DataSynchronizer } from "../../src/services/data-synchronizer"
24 import { IndexDataService } from "../../src/services/index-data"
25 import { IndexMetadataService } from "../../src/services/index-metadata"
26 import { IndexRelationService } from "../../src/services/index-relation"
27 import { IndexSyncService } from "../../src/services/index-sync"
28 import { PostgresProvider } from "../../src/services/postgres-provider"
29 import { FakeEventBus } from "./fake-event-bus"
30 import { FakeLocking } from "./fake-locking"
31 import { FakeLogger } from "./fake-logger"
32 import { FakeQuery } from "./fake-query"
33 import { remoteModulesJoinerConfigs } from "./joiner-configs"
34
35 export type IndexModuleTestBed = {
36 module: IndexModuleService
37 container: MedusaContainer
38 orm: MikroORM
39 manager: SqlEntityManager
40 query: FakeQuery
41 eventBus: FakeEventBus
42 locking: FakeLocking
43 logger: FakeLogger
44 forkManager: () => SqlEntityManager
45 truncateTables: () => Promise<void>
46 teardown: () => Promise<void>
47 }
48
49 const moduleModels = toMikroOrmEntities([
50 IndexData,
51 IndexRelation,
52 IndexMetadata,
53 IndexSync,
54 ])
55
56 /**
57 * The module's own migrations create the partitioned index tables, so they
58 * are replayed instead of generating the schema from the models. They are
59 * passed as an explicit list to avoid the migrator's file discovery, which
60 * does not go through the jest TypeScript transform.
61 */
62 function loadMigrationsList() {
63 const migrationsDir = path.join(__dirname, "..", "..", "src", "migrations")
64
65 return fs
66 .readdirSync(migrationsDir)
67 .filter((file) => /^Migration\d+\.ts$/.test(file))
68 .sort()
69 .map((file) => {
70 const name = file.replace(/\.ts$/, "")
71 const exported = require(path.join(migrationsDir, file))
72
73 return { name, class: exported[name] }
74 })
75 }
76
77 /**
78 * Boots the index module in isolation: a dedicated database with the
79 * module's own migrations, the module's real container (internal services,
80 * repositories, data synchronizer, postgres storage provider) and fakes for
81 * everything the module receives from the application — query, event bus,
82 * locking and logger. The fake remote modules' joiner configs are
83 * registered so the schema object representation can be built without
84 * loading any other module.
85 */
86 export async function createIndexTestBed({
87 schema,
88 workerMode = "shared",
89 }: {
90 schema: string
91 workerMode?: "shared" | "server"
92 }): Promise<IndexModuleTestBed> {
93 const dbName = `medusa-index-module-${Math.random()
94 .toString(36)
95 .substring(2, 12)}`
96
97 const logger = new FakeLogger()
98 const query = new FakeQuery()
99 const eventBus = new FakeEventBus()
100 const locking = new FakeLocking()
101
102 const dbUtils = TestDatabaseUtils.dbTestUtilFactory()
103 await dbUtils.create(dbName)
104
105 const orm = await MikroORM.init(
106 defineConfig({
107 clientUrl: TestDatabaseUtils.getDatabaseURL(dbName),
108 entities: moduleModels,
109 debug: false,
110 pool: { min: 2 },
111 migrations: {
112 migrationsList: loadMigrationsList(),
113 silent: true,
114 snapshot: false,
115 },
116 extensions: [CustomDBMigrator],
117 })
118 )
119
120 try {
121 await orm.getMigrator().up()
122
123 for (const joinerConfig of remoteModulesJoinerConfigs) {
124 MedusaModule.setJoinerConfig(joinerConfig.serviceName!, joinerConfig)
125 }
126
127 const container = createMedusaContainer()
128 const manager = orm.em.fork()
129
130 container.register({
131 [ContainerRegistrationKeys.LOGGER]: asValue(logger.asLogger()),
132 [ContainerRegistrationKeys.QUERY]: asValue(query as any),
133 [Modules.EVENT_BUS]: asValue(eventBus),
134 [Modules.LOCKING]: asValue(locking),
135 manager: asValue(manager),
136 storageProviderCtr: asValue(PostgresProvider),
137 storageProviderCtrOptions: asValue(undefined),
138 })
139
140 const containerLoader = ModulesSdkUtils.moduleContainerLoaderFactory({
141 moduleModels: moduleModels.reduce((acc, model) => {
142 acc[model.name] = model
143 return acc
144 }, {}),
145 moduleServices: {
146 DataSynchronizer,
147 IndexDataService,
148 IndexMetadataService,
149 IndexRelationService,
150 IndexSyncService,
151 },
152 })
153
154 await containerLoader({ container, options: {} } as any)
155
156 const module = new IndexModuleService(
157 container.cradle as any,
158 { schema } as any,
159 { worker_mode: workerMode } as any
160 )
161
162 // The module generates entry point types under `<cwd>/.medusa` on
163 // startup. Point it at a dedicated temp directory so parallel test
164 // suites do not race on the same file and the repo is not polluted.
165 const typesDir = fs.mkdtempSync(path.join(os.tmpdir(), "medusa-index-"))
166 const previousCwd = process.cwd()
167 process.chdir(typesDir)
168
169 try {
170 await module.__hooks.onApplicationStart.call(module)
171 } finally {
172 process.chdir(previousCwd)
173 }
174
175 if (logger.errors.length) {
176 throw logger.errors[0]
177 }
178
179 const teardown = async () => {
180 MedusaModule.clearInstances()
181 await orm.close(true)
182 await dbUtils.shutdown(dbName)
183 fs.rmSync(typesDir, { recursive: true, force: true })
184 }
185
186 const truncateTables = async () => {
187 await orm.em.execute(
188 `TRUNCATE TABLE index_data, index_relation, index_metadata, index_sync CASCADE`
189 )
190 }
191
192 return {
193 module,
194 container,
195 orm,
196 manager,
197 query,
198 eventBus,
199 locking,
200 logger,
201 forkManager: () => manager.fork(),
202 truncateTables,
203 teardown,
204 }
205 } catch (error) {
206 MedusaModule.clearInstances()
207 await orm.close(true).catch(() => void 0)
208 await dbUtils.shutdown(dbName).catch(() => void 0)
209 throw error
210 }
211 }