@open-mercato/cli 0.11.1-develop.8910.1.d07a49d70a → 0.11.1-develop.8920.1.d3c2cc4681
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 +1 -1
- package/dist/agentic/guides/module-facts.json +180 -194
- package/dist/agentic/guides/module-facts.v2.json +180 -194
- package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
- package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
- 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/index.md +1 -1
- 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/index.md +1 -1
- 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/index.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/index.md +1 -1
- package/dist/agentic/guides/modules/sales_invoices_gl_posting/index.md +1 -1
- package/dist/agentic/guides/modules/scheduler/index.md +1 -1
- package/dist/agentic/guides/modules/search/index.md +1 -1
- 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/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 +1 -1
- package/dist/agentic/guides/upstream/manifest.json +1 -1
- package/dist/lib/server-start-lock.js +120 -21
- package/dist/lib/server-start-lock.js.map +2 -2
- package/package.json +7 -7
- package/src/lib/__tests__/server-start-lock.test.ts +400 -0
- package/src/lib/server-start-lock.ts +170 -19
|
@@ -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
|
})
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
1
2
|
import fs from 'node:fs'
|
|
2
3
|
import path from 'node:path'
|
|
3
4
|
|
|
@@ -5,6 +6,9 @@ type ServerStartLockRecord = {
|
|
|
5
6
|
pid: number
|
|
6
7
|
port: string | null
|
|
7
8
|
startedAt: string
|
|
9
|
+
processStartTime: string | null
|
|
10
|
+
bootId: string | null
|
|
11
|
+
token: string | null
|
|
8
12
|
}
|
|
9
13
|
|
|
10
14
|
export type ServerStartLockHandle = {
|
|
@@ -12,9 +16,28 @@ export type ServerStartLockHandle = {
|
|
|
12
16
|
release: () => void
|
|
13
17
|
}
|
|
14
18
|
|
|
15
|
-
|
|
19
|
+
const BOOT_ID_PATH = '/proc/sys/kernel/random/boot_id'
|
|
20
|
+
const STAT_FIRST_FIELD_AFTER_COMMAND = 3
|
|
21
|
+
const STAT_START_TIME_FIELD = 22
|
|
22
|
+
const TAKEOVER_BUSY_WAIT_MS = 25
|
|
23
|
+
const MAX_TAKEOVER_ATTEMPTS = 400
|
|
24
|
+
|
|
25
|
+
function readOptionalString(value: unknown): string | null {
|
|
26
|
+
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function readRawFile(filePath: string): string | null {
|
|
30
|
+
try {
|
|
31
|
+
return fs.readFileSync(filePath, 'utf8')
|
|
32
|
+
} catch (error) {
|
|
33
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
|
|
34
|
+
throw error
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function parseServerStartLock(raw: string | null): ServerStartLockRecord | null {
|
|
39
|
+
if (raw === null) return null
|
|
16
40
|
try {
|
|
17
|
-
const raw = fs.readFileSync(lockPath, 'utf8')
|
|
18
41
|
const parsed = JSON.parse(raw) as Partial<ServerStartLockRecord>
|
|
19
42
|
if (typeof parsed.pid !== 'number' || !Number.isInteger(parsed.pid) || parsed.pid <= 0) {
|
|
20
43
|
return null
|
|
@@ -23,12 +46,42 @@ function readServerStartLock(lockPath: string): ServerStartLockRecord | null {
|
|
|
23
46
|
pid: parsed.pid,
|
|
24
47
|
port: typeof parsed.port === 'string' && parsed.port.trim().length > 0 ? parsed.port : null,
|
|
25
48
|
startedAt: typeof parsed.startedAt === 'string' ? parsed.startedAt : '',
|
|
49
|
+
processStartTime: readOptionalString(parsed.processStartTime),
|
|
50
|
+
bootId: readOptionalString(parsed.bootId),
|
|
51
|
+
token: readOptionalString(parsed.token),
|
|
26
52
|
}
|
|
27
53
|
} catch {
|
|
28
54
|
return null
|
|
29
55
|
}
|
|
30
56
|
}
|
|
31
57
|
|
|
58
|
+
/**
|
|
59
|
+
* Reads the start time of `pid` (field 22 of `/proc/<pid>/stat`). The command name
|
|
60
|
+
* in field 2 may contain spaces or parentheses, so only the text after the last `)`
|
|
61
|
+
* is split. Returns `null` when the platform has no `/proc` (macOS, Windows) or the
|
|
62
|
+
* entry cannot be read or parsed.
|
|
63
|
+
*/
|
|
64
|
+
export function readProcessStartTime(pid: number): string | null {
|
|
65
|
+
try {
|
|
66
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8')
|
|
67
|
+
const commandEnd = stat.lastIndexOf(')')
|
|
68
|
+
if (commandEnd < 0) return null
|
|
69
|
+
const fields = stat.slice(commandEnd + 1).trim().split(/\s+/)
|
|
70
|
+
const startTime = fields[STAT_START_TIME_FIELD - STAT_FIRST_FIELD_AFTER_COMMAND]
|
|
71
|
+
return startTime && /^\d+$/.test(startTime) ? startTime : null
|
|
72
|
+
} catch {
|
|
73
|
+
return null
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function readBootId(): string | null {
|
|
78
|
+
try {
|
|
79
|
+
return readOptionalString(fs.readFileSync(BOOT_ID_PATH, 'utf8'))
|
|
80
|
+
} catch {
|
|
81
|
+
return null
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
32
85
|
function isProcessAlive(pid: number): boolean {
|
|
33
86
|
try {
|
|
34
87
|
process.kill(pid, 0)
|
|
@@ -38,6 +91,98 @@ function isProcessAlive(pid: number): boolean {
|
|
|
38
91
|
}
|
|
39
92
|
}
|
|
40
93
|
|
|
94
|
+
/**
|
|
95
|
+
* A lock is held only while the process that wrote it is still running. A live pid
|
|
96
|
+
* alone is not enough: the lock file sits in the app directory and survives a
|
|
97
|
+
* container restart, while pid numbering starts again, so the recorded pid soon
|
|
98
|
+
* belongs to an unrelated process. When the lock carries the boot id and the
|
|
99
|
+
* process start time, both must still match. When either side cannot be read
|
|
100
|
+
* (old lock format, no `/proc`), the pid check alone decides, as before.
|
|
101
|
+
*/
|
|
102
|
+
function isLockOwnerAlive(lock: ServerStartLockRecord): boolean {
|
|
103
|
+
if (!isProcessAlive(lock.pid)) return false
|
|
104
|
+
|
|
105
|
+
if (lock.bootId) {
|
|
106
|
+
const currentBootId = readBootId()
|
|
107
|
+
if (currentBootId && currentBootId !== lock.bootId) return false
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (lock.processStartTime) {
|
|
111
|
+
const currentStartTime = readProcessStartTime(lock.pid)
|
|
112
|
+
if (currentStartTime && currentStartTime !== lock.processStartTime) return false
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return true
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Treats a record written by this very pid as dead: this process never holds a
|
|
120
|
+
* lock or a takeover guard while it inspects one, so a matching pid can only come
|
|
121
|
+
* from a previous run (pid numbering restarts with the container).
|
|
122
|
+
*/
|
|
123
|
+
function isHeldByAnotherLiveProcess(record: ServerStartLockRecord | null): record is ServerStartLockRecord {
|
|
124
|
+
return record !== null && record.pid !== process.pid && isLockOwnerAlive(record)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Creates `target` with `content` only if it does not exist yet. The content is
|
|
129
|
+
* written to a private temporary file first and hard-linked into place, so other
|
|
130
|
+
* processes never observe a half-written file. Returns `false` when `target`
|
|
131
|
+
* already exists.
|
|
132
|
+
*/
|
|
133
|
+
function publishExclusive(target: string, content: string): boolean {
|
|
134
|
+
const tempPath = `${target}.${process.pid}.${randomUUID()}.tmp`
|
|
135
|
+
fs.writeFileSync(tempPath, content, { encoding: 'utf8', flag: 'wx' })
|
|
136
|
+
try {
|
|
137
|
+
fs.linkSync(tempPath, target)
|
|
138
|
+
return true
|
|
139
|
+
} catch (error) {
|
|
140
|
+
if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false
|
|
141
|
+
throw error
|
|
142
|
+
} finally {
|
|
143
|
+
fs.rmSync(tempPath, { force: true })
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function sleepSync(ms: number): void {
|
|
148
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Removes the stale lock generation `staleRaw` unless another process has already
|
|
153
|
+
* replaced it. Several starts can inspect the same stale lock at once, and a plain
|
|
154
|
+
* unlink would let a late one delete the lock a faster one has just written. Only
|
|
155
|
+
* the process that exclusively creates the takeover guard for this generation may
|
|
156
|
+
* remove it, and it re-reads the lock under the guard first. A guard left behind
|
|
157
|
+
* by a process that died mid-takeover is skipped in favour of the next slot.
|
|
158
|
+
*
|
|
159
|
+
* Returns `false` when a live process holds the guard and the caller must retry.
|
|
160
|
+
*/
|
|
161
|
+
function removeStaleGeneration(lockPath: string, staleRaw: string, ownRaw: string): boolean {
|
|
162
|
+
const generation = createHash('sha256').update(staleRaw).digest('hex').slice(0, 16)
|
|
163
|
+
const skippedGuards: string[] = []
|
|
164
|
+
let ownedGuard: string | null = null
|
|
165
|
+
try {
|
|
166
|
+
for (let slot = 0; ; slot += 1) {
|
|
167
|
+
const guardPath = `${lockPath}.${generation}.${slot}.takeover`
|
|
168
|
+
if (publishExclusive(guardPath, ownRaw)) {
|
|
169
|
+
ownedGuard = guardPath
|
|
170
|
+
break
|
|
171
|
+
}
|
|
172
|
+
const guardRaw = readRawFile(guardPath)
|
|
173
|
+
if (guardRaw === null || isHeldByAnotherLiveProcess(parseServerStartLock(guardRaw))) return false
|
|
174
|
+
skippedGuards.push(guardPath)
|
|
175
|
+
}
|
|
176
|
+
if (readRawFile(lockPath) === staleRaw) {
|
|
177
|
+
fs.rmSync(lockPath, { force: true })
|
|
178
|
+
}
|
|
179
|
+
for (const guardPath of skippedGuards) fs.rmSync(guardPath, { force: true })
|
|
180
|
+
return true
|
|
181
|
+
} finally {
|
|
182
|
+
if (ownedGuard !== null) fs.rmSync(ownedGuard, { force: true })
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
41
186
|
export function getServerStartLockPath(appDir: string): string {
|
|
42
187
|
return path.join(appDir, '.mercato', 'server-start.lock')
|
|
43
188
|
}
|
|
@@ -51,29 +196,33 @@ export function acquireServerStartLock(
|
|
|
51
196
|
pid: process.pid,
|
|
52
197
|
port: typeof options.port === 'string' && options.port.trim().length > 0 ? options.port.trim() : null,
|
|
53
198
|
startedAt: new Date().toISOString(),
|
|
199
|
+
processStartTime: readProcessStartTime(process.pid),
|
|
200
|
+
bootId: readBootId(),
|
|
201
|
+
token: randomUUID(),
|
|
54
202
|
}
|
|
203
|
+
const ownRaw = JSON.stringify(lockRecord)
|
|
55
204
|
|
|
56
205
|
fs.mkdirSync(path.dirname(lockPath), { recursive: true })
|
|
57
206
|
|
|
58
|
-
for (
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
207
|
+
for (let attempt = 0; !publishExclusive(lockPath, ownRaw); attempt += 1) {
|
|
208
|
+
const existingRaw = readRawFile(lockPath)
|
|
209
|
+
if (existingRaw === null) continue
|
|
210
|
+
|
|
211
|
+
const existingLock = parseServerStartLock(existingRaw)
|
|
212
|
+
if (isHeldByAnotherLiveProcess(existingLock)) {
|
|
213
|
+
const portSuffix = existingLock.port ? ` on port ${existingLock.port}` : ''
|
|
214
|
+
throw new Error(
|
|
215
|
+
`[server] Another Open Mercato production server is already running for ${appDir} (pid ${existingLock.pid}${portSuffix}). Stop it before starting another instance.`,
|
|
216
|
+
)
|
|
217
|
+
}
|
|
67
218
|
|
|
68
|
-
|
|
69
|
-
if (
|
|
70
|
-
const portSuffix = existingLock.port ? ` on port ${existingLock.port}` : ''
|
|
219
|
+
if (!removeStaleGeneration(lockPath, existingRaw, ownRaw)) {
|
|
220
|
+
if (attempt >= MAX_TAKEOVER_ATTEMPTS) {
|
|
71
221
|
throw new Error(
|
|
72
|
-
`[server] Another
|
|
222
|
+
`[server] Another process is still replacing the stale server start lock for ${appDir}. Try again.`,
|
|
73
223
|
)
|
|
74
224
|
}
|
|
75
|
-
|
|
76
|
-
fs.rmSync(lockPath, { force: true })
|
|
225
|
+
sleepSync(TAKEOVER_BUSY_WAIT_MS)
|
|
77
226
|
}
|
|
78
227
|
}
|
|
79
228
|
|
|
@@ -82,8 +231,10 @@ export function acquireServerStartLock(
|
|
|
82
231
|
if (released) return
|
|
83
232
|
released = true
|
|
84
233
|
|
|
85
|
-
|
|
86
|
-
if
|
|
234
|
+
// Compare the token, not the pid: after a takeover the file belongs to
|
|
235
|
+
// another process even if it reuses this pid in a later container run.
|
|
236
|
+
const currentLock = parseServerStartLock(readRawFile(lockPath))
|
|
237
|
+
if (currentLock?.token === lockRecord.token) {
|
|
87
238
|
fs.rmSync(lockPath, { force: true })
|
|
88
239
|
}
|
|
89
240
|
}
|