|
| 1 | +import { randomBytes } from 'node:crypto'; |
| 2 | +import { setTimeout as sleep } from 'node:timers/promises'; |
| 3 | +import { mkdir, open, readFile, unlink } from 'node:fs/promises'; |
| 4 | +import { dirname, join } from 'node:path'; |
| 5 | + |
| 6 | +export interface RemoteControlLockInfo { |
| 7 | + readonly pid: number; |
| 8 | + readonly nonce: string; |
| 9 | + readonly localOrigin: string; |
| 10 | + readonly deviceId: string; |
| 11 | + readonly url: string; |
| 12 | + readonly startedAt: number; |
| 13 | +} |
| 14 | + |
| 15 | +interface RemoteControlLockDisk { |
| 16 | + readonly pid: number; |
| 17 | + readonly nonce: string; |
| 18 | + readonly local_origin: string; |
| 19 | + readonly device_id: string; |
| 20 | + readonly url: string; |
| 21 | + readonly started_at: number; |
| 22 | +} |
| 23 | + |
| 24 | +export class RemoteControlAlreadyRunningError extends Error { |
| 25 | + readonly holder: RemoteControlLockInfo; |
| 26 | + |
| 27 | + constructor(holder: RemoteControlLockInfo) { |
| 28 | + super(formatRemoteControlAlreadyRunning(holder)); |
| 29 | + this.name = 'RemoteControlAlreadyRunningError'; |
| 30 | + this.holder = holder; |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +export function formatRemoteControlAlreadyRunning(holder: RemoteControlLockInfo): string { |
| 35 | + return [ |
| 36 | + `Remote Control is already running on this machine (pid ${holder.pid}, ${holder.localOrigin}, since ${new Date(holder.startedAt).toLocaleString()}).`, |
| 37 | + `Use the existing link: ${holder.url}`, |
| 38 | + 'To start a new one here, stop the other `pythinker web --remote-control` process first.', |
| 39 | + ].join('\n'); |
| 40 | +} |
| 41 | + |
| 42 | +export function remoteControlLockPath(homeDir: string): string { |
| 43 | + return join(homeDir, 'server', 'rc.json'); |
| 44 | +} |
| 45 | + |
| 46 | +export interface RemoteControlLock { |
| 47 | + release(): Promise<void>; |
| 48 | +} |
| 49 | + |
| 50 | +const MAX_ACQUIRE_ATTEMPTS = 3; |
| 51 | +const ACQUIRE_RETRY_DELAY_MS = 25; |
| 52 | + |
| 53 | +export async function acquireRemoteControlLock( |
| 54 | + homeDir: string, |
| 55 | + details: { localOrigin: string; deviceId: string; url: string }, |
| 56 | +): Promise<RemoteControlLock> { |
| 57 | + const lockPath = remoteControlLockPath(homeDir); |
| 58 | + // The lock sits beside `server.token`; keep the same owner-only permissions. |
| 59 | + await mkdir(dirname(lockPath), { recursive: true, mode: 0o700 }); |
| 60 | + const info: RemoteControlLockInfo = { |
| 61 | + pid: process.pid, |
| 62 | + nonce: randomBytes(8).toString('hex'), |
| 63 | + localOrigin: details.localOrigin, |
| 64 | + deviceId: details.deviceId, |
| 65 | + url: details.url, |
| 66 | + startedAt: Date.now(), |
| 67 | + }; |
| 68 | + for (let attempt = 0; ; attempt += 1) { |
| 69 | + try { |
| 70 | + const handle = await open(lockPath, 'wx', 0o600); |
| 71 | + try { |
| 72 | + await handle.writeFile(encodeLock(info)); |
| 73 | + } finally { |
| 74 | + await handle.close(); |
| 75 | + } |
| 76 | + return { release: () => releaseRemoteControlLock(lockPath, info.nonce) }; |
| 77 | + } catch (error) { |
| 78 | + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') { |
| 79 | + throw error; |
| 80 | + } |
| 81 | + // Read the holder even on the last attempt: a second process can recreate |
| 82 | + // the lock between our unlink and our open, and a raw EEXIST tells the |
| 83 | + // user nothing about who holds it or how to stop them. |
| 84 | + const holder = await readRemoteControlLock(lockPath); |
| 85 | + if (holder !== undefined && pidAlive(holder.pid)) { |
| 86 | + throw new RemoteControlAlreadyRunningError(holder); |
| 87 | + } |
| 88 | + // `open(…, 'wx')` publishes an empty file before its JSON is written, so |
| 89 | + // an unreadable lock may simply be a rival mid-write. Deleting it there |
| 90 | + // would let both processes believe they hold the lock. Give the writer a |
| 91 | + // moment and re-read; only sweep it once it is still unreadable at the |
| 92 | + // end, which is the genuinely corrupt case. |
| 93 | + if (holder === undefined && attempt < MAX_ACQUIRE_ATTEMPTS) { |
| 94 | + await sleep(ACQUIRE_RETRY_DELAY_MS); |
| 95 | + continue; |
| 96 | + } |
| 97 | + if (attempt >= MAX_ACQUIRE_ATTEMPTS) { |
| 98 | + throw new Error( |
| 99 | + `Unable to acquire the Remote Control lock at ${lockPath}. Another process keeps recreating it.`, { cause: error }, |
| 100 | + ); |
| 101 | + } |
| 102 | + await removeFile(lockPath); |
| 103 | + } |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +export async function inspectRemoteControlLock( |
| 108 | + homeDir: string, |
| 109 | +): Promise<RemoteControlLockInfo | undefined> { |
| 110 | + const lockPath = remoteControlLockPath(homeDir); |
| 111 | + const info = await readRemoteControlLock(lockPath); |
| 112 | + if (info === undefined) return undefined; |
| 113 | + if (!pidAlive(info.pid)) { |
| 114 | + await removeFile(lockPath); |
| 115 | + return undefined; |
| 116 | + } |
| 117 | + return info; |
| 118 | +} |
| 119 | + |
| 120 | +async function releaseRemoteControlLock(lockPath: string, nonce: string): Promise<void> { |
| 121 | + const info = await readRemoteControlLock(lockPath); |
| 122 | + if (info === undefined || info.nonce !== nonce) return; |
| 123 | + await removeFile(lockPath); |
| 124 | +} |
| 125 | + |
| 126 | +async function readRemoteControlLock(lockPath: string): Promise<RemoteControlLockInfo | undefined> { |
| 127 | + let raw: string; |
| 128 | + try { |
| 129 | + raw = await readFile(lockPath, 'utf8'); |
| 130 | + } catch { |
| 131 | + return undefined; |
| 132 | + } |
| 133 | + return decodeLock(raw); |
| 134 | +} |
| 135 | + |
| 136 | +function encodeLock(info: RemoteControlLockInfo): string { |
| 137 | + const disk: RemoteControlLockDisk = { |
| 138 | + pid: info.pid, |
| 139 | + nonce: info.nonce, |
| 140 | + local_origin: info.localOrigin, |
| 141 | + device_id: info.deviceId, |
| 142 | + url: info.url, |
| 143 | + started_at: info.startedAt, |
| 144 | + }; |
| 145 | + return JSON.stringify(disk); |
| 146 | +} |
| 147 | + |
| 148 | +function decodeLock(raw: string): RemoteControlLockInfo | undefined { |
| 149 | + try { |
| 150 | + const parsed = JSON.parse(raw) as Partial<RemoteControlLockDisk>; |
| 151 | + if ( |
| 152 | + typeof parsed.pid === 'number' && |
| 153 | + // `process.kill(0, 0)` signals our own process group and reports "alive", |
| 154 | + // so a corrupt `"pid": 0` would pin the lock forever. |
| 155 | + Number.isInteger(parsed.pid) && |
| 156 | + parsed.pid > 0 && |
| 157 | + typeof parsed.nonce === 'string' && |
| 158 | + typeof parsed.local_origin === 'string' && |
| 159 | + typeof parsed.device_id === 'string' && |
| 160 | + typeof parsed.url === 'string' && |
| 161 | + typeof parsed.started_at === 'number' |
| 162 | + ) { |
| 163 | + return { |
| 164 | + pid: parsed.pid, |
| 165 | + nonce: parsed.nonce, |
| 166 | + localOrigin: parsed.local_origin, |
| 167 | + deviceId: parsed.device_id, |
| 168 | + url: parsed.url, |
| 169 | + startedAt: parsed.started_at, |
| 170 | + }; |
| 171 | + } |
| 172 | + return undefined; |
| 173 | + } catch { |
| 174 | + return undefined; |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +async function removeFile(lockPath: string): Promise<void> { |
| 179 | + try { |
| 180 | + await unlink(lockPath); |
| 181 | + } catch (error) { |
| 182 | + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +function pidAlive(pid: number): boolean { |
| 187 | + try { |
| 188 | + process.kill(pid, 0); |
| 189 | + return true; |
| 190 | + } catch (error) { |
| 191 | + if ((error as NodeJS.ErrnoException).code === 'ESRCH') return false; |
| 192 | + return true; |
| 193 | + } |
| 194 | +} |
0 commit comments