@open-mercato/shared 0.10.1-develop.8130.1.8964ae359f → 0.10.1-develop.8144.1.257d1a5737

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,6 +17,7 @@ import {
17
17
  } from "./duplicateEntityClassNames.js";
18
18
  const logger = createLogger("shared").child({ component: "orm" });
19
19
  let ormInstance = null;
20
+ let ormInitialization = null;
20
21
  let disposePoolInstrumentation;
21
22
  const GLOBAL_ENTITIES_KEY = "__openMercatoOrmEntities__";
22
23
  const GLOBAL_REPORTED_DUPLICATE_ENTITY_NAMES_KEY = "__openMercatoReportedDuplicateEntityClassNames__";
@@ -221,6 +222,14 @@ async function getOrm() {
221
222
  if (ormInstance) {
222
223
  return ormInstance;
223
224
  }
225
+ if (!ormInitialization) {
226
+ ormInitialization = initializeOrm().finally(() => {
227
+ ormInitialization = null;
228
+ });
229
+ }
230
+ return ormInitialization;
231
+ }
232
+ async function initializeOrm() {
224
233
  const entities = getOrmEntities();
225
234
  const clientUrl = process.env.DATABASE_URL;
226
235
  if (!clientUrl) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/db/mikro.ts"],
4
- "sourcesContent": ["import 'dotenv/config'\nimport 'reflect-metadata'\nimport { MikroORM } from '@mikro-orm/core'\nimport { ReflectMetadataProvider } from '@mikro-orm/decorators/legacy'\nimport { PostgreSqlDriver, type EntityManager as PostgreSqlEntityManager } from '@mikro-orm/postgresql'\nimport { performance } from 'node:perf_hooks'\nimport { getSslConfig } from './ssl'\nimport { createLogger } from '../logger'\nimport {\n getTelemetryRuntime,\n recordTelemetryMetric,\n registerTelemetryMetricCollector,\n} from '../telemetry/runtime'\nimport { findDuplicateRegisteredEntityClassNames } from './duplicateEntities'\nimport {\n toDuplicateEntityClassNameFields,\n type DuplicateEntityClassNameGroup,\n} from './duplicateEntityClassNames'\n\nconst logger = createLogger('shared').child({ component: 'orm' })\n\nexport type AppMikroORM = MikroORM<PostgreSqlDriver, PostgreSqlEntityManager<PostgreSqlDriver>>\n\nlet ormInstance: AppMikroORM | null = null\nlet disposePoolInstrumentation: (() => void) | undefined\n\n// Use globalThis so standalone apps survive duplicated shared package module instances.\nconst GLOBAL_ENTITIES_KEY = '__openMercatoOrmEntities__'\n// Same reason, plus HMR: a module-level map would reset on the very reloads it exists to\n// deduplicate across.\nconst GLOBAL_REPORTED_DUPLICATE_ENTITY_NAMES_KEY = '__openMercatoReportedDuplicateEntityClassNames__'\n\nfunction getReportedDuplicateEntityClassNames(): Map<string, string> {\n const globals = globalThis as Record<string, unknown>\n const existing = globals[GLOBAL_REPORTED_DUPLICATE_ENTITY_NAMES_KEY]\n if (existing instanceof Map) return existing as Map<string, string>\n const created = new Map<string, string>()\n globals[GLOBAL_REPORTED_DUPLICATE_ENTITY_NAMES_KEY] = created\n return created\n}\n\n/**\n * Identifies a collision by the modules and files that contribute to it, so a\n * re-registration reporting the same name from a different pair of modules is a new\n * collision rather than a repeat.\n */\nfunction fingerprintCollision(group: DuplicateEntityClassNameGroup): string {\n return group.sources\n .map((source) => `${source.moduleId ?? ''}|${source.sourcePath ?? ''}`)\n .sort((left, right) => left.localeCompare(right))\n .join(',')\n}\n\nfunction getRegisteredEntities(): any[] | null {\n return (globalThis as Record<string, unknown>)[GLOBAL_ENTITIES_KEY] as any[] | null ?? null\n}\n\nfunction setRegisteredEntities(entities: any[]): void {\n (globalThis as Record<string, unknown>)[GLOBAL_ENTITIES_KEY] = entities\n}\n\n/**\n * A duplicate entity class name across modules corrupts entity resolution silently, and\n * no build step catches it. Report it here \u2014 the one point every registration path goes\n * through \u2014 so the logs name the cause instead of only its distant symptoms.\n */\nfunction warnOnDuplicateEntityClassNames(entities: readonly unknown[]): void {\n try {\n const duplicates = findDuplicateRegisteredEntityClassNames(entities)\n // Development re-runs registration on every HMR reload, so report a collision only\n // when it appears or its contributing modules change. Reprinting the same warning on\n // every reload buries it, while tracking the previous registration rather than every\n // name ever seen keeps a collision that was fixed and reintroduced reportable.\n const reported = getReportedDuplicateEntityClassNames()\n const current = new Map(duplicates.map((group) => [group.className, fingerprintCollision(group)]))\n const fresh = duplicates.filter((group) => reported.get(group.className) !== current.get(group.className))\n reported.clear()\n for (const [className, fingerprint] of current) reported.set(className, fingerprint)\n if (fresh.length === 0) return\n logger.warn('Duplicate entity class names across enabled modules', toDuplicateEntityClassNameFields(fresh))\n } catch (err) {\n // This check is a diagnostic. It must never be the reason a bootstrap fails.\n logger.debug('Duplicate entity class name check skipped', { err })\n }\n}\n\nexport function registerOrmEntities(entities: any[]) {\n warnOnDuplicateEntityClassNames(entities)\n if (getRegisteredEntities() !== null && process.env.NODE_ENV === 'development') {\n logger.debug('ORM entities re-registered (this may occur during HMR)')\n }\n setRegisteredEntities(entities)\n}\n\nexport function getOrmEntities(): any[] {\n const entities = getRegisteredEntities()\n if (!entities) {\n throw new Error('[Bootstrap] ORM entities not registered. Call registerOrmEntities() at bootstrap.')\n }\n return entities\n}\n\nexport type ResolvedPoolConfig = {\n poolMin: number\n poolMax: number\n poolIdleTimeout: number\n poolAcquireTimeout: number\n idleSessionTimeoutMs: number | undefined\n idleInTransactionTimeoutMs: number | undefined\n statementTimeoutMs: number | undefined\n lockTimeoutMs: number | undefined\n}\n\n// Parse an optional positive-millisecond env var. Returns undefined when unset,\n// non-numeric, or non-positive so callers treat \"no value\" as \"no timeout\".\nfunction parsePositiveIntEnv(raw: string | undefined): number | undefined {\n const parsed = parseInt(raw || '')\n return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined\n}\n\nexport function resolvePoolConfig(env: NodeJS.ProcessEnv = process.env): ResolvedPoolConfig {\n const idleSessionTimeoutEnv = parseInt(env.DB_IDLE_SESSION_TIMEOUT_MS || '')\n const idleInTxTimeoutEnv = parseInt(env.DB_IDLE_IN_TRANSACTION_TIMEOUT_MS || '')\n return {\n poolMin: parseInt(env.DB_POOL_MIN || '2'),\n poolMax: parseInt(env.DB_POOL_MAX || '20'),\n poolIdleTimeout: parseInt(env.DB_POOL_IDLE_TIMEOUT || '3000'),\n poolAcquireTimeout: parseInt(env.DB_POOL_ACQUIRE_TIMEOUT || '6000'),\n idleSessionTimeoutMs: Number.isFinite(idleSessionTimeoutEnv)\n ? idleSessionTimeoutEnv\n : env.NODE_ENV === 'production'\n ? undefined\n : 600_000,\n // Finite default in every environment (including production) so a leaked or idle\n // open transaction cannot pin a pool connection indefinitely and exhaust the pool.\n // Mirrors the long-standing dev value; override (incl. 0 to disable) via env.\n idleInTransactionTimeoutMs: Number.isFinite(idleInTxTimeoutEnv) ? idleInTxTimeoutEnv : 120_000,\n // Opt-in guards against runaway statements and lock waits. No timeout when unset.\n statementTimeoutMs: parsePositiveIntEnv(env.DB_STATEMENT_TIMEOUT_MS),\n lockTimeoutMs: parsePositiveIntEnv(env.DB_LOCK_TIMEOUT_MS),\n }\n}\n\ntype PoolEventSource = {\n on(event: 'error', listener: (err: unknown) => void): unknown\n on(event: 'connect', listener: (client: { on(event: 'error', listener: (err: unknown) => void): unknown }) => void): unknown\n options?: Record<string, unknown>\n}\n\ntype PoolRelease = (release?: unknown) => void\ntype PoolConnectCallback = (\n err: Error | undefined,\n client: unknown,\n done: PoolRelease,\n) => void\n\ntype PoolConnect = {\n (): Promise<unknown>\n (callback: PoolConnectCallback): void\n}\ntype PromisePoolConnect = () => Promise<unknown>\ntype CallbackPoolConnect = (callback: PoolConnectCallback) => void\n\nexport type ObservablePool = PoolEventSource & {\n totalCount: number\n idleCount: number\n waitingCount: number\n connect: PoolConnect\n}\n\nconst GLOBAL_PRIMARY_POOL_INSTRUMENTATION_KEY = Symbol.for(\n '@open-mercato/shared.primaryPoolInstrumentation',\n)\n\ntype PrimaryPoolInstrumentation = {\n dispose(): void\n}\n\ntype PrimaryPoolInstrumentationStore = {\n active?: PrimaryPoolInstrumentation\n}\n\nfunction primaryPoolInstrumentationStore(): PrimaryPoolInstrumentationStore {\n const globalStore = globalThis as unknown as Record<\n symbol,\n PrimaryPoolInstrumentationStore | undefined\n >\n let current = globalStore[GLOBAL_PRIMARY_POOL_INSTRUMENTATION_KEY]\n if (!current) {\n current = {}\n globalStore[GLOBAL_PRIMARY_POOL_INSTRUMENTATION_KEY] = current\n }\n return current\n}\n\n// Postgres can terminate a connection at any moment (admin termination, network\n// drop, and \u2014 most relevantly for long-running daemons \u2014 the\n// `idle_in_transaction_session_timeout` configured above, FATAL 25P03). Where\n// node-postgres surfaces that depends on the client's state:\n// - IDLE (checked into the pool): pg-pool re-emits on the pool's 'error' event.\n// - CHECKED OUT (e.g. a connection pinned by an open transaction while the app\n// awaits non-DB work): pg-pool removes its idle listener, so the FATAL emits\n// on the Client itself.\n// Either way an unlistened 'error' event crashes the whole process (\"Scheduler\n// polling engine exited unexpectedly with exit code 1\"). Swallow both: the pool\n// discards the dead client, and any in-flight transaction still fails normally\n// on its next query/commit against the dead connection.\n// The per-client listener is deliberately attached once on 'connect' and never\n// removed: it is a last-resort sink whose only job is to guarantee the 'error'\n// event always has a listener, in every client state. It is not error handling\n// and must not be \"cleaned up\" \u2014 removing it reintroduces the process crash.\n// A reaped IDLE client therefore logs twice (once here, once via the pool-level\n// handler that pg-pool's own idle listener re-emits); the pool-level line is the\n// one that identifies the client as idle.\nexport function attachPoolErrorHandlers(pool: PoolEventSource): void {\n pool.on('error', (err: unknown) => {\n logger.warn('Idle pg pool client error (connection reaped/terminated)', { err })\n })\n pool.on('connect', (client) => {\n client.on('error', (err: unknown) => {\n logger.warn('pg client error (connection reaped/terminated)', { err })\n })\n })\n}\n\nfunction readPoolMaximum(pool: ObservablePool): number | undefined {\n const maximum = pool.options?.max\n return typeof maximum === 'number' && Number.isFinite(maximum)\n ? maximum\n : undefined\n}\n\n/**\n * Sampled primary-pool view under the app-owned `om.db.pool.*` namespace. The\n * semantic-convention `db.client.connection.*` names are left to\n * `@opentelemetry/instrumentation-pg`, which emits them as UpDownCounters in\n * OTLP mode; reusing them here would export two conflicting streams per name.\n */\nfunction recordPoolState(pool: ObservablePool): void {\n const idle = Math.max(0, pool.idleCount)\n const used = Math.max(0, pool.totalCount - idle)\n recordTelemetryMetric({\n kind: 'gauge',\n name: 'om.db.pool.connections',\n value: idle,\n labels: { pool: 'primary', state: 'idle' },\n unit: '{connection}',\n })\n recordTelemetryMetric({\n kind: 'gauge',\n name: 'om.db.pool.connections',\n value: used,\n labels: { pool: 'primary', state: 'used' },\n unit: '{connection}',\n })\n recordTelemetryMetric({\n kind: 'gauge',\n name: 'om.db.pool.pending_requests',\n value: Math.max(0, pool.waitingCount),\n labels: { pool: 'primary' },\n unit: '{request}',\n })\n\n const maximum = readPoolMaximum(pool)\n if (maximum !== undefined) {\n recordTelemetryMetric({\n kind: 'gauge',\n name: 'om.db.pool.max',\n value: maximum,\n labels: { pool: 'primary' },\n unit: '{connection}',\n })\n }\n}\n\nexport function instrumentPrimaryPool(\n pool: ObservablePool,\n now: () => number = () => performance.now(),\n): () => void {\n const instrumentationStore = primaryPoolInstrumentationStore()\n instrumentationStore.active?.dispose()\n const originalConnect = pool.connect\n const disposeCollector = registerTelemetryMetricCollector(() => recordPoolState(pool))\n let metricFailureLogged = false\n\n const recordWait = (startedAt: number) => {\n try {\n recordTelemetryMetric({\n kind: 'histogram',\n name: 'om.db.pool.wait_time',\n value: Math.max(0, now() - startedAt) / 1_000,\n labels: { pool: 'primary' },\n unit: 's',\n })\n } catch (err) {\n try {\n getTelemetryRuntime()?.reportError(err, {\n module: 'telemetry',\n code: 'telemetry.pool_wait_metric_failed',\n })\n } catch {}\n if (metricFailureLogged) return\n metricFailureLogged = true\n logger.warn('Failed to record pg pool acquisition wait metric', { err })\n }\n }\n\n const instrumentedConnect = function (\n this: ObservablePool,\n callback?: PoolConnectCallback,\n ): Promise<unknown> | void {\n const startedAt = now()\n if (typeof callback === 'function') {\n return (originalConnect as CallbackPoolConnect).call(this, (err, client, done) => {\n recordWait(startedAt)\n callback(err, client, done)\n })\n }\n\n try {\n return (originalConnect as PromisePoolConnect).call(this).then(\n (client: unknown) => {\n recordWait(startedAt)\n return client\n },\n (err: unknown) => {\n recordWait(startedAt)\n throw err\n },\n )\n } catch (err) {\n recordWait(startedAt)\n throw err\n }\n } as PoolConnect\n\n pool.connect = instrumentedConnect\n let disposed = false\n const instrumentation: PrimaryPoolInstrumentation = { dispose: () => {} }\n const dispose = () => {\n if (disposed) return\n disposed = true\n disposeCollector()\n if (pool.connect === instrumentedConnect) pool.connect = originalConnect\n if (instrumentationStore.active === instrumentation) {\n instrumentationStore.active = undefined\n }\n }\n instrumentation.dispose = dispose\n instrumentationStore.active = instrumentation\n return dispose\n}\n\nexport async function getOrm() {\n if (ormInstance) {\n return ormInstance\n }\n\n const entities = getOrmEntities()\n const clientUrl = process.env.DATABASE_URL\n if (!clientUrl) {\n throw new Error('DATABASE_URL is not set')\n }\n\n // Parse connection pool settings from environment\n const {\n poolMin,\n poolMax,\n poolIdleTimeout,\n poolAcquireTimeout,\n idleSessionTimeoutMs,\n idleInTransactionTimeoutMs,\n statementTimeoutMs,\n lockTimeoutMs,\n } = resolvePoolConfig()\n const connectionOptions =\n idleSessionTimeoutMs && idleSessionTimeoutMs > 0\n ? `-c idle_session_timeout=${idleSessionTimeoutMs}`\n : undefined\n\n const sslConfig = getSslConfig()\n\n if (process.env.OM_DB_POOL_DEBUG === '1' || process.env.OM_INTEGRATION_TEST === 'true') {\n logger.info('Pool config', {\n poolMin,\n poolMax,\n poolIdleTimeout,\n poolAcquireTimeout,\n idleSessionTimeoutMs,\n idleInTransactionTimeoutMs,\n statementTimeoutMs,\n lockTimeoutMs,\n nodeEnv: process.env.NODE_ENV,\n })\n }\n\n ormInstance = await MikroORM.init<PostgreSqlDriver, PostgreSqlEntityManager<PostgreSqlDriver>>({\n driver: PostgreSqlDriver,\n clientUrl,\n entities,\n debug: false,\n // v7 no longer defaults to ReflectMetadataProvider. Entities in this repo use\n // `@mikro-orm/decorators/legacy`, which relies on TypeScript `emitDecoratorMetadata`\n // + reflect-metadata for type inference (nullability, column types). Without this,\n // inferred types are silently wrong at runtime.\n metadataProvider: ReflectMetadataProvider,\n // MikroORM v7 pool shape (min/max/idleTimeoutMillis). Knex-era `acquireTimeoutMillis` /\n // `destroyTimeoutMillis` were removed; acquire wait maps to pg `connectionTimeoutMillis`\n // below under `driverOptions`. Mirror `connectionTimeoutMillis` here too \u2014 older Mikro\n // versions read it from `pool`; v7 reads from `driverOptions` but accepting both\n // costs nothing and protects us from upstream config-merge regressions.\n pool: {\n min: poolMin,\n max: poolMax,\n idleTimeoutMillis: poolIdleTimeout,\n acquireTimeoutMillis: poolAcquireTimeout,\n } as any,\n // Driver options are merged into pg.PoolConfig (ClientConfig + pg-pool).\n driverOptions: {\n connectionTimeoutMillis: poolAcquireTimeout,\n idle_in_transaction_session_timeout: idleInTransactionTimeoutMs,\n statement_timeout: statementTimeoutMs,\n lock_timeout: lockTimeoutMs,\n options: connectionOptions,\n ssl: sslConfig,\n onPoolCreated: (pool: ObservablePool) => {\n disposePoolInstrumentation?.()\n attachPoolErrorHandlers(pool)\n disposePoolInstrumentation = instrumentPrimaryPool(pool)\n if (process.env.OM_DB_POOL_DEBUG === '1' || process.env.OM_INTEGRATION_TEST === 'true') {\n logger.info('pg pool created with options', {\n max: pool.options?.max,\n min: pool.options?.min,\n idleTimeoutMillis: pool.options?.idleTimeoutMillis,\n connectionTimeoutMillis: pool.options?.connectionTimeoutMillis,\n })\n }\n },\n },\n })\n\n return ormInstance\n}\n\n\nasync function closeOrmIfLoaded(): Promise<void> {\n if (ormInstance) {\n disposePoolInstrumentation?.()\n disposePoolInstrumentation = undefined\n await ormInstance.close(true)\n ormInstance = null\n }\n}\n\n// In dev mode, handle reloads cleanly without leaving dangling connections.\nif (process.env.NODE_ENV !== 'production') {\n void closeOrmIfLoaded()\n}\n"],
5
- "mappings": "AAAA,OAAO;AACP,OAAO;AACP,SAAS,gBAAgB;AACzB,SAAS,+BAA+B;AACxC,SAAS,wBAAuE;AAChF,SAAS,mBAAmB;AAC5B,SAAS,oBAAo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KAAK;AAAA,MACL,KAAK;AAAA,MACL,mBAAmB;AAAA,MACnB,sBAAsB;AAAA,IACxB;AAAA;AAAA,IAEA,eAAe;AAAA,MACb,yBAAyB;AAAA,MACzB,qCAAqC;AAAA,MACrC,mBAAmB;AAAA,MACnB,cAAc;AAAA,MACd,SAAS;AAAA,MACT,KAAK;AAAA,MACL,eAAe,CAAC,SAAyB;AACvC,qCAA6B;AAC7B,gCAAwB,IAAI;AAC5B,qCAA6B,sBAAsB,IAAI;AACvD,YAAI,QAAQ,IAAI,qBAAqB,OAAO,QAAQ,IAAI,wBAAwB,QAAQ;AACtF,iBAAO,KAAK,gCAAgC;AAAA,YAC1C,KAAK,KAAK,SAAS;AAAA,YACnB,KAAK,KAAK,SAAS;AAAA,YACnB,mBAAmB,KAAK,SAAS;AAAA,YACjC,yBAAyB,KAAK,SAAS;AAAA,UACzC,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AAED,SAAO;AACT;AAGA,eAAe,mBAAkC;AAC/C,MAAI,aAAa;AACf,iCAA6B;AAC7B,iCAA6B;AAC7B,UAAM,YAAY,MAAM,IAAI;AAC5B,kBAAc;AAAA,EAChB;AACF;AAGA,IAAI,QAAQ,IAAI,aAAa,cAAc;AACzC,OAAK,iBAAiB;AACxB;",
4
+ "sourcesContent": ["import 'dotenv/config'\nimport 'reflect-metadata'\nimport { MikroORM } from '@mikro-orm/core'\nimport { ReflectMetadataProvider } from '@mikro-orm/decorators/legacy'\nimport { PostgreSqlDriver, type EntityManager as PostgreSqlEntityManager } from '@mikro-orm/postgresql'\nimport { performance } from 'node:perf_hooks'\nimport { getSslConfig } from './ssl'\nimport { createLogger } from '../logger'\nimport {\n getTelemetryRuntime,\n recordTelemetryMetric,\n registerTelemetryMetricCollector,\n} from '../telemetry/runtime'\nimport { findDuplicateRegisteredEntityClassNames } from './duplicateEntities'\nimport {\n toDuplicateEntityClassNameFields,\n type DuplicateEntityClassNameGroup,\n} from './duplicateEntityClassNames'\n\nconst logger = createLogger('shared').child({ component: 'orm' })\n\nexport type AppMikroORM = MikroORM<PostgreSqlDriver, PostgreSqlEntityManager<PostgreSqlDriver>>\n\nlet ormInstance: AppMikroORM | null = null\nlet ormInitialization: Promise<AppMikroORM> | null = null\nlet disposePoolInstrumentation: (() => void) | undefined\n\n// Use globalThis so standalone apps survive duplicated shared package module instances.\nconst GLOBAL_ENTITIES_KEY = '__openMercatoOrmEntities__'\n// Same reason, plus HMR: a module-level map would reset on the very reloads it exists to\n// deduplicate across.\nconst GLOBAL_REPORTED_DUPLICATE_ENTITY_NAMES_KEY = '__openMercatoReportedDuplicateEntityClassNames__'\n\nfunction getReportedDuplicateEntityClassNames(): Map<string, string> {\n const globals = globalThis as Record<string, unknown>\n const existing = globals[GLOBAL_REPORTED_DUPLICATE_ENTITY_NAMES_KEY]\n if (existing instanceof Map) return existing as Map<string, string>\n const created = new Map<string, string>()\n globals[GLOBAL_REPORTED_DUPLICATE_ENTITY_NAMES_KEY] = created\n return created\n}\n\n/**\n * Identifies a collision by the modules and files that contribute to it, so a\n * re-registration reporting the same name from a different pair of modules is a new\n * collision rather than a repeat.\n */\nfunction fingerprintCollision(group: DuplicateEntityClassNameGroup): string {\n return group.sources\n .map((source) => `${source.moduleId ?? ''}|${source.sourcePath ?? ''}`)\n .sort((left, right) => left.localeCompare(right))\n .join(',')\n}\n\nfunction getRegisteredEntities(): any[] | null {\n return (globalThis as Record<string, unknown>)[GLOBAL_ENTITIES_KEY] as any[] | null ?? null\n}\n\nfunction setRegisteredEntities(entities: any[]): void {\n (globalThis as Record<string, unknown>)[GLOBAL_ENTITIES_KEY] = entities\n}\n\n/**\n * A duplicate entity class name across modules corrupts entity resolution silently, and\n * no build step catches it. Report it here \u2014 the one point every registration path goes\n * through \u2014 so the logs name the cause instead of only its distant symptoms.\n */\nfunction warnOnDuplicateEntityClassNames(entities: readonly unknown[]): void {\n try {\n const duplicates = findDuplicateRegisteredEntityClassNames(entities)\n // Development re-runs registration on every HMR reload, so report a collision only\n // when it appears or its contributing modules change. Reprinting the same warning on\n // every reload buries it, while tracking the previous registration rather than every\n // name ever seen keeps a collision that was fixed and reintroduced reportable.\n const reported = getReportedDuplicateEntityClassNames()\n const current = new Map(duplicates.map((group) => [group.className, fingerprintCollision(group)]))\n const fresh = duplicates.filter((group) => reported.get(group.className) !== current.get(group.className))\n reported.clear()\n for (const [className, fingerprint] of current) reported.set(className, fingerprint)\n if (fresh.length === 0) return\n logger.warn('Duplicate entity class names across enabled modules', toDuplicateEntityClassNameFields(fresh))\n } catch (err) {\n // This check is a diagnostic. It must never be the reason a bootstrap fails.\n logger.debug('Duplicate entity class name check skipped', { err })\n }\n}\n\nexport function registerOrmEntities(entities: any[]) {\n warnOnDuplicateEntityClassNames(entities)\n if (getRegisteredEntities() !== null && process.env.NODE_ENV === 'development') {\n logger.debug('ORM entities re-registered (this may occur during HMR)')\n }\n setRegisteredEntities(entities)\n}\n\nexport function getOrmEntities(): any[] {\n const entities = getRegisteredEntities()\n if (!entities) {\n throw new Error('[Bootstrap] ORM entities not registered. Call registerOrmEntities() at bootstrap.')\n }\n return entities\n}\n\nexport type ResolvedPoolConfig = {\n poolMin: number\n poolMax: number\n poolIdleTimeout: number\n poolAcquireTimeout: number\n idleSessionTimeoutMs: number | undefined\n idleInTransactionTimeoutMs: number | undefined\n statementTimeoutMs: number | undefined\n lockTimeoutMs: number | undefined\n}\n\n// Parse an optional positive-millisecond env var. Returns undefined when unset,\n// non-numeric, or non-positive so callers treat \"no value\" as \"no timeout\".\nfunction parsePositiveIntEnv(raw: string | undefined): number | undefined {\n const parsed = parseInt(raw || '')\n return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined\n}\n\nexport function resolvePoolConfig(env: NodeJS.ProcessEnv = process.env): ResolvedPoolConfig {\n const idleSessionTimeoutEnv = parseInt(env.DB_IDLE_SESSION_TIMEOUT_MS || '')\n const idleInTxTimeoutEnv = parseInt(env.DB_IDLE_IN_TRANSACTION_TIMEOUT_MS || '')\n return {\n poolMin: parseInt(env.DB_POOL_MIN || '2'),\n poolMax: parseInt(env.DB_POOL_MAX || '20'),\n poolIdleTimeout: parseInt(env.DB_POOL_IDLE_TIMEOUT || '3000'),\n poolAcquireTimeout: parseInt(env.DB_POOL_ACQUIRE_TIMEOUT || '6000'),\n idleSessionTimeoutMs: Number.isFinite(idleSessionTimeoutEnv)\n ? idleSessionTimeoutEnv\n : env.NODE_ENV === 'production'\n ? undefined\n : 600_000,\n // Finite default in every environment (including production) so a leaked or idle\n // open transaction cannot pin a pool connection indefinitely and exhaust the pool.\n // Mirrors the long-standing dev value; override (incl. 0 to disable) via env.\n idleInTransactionTimeoutMs: Number.isFinite(idleInTxTimeoutEnv) ? idleInTxTimeoutEnv : 120_000,\n // Opt-in guards against runaway statements and lock waits. No timeout when unset.\n statementTimeoutMs: parsePositiveIntEnv(env.DB_STATEMENT_TIMEOUT_MS),\n lockTimeoutMs: parsePositiveIntEnv(env.DB_LOCK_TIMEOUT_MS),\n }\n}\n\ntype PoolEventSource = {\n on(event: 'error', listener: (err: unknown) => void): unknown\n on(event: 'connect', listener: (client: { on(event: 'error', listener: (err: unknown) => void): unknown }) => void): unknown\n options?: Record<string, unknown>\n}\n\ntype PoolRelease = (release?: unknown) => void\ntype PoolConnectCallback = (\n err: Error | undefined,\n client: unknown,\n done: PoolRelease,\n) => void\n\ntype PoolConnect = {\n (): Promise<unknown>\n (callback: PoolConnectCallback): void\n}\ntype PromisePoolConnect = () => Promise<unknown>\ntype CallbackPoolConnect = (callback: PoolConnectCallback) => void\n\nexport type ObservablePool = PoolEventSource & {\n totalCount: number\n idleCount: number\n waitingCount: number\n connect: PoolConnect\n}\n\nconst GLOBAL_PRIMARY_POOL_INSTRUMENTATION_KEY = Symbol.for(\n '@open-mercato/shared.primaryPoolInstrumentation',\n)\n\ntype PrimaryPoolInstrumentation = {\n dispose(): void\n}\n\ntype PrimaryPoolInstrumentationStore = {\n active?: PrimaryPoolInstrumentation\n}\n\nfunction primaryPoolInstrumentationStore(): PrimaryPoolInstrumentationStore {\n const globalStore = globalThis as unknown as Record<\n symbol,\n PrimaryPoolInstrumentationStore | undefined\n >\n let current = globalStore[GLOBAL_PRIMARY_POOL_INSTRUMENTATION_KEY]\n if (!current) {\n current = {}\n globalStore[GLOBAL_PRIMARY_POOL_INSTRUMENTATION_KEY] = current\n }\n return current\n}\n\n// Postgres can terminate a connection at any moment (admin termination, network\n// drop, and \u2014 most relevantly for long-running daemons \u2014 the\n// `idle_in_transaction_session_timeout` configured above, FATAL 25P03). Where\n// node-postgres surfaces that depends on the client's state:\n// - IDLE (checked into the pool): pg-pool re-emits on the pool's 'error' event.\n// - CHECKED OUT (e.g. a connection pinned by an open transaction while the app\n// awaits non-DB work): pg-pool removes its idle listener, so the FATAL emits\n// on the Client itself.\n// Either way an unlistened 'error' event crashes the whole process (\"Scheduler\n// polling engine exited unexpectedly with exit code 1\"). Swallow both: the pool\n// discards the dead client, and any in-flight transaction still fails normally\n// on its next query/commit against the dead connection.\n// The per-client listener is deliberately attached once on 'connect' and never\n// removed: it is a last-resort sink whose only job is to guarantee the 'error'\n// event always has a listener, in every client state. It is not error handling\n// and must not be \"cleaned up\" \u2014 removing it reintroduces the process crash.\n// A reaped IDLE client therefore logs twice (once here, once via the pool-level\n// handler that pg-pool's own idle listener re-emits); the pool-level line is the\n// one that identifies the client as idle.\nexport function attachPoolErrorHandlers(pool: PoolEventSource): void {\n pool.on('error', (err: unknown) => {\n logger.warn('Idle pg pool client error (connection reaped/terminated)', { err })\n })\n pool.on('connect', (client) => {\n client.on('error', (err: unknown) => {\n logger.warn('pg client error (connection reaped/terminated)', { err })\n })\n })\n}\n\nfunction readPoolMaximum(pool: ObservablePool): number | undefined {\n const maximum = pool.options?.max\n return typeof maximum === 'number' && Number.isFinite(maximum)\n ? maximum\n : undefined\n}\n\n/**\n * Sampled primary-pool view under the app-owned `om.db.pool.*` namespace. The\n * semantic-convention `db.client.connection.*` names are left to\n * `@opentelemetry/instrumentation-pg`, which emits them as UpDownCounters in\n * OTLP mode; reusing them here would export two conflicting streams per name.\n */\nfunction recordPoolState(pool: ObservablePool): void {\n const idle = Math.max(0, pool.idleCount)\n const used = Math.max(0, pool.totalCount - idle)\n recordTelemetryMetric({\n kind: 'gauge',\n name: 'om.db.pool.connections',\n value: idle,\n labels: { pool: 'primary', state: 'idle' },\n unit: '{connection}',\n })\n recordTelemetryMetric({\n kind: 'gauge',\n name: 'om.db.pool.connections',\n value: used,\n labels: { pool: 'primary', state: 'used' },\n unit: '{connection}',\n })\n recordTelemetryMetric({\n kind: 'gauge',\n name: 'om.db.pool.pending_requests',\n value: Math.max(0, pool.waitingCount),\n labels: { pool: 'primary' },\n unit: '{request}',\n })\n\n const maximum = readPoolMaximum(pool)\n if (maximum !== undefined) {\n recordTelemetryMetric({\n kind: 'gauge',\n name: 'om.db.pool.max',\n value: maximum,\n labels: { pool: 'primary' },\n unit: '{connection}',\n })\n }\n}\n\nexport function instrumentPrimaryPool(\n pool: ObservablePool,\n now: () => number = () => performance.now(),\n): () => void {\n const instrumentationStore = primaryPoolInstrumentationStore()\n instrumentationStore.active?.dispose()\n const originalConnect = pool.connect\n const disposeCollector = registerTelemetryMetricCollector(() => recordPoolState(pool))\n let metricFailureLogged = false\n\n const recordWait = (startedAt: number) => {\n try {\n recordTelemetryMetric({\n kind: 'histogram',\n name: 'om.db.pool.wait_time',\n value: Math.max(0, now() - startedAt) / 1_000,\n labels: { pool: 'primary' },\n unit: 's',\n })\n } catch (err) {\n try {\n getTelemetryRuntime()?.reportError(err, {\n module: 'telemetry',\n code: 'telemetry.pool_wait_metric_failed',\n })\n } catch {}\n if (metricFailureLogged) return\n metricFailureLogged = true\n logger.warn('Failed to record pg pool acquisition wait metric', { err })\n }\n }\n\n const instrumentedConnect = function (\n this: ObservablePool,\n callback?: PoolConnectCallback,\n ): Promise<unknown> | void {\n const startedAt = now()\n if (typeof callback === 'function') {\n return (originalConnect as CallbackPoolConnect).call(this, (err, client, done) => {\n recordWait(startedAt)\n callback(err, client, done)\n })\n }\n\n try {\n return (originalConnect as PromisePoolConnect).call(this).then(\n (client: unknown) => {\n recordWait(startedAt)\n return client\n },\n (err: unknown) => {\n recordWait(startedAt)\n throw err\n },\n )\n } catch (err) {\n recordWait(startedAt)\n throw err\n }\n } as PoolConnect\n\n pool.connect = instrumentedConnect\n let disposed = false\n const instrumentation: PrimaryPoolInstrumentation = { dispose: () => {} }\n const dispose = () => {\n if (disposed) return\n disposed = true\n disposeCollector()\n if (pool.connect === instrumentedConnect) pool.connect = originalConnect\n if (instrumentationStore.active === instrumentation) {\n instrumentationStore.active = undefined\n }\n }\n instrumentation.dispose = dispose\n instrumentationStore.active = instrumentation\n return dispose\n}\n\nexport async function getOrm() {\n if (ormInstance) {\n return ormInstance\n }\n\n if (!ormInitialization) {\n ormInitialization = initializeOrm().finally(() => {\n ormInitialization = null\n })\n }\n return ormInitialization\n}\n\nasync function initializeOrm(): Promise<AppMikroORM> {\n\n const entities = getOrmEntities()\n const clientUrl = process.env.DATABASE_URL\n if (!clientUrl) {\n throw new Error('DATABASE_URL is not set')\n }\n\n // Parse connection pool settings from environment\n const {\n poolMin,\n poolMax,\n poolIdleTimeout,\n poolAcquireTimeout,\n idleSessionTimeoutMs,\n idleInTransactionTimeoutMs,\n statementTimeoutMs,\n lockTimeoutMs,\n } = resolvePoolConfig()\n const connectionOptions =\n idleSessionTimeoutMs && idleSessionTimeoutMs > 0\n ? `-c idle_session_timeout=${idleSessionTimeoutMs}`\n : undefined\n\n const sslConfig = getSslConfig()\n\n if (process.env.OM_DB_POOL_DEBUG === '1' || process.env.OM_INTEGRATION_TEST === 'true') {\n logger.info('Pool config', {\n poolMin,\n poolMax,\n poolIdleTimeout,\n poolAcquireTimeout,\n idleSessionTimeoutMs,\n idleInTransactionTimeoutMs,\n statementTimeoutMs,\n lockTimeoutMs,\n nodeEnv: process.env.NODE_ENV,\n })\n }\n\n ormInstance = await MikroORM.init<PostgreSqlDriver, PostgreSqlEntityManager<PostgreSqlDriver>>({\n driver: PostgreSqlDriver,\n clientUrl,\n entities,\n debug: false,\n // v7 no longer defaults to ReflectMetadataProvider. Entities in this repo use\n // `@mikro-orm/decorators/legacy`, which relies on TypeScript `emitDecoratorMetadata`\n // + reflect-metadata for type inference (nullability, column types). Without this,\n // inferred types are silently wrong at runtime.\n metadataProvider: ReflectMetadataProvider,\n // MikroORM v7 pool shape (min/max/idleTimeoutMillis). Knex-era `acquireTimeoutMillis` /\n // `destroyTimeoutMillis` were removed; acquire wait maps to pg `connectionTimeoutMillis`\n // below under `driverOptions`. Mirror `connectionTimeoutMillis` here too \u2014 older Mikro\n // versions read it from `pool`; v7 reads from `driverOptions` but accepting both\n // costs nothing and protects us from upstream config-merge regressions.\n pool: {\n min: poolMin,\n max: poolMax,\n idleTimeoutMillis: poolIdleTimeout,\n acquireTimeoutMillis: poolAcquireTimeout,\n } as any,\n // Driver options are merged into pg.PoolConfig (ClientConfig + pg-pool).\n driverOptions: {\n connectionTimeoutMillis: poolAcquireTimeout,\n idle_in_transaction_session_timeout: idleInTransactionTimeoutMs,\n statement_timeout: statementTimeoutMs,\n lock_timeout: lockTimeoutMs,\n options: connectionOptions,\n ssl: sslConfig,\n onPoolCreated: (pool: ObservablePool) => {\n disposePoolInstrumentation?.()\n attachPoolErrorHandlers(pool)\n disposePoolInstrumentation = instrumentPrimaryPool(pool)\n if (process.env.OM_DB_POOL_DEBUG === '1' || process.env.OM_INTEGRATION_TEST === 'true') {\n logger.info('pg pool created with options', {\n max: pool.options?.max,\n min: pool.options?.min,\n idleTimeoutMillis: pool.options?.idleTimeoutMillis,\n connectionTimeoutMillis: pool.options?.connectionTimeoutMillis,\n })\n }\n },\n },\n })\n\n return ormInstance\n}\n\n\nasync function closeOrmIfLoaded(): Promise<void> {\n if (ormInstance) {\n disposePoolInstrumentation?.()\n disposePoolInstrumentation = undefined\n await ormInstance.close(true)\n ormInstance = null\n }\n}\n\n// In dev mode, handle reloads cleanly without leaving dangling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develop.8130.1.8964ae359f";
1
+ const APP_VERSION = "0.10.1-develop.8144.1.257d1a5737";
2
2
  const appVersion = APP_VERSION;
3
3
  export {
4
4
  APP_VERSION,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/version.ts"],
4
- "sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.8130.1.8964ae359f';\nexport const appVersion = APP_VERSION;\n"],
4
+ "sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.8144.1.257d1a5737';\nexport const appVersion = APP_VERSION;\n"],
5
5
  "mappings": "AACO,MAAM,cAAc;AACpB,MAAM,aAAa;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/shared",
3
- "version": "0.10.1-develop.8130.1.8964ae359f",
3
+ "version": "0.10.1-develop.8144.1.257d1a5737",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -130,7 +130,7 @@
130
130
  "@mikro-orm/core": "^7.1.14",
131
131
  "@mikro-orm/decorators": "^7.1.14",
132
132
  "@mikro-orm/postgresql": "^7.1.14",
133
- "@open-mercato/cache": "0.10.1-develop.8130.1.8964ae359f",
133
+ "@open-mercato/cache": "0.10.1-develop.8144.1.257d1a5737",
134
134
  "@types/html-to-text": "^9.0.4",
135
135
  "@types/sanitize-html": "^2.16.1",
136
136
  "dotenv": "^17.4.2",
@@ -0,0 +1,58 @@
1
+ import type { AppMikroORM } from '../mikro'
2
+
3
+ const entitiesKey = '__openMercatoOrmEntities__'
4
+ const globals = globalThis as Record<string, unknown>
5
+ const originalEntities = globals[entitiesKey]
6
+ const originalDatabaseUrl = process.env.DATABASE_URL
7
+
8
+ beforeEach(() => {
9
+ jest.resetModules()
10
+ process.env.DATABASE_URL = 'postgresql://localhost/orm_initialization_test'
11
+ })
12
+
13
+ afterEach(() => {
14
+ jest.restoreAllMocks()
15
+ if (originalDatabaseUrl === undefined) delete process.env.DATABASE_URL
16
+ else process.env.DATABASE_URL = originalDatabaseUrl
17
+ if (originalEntities === undefined) delete globals[entitiesKey]
18
+ else globals[entitiesKey] = originalEntities
19
+ })
20
+
21
+ test('concurrent callers share one initialization and retain the resulting ORM', async () => {
22
+ const { MikroORM } = await import('@mikro-orm/core')
23
+ const { getOrm, registerOrmEntities } = await import('../mikro')
24
+ registerOrmEntities([])
25
+ const instance = { em: {} } as AppMikroORM
26
+ let finishInitialization!: (orm: AppMikroORM) => void
27
+ const initialization = new Promise<AppMikroORM>((resolve) => {
28
+ finishInitialization = resolve
29
+ })
30
+ const initialize = jest.spyOn(MikroORM, 'init').mockImplementation(() => initialization)
31
+
32
+ const callers = Array.from({ length: 8 }, () => getOrm())
33
+ expect(initialize).toHaveBeenCalledTimes(1)
34
+ finishInitialization(instance)
35
+ const results = await Promise.all(callers)
36
+
37
+ expect(results.every((result) => result === instance)).toBe(true)
38
+ expect(await getOrm()).toBe(instance)
39
+ expect(initialize).toHaveBeenCalledTimes(1)
40
+ })
41
+
42
+ test('all waiting callers receive initialization failure and a later call can retry', async () => {
43
+ const { MikroORM } = await import('@mikro-orm/core')
44
+ const { getOrm, registerOrmEntities } = await import('../mikro')
45
+ registerOrmEntities([])
46
+ const failure = new Error('Database unavailable')
47
+ const instance = { em: {} } as AppMikroORM
48
+ const initialize = jest.spyOn(MikroORM, 'init')
49
+ .mockRejectedValueOnce(failure)
50
+ .mockResolvedValueOnce(instance)
51
+
52
+ const results = await Promise.allSettled([getOrm(), getOrm(), getOrm()])
53
+
54
+ expect(results).toEqual(Array.from({ length: 3 }, () => ({ status: 'rejected', reason: failure })))
55
+ expect(initialize).toHaveBeenCalledTimes(1)
56
+ expect(await getOrm()).toBe(instance)
57
+ expect(initialize).toHaveBeenCalledTimes(2)
58
+ })
@@ -22,6 +22,7 @@ const logger = createLogger('shared').child({ component: 'orm' })
22
22
  export type AppMikroORM = MikroORM<PostgreSqlDriver, PostgreSqlEntityManager<PostgreSqlDriver>>
23
23
 
24
24
  let ormInstance: AppMikroORM | null = null
25
+ let ormInitialization: Promise<AppMikroORM> | null = null
25
26
  let disposePoolInstrumentation: (() => void) | undefined
26
27
 
27
28
  // Use globalThis so standalone apps survive duplicated shared package module instances.
@@ -356,6 +357,16 @@ export async function getOrm() {
356
357
  return ormInstance
357
358
  }
358
359
 
360
+ if (!ormInitialization) {
361
+ ormInitialization = initializeOrm().finally(() => {
362
+ ormInitialization = null
363
+ })
364
+ }
365
+ return ormInitialization
366
+ }
367
+
368
+ async function initializeOrm(): Promise<AppMikroORM> {
369
+
359
370
  const entities = getOrmEntities()
360
371
  const clientUrl = process.env.DATABASE_URL
361
372
  if (!clientUrl) {