-
Notifications
You must be signed in to change notification settings - Fork 16.5k
Expand file tree
/
Copy pathpipeRegistry.ts
More file actions
523 lines (470 loc) · 14.4 KB
/
Copy pathpipeRegistry.ts
File metadata and controls
523 lines (470 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/**
* Pipe Registry — central registry for multi-instance pipe coordination.
*
* Manages a shared registry.json that tracks all CLI instances (main + subs).
* Main role is bound to machineId (OS-level stable fingerprint), not to
* instance startup order.
*
* File locking prevents race conditions when multiple instances start
* simultaneously.
*/
import { readFile, writeFile, unlink, mkdir } from 'fs/promises'
import { join } from 'path'
import { createHash } from 'crypto'
import { isPipeAlive, getPipesDir } from './pipeTransport.js'
import type { TcpEndpoint } from './pipeTransport.js'
import type { LanAnnounce } from './lanBeacon.js'
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface PipeRegistryEntry {
id: string
pid: number
machineId: string
startedAt: number
ip: string
mac: string
hostname: string
pipeName: string
tcpPort?: number
lanVisible?: boolean
}
export interface PipeRegistrySub extends PipeRegistryEntry {
subIndex: number
boundToMain: string | null
}
export interface PipeRegistry {
version: number
mainMachineId: string | null
main: PipeRegistryEntry | null
subs: PipeRegistrySub[]
}
export type DetermineRoleResult =
| { role: 'main' }
| { role: 'main-recover' }
| { role: 'sub'; subIndex: number }
// ---------------------------------------------------------------------------
// Paths
// ---------------------------------------------------------------------------
function getRegistryPath(): string {
return join(getPipesDir(), 'registry.json')
}
function getLockPath(): string {
return join(getPipesDir(), 'registry.lock')
}
// ---------------------------------------------------------------------------
// Machine ID — stable OS-level fingerprint
// ---------------------------------------------------------------------------
let _cachedMachineId: string | null = null
export async function getMachineId(): Promise<string> {
if (_cachedMachineId) return _cachedMachineId
let raw: string | null = null
if (process.platform === 'win32') {
// Windows: HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid (async)
try {
const { execFile } =
require('child_process') as typeof import('child_process')
raw = await new Promise<string>((resolve, reject) => {
execFile(
'reg',
[
'query',
'HKLM\\SOFTWARE\\Microsoft\\Cryptography',
'/v',
'MachineGuid',
],
{ timeout: 3000 },
(err, stdout) => (err ? reject(err) : resolve(stdout)),
)
})
const match = raw.match(/MachineGuid\s+REG_SZ\s+(\S+)/)
if (match) {
_cachedMachineId = match[1]!
return _cachedMachineId
}
} catch {}
} else if (process.platform === 'linux') {
// Linux: /etc/machine-id (already async)
try {
raw = await readFile('/etc/machine-id', 'utf8')
raw = raw.trim()
if (raw) {
_cachedMachineId = raw
return _cachedMachineId
}
} catch {}
} else if (process.platform === 'darwin') {
// macOS: IOPlatformSerialNumber (async)
try {
const { execFile } =
require('child_process') as typeof import('child_process')
raw = await new Promise<string>((resolve, reject) => {
execFile(
'bash',
[
'-c',
'ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformSerialNumber',
],
{ timeout: 3000 },
(err, stdout) => (err ? reject(err) : resolve(stdout)),
)
})
const match = raw.match(/"IOPlatformSerialNumber"\s*=\s*"(\S+)"/)
if (match) {
_cachedMachineId = match[1]!
return _cachedMachineId
}
} catch {}
}
// Fallback: hash hostname + MAC addresses
_cachedMachineId = generateFallbackId()
return _cachedMachineId
}
function generateFallbackId(): string {
const os = require('os') as typeof import('os')
const nets = os.networkInterfaces()
const macs: string[] = []
for (const name of Object.keys(nets)) {
for (const net of nets[name] ?? []) {
if (net.mac && net.mac !== '00:00:00:00:00:00') {
macs.push(net.mac)
}
}
}
macs.sort()
const raw = `${os.hostname()}:${macs.join(',')}`
return createHash('sha256').update(raw).digest('hex').slice(0, 32)
}
export function getMacAddress(): string {
const os = require('os') as typeof import('os')
const nets = os.networkInterfaces()
for (const name of Object.keys(nets)) {
for (const net of nets[name] ?? []) {
if (
net.family === 'IPv4' &&
!net.internal &&
net.mac &&
net.mac !== '00:00:00:00:00:00'
) {
return net.mac
}
}
}
return '00:00:00:00:00:00'
}
// ---------------------------------------------------------------------------
// File lock — simple .lock file with timeout
// ---------------------------------------------------------------------------
const LOCK_TIMEOUT_MS = 2000
const LOCK_RETRY_MS = 50
async function acquireLock(): Promise<void> {
await mkdir(getPipesDir(), { recursive: true })
const lockPath = getLockPath()
const deadline = Date.now() + LOCK_TIMEOUT_MS
while (Date.now() < deadline) {
try {
// O_CREAT | O_EXCL — fails if file exists
await writeFile(lockPath, String(process.pid), { flag: 'wx' })
return // Lock acquired
} catch (err: any) {
if (err.code === 'EEXIST') {
// Check if lock is stale (older than LOCK_TIMEOUT_MS)
try {
const content = await readFile(lockPath, 'utf8')
const lockPid = parseInt(content, 10)
if (lockPid && lockPid !== process.pid) {
try {
process.kill(lockPid, 0) // Check if process alive
} catch {
// Process dead — remove stale lock
await unlink(lockPath).catch(() => {})
continue
}
}
} catch {
// Can't read lock file — try to remove
await unlink(lockPath).catch(() => {})
continue
}
await new Promise(r => setTimeout(r, LOCK_RETRY_MS))
} else {
throw err
}
}
}
// Timeout — force remove and retry once
await unlink(getLockPath()).catch(() => {})
await writeFile(lockPath, String(process.pid), { flag: 'wx' }).catch(() => {})
}
async function releaseLock(): Promise<void> {
await unlink(getLockPath()).catch(() => {})
}
// ---------------------------------------------------------------------------
// Registry CRUD
// ---------------------------------------------------------------------------
const EMPTY_REGISTRY: PipeRegistry = {
version: 1,
mainMachineId: null,
main: null,
subs: [],
}
export async function readRegistry(): Promise<PipeRegistry> {
try {
const content = await readFile(getRegistryPath(), 'utf8')
const parsed = JSON.parse(content) as PipeRegistry
if (parsed.version !== 1) return { ...EMPTY_REGISTRY }
return parsed
} catch {
return { ...EMPTY_REGISTRY }
}
}
export async function writeRegistry(registry: PipeRegistry): Promise<void> {
await mkdir(getPipesDir(), { recursive: true })
await writeFile(getRegistryPath(), JSON.stringify(registry, null, 2))
}
// ---------------------------------------------------------------------------
// Role management (all operations are lock-protected)
// ---------------------------------------------------------------------------
export async function determineRole(
machineId: string,
): Promise<DetermineRoleResult> {
await acquireLock()
try {
const registry = await readRegistry()
// Case A: no main registered
if (!registry.mainMachineId || !registry.main) {
return { role: 'main' }
}
// Case B: this machine is the main machine
if (registry.mainMachineId === machineId) {
if (registry.main && (await isPipeAlive(registry.main.pipeName, 1000))) {
// Main instance is alive → this is a same-machine sub
const subIndex = registry.subs.length + 1
return { role: 'sub', subIndex }
}
// Main instance is dead → recover main on same machine
return { role: 'main-recover' }
}
// Case C: different machine
const subIndex = registry.subs.length + 1
return { role: 'sub', subIndex }
} finally {
await releaseLock()
}
}
export async function registerAsMain(entry: PipeRegistryEntry): Promise<void> {
await acquireLock()
try {
const registry = await readRegistry()
registry.mainMachineId = entry.machineId
registry.main = entry
await writeRegistry(registry)
} finally {
await releaseLock()
}
}
export async function registerAsSub(
entry: PipeRegistryEntry,
subIndex: number,
): Promise<void> {
await acquireLock()
try {
const registry = await readRegistry()
// Remove existing entry with same id (re-registration)
registry.subs = registry.subs.filter(s => s.id !== entry.id)
registry.subs.push({
...entry,
subIndex,
boundToMain: registry.main?.id ?? null,
})
await writeRegistry(registry)
} finally {
await releaseLock()
}
}
export async function unregister(id: string): Promise<void> {
await acquireLock()
try {
const registry = await readRegistry()
if (registry.main?.id === id) {
registry.main = null
// Don't clear mainMachineId — same machine can recover
}
registry.subs = registry.subs.filter(s => s.id !== id)
await writeRegistry(registry)
} finally {
await releaseLock()
}
}
export async function revertToIndependent(id: string): Promise<void> {
await acquireLock()
try {
const registry = await readRegistry()
const sub = registry.subs.find(s => s.id === id)
if (sub) {
sub.boundToMain = null
}
await writeRegistry(registry)
} finally {
await releaseLock()
}
}
export async function claimMain(
newMachineId: string,
entry: PipeRegistryEntry,
): Promise<void> {
await acquireLock()
try {
const registry = await readRegistry()
registry.mainMachineId = newMachineId
registry.main = entry
// All existing subs become bound to new main
for (const sub of registry.subs) {
sub.boundToMain = entry.id
}
await writeRegistry(registry)
} finally {
await releaseLock()
}
}
// ---------------------------------------------------------------------------
// Queries
// ---------------------------------------------------------------------------
export async function isMainAlive(): Promise<boolean> {
const registry = await readRegistry()
if (!registry.main) return false
return isPipeAlive(registry.main.pipeName, 1000)
}
export function isMainMachine(
machineId: string,
registry: PipeRegistry,
): boolean {
return registry.mainMachineId === machineId
}
export async function getAliveSubs(): Promise<PipeRegistrySub[]> {
const registry = await readRegistry()
const results = await Promise.all(
registry.subs.map(sub =>
isPipeAlive(sub.pipeName, 1000).then(alive => (alive ? sub : null)),
),
)
return results.filter((s): s is PipeRegistrySub => s !== null)
}
export async function cleanupStaleEntries(): Promise<void> {
// Phase 1: Probe all entries in parallel WITHOUT holding the lock
const registry = await readRegistry()
const [mainAlive, subResults] = await Promise.all([
registry.main
? isPipeAlive(registry.main.pipeName, 1000)
: Promise.resolve(true),
Promise.all(
registry.subs.map(sub =>
isPipeAlive(sub.pipeName, 1000).then(alive => ({ sub, alive })),
),
),
])
const needsWrite = !mainAlive || subResults.some(r => !r.alive)
if (!needsWrite) return
// Phase 2: Briefly hold lock to apply changes
await acquireLock()
try {
const fresh = await readRegistry()
let changed = false
if (!mainAlive && fresh.main?.pipeName === registry.main?.pipeName) {
fresh.main = null
changed = true
}
const deadNames = new Set(
subResults.reduce((acc: string[], r) => {
if (!r.alive) acc.push(r.sub.pipeName);
return acc;
}, [])
)
const aliveSubs = fresh.subs.filter(s => !deadNames.has(s.pipeName))
if (aliveSubs.length !== fresh.subs.length) {
fresh.subs = aliveSubs
changed = true
}
if (changed) {
await writeRegistry(fresh)
}
} finally {
await releaseLock()
}
}
// ---------------------------------------------------------------------------
// LAN peer merging
// ---------------------------------------------------------------------------
export type MergedPipeEntry = {
id: string
pipeName: string
role: string
machineId: string
ip: string
hostname: string
alive: boolean
source: 'local' | 'lan'
tcpEndpoint?: TcpEndpoint
}
/**
* Merge local registry entries with LAN beacon-discovered peers.
* Local entries take precedence — LAN peers are only added if not
* already present in the local registry.
*/
export function mergeWithLanPeers(
registry: PipeRegistry,
lanPeers: Map<string, LanAnnounce>,
): MergedPipeEntry[] {
const result: MergedPipeEntry[] = []
const knownPipes = new Set<string>()
// Add main from local registry
if (registry.main) {
knownPipes.add(registry.main.pipeName)
result.push({
id: registry.main.id,
pipeName: registry.main.pipeName,
role: 'main',
machineId: registry.main.machineId,
ip: registry.main.ip,
hostname: registry.main.hostname,
alive: true, // caller should verify
source: 'local',
tcpEndpoint: registry.main.tcpPort
? { host: registry.main.ip, port: registry.main.tcpPort }
: undefined,
})
}
// Add subs from local registry
for (const sub of registry.subs) {
knownPipes.add(sub.pipeName)
result.push({
id: sub.id,
pipeName: sub.pipeName,
role: `sub-${sub.subIndex}`,
machineId: sub.machineId,
ip: sub.ip,
hostname: sub.hostname,
alive: true,
source: 'local',
tcpEndpoint: sub.tcpPort
? { host: sub.ip, port: sub.tcpPort }
: undefined,
})
}
// Add LAN peers not already in local registry
for (const [pipeName, peer] of lanPeers) {
if (knownPipes.has(pipeName)) continue
result.push({
id: `lan-${pipeName}`,
pipeName,
role: peer.role,
machineId: peer.machineId,
ip: peer.ip,
hostname: peer.hostname,
alive: true,
source: 'lan',
tcpEndpoint: { host: peer.ip, port: peer.tcpPort },
})
}
return result
}