@open-mercato/cli 0.11.1-develop.8910.1.d07a49d70a → 0.11.1-develop.8929.1.493f6c653c

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.
Files changed (188) hide show
  1. package/.turbo/turbo-build.log +6 -2
  2. package/dist/agentic/guides/module-facts.json +356 -399
  3. package/dist/agentic/guides/module-facts.v2.json +356 -399
  4. package/dist/agentic/guides/modules/agent_orchestrator/active-extension-bindings.md +1 -1
  5. package/dist/agentic/guides/modules/agent_orchestrator/exact-override-targets.md +1 -1
  6. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  7. package/dist/agentic/guides/modules/agent_orchestrator/workers.md +1 -1
  8. package/dist/agentic/guides/modules/ai_assistant/exact-override-targets.md +2 -2
  9. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  10. package/dist/agentic/guides/modules/ai_assistant/workers.md +2 -2
  11. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  12. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  13. package/dist/agentic/guides/modules/assisted_selling/index.md +1 -1
  14. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  15. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  16. package/dist/agentic/guides/modules/auth/entities.md +1 -0
  17. package/dist/agentic/guides/modules/auth/index.md +2 -2
  18. package/dist/agentic/guides/modules/auth/umes-hosts.md +1 -0
  19. package/dist/agentic/guides/modules/availability/index.md +1 -1
  20. package/dist/agentic/guides/modules/backups/index.md +1 -1
  21. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  22. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  23. package/dist/agentic/guides/modules/cart/index.md +1 -1
  24. package/dist/agentic/guides/modules/catalog/domain-commands.md +0 -1
  25. package/dist/agentic/guides/modules/catalog/index.md +1 -1
  26. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  27. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  28. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  29. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  30. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  31. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  32. package/dist/agentic/guides/modules/channel_ms365/index.md +1 -1
  33. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  34. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  35. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  36. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  37. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  38. package/dist/agentic/guides/modules/configs/index.md +1 -1
  39. package/dist/agentic/guides/modules/content/index.md +1 -1
  40. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  41. package/dist/agentic/guides/modules/customer_accounts/exact-override-targets.md +4 -4
  42. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  43. package/dist/agentic/guides/modules/customer_accounts/workers.md +4 -4
  44. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  45. package/dist/agentic/guides/modules/customers/index.md +1 -1
  46. package/dist/agentic/guides/modules/dashboards/index.md +1 -1
  47. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  48. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  49. package/dist/agentic/guides/modules/devices/index.md +1 -1
  50. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  51. package/dist/agentic/guides/modules/directory/index.md +1 -1
  52. package/dist/agentic/guides/modules/documents/index.md +1 -1
  53. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  54. package/dist/agentic/guides/modules/entities/index.md +1 -1
  55. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  56. package/dist/agentic/guides/modules/events/index.md +1 -1
  57. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  58. package/dist/agentic/guides/modules/forms/index.md +1 -1
  59. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  60. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  61. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  62. package/dist/agentic/guides/modules/generators/index.md +1 -1
  63. package/dist/agentic/guides/modules/gus_regon/index.md +1 -1
  64. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  65. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  66. package/dist/agentic/guides/modules/ledger/index.md +1 -1
  67. package/dist/agentic/guides/modules/maintenance/index.md +1 -1
  68. package/dist/agentic/guides/modules/messages/index.md +1 -1
  69. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  70. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  71. package/dist/agentic/guides/modules/payment_gateways/exact-override-targets.md +1 -1
  72. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  73. package/dist/agentic/guides/modules/payment_gateways/workers.md +1 -1
  74. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  75. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  76. package/dist/agentic/guides/modules/planner/index.md +1 -1
  77. package/dist/agentic/guides/modules/portal/index.md +1 -1
  78. package/dist/agentic/guides/modules/progress/index.md +1 -1
  79. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  80. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  81. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  82. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  83. package/dist/agentic/guides/modules/resources/index.md +1 -1
  84. package/dist/agentic/guides/modules/sales/exact-override-targets.md +4 -4
  85. package/dist/agentic/guides/modules/sales/index.md +1 -1
  86. package/dist/agentic/guides/modules/sales/setup.md +1 -1
  87. package/dist/agentic/guides/modules/sales_invoices_gl_posting/index.md +1 -1
  88. package/dist/agentic/guides/modules/scheduler/di-registrations-rich.md +3 -3
  89. package/dist/agentic/guides/modules/scheduler/di-service-tokens.md +3 -3
  90. package/dist/agentic/guides/modules/scheduler/exact-override-targets.md +4 -9
  91. package/dist/agentic/guides/modules/scheduler/index.md +3 -4
  92. package/dist/agentic/guides/modules/scheduler/workers.md +1 -1
  93. package/dist/agentic/guides/modules/search/di-registrations-rich.md +4 -4
  94. package/dist/agentic/guides/modules/search/di-service-tokens.md +13 -0
  95. package/dist/agentic/guides/modules/search/exact-override-targets.md +4 -4
  96. package/dist/agentic/guides/modules/search/index.md +3 -2
  97. package/dist/agentic/guides/modules/security/index.md +1 -1
  98. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  99. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  100. package/dist/agentic/guides/modules/sso/index.md +1 -1
  101. package/dist/agentic/guides/modules/staff/index.md +1 -1
  102. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  103. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  104. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  105. package/dist/agentic/guides/modules/sync_shopify/index.md +1 -1
  106. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  107. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  108. package/dist/agentic/guides/modules/tenant_boundaries/generator-plugins.md +11 -0
  109. package/dist/agentic/guides/modules/tenant_boundaries/index.md +13 -0
  110. package/dist/agentic/guides/modules/tenant_boundaries/owned-contract-module-metadata.md +11 -0
  111. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  112. package/dist/agentic/guides/modules/translations/index.md +1 -1
  113. package/dist/agentic/guides/modules/upgrade_actions/index.md +1 -1
  114. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  115. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  116. package/dist/agentic/guides/modules/wms/index.md +1 -1
  117. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  118. package/dist/agentic/guides/reference-module-facts.json +2 -2
  119. package/dist/agentic/guides/reference-modules/example/index.md +1 -1
  120. package/dist/agentic/guides/upstream/manifest.json +1 -1
  121. package/dist/agentic/shared/AGENTS.md.template +3 -3
  122. package/dist/agentic/shared/ai/harness/cases.json +4 -4
  123. package/dist/bin.js +6 -3
  124. package/dist/bin.js.map +2 -2
  125. package/dist/i18n/de.json +5 -1
  126. package/dist/i18n/en.json +5 -1
  127. package/dist/i18n/es.json +5 -1
  128. package/dist/i18n/ko.json +5 -1
  129. package/dist/i18n/pl.json +5 -1
  130. package/dist/lib/cli-bootstrap-mode.js +10 -1
  131. package/dist/lib/cli-bootstrap-mode.js.map +2 -2
  132. package/dist/lib/db/commands.js +18 -3
  133. package/dist/lib/db/commands.js.map +2 -2
  134. package/dist/lib/db/maintenance-client.js +72 -0
  135. package/dist/lib/db/maintenance-client.js.map +7 -0
  136. package/dist/lib/generate-watch-structure.js +2 -1
  137. package/dist/lib/generate-watch-structure.js.map +2 -2
  138. package/dist/lib/generators/database-declarations.js +21 -0
  139. package/dist/lib/generators/database-declarations.js.map +7 -0
  140. package/dist/lib/generators/module-registry.js +19 -3
  141. package/dist/lib/generators/module-registry.js.map +2 -2
  142. package/dist/lib/init-existing-database.js +91 -1
  143. package/dist/lib/init-existing-database.js.map +2 -2
  144. package/dist/lib/init-i18n.js +13 -0
  145. package/dist/lib/init-i18n.js.map +7 -0
  146. package/dist/lib/init-secrets.js +2 -10
  147. package/dist/lib/init-secrets.js.map +2 -2
  148. package/dist/lib/scheduler-supervisor.js +47 -7
  149. package/dist/lib/scheduler-supervisor.js.map +2 -2
  150. package/dist/lib/server-start-lock.js +120 -21
  151. package/dist/lib/server-start-lock.js.map +2 -2
  152. package/dist/lib/worker-job-handler.js +36 -26
  153. package/dist/lib/worker-job-handler.js.map +2 -2
  154. package/dist/mercato.js +93 -54
  155. package/dist/mercato.js.map +3 -3
  156. package/package.json +7 -7
  157. package/src/__tests__/mercato.test.ts +166 -9
  158. package/src/bin.ts +10 -4
  159. package/src/i18n/de.json +5 -1
  160. package/src/i18n/en.json +5 -1
  161. package/src/i18n/es.json +5 -1
  162. package/src/i18n/ko.json +5 -1
  163. package/src/i18n/pl.json +5 -1
  164. package/src/lib/__tests__/cli-bootstrap-mode.test.ts +76 -1
  165. package/src/lib/__tests__/generate-watch-structure.test.ts +26 -0
  166. package/src/lib/__tests__/rotation-kms-warning-presentation.test.ts +1 -1
  167. package/src/lib/__tests__/scheduler-supervisor.test.ts +107 -0
  168. package/src/lib/__tests__/server-start-lock.test.ts +400 -0
  169. package/src/lib/__tests__/worker-job-handler.database.test.ts +76 -0
  170. package/src/lib/cli-bootstrap-mode.ts +12 -2
  171. package/src/lib/db/__tests__/commands.migrate-reindex.test.ts +72 -1
  172. package/src/lib/db/__tests__/maintenance-client.test.ts +70 -0
  173. package/src/lib/db/commands.ts +20 -6
  174. package/src/lib/db/maintenance-client.ts +54 -0
  175. package/src/lib/generate-watch-structure.ts +2 -1
  176. package/src/lib/generators/__tests__/database-declarations.test.ts +69 -0
  177. package/src/lib/generators/__tests__/incremental-registry.test.ts +1 -1
  178. package/src/lib/generators/__tests__/module-subset.test.ts +17 -1
  179. package/src/lib/generators/database-declarations.ts +19 -0
  180. package/src/lib/generators/module-registry.ts +23 -4
  181. package/src/lib/init-existing-database.ts +107 -0
  182. package/src/lib/init-i18n.ts +11 -0
  183. package/src/lib/init-secrets.ts +2 -12
  184. package/src/lib/scheduler-supervisor.ts +40 -7
  185. package/src/lib/server-start-lock.ts +170 -19
  186. package/src/lib/worker-job-handler.ts +39 -28
  187. package/src/mercato.ts +92 -53
  188. package/dist/agentic/guides/modules/scheduler/cli-commands.md +0 -15
@@ -0,0 +1,70 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
+ import { createCliMaintenanceClient } from '../maintenance-client'
3
+ import { configureDatabasePool, isDatabaseRuntimeEnabled, runWithFreshDatabaseExecutionContext } from '@open-mercato/shared/lib/db/runtime'
4
+
5
+ const query = jest.fn(async () => ({ rows: [] }))
6
+ const end = jest.fn(async () => undefined)
7
+ const ready = jest.fn(async () => undefined)
8
+ const dispose = jest.fn()
9
+ const connectionScope = new AsyncLocalStorage<symbol>()
10
+ const sessionQuery = jest.fn(async (_sql: string) => ({ rows: [{ owner: connectionScope.getStore() }] }))
11
+ const release = jest.fn()
12
+ const connect = jest.fn(async () => ({ query: sessionQuery, release, on: jest.fn() }))
13
+ jest.mock('pg', () => ({
14
+ Pool: jest.fn(() => ({ connect, query, end })),
15
+ Client: jest.fn(() => ({ legacy: true })),
16
+ }))
17
+ jest.mock('@open-mercato/shared/lib/db/ssl', () => ({ getSslConfig: () => undefined }))
18
+ jest.mock('@open-mercato/shared/lib/db/runtime', () => ({
19
+ isDatabaseRuntimeEnabled: jest.fn(() => true),
20
+ resolveDatabaseConnectionUrl: jest.fn(() => 'private-maintenance-connection'),
21
+ configureDatabasePool: jest.fn(() => ({ ready, dispose })),
22
+ runWithFreshDatabaseExecutionContext: jest.fn((_context, callback) => callback()),
23
+ }))
24
+ beforeEach(() => { jest.clearAllMocks(); jest.mocked(isDatabaseRuntimeEnabled).mockReturnValue(true); ready.mockResolvedValue(undefined) })
25
+ it('routes readiness and SQL through explicit maintenance scopes and drains registration', async () => {
26
+ const client = await createCliMaintenanceClient('private-runtime-connection')
27
+ await client.connect()
28
+ await client.query('SELECT 1')
29
+ await client.end()
30
+ expect(configureDatabasePool).toHaveBeenCalledWith(expect.any(Object), { id: 'cli.maintenance', purpose: 'maintenance', tables: [] })
31
+ expect(runWithFreshDatabaseExecutionContext).toHaveBeenCalledTimes(2)
32
+ expect(runWithFreshDatabaseExecutionContext).toHaveBeenLastCalledWith({ kind: 'maintenance', tenantId: null, source: 'cli', operation: 'database-maintenance' }, expect.any(Function))
33
+ expect(query).toHaveBeenCalledWith('SELECT 1')
34
+ expect(end).toHaveBeenCalledTimes(1)
35
+ expect(dispose).toHaveBeenCalledTimes(1)
36
+ })
37
+ it('rejects SQL when physical role verification fails', async () => {
38
+ ready.mockRejectedValueOnce(new Error('wrong role'))
39
+ const client = await createCliMaintenanceClient('private-runtime-connection')
40
+ await expect(client.query('SELECT 1')).rejects.toThrow('wrong role')
41
+ expect(query).not.toHaveBeenCalled()
42
+ await client.end()
43
+ })
44
+
45
+ it('retains the same maintenance invocation and physical client across initialization queries', async () => {
46
+ const owner = Symbol('maintenance invocation')
47
+ jest.mocked(runWithFreshDatabaseExecutionContext).mockImplementationOnce((_context, callback) => connectionScope.run(owner, callback))
48
+ const client = await createCliMaintenanceClient('private-runtime-connection', { pinned: true })
49
+ await client.connect()
50
+ try {
51
+ expect(await client.query('SELECT pg_try_advisory_lock(1)')).toEqual({ rows: [{ owner }] })
52
+ expect(await client.query('SELECT 1')).toEqual({ rows: [{ owner }] })
53
+ expect(connect).toHaveBeenCalledTimes(1)
54
+ expect(query).not.toHaveBeenCalled()
55
+ expect(release).not.toHaveBeenCalled()
56
+ } finally {
57
+ await client.end()
58
+ }
59
+ expect(release).toHaveBeenCalledWith(true)
60
+ expect(end).toHaveBeenCalledTimes(1)
61
+ expect(dispose).toHaveBeenCalledTimes(1)
62
+ })
63
+ it('preserves the legacy client and closes pools after registration rejection', async () => {
64
+ jest.mocked(isDatabaseRuntimeEnabled).mockReturnValue(false)
65
+ expect(await createCliMaintenanceClient(undefined)).toEqual({ legacy: true })
66
+ jest.mocked(isDatabaseRuntimeEnabled).mockReturnValue(true)
67
+ jest.mocked(configureDatabasePool).mockImplementationOnce(() => { throw new Error('registration rejected') })
68
+ await expect(createCliMaintenanceClient('private-runtime-connection')).rejects.toThrow('registration rejected')
69
+ expect(end).toHaveBeenCalledTimes(1)
70
+ })
@@ -7,6 +7,7 @@ import { ReflectMetadataProvider } from '@mikro-orm/decorators/legacy'
7
7
  import { Migrator } from '@mikro-orm/migrations'
8
8
  import { PostgreSqlDriver } from '@mikro-orm/postgresql'
9
9
  import { getSslConfig } from '@open-mercato/shared/lib/db/ssl'
10
+ import { afterDatabaseMigrate, beforeDatabaseMigrate, resolveDatabaseConnectionUrl, runWithDatabaseExecutionContext, shouldRecoverDatabaseMigrationReindex } from '@open-mercato/shared/lib/db/runtime'
10
11
  import type { PackageResolver, ModuleEntry } from '../resolver'
11
12
  import { quotePostgresIdentifier } from './identifiers'
12
13
  import { preserveUnconstrainedNumericSnapshots } from './numeric-snapshots'
@@ -446,11 +447,18 @@ export async function dbGenerate(resolver: PackageResolver, options: DbOptions =
446
447
  }
447
448
 
448
449
  export async function dbMigrate(resolver: PackageResolver, options: DbOptions = {}): Promise<void> {
450
+ return runWithDatabaseExecutionContext({ kind: 'maintenance', tenantId: null, source: 'cli', operation: 'db:migrate' }, () => migrateModules(resolver, options))
451
+ }
452
+
453
+ async function migrateModules(resolver: PackageResolver, _options: DbOptions): Promise<void> {
449
454
  const modules = resolver.loadEnabledModules()
450
455
  const ordered = sortModules(modules)
451
456
  const results: string[] = []
452
457
  const appliedMigrations: AppliedMigration[] = []
458
+ const recoverHistory = shouldRecoverDatabaseMigrationReindex()
459
+ let reconciled = false
453
460
 
461
+ await beforeDatabaseMigrate()
454
462
  try {
455
463
  for (const entry of ordered) {
456
464
  const modId = entry.id
@@ -474,7 +482,7 @@ export async function dbMigrate(resolver: PackageResolver, options: DbOptions =
474
482
  const sslConfig = getSslConfig()
475
483
  const orm = await MikroORM.init<PostgreSqlDriver>({
476
484
  driver: PostgreSqlDriver,
477
- clientUrl: getClientUrl(),
485
+ clientUrl: resolveDatabaseConnectionUrl('maintenance', getClientUrl()),
478
486
  loggerFactory: () => createMinimalLogger(),
479
487
  dynamicImportProvider,
480
488
  entities: [],
@@ -503,6 +511,12 @@ export async function dbMigrate(resolver: PackageResolver, options: DbOptions =
503
511
 
504
512
  try {
505
513
  const migrator = orm.migrator as Migrator
514
+ if (recoverHistory) {
515
+ const executed = await migrator.getExecuted()
516
+ for (const migration of executed) {
517
+ appliedMigrations.push({ moduleId: modId, migrationsPath, name: migration.name })
518
+ }
519
+ }
506
520
  const pending = await migrator.getPending()
507
521
  if (!pending.length) {
508
522
  results.push(formatResult(modId, 'no pending migrations', ''))
@@ -514,16 +528,14 @@ export async function dbMigrate(resolver: PackageResolver, options: DbOptions =
514
528
  }
515
529
  for (const migration of pending) {
516
530
  const migrationName =
517
- typeof migration === 'string'
518
- ? migration
519
- : (migration as any).name ?? (migration as any).fileName
531
+ typeof migration === 'string' ? migration : migration.name
520
532
  await migrator.up(migrationName ? { migrations: [migrationName] } : undefined)
521
533
  if (migrationName) {
522
534
  appliedMigrations.push({
523
535
  moduleId: modId,
524
536
  migrationsPath,
525
537
  name: String(migrationName),
526
- filePath: typeof migration === 'string' ? null : (migration as any).path ?? null,
538
+ filePath: typeof migration === 'string' ? null : migration.path ?? null,
527
539
  })
528
540
  }
529
541
  applied += 1
@@ -540,9 +552,11 @@ export async function dbMigrate(resolver: PackageResolver, options: DbOptions =
540
552
  await orm.close(true)
541
553
  }
542
554
  }
555
+ await afterDatabaseMigrate()
556
+ reconciled = true
543
557
  } finally {
544
558
  console.log(results.join('\n'))
545
- await dischargeQueryIndexReindexRequests(appliedMigrations)
559
+ if (!recoverHistory || reconciled) await dischargeQueryIndexReindexRequests(appliedMigrations)
546
560
  }
547
561
  }
548
562
 
@@ -0,0 +1,54 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
+ import { Client, Pool } from 'pg'
3
+ import { configureDatabasePool, isDatabaseRuntimeEnabled, resolveDatabaseConnectionUrl, runWithFreshDatabaseExecutionContext } from '@open-mercato/shared/lib/db/runtime'
4
+ import { getSslConfig } from '@open-mercato/shared/lib/db/ssl'
5
+
6
+ export async function createCliMaintenanceClient(connectionString: string | undefined, options?: { pinned?: boolean }) {
7
+ if (!isDatabaseRuntimeEnabled()) {
8
+ const client = new Client({ connectionString, ssl: getSslConfig(), ...(options?.pinned ? { keepAlive: true } : {}) })
9
+ if (options?.pinned) client.on('error', () => undefined)
10
+ return client
11
+ }
12
+ if (!connectionString) throw new Error('[internal] Database maintenance requires a configured connection')
13
+ const pool = new Pool({ connectionString: resolveDatabaseConnectionUrl('maintenance', connectionString), ssl: getSslConfig(), max: 1, connectionTimeoutMillis: 5_000, statement_timeout: 30_000, ...(options?.pinned ? { keepAlive: true } : {}) })
14
+ const lifecycle = await (async () => {
15
+ try { return configureDatabasePool(pool, { id: 'cli.maintenance', purpose: 'maintenance', tables: [] }) } catch (error) { await pool.end(); throw error }
16
+ })()
17
+ const invoke = <Result>(callback: () => Promise<Result>) => runWithFreshDatabaseExecutionContext({ kind: 'maintenance', tenantId: null, source: 'cli', operation: 'database-maintenance' }, callback)
18
+ const end = async () => { try { await pool.end() } finally { lifecycle.dispose() } }
19
+ if (options?.pinned) {
20
+ const connection = Promise.withResolvers<Pool['query']>()
21
+ const closed = Promise.withResolvers<void>()
22
+ let lease: Promise<void> | undefined
23
+ return {
24
+ connect: async () => {
25
+ lease ??= invoke(async () => {
26
+ await lifecycle.ready()
27
+ const client = await pool.connect()
28
+ const runInOwnerScope = AsyncLocalStorage.snapshot()
29
+ try {
30
+ client.on('error', () => undefined)
31
+ connection.resolve(((...args: unknown[]) => runInOwnerScope(() => Reflect.apply(client.query, client, args))) as Pool['query'])
32
+ await closed.promise
33
+ } finally {
34
+ client.release(true)
35
+ }
36
+ }).catch(connection.reject)
37
+ await connection.promise
38
+ },
39
+ query: (async (...args: unknown[]) => Reflect.apply(await connection.promise, undefined, args)) as Pool['query'],
40
+ end: async () => {
41
+ closed.resolve()
42
+ try { await lease } finally { await end() }
43
+ },
44
+ }
45
+ }
46
+ return {
47
+ connect: () => invoke(() => lifecycle.ready()),
48
+ query: ((...arguments_: unknown[]) => invoke(async () => {
49
+ await lifecycle.ready()
50
+ return Reflect.apply(pool.query, pool, arguments_)
51
+ })) as Pool['query'],
52
+ end,
53
+ }
54
+ }
@@ -2,6 +2,7 @@ import crypto from 'node:crypto'
2
2
  import fs from 'node:fs'
3
3
  import path from 'node:path'
4
4
  import ts from 'typescript-js'
5
+ import { databaseDeclarationsPlugin } from './generators/database-declarations'
5
6
  import {
6
7
  MODULE_CODE_EXTENSIONS,
7
8
  SCAN_CONFIGS,
@@ -632,7 +633,7 @@ export function collectGenerateWatchStructureSnapshot(
632
633
  const collector = new SnapshotCollector(cacheState)
633
634
  for (const reason of options.webResearchAdapterFullReasons ?? []) collector.fullReasons.add(reason)
634
635
  collector.file(`configuration:${options.modulesFile}`, options.modulesFile, { category: 'configuration' })
635
- const plugins = new Set<string>()
636
+ const plugins = new Set([databaseDeclarationsPlugin.conventionFile])
636
637
  options.moduleRoots.forEach((roots, index) => addModule(collector, roots, index, plugins))
637
638
  options.moduleRoots.forEach((roots, index) => {
638
639
  const identity = `module:${index}:${roots.moduleId ?? path.basename(roots.appBase)}:${roots.appBase}:${roots.pkgBase}`
@@ -0,0 +1,69 @@
1
+ import fs from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+ import type { ModuleEntry, PackageResolver } from '../../resolver'
5
+ import { generateModuleRegistry, generateModuleRegistryCli } from '../module-registry'
6
+
7
+ let fixtureRoot: string
8
+
9
+ function write(relative: string, content: string): void {
10
+ const target = path.join(fixtureRoot, relative)
11
+ fs.mkdirSync(path.dirname(target), { recursive: true })
12
+ fs.writeFileSync(target, content)
13
+ }
14
+
15
+ beforeEach(() => { fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'database-declarations-generator-')) })
16
+ afterEach(() => fs.rmSync(fixtureRoot, { recursive: true, force: true }))
17
+
18
+ it.each([false, true])('discovers neutral database declarations without enterprise (standalone=%s)', async (standalone) => {
19
+ const packageRoot = standalone ? 'node_modules/fixture' : 'packages/core'
20
+ const moduleRoot = `${packageRoot}/${standalone ? 'dist' : 'src'}/modules`
21
+ const extension = standalone ? 'js' : 'ts'
22
+ write(`${moduleRoot}/owner/database.${extension}`, 'export const databaseDeclarations = { bindingValidators: [] }')
23
+ write(`${moduleRoot}/extension/database.${extension}`, 'export const databaseDeclarations = {}')
24
+ const outputDir = path.join(fixtureRoot, '.mercato/generated')
25
+ const entries: ModuleEntry[] = [
26
+ { id: 'owner', from: '@fixture/owner' },
27
+ { id: 'extension', from: '@fixture/extension' },
28
+ ]
29
+ const resolver: PackageResolver = {
30
+ isMonorepo: () => !standalone,
31
+ getRootDir: () => fixtureRoot,
32
+ getAppDir: () => fixtureRoot,
33
+ getOutputDir: () => outputDir,
34
+ getModulesConfigPath: () => path.join(fixtureRoot, 'src/modules.ts'),
35
+ discoverPackages: () => [],
36
+ loadEnabledModules: () => entries,
37
+ getModulePaths: (entry) => ({
38
+ appBase: path.join(fixtureRoot, 'src/modules', entry.id),
39
+ pkgBase: path.join(fixtureRoot, moduleRoot, entry.id),
40
+ }),
41
+ getModuleImportBase: (entry) => ({
42
+ appBase: `@/modules/${entry.id}`,
43
+ pkgBase: `${entry.from}/modules/${entry.id}`,
44
+ }),
45
+ getPackageOutputDir: () => outputDir,
46
+ getPackageRoot: () => path.join(fixtureRoot, packageRoot),
47
+ }
48
+ expect((await generateModuleRegistry({ resolver, quiet: true })).errors).toEqual([])
49
+ expect((await generateModuleRegistryCli({ resolver, quiet: true })).errors).toEqual([])
50
+ const read = (name: string) => fs.readFileSync(path.join(outputDir, name), 'utf8')
51
+ expect(read('database-declarations.generated.ts')).toContain('@fixture/owner/modules/owner/database')
52
+ expect(read('database-declarations.generated.ts')).toContain('@fixture/extension/modules/extension/database')
53
+ expect(read('bootstrap-registrations.generated.ts')).toContain('registerDatabaseModuleDeclarations(databaseModuleDeclarations)')
54
+ expect(read('bootstrap-registrations.generated.ts')).not.toContain('@open-mercato/enterprise')
55
+ expect(JSON.parse(read('dev-supervisor.generated.json')).requiresFullBootstrap).toBe(true)
56
+ expect(fs.existsSync(path.join(outputDir, 'tenant-boundaries.generated.ts'))).toBe(false)
57
+
58
+ entries.splice(0, 1)
59
+ expect((await generateModuleRegistry({ resolver, quiet: true })).errors).toEqual([])
60
+ expect(read('database-declarations.generated.ts')).not.toContain('@fixture/owner/modules/owner/database')
61
+ expect(read('database-declarations.generated.ts')).toContain('@fixture/extension/modules/extension/database')
62
+
63
+ entries.splice(0)
64
+ expect((await generateModuleRegistry({ resolver, quiet: true })).errors).toEqual([])
65
+ expect((await generateModuleRegistryCli({ resolver, quiet: true })).errors).toEqual([])
66
+ expect(read('database-declarations.generated.ts')).toContain('databaseModuleDeclarations')
67
+ expect(read('database-declarations.generated.ts')).not.toContain('@fixture/')
68
+ expect(JSON.parse(read('dev-supervisor.generated.json')).requiresFullBootstrap).toBe(false)
69
+ })
@@ -229,7 +229,7 @@ it('preserves unselected plugin ownership and reconciles it on the next full gen
229
229
  const full = capture()
230
230
  expect(full['extra.generated.ts']).toBeUndefined()
231
231
  expect(full['extra.generated.checksum']).toBeUndefined()
232
- expect(full['.generator-plugin-outputs.json']).toBeUndefined()
232
+ expect(JSON.parse(full['.generator-plugin-outputs.json'].content)).toEqual(['database-declarations.generated.ts'])
233
233
  })
234
234
 
235
235
  it('emits the aggregate command loader once without unrelated registry families', async () => {
@@ -1253,6 +1253,22 @@ export default async function handle(): Promise<void> {}
1253
1253
  expect(second.filesWritten).not.toContain(manifestPath)
1254
1254
  })
1255
1255
 
1256
+ it('runs bootstrap registrations before dev supervisor probes for any enabled plugin owner', async () => {
1257
+ scaffoldModule(tmpDir, 'custom_runtime', 'pkg', ['generators.ts'])
1258
+ touchFile(
1259
+ path.join(tmpDir, 'packages', 'core', 'src', 'modules', 'custom_runtime', 'generators.ts'),
1260
+ `export const generatorPlugins = [{
1261
+ id: 'custom.runtime',
1262
+ bootstrapRegistration: { entriesExportName: 'entries', registrationImports: [], buildCall: () => '' },
1263
+ }]`,
1264
+ )
1265
+ const resolver = createMockResolver(tmpDir, [{ id: 'custom_runtime', from: '@open-mercato/core' }])
1266
+ const result = await generateModuleRegistryCli({ resolver, quiet: true })
1267
+ expect(result.errors).toEqual([])
1268
+ const manifestPath = path.join(tmpDir, 'output', 'generated', 'dev-supervisor.generated.json')
1269
+ expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8')).requiresFullBootstrap).toBe(true)
1270
+ })
1271
+
1256
1272
  it('falls back to full bootstrap for worker overrides and computed scheduler commands', async () => {
1257
1273
  scaffoldModule(tmpDir, 'events', 'pkg', ['workers/dispatch.ts'])
1258
1274
  scaffoldModule(tmpDir, 'scheduler', 'pkg', ['cli.ts'])
@@ -2092,7 +2108,7 @@ describe('all generated files are valid with varying subsets', () => {
2092
2108
  await generateModuleRegistry({ resolver: disabledResolver, quiet: true })
2093
2109
  expect(fs.existsSync(outputPath)).toBe(false)
2094
2110
  expect(fs.existsSync(checksumPath)).toBe(false)
2095
- expect(fs.existsSync(manifestPath)).toBe(false)
2111
+ expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8'))).toEqual(['database-declarations.generated.ts'])
2096
2112
  })
2097
2113
 
2098
2114
  it('notifications.generated.ts uses typed fallback for legacy "types" export', async () => {
@@ -0,0 +1,19 @@
1
+ import type { GeneratorPlugin } from '@open-mercato/shared/modules/generators'
2
+
3
+ export const databaseDeclarationsPlugin: GeneratorPlugin = {
4
+ id: 'database.declarations',
5
+ conventionFile: 'database.ts',
6
+ importPrefix: 'DATABASE_DECLARATIONS',
7
+ configExpr: (name, moduleId) => `{ moduleId: '${moduleId}', declarations: ${name}.databaseDeclarations }`,
8
+ outputFileName: 'database-declarations.generated.ts',
9
+ buildOutput: ({ importSection, entriesLiteral }) => `// AUTO-GENERATED by mercato generate registry
10
+ import type { DatabaseModuleDeclarationEntry } from '@open-mercato/shared/lib/db/declarations'
11
+ ${importSection}
12
+ export const databaseModuleDeclarations: DatabaseModuleDeclarationEntry[] = [${entriesLiteral}]
13
+ `,
14
+ bootstrapRegistration: {
15
+ entriesExportName: 'databaseModuleDeclarations',
16
+ registrationImports: ["import { registerDatabaseModuleDeclarations } from '@open-mercato/shared/lib/db/declarations'"],
17
+ buildCall: (name) => `registerDatabaseModuleDeclarations(${name})`,
18
+ },
19
+ }
@@ -80,6 +80,7 @@ import {
80
80
  resolveStandaloneSourceMirrorBase,
81
81
  } from './scanner'
82
82
  import { loadGeneratorExtensions } from './extensions'
83
+ import { databaseDeclarationsPlugin } from './database-declarations'
83
84
  import { resolveDashboardWidgetKey } from './extensions/dashboard-widgets'
84
85
  import { prepareCrudFormSectionRegistries, writeCrudFormSectionRegistries, writeDerivedCrudFormSectionRoutes } from './form-sections'
85
86
  import type { ModuleScanContext, StandaloneConfigOptions } from './extension'
@@ -3784,9 +3785,13 @@ async function generateModuleRegistryFromDiscovery(options: ModuleRegistryRender
3784
3785
  const enabled = discovery.enabled
3785
3786
  const extensions = loadGeneratorExtensions(resolver)
3786
3787
 
3787
- // Pre-pass: collect generator plugins from each enabled module's generators.ts
3788
- const pluginRegistry = new Map<string, import('@open-mercato/shared/modules/generators').GeneratorPlugin>()
3789
- const pluginState = new Map<string, { imports: string[]; configs: string[] }>()
3788
+ // Pre-pass: register the built-in plugin and collect plugins from enabled modules.
3789
+ const pluginRegistry = new Map<string, import('@open-mercato/shared/modules/generators').GeneratorPlugin>([
3790
+ [databaseDeclarationsPlugin.id, databaseDeclarationsPlugin],
3791
+ ])
3792
+ const pluginState = new Map<string, { imports: string[]; configs: string[] }>([
3793
+ [databaseDeclarationsPlugin.id, { imports: [], configs: [] }],
3794
+ ])
3790
3795
  for (const discovered of discovery.modules) {
3791
3796
  const resolved = discovered.resolve('generators.ts')
3792
3797
  if (!resolved) continue
@@ -4968,7 +4973,8 @@ async function generateModuleRegistryCliFromDiscovery(options: ModuleRegistryRen
4968
4973
  const devSupervisorWorkers: DevSupervisorWorkerDescriptor[] = []
4969
4974
  let schedulerStartStatus: DevSupervisorSchedulerStartStatus = 'missing-module'
4970
4975
  let requiresFullBootstrap = selectsRegistryOutput(options, 'supervisor') && (
4971
- enabled.some((entry) => entry.devSupervisorRequiresFullBootstrap === true)
4976
+ discovery.modules.some((module) => Boolean(module.resolve(databaseDeclarationsPlugin.conventionFile)))
4977
+ || enabled.some((entry) => entry.devSupervisorRequiresFullBootstrap === true)
4972
4978
  || appDeclaresProgrammaticDevSupervisorOverrides(resolver.getAppDir())
4973
4979
  )
4974
4980
 
@@ -4976,6 +4982,19 @@ async function generateModuleRegistryCliFromDiscovery(options: ModuleRegistryRen
4976
4982
  const { modId, imps, appImportBase } = discovered
4977
4983
  commandLoaderEntries.push(...discovered.commandLoaderEntries)
4978
4984
 
4985
+ const generatorSource = discovered.resolve('generators.ts')
4986
+ if (generatorSource) {
4987
+ assertGeneratorPluginUsesTypeOnlyImports(generatorSource.absolutePath)
4988
+ try {
4989
+ const pluginModule = await import(buildCacheBustedSourceImportUrl(generatorSource.absolutePath))
4990
+ const plugins: import('@open-mercato/shared/modules/generators').GeneratorPlugin[] =
4991
+ pluginModule.generatorPlugins ?? pluginModule.default ?? []
4992
+ requiresFullBootstrap ||= plugins.some((plugin) => Boolean(plugin.bootstrapRegistration))
4993
+ } catch {
4994
+ requiresFullBootstrap = true
4995
+ }
4996
+ }
4997
+
4979
4998
  let cliImportName: string | null = null
4980
4999
  const translations: GeneratedObjectEntry[] = []
4981
5000
  const subscribers: WriterFunction[] = []
@@ -1,10 +1,111 @@
1
+ import type { Client } from 'pg'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { createCliMaintenanceClient } from './db/maintenance-client'
4
+ import { createInitTranslator } from './init-i18n'
5
+
6
+ const INITIALIZATION_NAME = 'mercato-init'
7
+
1
8
  export type ExistingDatabaseDecision = 'proceed' | 'skip' | 'abort'
9
+ type InitializationClient = Pick<Client, 'query'>
2
10
 
3
11
  export function decideExistingDatabase(existingUsersCount: number, skipIfInitialized: boolean): ExistingDatabaseDecision {
4
12
  if (!Number.isFinite(existingUsersCount) || existingUsersCount <= 0) return 'proceed'
5
13
  return skipIfInitialized ? 'skip' : 'abort'
6
14
  }
7
15
 
16
+ export async function withInitializationClient<T>(
17
+ databaseUrl: string,
18
+ action: (client: InitializationClient) => Promise<T>,
19
+ ): Promise<T> {
20
+ const client = await createCliMaintenanceClient(databaseUrl)
21
+ try {
22
+ await client.connect()
23
+ return await action(client)
24
+ } finally {
25
+ await client.end()
26
+ }
27
+ }
28
+
29
+ export async function hasIncompleteInitialization(client: InitializationClient): Promise<boolean> {
30
+ const table = await client.query<{ regclass: string | null }>(
31
+ "SELECT to_regclass('app_initializations') AS regclass",
32
+ )
33
+ if (!table.rows[0]?.regclass) return false
34
+
35
+ const result = await client.query<{ pending: boolean }>(
36
+ 'SELECT completed_at IS NULL AS pending FROM app_initializations WHERE name = $1',
37
+ [INITIALIZATION_NAME],
38
+ )
39
+ return result.rows[0]?.pending === true
40
+ }
41
+
42
+ export type InitializationStart = { initializationId: string; clearedInterruptedAttempt: boolean }
43
+
44
+ export async function startInitialization(client: InitializationClient): Promise<InitializationStart> {
45
+ const translate = createInitTranslator(process.env)
46
+ const lock = await client.query<{ locked: boolean }>(
47
+ 'SELECT pg_try_advisory_lock(hashtext($1)) AS locked',
48
+ [INITIALIZATION_NAME],
49
+ )
50
+ if (lock.rows[0]?.locked !== true) {
51
+ throw new Error(translate('cli.init.errors.concurrentInitialization'))
52
+ }
53
+ const cleared = await client.query(
54
+ 'DELETE FROM app_initializations WHERE name = $1 AND completed_at IS NULL AND NOT EXISTS (SELECT 1 FROM users)',
55
+ [INITIALIZATION_NAME],
56
+ )
57
+ const initializationId = randomUUID()
58
+ const result = await client.query(
59
+ 'INSERT INTO app_initializations (id, name) VALUES ($1, $2) ON CONFLICT (name) DO NOTHING',
60
+ [initializationId, INITIALIZATION_NAME],
61
+ )
62
+ if (result.rowCount !== 1) {
63
+ throw new Error(translate('cli.init.errors.concurrentInitialization'))
64
+ }
65
+ return { initializationId, clearedInterruptedAttempt: cleared.rowCount === 1 }
66
+ }
67
+
68
+ export type InitializationSession = {
69
+ clearedInterruptedAttempt: boolean
70
+ cancelWithoutUsers: () => Promise<void>
71
+ complete: () => Promise<void>
72
+ close: () => Promise<void>
73
+ }
74
+
75
+ export async function openInitializationSession(databaseUrl: string): Promise<InitializationSession> {
76
+ const client = await createCliMaintenanceClient(databaseUrl, { pinned: true })
77
+ try {
78
+ await client.connect()
79
+ const { initializationId, clearedInterruptedAttempt } = await startInitialization(client)
80
+ return {
81
+ clearedInterruptedAttempt,
82
+ cancelWithoutUsers: () => cancelInitializationWithoutUsers(client, initializationId),
83
+ complete: () => completeInitialization(client, initializationId),
84
+ close: () => client.end(),
85
+ }
86
+ } catch (error) {
87
+ await client.end()
88
+ throw error
89
+ }
90
+ }
91
+
92
+ export async function cancelInitializationWithoutUsers(client: InitializationClient, initializationId: string): Promise<void> {
93
+ await client.query(
94
+ 'DELETE FROM app_initializations WHERE id = $1 AND completed_at IS NULL AND NOT EXISTS (SELECT 1 FROM users)',
95
+ [initializationId],
96
+ )
97
+ }
98
+
99
+ export async function completeInitialization(client: InitializationClient, initializationId: string): Promise<void> {
100
+ const result = await client.query(
101
+ 'UPDATE app_initializations SET completed_at = now() WHERE id = $1 AND completed_at IS NULL',
102
+ [initializationId],
103
+ )
104
+ if (result.rowCount !== 1) {
105
+ throw new Error(createInitTranslator(process.env)('cli.init.errors.initializationStateMissing'))
106
+ }
107
+ }
108
+
8
109
  export function describeDatabaseTarget(databaseUrl: string): string {
9
110
  try {
10
111
  const url = new URL(databaseUrl)
@@ -22,3 +123,9 @@ export function formatSkipIfInitializedMessage(existingUsersCount: number, datab
22
123
  ' Not the database you expected? Check DATABASE_URL in .env. To wipe it and seed from scratch: yarn mercato init --reinstall',
23
124
  ]
24
125
  }
126
+
127
+ export function formatIncompleteInitializationMessage(databaseUrl: string): string {
128
+ return createInitTranslator(process.env)('cli.init.errors.incompleteInitialization', {
129
+ database: describeDatabaseTarget(databaseUrl),
130
+ })
131
+ }
@@ -0,0 +1,11 @@
1
+ import { createTranslator } from '@open-mercato/shared/lib/i18n/translate'
2
+ import { createRequire } from 'node:module'
3
+
4
+ const requireLocale = createRequire(import.meta.url)
5
+
6
+ export function createInitTranslator(env: NodeJS.ProcessEnv) {
7
+ const locale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || 'en').split(/[_.-]/)[0].toLowerCase()
8
+ const supportedLocale = ['en', 'pl', 'es', 'de', 'ko'].includes(locale) ? locale : 'en'
9
+ const dictionary: Record<string, string> = requireLocale(`../i18n/${supportedLocale}.json`)
10
+ return createTranslator(dictionary)
11
+ }
@@ -1,17 +1,7 @@
1
1
  import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'
2
2
  import { getPasswordPolicy, validatePassword } from '@open-mercato/shared/lib/auth/passwordPolicy'
3
3
  import { randomBytes } from 'node:crypto'
4
- import { createTranslator } from '@open-mercato/shared/lib/i18n/translate'
5
- import { createRequire } from 'node:module'
6
-
7
- const requireLocale = createRequire(import.meta.url)
8
-
9
- function initTranslator(env: NodeJS.ProcessEnv) {
10
- const locale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || 'en').split(/[_.-]/)[0].toLowerCase()
11
- const supportedLocale = ['en', 'pl', 'es', 'de', 'ko'].includes(locale) ? locale : 'en'
12
- const dictionary: Record<string, string> = requireLocale(`../i18n/${supportedLocale}.json`)
13
- return createTranslator(dictionary)
14
- }
4
+ import { createInitTranslator } from './init-i18n'
15
5
 
16
6
  type EnvReader = (key: string) => string | undefined
17
7
 
@@ -97,7 +87,7 @@ export function resolveInitSuperadminCredentials(args: string[], env: NodeJS.Pro
97
87
  ? parseBooleanToken(skipPolicyArg.split('=')[1] ?? 'true') ?? true
98
88
  : true)
99
89
  if (isProduction) {
100
- const t = initTranslator(env)
90
+ const t = createInitTranslator(env)
101
91
  const placeholder = suppliedPassword?.trim().toLowerCase()
102
92
  if (!suppliedPassword || !placeholder || ['secret', 'password', 'changeme', 'change-me', 'change_me', 'replace-me', 'replace_me'].includes(placeholder)) {
103
93
  throw new Error(t('cli.init.errors.superadminPasswordRequired'))
@@ -10,6 +10,8 @@
10
10
  import { spawn as nodeSpawn } from 'node:child_process'
11
11
  import type { ChildProcess, SpawnOptions } from 'node:child_process'
12
12
  import { getSslConfig } from '@open-mercato/shared/lib/db/ssl'
13
+ import { configureDatabasePool, isDatabaseRuntimeEnabled, resolveDatabaseConnectionUrl, runWithFreshDatabaseExecutionContext } from '@open-mercato/shared/lib/db/runtime'
14
+ import type { DatabasePoolLifecycle } from '@open-mercato/shared/lib/db/runtime'
13
15
 
14
16
  export type SchedulerScheduleProbeResult = {
15
17
  enabledSchedules: number
@@ -80,15 +82,39 @@ export async function probeEnabledSchedules(env: NodeJS.ProcessEnv = process.env
80
82
  }
81
83
  }
82
84
 
83
- const { Client } = await import('pg')
84
- const client = new Client({
85
- connectionString: databaseUrl,
86
- ssl: getSslConfig(),
87
- })
85
+ if (isDatabaseRuntimeEnabled()) {
86
+ return runWithFreshDatabaseExecutionContext({
87
+ kind: 'maintenance', tenantId: null, source: 'scheduler', operation: 'scheduler.lazy-probe',
88
+ }, () => probeScheduleConnection(databaseUrl, true))
89
+ }
90
+ return probeScheduleConnection(databaseUrl, false)
91
+ }
88
92
 
93
+ async function probeScheduleConnection(databaseUrl: string, maintenance: boolean): Promise<SchedulerScheduleProbeResult> {
94
+ let clientEnded = false
95
+ let lifecycle: DatabasePoolLifecycle | undefined
96
+ let release: (() => void) | undefined
97
+ let client: InstanceType<typeof import('pg').Client> | undefined
89
98
  try {
99
+ const { Client } = await import('pg')
100
+ client = new Client({
101
+ connectionString: maintenance ? resolveDatabaseConnectionUrl('maintenance', databaseUrl) : databaseUrl,
102
+ ssl: getSslConfig(),
103
+ ...(maintenance ? { connectionTimeoutMillis: 5000, query_timeout: 5000 } : {}),
104
+ })
105
+
90
106
  await client.connect()
91
- const result = await client.query(`
107
+ let connection: Pick<InstanceType<typeof Client>, 'query'> = client
108
+ if (maintenance) {
109
+ const physical = { query: client.query.bind(client), release: () => undefined }
110
+ const pool = { connect: async () => physical, get ended() { return clientEnded } }
111
+ lifecycle = configureDatabasePool(pool, { id: 'scheduler-lazy-probe', purpose: 'maintenance', tables: ['scheduled_jobs'] })
112
+ await lifecycle.ready()
113
+ const guarded = await pool.connect()
114
+ connection = guarded
115
+ release = guarded.release
116
+ }
117
+ const result = await connection.query(`
92
118
  select
93
119
  count(*)::int as enabled_schedules,
94
120
  count(*) filter (where next_run_at <= now())::int as due_schedules
@@ -117,7 +143,14 @@ export async function probeEnabledSchedules(env: NodeJS.ProcessEnv = process.env
117
143
  errorMessage: error instanceof Error ? error.message : String(error),
118
144
  }
119
145
  } finally {
120
- await client.end().catch(() => undefined)
146
+ try { release?.() } finally {
147
+ try {
148
+ if (client) {
149
+ await client.end()
150
+ clientEnded = true
151
+ }
152
+ } finally { lifecycle?.dispose() }
153
+ }
121
154
  }
122
155
  }
123
156