-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathdaemon-client.ts
More file actions
418 lines (382 loc) · 12.6 KB
/
daemon-client.ts
File metadata and controls
418 lines (382 loc) · 12.6 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
import net from 'node:net';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { AppError } from './utils/errors.ts';
import type { DaemonRequest as SharedDaemonRequest, DaemonResponse as SharedDaemonResponse } from './daemon/types.ts';
import { runCmdDetached, runCmdSync } from './utils/exec.ts';
import { findProjectRoot, readVersion } from './utils/version.ts';
import { createRequestId, emitDiagnostic, withDiagnosticTimer } from './utils/diagnostics.ts';
import {
isAgentDeviceDaemonProcess,
stopProcessForTakeover,
} from './utils/process-identity.ts';
export type DaemonRequest = SharedDaemonRequest;
export type DaemonResponse = SharedDaemonResponse;
type DaemonInfo = {
port: number;
token: string;
pid: number;
version?: string;
codeSignature?: string;
processStartTime?: string;
};
type DaemonLockInfo = {
pid: number;
processStartTime?: string;
startedAt?: number;
};
type DaemonMetadataState = {
hasInfo: boolean;
hasLock: boolean;
};
const baseDir = path.join(os.homedir(), '.agent-device');
const infoPath = path.join(baseDir, 'daemon.json');
const lockPath = path.join(baseDir, 'daemon.lock');
const REQUEST_TIMEOUT_MS = resolveDaemonRequestTimeoutMs();
const DAEMON_STARTUP_TIMEOUT_MS = 5000;
const DAEMON_TAKEOVER_TERM_TIMEOUT_MS = 3000;
const DAEMON_TAKEOVER_KILL_TIMEOUT_MS = 1000;
const IOS_RUNNER_XCODEBUILD_KILL_PATTERNS = [
'xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand',
'xcodebuild .*AgentDeviceRunner\\.env\\.session-',
'xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj',
];
export async function sendToDaemon(req: Omit<DaemonRequest, 'token'>): Promise<DaemonResponse> {
const requestId = req.meta?.requestId ?? createRequestId();
const debug = Boolean(req.meta?.debug || req.flags?.verbose);
const info = await withDiagnosticTimer(
'daemon_startup',
async () => await ensureDaemon(),
{ requestId, session: req.session },
);
const request = {
...req,
token: info.token,
meta: {
requestId,
debug,
cwd: req.meta?.cwd,
},
};
emitDiagnostic({
level: 'info',
phase: 'daemon_request_prepare',
data: {
requestId,
command: req.command,
session: req.session,
},
});
return await withDiagnosticTimer(
'daemon_request',
async () => await sendRequest(info, request),
{ requestId, command: req.command },
);
}
async function ensureDaemon(): Promise<DaemonInfo> {
const existing = readDaemonInfo();
const localVersion = readVersion();
const localCodeSignature = resolveLocalDaemonCodeSignature();
const existingReachable = existing ? await canConnect(existing) : false;
if (
existing
&& existing.version === localVersion
&& existing.codeSignature === localCodeSignature
&& existingReachable
) {
return existing;
}
if (
existing
&& (
existing.version !== localVersion
|| existing.codeSignature !== localCodeSignature
|| !existingReachable
)
) {
await stopDaemonProcessForTakeover(existing);
removeDaemonInfo();
}
cleanupStaleDaemonLockIfSafe();
await startDaemon();
const started = await waitForDaemonInfo(DAEMON_STARTUP_TIMEOUT_MS);
if (started) return started;
if (await recoverDaemonLockHolder()) {
await startDaemon();
const recovered = await waitForDaemonInfo(DAEMON_STARTUP_TIMEOUT_MS);
if (recovered) return recovered;
}
throw new AppError('COMMAND_FAILED', 'Failed to start daemon', {
kind: 'daemon_startup_failed',
infoPath,
lockPath,
hint: resolveDaemonStartupHint(getDaemonMetadataState()),
});
}
async function waitForDaemonInfo(timeoutMs: number): Promise<DaemonInfo | null> {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const info = readDaemonInfo();
if (info && (await canConnect(info))) return info;
await new Promise((resolve) => setTimeout(resolve, 100));
}
return null;
}
async function recoverDaemonLockHolder(): Promise<boolean> {
const state = getDaemonMetadataState();
if (!state.hasLock || state.hasInfo) return false;
const lockInfo = readDaemonLockInfo();
if (!lockInfo) {
removeDaemonLock();
return true;
}
if (!isAgentDeviceDaemonProcess(lockInfo.pid, lockInfo.processStartTime)) {
removeDaemonLock();
return true;
}
await stopProcessForTakeover(lockInfo.pid, {
termTimeoutMs: DAEMON_TAKEOVER_TERM_TIMEOUT_MS,
killTimeoutMs: DAEMON_TAKEOVER_KILL_TIMEOUT_MS,
expectedStartTime: lockInfo.processStartTime,
});
removeDaemonLock();
return true;
}
async function stopDaemonProcessForTakeover(info: DaemonInfo): Promise<void> {
await stopProcessForTakeover(info.pid, {
termTimeoutMs: DAEMON_TAKEOVER_TERM_TIMEOUT_MS,
killTimeoutMs: DAEMON_TAKEOVER_KILL_TIMEOUT_MS,
expectedStartTime: info.processStartTime,
});
}
function readDaemonInfo(): DaemonInfo | null {
const data = readJsonFile(infoPath) as DaemonInfo | null;
if (!data || !data.port || !data.token) return null;
return {
...data,
pid: Number.isInteger(data.pid) && data.pid > 0 ? data.pid : 0,
};
}
function readDaemonLockInfo(): DaemonLockInfo | null {
const data = readJsonFile(lockPath) as DaemonLockInfo | null;
if (!data || !Number.isInteger(data.pid) || data.pid <= 0) {
return null;
}
return data;
}
function removeDaemonInfo(): void {
removeFileIfExists(infoPath);
}
function removeDaemonLock(): void {
removeFileIfExists(lockPath);
}
function cleanupStaleDaemonLockIfSafe(): void {
const state = getDaemonMetadataState();
if (!state.hasLock || state.hasInfo) return;
const lockInfo = readDaemonLockInfo();
if (!lockInfo) {
removeDaemonLock();
return;
}
if (isAgentDeviceDaemonProcess(lockInfo.pid, lockInfo.processStartTime)) {
return;
}
removeDaemonLock();
}
function getDaemonMetadataState(): DaemonMetadataState {
return {
hasInfo: fs.existsSync(infoPath),
hasLock: fs.existsSync(lockPath),
};
}
function readJsonFile(filePath: string): unknown | null {
if (!fs.existsSync(filePath)) return null;
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8')) as unknown;
} catch {
return null;
}
}
function removeFileIfExists(filePath: string): void {
try {
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
} catch {
// Best-effort cleanup only.
}
}
async function canConnect(info: DaemonInfo): Promise<boolean> {
return new Promise((resolve) => {
const socket = net.createConnection({ host: '127.0.0.1', port: info.port }, () => {
socket.destroy();
resolve(true);
});
socket.on('error', () => {
resolve(false);
});
});
}
async function startDaemon(): Promise<void> {
const launchSpec = resolveDaemonLaunchSpec();
const args = launchSpec.useSrc
? ['--experimental-strip-types', launchSpec.srcPath]
: [launchSpec.distPath];
runCmdDetached(process.execPath, args);
}
type DaemonLaunchSpec = {
root: string;
distPath: string;
srcPath: string;
useSrc: boolean;
};
function resolveDaemonLaunchSpec(): DaemonLaunchSpec {
const root = findProjectRoot();
const distPath = path.join(root, 'dist', 'src', 'daemon.js');
const srcPath = path.join(root, 'src', 'daemon.ts');
const hasDist = fs.existsSync(distPath);
const hasSrc = fs.existsSync(srcPath);
if (!hasDist && !hasSrc) {
throw new AppError('COMMAND_FAILED', 'Daemon entry not found', { distPath, srcPath });
}
const runningFromSource = process.execArgv.includes('--experimental-strip-types');
const useSrc = runningFromSource ? hasSrc : !hasDist && hasSrc;
return { root, distPath, srcPath, useSrc };
}
function resolveLocalDaemonCodeSignature(): string {
const launchSpec = resolveDaemonLaunchSpec();
const entryPath = launchSpec.useSrc ? launchSpec.srcPath : launchSpec.distPath;
return computeDaemonCodeSignature(entryPath, launchSpec.root);
}
export function computeDaemonCodeSignature(entryPath: string, root: string = findProjectRoot()): string {
try {
const stat = fs.statSync(entryPath);
const relativePath = path.relative(root, entryPath) || entryPath;
return `${relativePath}:${stat.size}:${Math.trunc(stat.mtimeMs)}`;
} catch {
return 'unknown';
}
}
async function sendRequest(info: DaemonInfo, req: DaemonRequest): Promise<DaemonResponse> {
return new Promise((resolve, reject) => {
const socket = net.createConnection({ host: '127.0.0.1', port: info.port }, () => {
socket.write(`${JSON.stringify(req)}\n`);
});
const timeout = setTimeout(() => {
socket.destroy();
const cleanup = cleanupTimedOutIosRunnerBuilds();
const daemonReset = resetDaemonAfterTimeout(info);
emitDiagnostic({
level: 'error',
phase: 'daemon_request_timeout',
data: {
timeoutMs: REQUEST_TIMEOUT_MS,
requestId: req.meta?.requestId,
command: req.command,
timedOutRunnerPidsTerminated: cleanup.terminated,
timedOutRunnerCleanupError: cleanup.error,
daemonPidReset: info.pid,
daemonPidForceKilled: daemonReset.forcedKill,
},
});
reject(
new AppError('COMMAND_FAILED', 'Daemon request timed out', {
timeoutMs: REQUEST_TIMEOUT_MS,
requestId: req.meta?.requestId,
hint: 'Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected.',
}),
);
}, REQUEST_TIMEOUT_MS);
let buffer = '';
socket.setEncoding('utf8');
socket.on('data', (chunk) => {
buffer += chunk;
const idx = buffer.indexOf('\n');
if (idx === -1) return;
const line = buffer.slice(0, idx).trim();
if (!line) return;
try {
const response = JSON.parse(line) as DaemonResponse;
socket.end();
clearTimeout(timeout);
resolve(response);
} catch (err) {
clearTimeout(timeout);
reject(new AppError('COMMAND_FAILED', 'Invalid daemon response', {
requestId: req.meta?.requestId,
line,
}, err instanceof Error ? err : undefined));
}
});
socket.on('error', (err) => {
clearTimeout(timeout);
emitDiagnostic({
level: 'error',
phase: 'daemon_request_socket_error',
data: {
requestId: req.meta?.requestId,
message: err instanceof Error ? err.message : String(err),
},
});
reject(
new AppError(
'COMMAND_FAILED',
'Failed to communicate with daemon',
{
requestId: req.meta?.requestId,
hint: 'Retry command. If this persists, clean stale daemon metadata and start a fresh session.',
},
err,
),
);
});
});
}
function cleanupTimedOutIosRunnerBuilds(): { terminated: number; error?: string } {
let terminated = 0;
try {
for (const pattern of IOS_RUNNER_XCODEBUILD_KILL_PATTERNS) {
const result = runCmdSync('pkill', ['-f', pattern], { allowFailure: true });
if (result.exitCode === 0) terminated += 1;
}
return { terminated };
} catch (error) {
return {
terminated,
error: error instanceof Error ? error.message : String(error),
};
}
}
function resetDaemonAfterTimeout(info: DaemonInfo): { forcedKill: boolean } {
let forcedKill = false;
try {
if (isAgentDeviceDaemonProcess(info.pid, info.processStartTime)) {
process.kill(info.pid, 'SIGKILL');
forcedKill = true;
}
} catch {
void stopProcessForTakeover(info.pid, {
termTimeoutMs: DAEMON_TAKEOVER_TERM_TIMEOUT_MS,
killTimeoutMs: DAEMON_TAKEOVER_KILL_TIMEOUT_MS,
expectedStartTime: info.processStartTime,
});
} finally {
removeDaemonInfo();
removeDaemonLock();
}
return { forcedKill };
}
export function resolveDaemonRequestTimeoutMs(raw: string | undefined = process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS): number {
if (!raw) return 90000;
const parsed = Number(raw);
if (!Number.isFinite(parsed)) return 90000;
return Math.max(1000, Math.floor(parsed));
}
export function resolveDaemonStartupHint(state: { hasInfo: boolean; hasLock: boolean }): string {
if (state.hasLock && !state.hasInfo) {
return 'Detected ~/.agent-device/daemon.lock without daemon.json. If no agent-device daemon process is running, delete ~/.agent-device/daemon.lock and retry.';
}
if (state.hasLock && state.hasInfo) {
return 'Daemon metadata may be stale. If no agent-device daemon process is running, delete ~/.agent-device/daemon.json and ~/.agent-device/daemon.lock, then retry.';
}
return 'Daemon metadata is missing or stale. Delete ~/.agent-device/daemon.json if present and retry.';
}