@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.
- package/.turbo/turbo-build.log +6 -2
- package/dist/agentic/guides/module-facts.json +356 -399
- package/dist/agentic/guides/module-facts.v2.json +356 -399
- package/dist/agentic/guides/modules/agent_orchestrator/active-extension-bindings.md +1 -1
- package/dist/agentic/guides/modules/agent_orchestrator/exact-override-targets.md +1 -1
- package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
- package/dist/agentic/guides/modules/agent_orchestrator/workers.md +1 -1
- package/dist/agentic/guides/modules/ai_assistant/exact-override-targets.md +2 -2
- package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
- package/dist/agentic/guides/modules/ai_assistant/workers.md +2 -2
- package/dist/agentic/guides/modules/api_docs/index.md +1 -1
- package/dist/agentic/guides/modules/api_keys/index.md +1 -1
- package/dist/agentic/guides/modules/assisted_selling/index.md +1 -1
- package/dist/agentic/guides/modules/attachments/index.md +1 -1
- package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
- package/dist/agentic/guides/modules/auth/entities.md +1 -0
- package/dist/agentic/guides/modules/auth/index.md +2 -2
- package/dist/agentic/guides/modules/auth/umes-hosts.md +1 -0
- package/dist/agentic/guides/modules/availability/index.md +1 -1
- package/dist/agentic/guides/modules/backups/index.md +1 -1
- package/dist/agentic/guides/modules/business_rules/index.md +1 -1
- package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
- package/dist/agentic/guides/modules/cart/index.md +1 -1
- package/dist/agentic/guides/modules/catalog/domain-commands.md +0 -1
- package/dist/agentic/guides/modules/catalog/index.md +1 -1
- package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
- package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
- package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
- package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
- package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
- package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
- package/dist/agentic/guides/modules/channel_ms365/index.md +1 -1
- package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
- package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
- package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
- package/dist/agentic/guides/modules/checkout/index.md +1 -1
- package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
- package/dist/agentic/guides/modules/configs/index.md +1 -1
- package/dist/agentic/guides/modules/content/index.md +1 -1
- package/dist/agentic/guides/modules/currencies/index.md +1 -1
- package/dist/agentic/guides/modules/customer_accounts/exact-override-targets.md +4 -4
- package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
- package/dist/agentic/guides/modules/customer_accounts/workers.md +4 -4
- package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
- package/dist/agentic/guides/modules/customers/index.md +1 -1
- package/dist/agentic/guides/modules/dashboards/index.md +1 -1
- package/dist/agentic/guides/modules/data_sync/index.md +1 -1
- package/dist/agentic/guides/modules/design_system/index.md +1 -1
- package/dist/agentic/guides/modules/devices/index.md +1 -1
- package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
- package/dist/agentic/guides/modules/directory/index.md +1 -1
- package/dist/agentic/guides/modules/documents/index.md +1 -1
- package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
- package/dist/agentic/guides/modules/entities/index.md +1 -1
- package/dist/agentic/guides/modules/eudr/index.md +1 -1
- package/dist/agentic/guides/modules/events/index.md +1 -1
- package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
- package/dist/agentic/guides/modules/forms/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
- package/dist/agentic/guides/modules/generators/index.md +1 -1
- package/dist/agentic/guides/modules/gus_regon/index.md +1 -1
- package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
- package/dist/agentic/guides/modules/integrations/index.md +1 -1
- package/dist/agentic/guides/modules/ledger/index.md +1 -1
- package/dist/agentic/guides/modules/maintenance/index.md +1 -1
- package/dist/agentic/guides/modules/messages/index.md +1 -1
- package/dist/agentic/guides/modules/notifications/index.md +1 -1
- package/dist/agentic/guides/modules/onboarding/index.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/exact-override-targets.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/workers.md +1 -1
- package/dist/agentic/guides/modules/perspectives/index.md +1 -1
- package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
- package/dist/agentic/guides/modules/planner/index.md +1 -1
- package/dist/agentic/guides/modules/portal/index.md +1 -1
- package/dist/agentic/guides/modules/progress/index.md +1 -1
- package/dist/agentic/guides/modules/promotions/index.md +1 -1
- package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
- package/dist/agentic/guides/modules/query_index/index.md +1 -1
- package/dist/agentic/guides/modules/record_locks/index.md +1 -1
- package/dist/agentic/guides/modules/resources/index.md +1 -1
- package/dist/agentic/guides/modules/sales/exact-override-targets.md +4 -4
- package/dist/agentic/guides/modules/sales/index.md +1 -1
- package/dist/agentic/guides/modules/sales/setup.md +1 -1
- package/dist/agentic/guides/modules/sales_invoices_gl_posting/index.md +1 -1
- package/dist/agentic/guides/modules/scheduler/di-registrations-rich.md +3 -3
- package/dist/agentic/guides/modules/scheduler/di-service-tokens.md +3 -3
- package/dist/agentic/guides/modules/scheduler/exact-override-targets.md +4 -9
- package/dist/agentic/guides/modules/scheduler/index.md +3 -4
- package/dist/agentic/guides/modules/scheduler/workers.md +1 -1
- package/dist/agentic/guides/modules/search/di-registrations-rich.md +4 -4
- package/dist/agentic/guides/modules/search/di-service-tokens.md +13 -0
- package/dist/agentic/guides/modules/search/exact-override-targets.md +4 -4
- package/dist/agentic/guides/modules/search/index.md +3 -2
- package/dist/agentic/guides/modules/security/index.md +1 -1
- package/dist/agentic/guides/modules/seeds/index.md +1 -1
- package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
- package/dist/agentic/guides/modules/sso/index.md +1 -1
- package/dist/agentic/guides/modules/staff/index.md +1 -1
- package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
- package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
- package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
- package/dist/agentic/guides/modules/sync_shopify/index.md +1 -1
- package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
- package/dist/agentic/guides/modules/telemetry/index.md +1 -1
- package/dist/agentic/guides/modules/tenant_boundaries/generator-plugins.md +11 -0
- package/dist/agentic/guides/modules/tenant_boundaries/index.md +13 -0
- package/dist/agentic/guides/modules/tenant_boundaries/owned-contract-module-metadata.md +11 -0
- package/dist/agentic/guides/modules/tillio/index.md +1 -1
- package/dist/agentic/guides/modules/translations/index.md +1 -1
- package/dist/agentic/guides/modules/upgrade_actions/index.md +1 -1
- package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
- package/dist/agentic/guides/modules/webhooks/index.md +1 -1
- package/dist/agentic/guides/modules/wms/index.md +1 -1
- package/dist/agentic/guides/modules/workflows/index.md +1 -1
- package/dist/agentic/guides/reference-module-facts.json +2 -2
- package/dist/agentic/guides/reference-modules/example/index.md +1 -1
- package/dist/agentic/guides/upstream/manifest.json +1 -1
- package/dist/agentic/shared/AGENTS.md.template +3 -3
- package/dist/agentic/shared/ai/harness/cases.json +4 -4
- package/dist/bin.js +6 -3
- package/dist/bin.js.map +2 -2
- package/dist/i18n/de.json +5 -1
- package/dist/i18n/en.json +5 -1
- package/dist/i18n/es.json +5 -1
- package/dist/i18n/ko.json +5 -1
- package/dist/i18n/pl.json +5 -1
- package/dist/lib/cli-bootstrap-mode.js +10 -1
- package/dist/lib/cli-bootstrap-mode.js.map +2 -2
- package/dist/lib/db/commands.js +18 -3
- package/dist/lib/db/commands.js.map +2 -2
- package/dist/lib/db/maintenance-client.js +72 -0
- package/dist/lib/db/maintenance-client.js.map +7 -0
- package/dist/lib/generate-watch-structure.js +2 -1
- package/dist/lib/generate-watch-structure.js.map +2 -2
- package/dist/lib/generators/database-declarations.js +21 -0
- package/dist/lib/generators/database-declarations.js.map +7 -0
- package/dist/lib/generators/module-registry.js +19 -3
- package/dist/lib/generators/module-registry.js.map +2 -2
- package/dist/lib/init-existing-database.js +91 -1
- package/dist/lib/init-existing-database.js.map +2 -2
- package/dist/lib/init-i18n.js +13 -0
- package/dist/lib/init-i18n.js.map +7 -0
- package/dist/lib/init-secrets.js +2 -10
- package/dist/lib/init-secrets.js.map +2 -2
- package/dist/lib/scheduler-supervisor.js +47 -7
- package/dist/lib/scheduler-supervisor.js.map +2 -2
- package/dist/lib/server-start-lock.js +120 -21
- package/dist/lib/server-start-lock.js.map +2 -2
- package/dist/lib/worker-job-handler.js +36 -26
- package/dist/lib/worker-job-handler.js.map +2 -2
- package/dist/mercato.js +93 -54
- package/dist/mercato.js.map +3 -3
- package/package.json +7 -7
- package/src/__tests__/mercato.test.ts +166 -9
- package/src/bin.ts +10 -4
- package/src/i18n/de.json +5 -1
- package/src/i18n/en.json +5 -1
- package/src/i18n/es.json +5 -1
- package/src/i18n/ko.json +5 -1
- package/src/i18n/pl.json +5 -1
- package/src/lib/__tests__/cli-bootstrap-mode.test.ts +76 -1
- package/src/lib/__tests__/generate-watch-structure.test.ts +26 -0
- package/src/lib/__tests__/rotation-kms-warning-presentation.test.ts +1 -1
- package/src/lib/__tests__/scheduler-supervisor.test.ts +107 -0
- package/src/lib/__tests__/server-start-lock.test.ts +400 -0
- package/src/lib/__tests__/worker-job-handler.database.test.ts +76 -0
- package/src/lib/cli-bootstrap-mode.ts +12 -2
- package/src/lib/db/__tests__/commands.migrate-reindex.test.ts +72 -1
- package/src/lib/db/__tests__/maintenance-client.test.ts +70 -0
- package/src/lib/db/commands.ts +20 -6
- package/src/lib/db/maintenance-client.ts +54 -0
- package/src/lib/generate-watch-structure.ts +2 -1
- package/src/lib/generators/__tests__/database-declarations.test.ts +69 -0
- package/src/lib/generators/__tests__/incremental-registry.test.ts +1 -1
- package/src/lib/generators/__tests__/module-subset.test.ts +17 -1
- package/src/lib/generators/database-declarations.ts +19 -0
- package/src/lib/generators/module-registry.ts +23 -4
- package/src/lib/init-existing-database.ts +107 -0
- package/src/lib/init-i18n.ts +11 -0
- package/src/lib/init-secrets.ts +2 -12
- package/src/lib/scheduler-supervisor.ts +40 -7
- package/src/lib/server-start-lock.ts +170 -19
- package/src/lib/worker-job-handler.ts +39 -28
- package/src/mercato.ts +92 -53
- package/dist/agentic/guides/modules/scheduler/cli-commands.md +0 -15
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { spawn, type ChildProcess } from 'node:child_process'
|
|
2
|
+
import { createHash } from 'node:crypto'
|
|
1
3
|
import fs from 'node:fs'
|
|
2
4
|
import os from 'node:os'
|
|
3
5
|
import path from 'node:path'
|
|
@@ -5,8 +7,105 @@ import path from 'node:path'
|
|
|
5
7
|
import {
|
|
6
8
|
acquireServerStartLock,
|
|
7
9
|
getServerStartLockPath,
|
|
10
|
+
readProcessStartTime,
|
|
8
11
|
} from '../server-start-lock'
|
|
9
12
|
|
|
13
|
+
const BOOT_ID_PATH = '/proc/sys/kernel/random/boot_id'
|
|
14
|
+
const CURRENT_BOOT_ID = '6f1c2a7e-0b3d-4c58-9a51-2f7e8d4b1c90'
|
|
15
|
+
const hasProcFs = fs.existsSync(`/proc/${process.pid}/stat`)
|
|
16
|
+
|
|
17
|
+
function buildStatLine(pid: number, startTime: string, command = 'node'): string {
|
|
18
|
+
const fieldsBeforeStartTime = ['S', ...Array.from({ length: 18 }, () => '0')]
|
|
19
|
+
return `${pid} (${command}) ${[...fieldsBeforeStartTime, startTime, '1024', '256'].join(' ')}\n`
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function mockProcFs(entries: Record<string, string>) {
|
|
23
|
+
const realReadFileSync = fs.readFileSync
|
|
24
|
+
return jest.spyOn(fs, 'readFileSync').mockImplementation(((
|
|
25
|
+
file: fs.PathOrFileDescriptor,
|
|
26
|
+
options?: Parameters<typeof fs.readFileSync>[1],
|
|
27
|
+
) => {
|
|
28
|
+
if (typeof file === 'string' && file.startsWith('/proc/')) {
|
|
29
|
+
const content = entries[file]
|
|
30
|
+
if (content === undefined) {
|
|
31
|
+
const missing = new Error(`ENOENT: no such file or directory, open '${file}'`) as NodeJS.ErrnoException
|
|
32
|
+
missing.code = 'ENOENT'
|
|
33
|
+
throw missing
|
|
34
|
+
}
|
|
35
|
+
return content
|
|
36
|
+
}
|
|
37
|
+
return realReadFileSync(file, options)
|
|
38
|
+
}) as typeof fs.readFileSync)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function writeLock(lockPath: string, record: Record<string, unknown>) {
|
|
42
|
+
fs.mkdirSync(path.dirname(lockPath), { recursive: true })
|
|
43
|
+
fs.writeFileSync(lockPath, JSON.stringify(record))
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const LOCK_MODULE_PATH = path.resolve(__dirname, '../server-start-lock.ts')
|
|
47
|
+
|
|
48
|
+
// Runs acquireServerStartLock in a separate Node process. The "late" contender
|
|
49
|
+
// pauses right after it has inspected the stale lock, at the first step that
|
|
50
|
+
// could remove it (claiming the takeover guard, or deleting the lock file), and
|
|
51
|
+
// waits for the `late-resume` marker. Each contender reports `acquired` or
|
|
52
|
+
// `refused` and stays alive, holding what it got, until the `exit` marker.
|
|
53
|
+
const CONTENDER_SCRIPT = `
|
|
54
|
+
import fs from 'node:fs'
|
|
55
|
+
import path from 'node:path'
|
|
56
|
+
|
|
57
|
+
const [modulePath, appDir, role, syncDir] = process.argv.slice(2)
|
|
58
|
+
const lockPath = path.join(appDir, '.mercato', 'server-start.lock')
|
|
59
|
+
const marker = (name) => path.join(syncDir, name)
|
|
60
|
+
const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
|
|
61
|
+
const waitFor = (name) => { while (!fs.existsSync(marker(name))) sleep(5) }
|
|
62
|
+
|
|
63
|
+
if (role === 'late') {
|
|
64
|
+
const realLinkSync = fs.linkSync
|
|
65
|
+
const realRmSync = fs.rmSync
|
|
66
|
+
let paused = false
|
|
67
|
+
const pause = () => {
|
|
68
|
+
if (paused) return
|
|
69
|
+
paused = true
|
|
70
|
+
fs.writeFileSync(marker('late-paused'), '')
|
|
71
|
+
waitFor('late-resume')
|
|
72
|
+
}
|
|
73
|
+
fs.linkSync = (source, target) => {
|
|
74
|
+
if (String(target).endsWith('.takeover')) pause()
|
|
75
|
+
return realLinkSync(source, target)
|
|
76
|
+
}
|
|
77
|
+
fs.rmSync = (target, options) => {
|
|
78
|
+
if (String(target) === lockPath) pause()
|
|
79
|
+
return realRmSync(target, options)
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const { acquireServerStartLock } = await import(modulePath)
|
|
84
|
+
let result
|
|
85
|
+
try {
|
|
86
|
+
acquireServerStartLock(appDir, { port: role })
|
|
87
|
+
result = 'acquired'
|
|
88
|
+
} catch (error) {
|
|
89
|
+
result = 'refused: ' + error.message
|
|
90
|
+
}
|
|
91
|
+
fs.writeFileSync(marker(role + '-result'), result)
|
|
92
|
+
waitFor('exit')
|
|
93
|
+
`
|
|
94
|
+
|
|
95
|
+
async function waitForFile(filePath: string, timeoutMs = 15000): Promise<string> {
|
|
96
|
+
const deadline = Date.now() + timeoutMs
|
|
97
|
+
while (!fs.existsSync(filePath)) {
|
|
98
|
+
if (Date.now() > deadline) throw new Error(`Timed out waiting for ${filePath}`)
|
|
99
|
+
await new Promise((resolve) => setTimeout(resolve, 5))
|
|
100
|
+
}
|
|
101
|
+
return fs.readFileSync(filePath, 'utf8')
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function waitForExit(child: ChildProcess): Promise<void> {
|
|
105
|
+
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve()
|
|
106
|
+
return new Promise((resolve) => child.once('exit', () => resolve()))
|
|
107
|
+
}
|
|
108
|
+
|
|
10
109
|
describe('server start lock', () => {
|
|
11
110
|
let tempDir: string
|
|
12
111
|
|
|
@@ -15,6 +114,7 @@ describe('server start lock', () => {
|
|
|
15
114
|
})
|
|
16
115
|
|
|
17
116
|
afterEach(() => {
|
|
117
|
+
jest.restoreAllMocks()
|
|
18
118
|
fs.rmSync(tempDir, { recursive: true, force: true })
|
|
19
119
|
})
|
|
20
120
|
|
|
@@ -63,4 +163,304 @@ describe('server start lock', () => {
|
|
|
63
163
|
`Another Open Mercato production server is already running for ${tempDir}`,
|
|
64
164
|
)
|
|
65
165
|
})
|
|
166
|
+
|
|
167
|
+
it('takes over a lock whose pid now belongs to an unrelated process', () => {
|
|
168
|
+
mockProcFs({
|
|
169
|
+
[BOOT_ID_PATH]: `${CURRENT_BOOT_ID}\n`,
|
|
170
|
+
[`/proc/${process.pid}/stat`]: buildStatLine(process.pid, '90210'),
|
|
171
|
+
[`/proc/${process.ppid}/stat`]: buildStatLine(process.ppid, '4321', 'sh'),
|
|
172
|
+
})
|
|
173
|
+
const lockPath = getServerStartLockPath(tempDir)
|
|
174
|
+
writeLock(lockPath, {
|
|
175
|
+
pid: process.ppid,
|
|
176
|
+
port: '3000',
|
|
177
|
+
startedAt: new Date().toISOString(),
|
|
178
|
+
processStartTime: '1234',
|
|
179
|
+
bootId: CURRENT_BOOT_ID,
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
const handle = acquireServerStartLock(tempDir, { port: '3000' })
|
|
183
|
+
|
|
184
|
+
const written = JSON.parse(fs.readFileSync(lockPath, 'utf8'))
|
|
185
|
+
expect(written).toMatchObject({
|
|
186
|
+
pid: process.pid,
|
|
187
|
+
port: '3000',
|
|
188
|
+
processStartTime: '90210',
|
|
189
|
+
bootId: CURRENT_BOOT_ID,
|
|
190
|
+
})
|
|
191
|
+
|
|
192
|
+
handle.release()
|
|
193
|
+
})
|
|
194
|
+
|
|
195
|
+
it('refuses a lock whose owner is still the same running process', () => {
|
|
196
|
+
mockProcFs({
|
|
197
|
+
[BOOT_ID_PATH]: `${CURRENT_BOOT_ID}\n`,
|
|
198
|
+
[`/proc/${process.pid}/stat`]: buildStatLine(process.pid, '90210'),
|
|
199
|
+
[`/proc/${process.ppid}/stat`]: buildStatLine(process.ppid, '1234'),
|
|
200
|
+
})
|
|
201
|
+
const lockPath = getServerStartLockPath(tempDir)
|
|
202
|
+
writeLock(lockPath, {
|
|
203
|
+
pid: process.ppid,
|
|
204
|
+
port: '3000',
|
|
205
|
+
startedAt: new Date().toISOString(),
|
|
206
|
+
processStartTime: '1234',
|
|
207
|
+
bootId: CURRENT_BOOT_ID,
|
|
208
|
+
})
|
|
209
|
+
|
|
210
|
+
expect(() => acquireServerStartLock(tempDir, { port: '3000' })).toThrow(
|
|
211
|
+
`Another Open Mercato production server is already running for ${tempDir} (pid ${process.ppid} on port 3000)`,
|
|
212
|
+
)
|
|
213
|
+
expect(JSON.parse(fs.readFileSync(lockPath, 'utf8')).pid).toBe(process.ppid)
|
|
214
|
+
})
|
|
215
|
+
|
|
216
|
+
it('takes over a lock written before a reboot', () => {
|
|
217
|
+
mockProcFs({
|
|
218
|
+
[BOOT_ID_PATH]: `${CURRENT_BOOT_ID}\n`,
|
|
219
|
+
[`/proc/${process.pid}/stat`]: buildStatLine(process.pid, '90210'),
|
|
220
|
+
[`/proc/${process.ppid}/stat`]: buildStatLine(process.ppid, '1234'),
|
|
221
|
+
})
|
|
222
|
+
const lockPath = getServerStartLockPath(tempDir)
|
|
223
|
+
writeLock(lockPath, {
|
|
224
|
+
pid: process.ppid,
|
|
225
|
+
port: '3000',
|
|
226
|
+
startedAt: new Date().toISOString(),
|
|
227
|
+
processStartTime: '1234',
|
|
228
|
+
bootId: 'a-previous-boot',
|
|
229
|
+
})
|
|
230
|
+
|
|
231
|
+
const handle = acquireServerStartLock(tempDir, { port: '3000' })
|
|
232
|
+
|
|
233
|
+
expect(JSON.parse(fs.readFileSync(lockPath, 'utf8')).pid).toBe(process.pid)
|
|
234
|
+
handle.release()
|
|
235
|
+
})
|
|
236
|
+
|
|
237
|
+
it('keeps refusing a live pid from a lock written by an older version', () => {
|
|
238
|
+
mockProcFs({
|
|
239
|
+
[BOOT_ID_PATH]: `${CURRENT_BOOT_ID}\n`,
|
|
240
|
+
[`/proc/${process.pid}/stat`]: buildStatLine(process.pid, '90210'),
|
|
241
|
+
[`/proc/${process.ppid}/stat`]: buildStatLine(process.ppid, '4321'),
|
|
242
|
+
})
|
|
243
|
+
const lockPath = getServerStartLockPath(tempDir)
|
|
244
|
+
writeLock(lockPath, {
|
|
245
|
+
pid: process.ppid,
|
|
246
|
+
port: '3000',
|
|
247
|
+
startedAt: new Date().toISOString(),
|
|
248
|
+
})
|
|
249
|
+
|
|
250
|
+
expect(() => acquireServerStartLock(tempDir, { port: '3000' })).toThrow(
|
|
251
|
+
`Another Open Mercato production server is already running for ${tempDir}`,
|
|
252
|
+
)
|
|
253
|
+
})
|
|
254
|
+
|
|
255
|
+
it('falls back to the pid check where /proc is unavailable', () => {
|
|
256
|
+
mockProcFs({})
|
|
257
|
+
const lockPath = getServerStartLockPath(tempDir)
|
|
258
|
+
writeLock(lockPath, {
|
|
259
|
+
pid: process.ppid,
|
|
260
|
+
port: '3000',
|
|
261
|
+
startedAt: new Date().toISOString(),
|
|
262
|
+
processStartTime: '1234',
|
|
263
|
+
bootId: CURRENT_BOOT_ID,
|
|
264
|
+
})
|
|
265
|
+
|
|
266
|
+
expect(() => acquireServerStartLock(tempDir, { port: '3000' })).toThrow(
|
|
267
|
+
`Another Open Mercato production server is already running for ${tempDir}`,
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
fs.rmSync(lockPath)
|
|
271
|
+
const handle = acquireServerStartLock(tempDir, { port: '3000' })
|
|
272
|
+
expect(JSON.parse(fs.readFileSync(lockPath, 'utf8'))).toMatchObject({
|
|
273
|
+
pid: process.pid,
|
|
274
|
+
processStartTime: null,
|
|
275
|
+
bootId: null,
|
|
276
|
+
})
|
|
277
|
+
handle.release()
|
|
278
|
+
})
|
|
279
|
+
|
|
280
|
+
it('reads the start time when the command name contains spaces and parentheses', () => {
|
|
281
|
+
mockProcFs({
|
|
282
|
+
'/proc/4242/stat': buildStatLine(4242, '777001', 'node (server) 9 S'),
|
|
283
|
+
'/proc/4243/stat': '4243 (broken',
|
|
284
|
+
})
|
|
285
|
+
|
|
286
|
+
expect(readProcessStartTime(4242)).toBe('777001')
|
|
287
|
+
expect(readProcessStartTime(4243)).toBeNull()
|
|
288
|
+
expect(readProcessStartTime(4244)).toBeNull()
|
|
289
|
+
})
|
|
290
|
+
|
|
291
|
+
;(hasProcFs ? it : it.skip)('identifies the real lock owner through /proc', () => {
|
|
292
|
+
const parentStartTime = readProcessStartTime(process.ppid)
|
|
293
|
+
expect(parentStartTime).toMatch(/^\d+$/)
|
|
294
|
+
const lockPath = getServerStartLockPath(tempDir)
|
|
295
|
+
writeLock(lockPath, {
|
|
296
|
+
pid: process.ppid,
|
|
297
|
+
port: '3000',
|
|
298
|
+
startedAt: new Date().toISOString(),
|
|
299
|
+
processStartTime: parentStartTime,
|
|
300
|
+
})
|
|
301
|
+
|
|
302
|
+
expect(() => acquireServerStartLock(tempDir, { port: '3000' })).toThrow(
|
|
303
|
+
`Another Open Mercato production server is already running for ${tempDir}`,
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
writeLock(lockPath, {
|
|
307
|
+
pid: process.ppid,
|
|
308
|
+
port: '3000',
|
|
309
|
+
startedAt: new Date().toISOString(),
|
|
310
|
+
processStartTime: `${parentStartTime}1`,
|
|
311
|
+
})
|
|
312
|
+
const handle = acquireServerStartLock(tempDir, { port: '3000' })
|
|
313
|
+
expect(JSON.parse(fs.readFileSync(lockPath, 'utf8')).processStartTime).toBe(readProcessStartTime(process.pid))
|
|
314
|
+
handle.release()
|
|
315
|
+
})
|
|
316
|
+
|
|
317
|
+
it('does not let an old owner release a lock that has been taken over', () => {
|
|
318
|
+
const handle = acquireServerStartLock(tempDir, { port: '3000' })
|
|
319
|
+
const lockPath = handle.lockPath
|
|
320
|
+
const winner = {
|
|
321
|
+
pid: process.pid,
|
|
322
|
+
port: '3001',
|
|
323
|
+
startedAt: new Date().toISOString(),
|
|
324
|
+
token: 'winner-token',
|
|
325
|
+
}
|
|
326
|
+
writeLock(lockPath, winner)
|
|
327
|
+
|
|
328
|
+
handle.release()
|
|
329
|
+
|
|
330
|
+
expect(JSON.parse(fs.readFileSync(lockPath, 'utf8'))).toMatchObject(winner)
|
|
331
|
+
})
|
|
332
|
+
|
|
333
|
+
it('waits for a live takeover in progress and then refuses the new owner', () => {
|
|
334
|
+
const lockPath = getServerStartLockPath(tempDir)
|
|
335
|
+
const staleRaw = JSON.stringify({ pid: 999999, port: '3000', startedAt: new Date(0).toISOString() })
|
|
336
|
+
fs.mkdirSync(path.dirname(lockPath), { recursive: true })
|
|
337
|
+
fs.writeFileSync(lockPath, staleRaw)
|
|
338
|
+
|
|
339
|
+
// Another live process holds the takeover guard of this generation. While it
|
|
340
|
+
// holds it, this process must neither remove the stale lock nor claim a guard
|
|
341
|
+
// slot of its own. Once the holder has written its lock, this process refuses.
|
|
342
|
+
const realLinkSync = fs.linkSync
|
|
343
|
+
let guardAttempts = 0
|
|
344
|
+
jest.spyOn(fs, 'linkSync').mockImplementation(((source: fs.PathLike, target: fs.PathLike) => {
|
|
345
|
+
if (String(target).endsWith('.takeover')) {
|
|
346
|
+
guardAttempts += 1
|
|
347
|
+
if (guardAttempts === 1) {
|
|
348
|
+
realLinkSync(source, target)
|
|
349
|
+
fs.writeFileSync(String(target), JSON.stringify({ pid: process.ppid, port: '3001', startedAt: '' }))
|
|
350
|
+
const busy = new Error('EEXIST') as NodeJS.ErrnoException
|
|
351
|
+
busy.code = 'EEXIST'
|
|
352
|
+
throw busy
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
return realLinkSync(source, target)
|
|
356
|
+
}) as typeof fs.linkSync)
|
|
357
|
+
const realRmSync = fs.rmSync
|
|
358
|
+
let finishedForeignTakeover = false
|
|
359
|
+
jest.spyOn(global.Atomics, 'wait').mockImplementation(() => {
|
|
360
|
+
if (!finishedForeignTakeover) {
|
|
361
|
+
finishedForeignTakeover = true
|
|
362
|
+
expect(fs.readFileSync(lockPath, 'utf8')).toBe(staleRaw)
|
|
363
|
+
realRmSync(lockPath)
|
|
364
|
+
fs.writeFileSync(lockPath, JSON.stringify({ pid: process.ppid, port: '3001', startedAt: '' }))
|
|
365
|
+
for (const entry of fs.readdirSync(path.dirname(lockPath))) {
|
|
366
|
+
if (entry.endsWith('.takeover')) realRmSync(path.join(path.dirname(lockPath), entry))
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return 'timed-out'
|
|
370
|
+
})
|
|
371
|
+
|
|
372
|
+
expect(() => acquireServerStartLock(tempDir, { port: '3000' })).toThrow(
|
|
373
|
+
`Another Open Mercato production server is already running for ${tempDir} (pid ${process.ppid} on port 3001)`,
|
|
374
|
+
)
|
|
375
|
+
expect(guardAttempts).toBe(1)
|
|
376
|
+
expect(JSON.parse(fs.readFileSync(lockPath, 'utf8')).port).toBe('3001')
|
|
377
|
+
})
|
|
378
|
+
|
|
379
|
+
it('skips a takeover guard left behind by a process that died mid-takeover', () => {
|
|
380
|
+
const lockPath = getServerStartLockPath(tempDir)
|
|
381
|
+
fs.mkdirSync(path.dirname(lockPath), { recursive: true })
|
|
382
|
+
fs.writeFileSync(lockPath, JSON.stringify({ pid: 999999, port: '3000', startedAt: new Date(0).toISOString() }))
|
|
383
|
+
const realLinkSync = fs.linkSync
|
|
384
|
+
let plantedDeadGuard = false
|
|
385
|
+
jest.spyOn(fs, 'linkSync').mockImplementation(((source: fs.PathLike, target: fs.PathLike) => {
|
|
386
|
+
if (!plantedDeadGuard && String(target).endsWith('.0.takeover')) {
|
|
387
|
+
plantedDeadGuard = true
|
|
388
|
+
fs.writeFileSync(String(target), JSON.stringify({ pid: 999998, port: null, startedAt: '' }))
|
|
389
|
+
}
|
|
390
|
+
return realLinkSync(source, target)
|
|
391
|
+
}) as typeof fs.linkSync)
|
|
392
|
+
|
|
393
|
+
const handle = acquireServerStartLock(tempDir, { port: '3000' })
|
|
394
|
+
|
|
395
|
+
expect(plantedDeadGuard).toBe(true)
|
|
396
|
+
expect(JSON.parse(fs.readFileSync(lockPath, 'utf8')).pid).toBe(process.pid)
|
|
397
|
+
handle.release()
|
|
398
|
+
expect(fs.readdirSync(path.dirname(lockPath))).toEqual([])
|
|
399
|
+
})
|
|
400
|
+
|
|
401
|
+
it('preserves a live takeover guard when reading it fails', () => {
|
|
402
|
+
const lockPath = getServerStartLockPath(tempDir)
|
|
403
|
+
const staleLock = { pid: 999999, port: '3000', startedAt: new Date(0).toISOString() }
|
|
404
|
+
writeLock(lockPath, staleLock)
|
|
405
|
+
|
|
406
|
+
const generation = createHash('sha256').update(JSON.stringify(staleLock)).digest('hex').slice(0, 16)
|
|
407
|
+
const guardPath = `${lockPath}.${generation}.0.takeover`
|
|
408
|
+
const liveGuard = { pid: process.ppid, port: null, startedAt: '' }
|
|
409
|
+
writeLock(guardPath, liveGuard)
|
|
410
|
+
|
|
411
|
+
const readError = Object.assign(new Error('takeover guard read failed'), { code: 'EIO' })
|
|
412
|
+
const realReadFileSync = fs.readFileSync
|
|
413
|
+
const readSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(((
|
|
414
|
+
filePath: fs.PathOrFileDescriptor,
|
|
415
|
+
options?: Parameters<typeof fs.readFileSync>[1],
|
|
416
|
+
) => {
|
|
417
|
+
if (filePath === guardPath) throw readError
|
|
418
|
+
return realReadFileSync(filePath, options)
|
|
419
|
+
}) as typeof fs.readFileSync)
|
|
420
|
+
|
|
421
|
+
expect(() => acquireServerStartLock(tempDir)).toThrow(readError)
|
|
422
|
+
readSpy.mockRestore()
|
|
423
|
+
expect(JSON.parse(fs.readFileSync(guardPath, 'utf8'))).toEqual(liveGuard)
|
|
424
|
+
expect(JSON.parse(fs.readFileSync(lockPath, 'utf8'))).toEqual(staleLock)
|
|
425
|
+
})
|
|
426
|
+
|
|
427
|
+
it('lets exactly one of two processes recover the same stale lock', async () => {
|
|
428
|
+
const scriptPath = path.join(tempDir, 'contender.mjs')
|
|
429
|
+
fs.writeFileSync(scriptPath, CONTENDER_SCRIPT)
|
|
430
|
+
const env = { ...process.env }
|
|
431
|
+
delete env.NODE_OPTIONS
|
|
432
|
+
|
|
433
|
+
for (let trial = 0; trial < 10; trial += 1) {
|
|
434
|
+
const appDir = path.join(tempDir, `app-${trial}`)
|
|
435
|
+
const syncDir = path.join(tempDir, `sync-${trial}`)
|
|
436
|
+
fs.mkdirSync(syncDir, { recursive: true })
|
|
437
|
+
const lockPath = getServerStartLockPath(appDir)
|
|
438
|
+
writeLock(lockPath, { pid: 999999, port: '3000', startedAt: new Date(0).toISOString() })
|
|
439
|
+
|
|
440
|
+
const startContender = (role: 'early' | 'late') =>
|
|
441
|
+
spawn(process.execPath, [scriptPath, LOCK_MODULE_PATH, appDir, role, syncDir], {
|
|
442
|
+
env,
|
|
443
|
+
stdio: ['ignore', 'ignore', 'inherit'],
|
|
444
|
+
})
|
|
445
|
+
|
|
446
|
+
const late = startContender('late')
|
|
447
|
+
let early: ChildProcess | null = null
|
|
448
|
+
try {
|
|
449
|
+
await waitForFile(path.join(syncDir, 'late-paused'))
|
|
450
|
+
early = startContender('early')
|
|
451
|
+
expect(await waitForFile(path.join(syncDir, 'early-result'))).toBe('acquired')
|
|
452
|
+
|
|
453
|
+
fs.writeFileSync(path.join(syncDir, 'late-resume'), '')
|
|
454
|
+
expect(await waitForFile(path.join(syncDir, 'late-result'))).toContain(
|
|
455
|
+
`refused: [server] Another Open Mercato production server is already running for ${appDir} (pid ${early.pid} on port early)`,
|
|
456
|
+
)
|
|
457
|
+
expect(JSON.parse(fs.readFileSync(lockPath, 'utf8'))).toMatchObject({ pid: early.pid, port: 'early' })
|
|
458
|
+
} finally {
|
|
459
|
+
fs.writeFileSync(path.join(syncDir, 'exit'), '')
|
|
460
|
+
await Promise.all([waitForExit(late), early ? waitForExit(early) : Promise.resolve()])
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
expect(fs.readdirSync(path.dirname(lockPath))).toEqual([])
|
|
464
|
+
}
|
|
465
|
+
}, 120000)
|
|
66
466
|
})
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import type { ModuleWorker } from '@open-mercato/shared/modules/registry'
|
|
3
|
+
import { registerDatabaseRuntimeAdapter, type DatabaseExecutionContext } from '@open-mercato/shared/lib/db/runtime'
|
|
4
|
+
import { registerDatabaseModuleDeclarations } from '@open-mercato/shared/lib/db/declarations'
|
|
5
|
+
import { createPerJobWorkerHandler } from '../worker-job-handler'
|
|
6
|
+
|
|
7
|
+
const storage = new AsyncLocalStorage<DatabaseExecutionContext>()
|
|
8
|
+
const binding = jest.fn(async () => true)
|
|
9
|
+
const declarationsKey = Symbol.for('@open-mercato/shared.databaseModuleDeclarations.v1')
|
|
10
|
+
const runtimeKey = Symbol.for('@open-mercato/shared.databaseRuntime.v1')
|
|
11
|
+
const tenantId = '22222222-2222-4222-8222-222222222222'
|
|
12
|
+
const otherTenantId = '11111111-1111-4111-8111-111111111111'
|
|
13
|
+
const context = { jobId: 'job', attemptNumber: 1, queueName: 'extension' }
|
|
14
|
+
|
|
15
|
+
beforeEach(() => {
|
|
16
|
+
delete (globalThis as Record<symbol, unknown>)[runtimeKey]
|
|
17
|
+
delete (globalThis as Record<symbol, unknown>)[declarationsKey]
|
|
18
|
+
binding.mockReset().mockResolvedValue(true)
|
|
19
|
+
registerDatabaseModuleDeclarations([{ moduleId: 'fixture', declarations: { bindingValidators: [binding] } }])
|
|
20
|
+
registerDatabaseRuntimeAdapter({
|
|
21
|
+
id: 'test', version: '1', configurationKey: '1',
|
|
22
|
+
configurePool: () => ({ ready: async () => undefined, dispose: () => undefined }),
|
|
23
|
+
run: (scope, callback) => storage.run(scope, callback),
|
|
24
|
+
})
|
|
25
|
+
})
|
|
26
|
+
afterEach(() => { delete (globalThis as Record<symbol, unknown>)[runtimeKey]; delete (globalThis as Record<symbol, unknown>)[declarationsKey] })
|
|
27
|
+
|
|
28
|
+
function job(tenant: string) {
|
|
29
|
+
return { id: tenant, createdAt: new Date().toISOString(), payload: { tenantId: tenant } }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
test('binds each concurrent job before creating its container, through dispatch and cleanup', async () => {
|
|
33
|
+
const seen: string[] = []
|
|
34
|
+
const factory = jest.fn(async () => {
|
|
35
|
+
const owner = storage.getStore()
|
|
36
|
+
expect(owner?.kind).toBe('tenant')
|
|
37
|
+
seen.push(owner!.tenantId!)
|
|
38
|
+
return { resolve: <Result,>() => ({ clear: () => expect(storage.getStore()).toBe(owner) }) as Result }
|
|
39
|
+
})
|
|
40
|
+
const worker: ModuleWorker = { id: 'extension:work', queue: 'extension', concurrency: 2, handler: async (queued) => {
|
|
41
|
+
await new Promise<void>((resolve) => setImmediate(resolve))
|
|
42
|
+
expect(storage.getStore()?.tenantId).toBe((queued.payload as { tenantId: string }).tenantId)
|
|
43
|
+
} }
|
|
44
|
+
const handler = createPerJobWorkerHandler([worker], factory)
|
|
45
|
+
await Promise.all([handler(job(tenantId), context), handler(job(otherTenantId), context)])
|
|
46
|
+
expect(seen.sort()).toEqual([tenantId, otherTenantId].sort())
|
|
47
|
+
expect(storage.getStore()).toBeUndefined()
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
test('rejects invalid scope before container creation and preserves worker failure for retry', async () => {
|
|
51
|
+
const clear = jest.fn()
|
|
52
|
+
const factory = jest.fn(async () => ({ resolve: <Result,>() => ({ clear }) as Result }))
|
|
53
|
+
const failure = new Error('[internal] Retry me')
|
|
54
|
+
const handler = createPerJobWorkerHandler([{ id: 'extension:work', queue: 'extension', concurrency: 1, handler: async () => { throw failure } }], factory)
|
|
55
|
+
await expect(handler(job('invalid'), context)).rejects.toThrow('verified tenant UUID')
|
|
56
|
+
expect(factory).not.toHaveBeenCalled()
|
|
57
|
+
await expect(handler(job(tenantId), context)).rejects.toBe(failure)
|
|
58
|
+
await expect(handler(job(tenantId), { ...context, attemptNumber: 2 })).rejects.toBe(failure)
|
|
59
|
+
expect(clear).toHaveBeenCalledTimes(2)
|
|
60
|
+
expect(storage.getStore()).toBeUndefined()
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
test('rejects inactive persisted tenants before creating a container', async () => {
|
|
64
|
+
binding.mockImplementation(async () => { expect(storage.getStore()?.kind).toBe('identity'); return false })
|
|
65
|
+
const factory = jest.fn()
|
|
66
|
+
const handler = createPerJobWorkerHandler([], factory)
|
|
67
|
+
await expect(handler(job(tenantId), context)).rejects.toThrow('persisted active tenant')
|
|
68
|
+
expect(factory).not.toHaveBeenCalled()
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
test('awaits container disposal inside the live invocation after a failed job', async () => {
|
|
72
|
+
const dispose = jest.fn(async () => { await new Promise<void>((resolve) => setImmediate(resolve)); expect(storage.getStore()?.tenantId).toBe(tenantId) })
|
|
73
|
+
const handler = createPerJobWorkerHandler([{ id: 'extension:work', queue: 'extension', handler: async () => { throw new Error('retry') } }], async () => ({ resolve: <Result,>() => ({ clear: () => undefined }) as Result, dispose }))
|
|
74
|
+
await expect(handler(job(tenantId), context)).rejects.toThrow('retry')
|
|
75
|
+
expect(dispose).toHaveBeenCalledTimes(1)
|
|
76
|
+
})
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'
|
|
2
|
+
|
|
3
|
+
export type CliBootstrapMode = 'none' | 'dev-supervisor' | 'full' | 'database-migrate'
|
|
2
4
|
|
|
3
5
|
const BOOTSTRAP_FREE_COMMANDS = new Set([
|
|
4
6
|
'generate',
|
|
@@ -24,8 +26,16 @@ const BOOTSTRAP_FREE_COMMANDS = new Set([
|
|
|
24
26
|
])
|
|
25
27
|
|
|
26
28
|
export function resolveCliBootstrapMode(argv: readonly string[]): CliBootstrapMode {
|
|
27
|
-
const [, , first, second] = argv
|
|
29
|
+
const [, , first, second, ...args] = argv
|
|
30
|
+
if (first === 'db' && second === 'migrate' && !args.some((arg) => arg === '--help' || arg === '-h')) {
|
|
31
|
+
return 'database-migrate'
|
|
32
|
+
}
|
|
28
33
|
if (!first || BOOTSTRAP_FREE_COMMANDS.has(first)) return 'none'
|
|
29
34
|
if (first === 'server' && second === 'dev') return 'dev-supervisor'
|
|
30
35
|
return 'full'
|
|
31
36
|
}
|
|
37
|
+
|
|
38
|
+
export function requiresDatabaseRuntimeForMigration(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
39
|
+
const configured = env.OM_TENANT_RLS?.trim()
|
|
40
|
+
return Boolean(configured) && parseBooleanToken(configured) !== false
|
|
41
|
+
}
|
|
@@ -8,6 +8,17 @@ import type { ModuleEntry, PackageResolver } from '../../resolver'
|
|
|
8
8
|
const collectQueryIndexReindexEntityTypes = jest.fn<Promise<string[]>, [any, any]>()
|
|
9
9
|
const requestQueryIndexReindex = jest.fn<Promise<{ requested: string[]; queued: boolean }>, [any, any]>()
|
|
10
10
|
const isMigrationReindexEnabled = jest.fn<boolean, []>()
|
|
11
|
+
const beforeMigrate = jest.fn<Promise<void>, []>()
|
|
12
|
+
const afterMigrate = jest.fn<Promise<void>, []>()
|
|
13
|
+
const recoverHistory = jest.fn<boolean, []>()
|
|
14
|
+
|
|
15
|
+
jest.mock('@open-mercato/shared/lib/db/runtime', () => ({
|
|
16
|
+
beforeDatabaseMigrate: () => beforeMigrate(),
|
|
17
|
+
afterDatabaseMigrate: () => afterMigrate(),
|
|
18
|
+
shouldRecoverDatabaseMigrationReindex: () => recoverHistory(),
|
|
19
|
+
resolveDatabaseConnectionUrl: (_purpose: string, defaultUrl: string) => recoverHistory() ? 'postgres://maintenance@localhost:5432/test' : defaultUrl,
|
|
20
|
+
runWithDatabaseExecutionContext: (_context: unknown, callback: () => unknown) => callback(),
|
|
21
|
+
}))
|
|
11
22
|
|
|
12
23
|
jest.mock('../migration-reindex', () => ({
|
|
13
24
|
collectQueryIndexReindexEntityTypes: (...args: any[]) => collectQueryIndexReindexEntityTypes(...(args as [any, any])),
|
|
@@ -19,7 +30,7 @@ jest.mock('../migration-reindex', () => ({
|
|
|
19
30
|
// real `MikroORM` class at import time, so replacing the module export breaks the driver import.
|
|
20
31
|
const ormInit = jest.fn()
|
|
21
32
|
|
|
22
|
-
type PendingPlan = { pending: string[]; failOn?: string }
|
|
33
|
+
type PendingPlan = { pending: string[]; executed?: string[]; failOn?: string }
|
|
23
34
|
|
|
24
35
|
const tempDirs: string[] = []
|
|
25
36
|
const ormCloses: string[] = []
|
|
@@ -68,6 +79,7 @@ function stubOrmsFor(plans: Record<string, PendingPlan>): void {
|
|
|
68
79
|
const plan = moduleId ? plans[moduleId] : { pending: [] }
|
|
69
80
|
return {
|
|
70
81
|
migrator: {
|
|
82
|
+
getExecuted: async () => (plan.executed ?? []).map((name) => ({ name })),
|
|
71
83
|
getPending: async () => plan.pending.map((name) => ({ name, path: null })),
|
|
72
84
|
up: async (options: { migrations?: string[] } = {}) => {
|
|
73
85
|
const name = options.migrations?.[0]
|
|
@@ -89,6 +101,9 @@ describe('dbMigrate discharges query-index reindex declarations', () => {
|
|
|
89
101
|
|
|
90
102
|
beforeEach(() => {
|
|
91
103
|
process.env.DATABASE_URL = process.env.DATABASE_URL || 'postgres://noop@localhost:5432/test'
|
|
104
|
+
beforeMigrate.mockReset().mockResolvedValue(undefined)
|
|
105
|
+
afterMigrate.mockReset().mockResolvedValue(undefined)
|
|
106
|
+
recoverHistory.mockReset().mockReturnValue(false)
|
|
92
107
|
ormCloses.length = 0
|
|
93
108
|
ormInit.mockReset()
|
|
94
109
|
initSpy = jest.spyOn(MikroORM, 'init').mockImplementation((...args: any[]) => ormInit(...args))
|
|
@@ -186,4 +201,60 @@ describe('dbMigrate discharges query-index reindex declarations', () => {
|
|
|
186
201
|
expect(collectQueryIndexReindexEntityTypes).not.toHaveBeenCalled()
|
|
187
202
|
expect(requestQueryIndexReindex).not.toHaveBeenCalled()
|
|
188
203
|
})
|
|
204
|
+
it('preflights before opening module ORMs and reconciles even with no pending migrations', async () => {
|
|
205
|
+
recoverHistory.mockReturnValue(true)
|
|
206
|
+
const module = { id: 'alpha', dir: createTempModule('alpha') }
|
|
207
|
+
stubOrmsFor({ alpha: { pending: [], executed: ['MigrationCommittedBeforeRetry'] } })
|
|
208
|
+
beforeMigrate.mockImplementation(async () => { expect(ormInit).not.toHaveBeenCalled() })
|
|
209
|
+
afterMigrate.mockImplementation(async () => {
|
|
210
|
+
expect(ormCloses).toEqual(['alpha'])
|
|
211
|
+
expect(requestQueryIndexReindex).not.toHaveBeenCalled()
|
|
212
|
+
})
|
|
213
|
+
await dbMigrate(createMockResolver([module]))
|
|
214
|
+
expect(afterMigrate).toHaveBeenCalledTimes(1)
|
|
215
|
+
expect(ormInit.mock.calls[0][0].clientUrl).toBe('postgres://maintenance@localhost:5432/test')
|
|
216
|
+
expect(collectQueryIndexReindexEntityTypes.mock.calls[0][0]).toEqual([
|
|
217
|
+
expect.objectContaining({ moduleId: 'alpha', name: 'MigrationCommittedBeforeRetry' }),
|
|
218
|
+
])
|
|
219
|
+
expect(requestQueryIndexReindex).toHaveBeenCalledTimes(1)
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
it('recovers committed history together with newly applied declarations after reconciliation', async () => {
|
|
223
|
+
recoverHistory.mockReturnValue(true)
|
|
224
|
+
const module = { id: 'alpha', dir: createTempModule('alpha') }
|
|
225
|
+
stubOrmsFor({ alpha: { pending: ['MigrationNew'], executed: ['MigrationCommitted'] } })
|
|
226
|
+
await dbMigrate(createMockResolver([module]))
|
|
227
|
+
expect(collectQueryIndexReindexEntityTypes.mock.calls[0][0].map((migration: { name: string }) => migration.name))
|
|
228
|
+
.toEqual(['MigrationCommitted', 'MigrationNew'])
|
|
229
|
+
})
|
|
230
|
+
|
|
231
|
+
it('dispatches no protected reindex after a partial schema failure', async () => {
|
|
232
|
+
recoverHistory.mockReturnValue(true)
|
|
233
|
+
const module = { id: 'alpha', dir: createTempModule('alpha') }
|
|
234
|
+
stubOrmsFor({ alpha: { pending: ['MigrationCommitted', 'MigrationBroken'], failOn: 'MigrationBroken' } })
|
|
235
|
+
await expect(dbMigrate(createMockResolver([module]))).rejects.toThrow('MigrationBroken')
|
|
236
|
+
expect(afterMigrate).not.toHaveBeenCalled()
|
|
237
|
+
expect(collectQueryIndexReindexEntityTypes).not.toHaveBeenCalled()
|
|
238
|
+
expect(requestQueryIndexReindex).not.toHaveBeenCalled()
|
|
239
|
+
expect(ormCloses).toEqual(['alpha'])
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
it('propagates reconciliation failure without dispatching protected reindex', async () => {
|
|
243
|
+
recoverHistory.mockReturnValue(true)
|
|
244
|
+
const module = { id: 'alpha', dir: createTempModule('alpha') }
|
|
245
|
+
stubOrmsFor({ alpha: { pending: [] } })
|
|
246
|
+
afterMigrate.mockRejectedValue(new Error('[internal] policy reconciliation failed'))
|
|
247
|
+
await expect(dbMigrate(createMockResolver([module]))).rejects.toThrow('policy reconciliation failed')
|
|
248
|
+
expect(requestQueryIndexReindex).not.toHaveBeenCalled()
|
|
249
|
+
expect(ormCloses).toEqual(['alpha'])
|
|
250
|
+
})
|
|
251
|
+
|
|
252
|
+
it('opens no module ORM if privileged preflight fails', async () => {
|
|
253
|
+
beforeMigrate.mockRejectedValue(new Error('[internal] unsafe maintenance role'))
|
|
254
|
+
const module = { id: 'alpha', dir: createTempModule('alpha') }
|
|
255
|
+
await expect(dbMigrate(createMockResolver([module]))).rejects.toThrow('unsafe maintenance role')
|
|
256
|
+
expect(ormInit).not.toHaveBeenCalled()
|
|
257
|
+
expect(requestQueryIndexReindex).not.toHaveBeenCalled()
|
|
258
|
+
})
|
|
259
|
+
|
|
189
260
|
})
|