-
-
Notifications
You must be signed in to change notification settings - Fork 247
Expand file tree
/
Copy pathdaemon.ts
More file actions
409 lines (352 loc) · 12 KB
/
daemon.ts
File metadata and controls
409 lines (352 loc) · 12 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
#!/usr/bin/env node
import net from 'node:net';
import { dirname } from 'node:path';
import { existsSync, mkdirSync, renameSync, statSync } from 'node:fs';
import { bootstrapRuntime } from './runtime/bootstrap-runtime.ts';
import { buildDaemonToolCatalogFromManifest } from './runtime/tool-catalog.ts';
import { loadManifest } from './core/manifest/load-manifest.ts';
import {
ensureSocketDir,
removeStaleSocket,
getSocketPath,
getWorkspaceKey,
resolveWorkspaceRoot,
logPathForWorkspaceKey,
} from './daemon/socket-path.ts';
import { startDaemonServer } from './daemon/daemon-server.ts';
import {
writeDaemonRegistryEntry,
removeDaemonRegistryEntry,
cleanupWorkspaceDaemonFiles,
} from './daemon/daemon-registry.ts';
import { log, normalizeLogLevel, setLogFile, setLogLevel } from './utils/logger.ts';
import { version } from './version.ts';
import {
DAEMON_IDLE_TIMEOUT_ENV_KEY,
DEFAULT_DAEMON_IDLE_CHECK_INTERVAL_MS,
resolveDaemonIdleTimeoutMs,
hasActiveRuntimeSessions,
} from './daemon/idle-shutdown.ts';
import { getDaemonActivitySnapshot } from './daemon/activity-registry.ts';
import { getDefaultCommandExecutor } from './utils/command.ts';
import { resolveAxeBinary } from './utils/axe/index.ts';
import {
flushAndCloseSentry,
getAxeVersionMetadata,
getXcodeVersionMetadata,
initSentry,
recordBootstrapDurationMetric,
recordDaemonGaugeMetric,
recordDaemonLifecycleMetric,
setSentryRuntimeContext,
} from './utils/sentry.ts';
import { isXcodemakeBinaryAvailable, isXcodemakeEnabled } from './utils/xcodemake/index.ts';
import { hydrateSentryDisabledEnvFromProjectConfig } from './utils/sentry-config.ts';
async function checkExistingDaemon(socketPath: string): Promise<boolean> {
return new Promise<boolean>((resolve) => {
const socket = net.createConnection(socketPath);
socket.on('connect', () => {
socket.end();
resolve(true);
});
socket.on('error', () => {
resolve(false);
});
});
}
function writeLine(text: string): void {
process.stdout.write(`${text}\n`);
}
const MAX_LOG_BYTES = 10 * 1024 * 1024;
const MAX_LOG_ROTATIONS = 3;
function rotateLogIfNeeded(logPath: string): void {
if (!existsSync(logPath)) {
return;
}
const size = statSync(logPath).size;
if (size < MAX_LOG_BYTES) {
return;
}
for (let index = MAX_LOG_ROTATIONS - 1; index >= 1; index -= 1) {
const from = `${logPath}.${index}`;
const to = `${logPath}.${index + 1}`;
if (existsSync(from)) {
renameSync(from, to);
}
}
renameSync(logPath, `${logPath}.1`);
}
function resolveDaemonLogPath(workspaceKey: string): string | null {
const override = process.env.XCODEBUILDMCP_DAEMON_LOG_PATH?.trim();
if (override) {
return override;
}
return logPathForWorkspaceKey(workspaceKey);
}
function ensureLogDir(logPath: string): void {
const dir = dirname(logPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: 0o700 });
}
}
function resolveLogLevel(): ReturnType<typeof normalizeLogLevel> {
const raw = process.env.XCODEBUILDMCP_DAEMON_LOG_LEVEL;
if (!raw) {
return null;
}
return normalizeLogLevel(raw);
}
async function main(): Promise<void> {
const daemonBootstrapStart = Date.now();
const result = await bootstrapRuntime({
runtime: 'daemon',
configOverrides: {
disableSessionDefaults: true,
},
});
const workspaceRoot = resolveWorkspaceRoot({
cwd: result.runtime.cwd,
projectConfigPath: result.configPath,
});
const workspaceKey = getWorkspaceKey({
cwd: result.runtime.cwd,
projectConfigPath: result.configPath,
});
const logPath = resolveDaemonLogPath(workspaceKey);
if (logPath) {
ensureLogDir(logPath);
rotateLogIfNeeded(logPath);
setLogFile(logPath);
setLogLevel(resolveLogLevel() ?? 'info');
}
await hydrateSentryDisabledEnvFromProjectConfig({
cwd: result.runtime.cwd,
});
initSentry({ mode: 'cli-daemon' });
recordDaemonLifecycleMetric('start');
log('info', `[Daemon] xcodebuildmcp daemon ${version} starting...`);
const socketPath = getSocketPath({
cwd: result.runtime.cwd,
projectConfigPath: result.configPath,
});
log('info', `[Daemon] Workspace: ${workspaceRoot}`);
log('info', `[Daemon] Socket: ${socketPath}`);
if (logPath) {
log('info', `[Daemon] Logs: ${logPath}`);
}
ensureSocketDir(socketPath);
const isRunning = await checkExistingDaemon(socketPath);
if (isRunning) {
log('error', '[Daemon] Another daemon is already running for this workspace');
console.error('Error: Daemon is already running for this workspace');
await flushAndCloseSentry(1000);
process.exit(1);
}
removeStaleSocket(socketPath);
const excludedWorkflows = ['session-management', 'workflow-discovery'];
// Daemon runtime serves CLI routing and should not be filtered by enabledWorkflows.
// CLI exposure is controlled at CLI catalog/command registration time.
// Get all workflows from manifest (for reporting purposes and filtering).
const manifest = loadManifest();
const allWorkflowIds = Array.from(manifest.workflows.keys());
const daemonWorkflows = allWorkflowIds.filter(
(workflowId) => !excludedWorkflows.includes(workflowId),
);
const xcodeIdeWorkflowEnabled = daemonWorkflows.includes('xcode-ide');
const axeBinary = resolveAxeBinary();
const axeAvailable = axeBinary !== null;
const axeSource: 'env' | 'bundled' | 'path' | 'unavailable' = axeBinary?.source ?? 'unavailable';
const xcodemakeAvailable = isXcodemakeBinaryAvailable();
const xcodemakeEnabled = isXcodemakeEnabled();
const baseSentryRuntimeContext = {
mode: 'cli-daemon' as const,
enabledWorkflows: daemonWorkflows,
disableSessionDefaults: result.runtime.config.disableSessionDefaults,
disableXcodeAutoSync: result.runtime.config.disableXcodeAutoSync,
incrementalBuildsEnabled: result.runtime.config.incrementalBuildsEnabled,
debugEnabled: result.runtime.config.debug,
uiDebuggerGuardMode: result.runtime.config.uiDebuggerGuardMode,
xcodeIdeWorkflowEnabled,
axeAvailable,
axeSource,
xcodemakeAvailable,
xcodemakeEnabled,
};
setSentryRuntimeContext(baseSentryRuntimeContext);
const enrichSentryMetadata = async (): Promise<void> => {
const commandExecutor = getDefaultCommandExecutor();
const xcodeVersion = await getXcodeVersionMetadata(async (command) => {
const result = await commandExecutor(command, 'Get Xcode Version');
return { success: result.success, output: result.output };
});
const xcodeAvailable = Boolean(
xcodeVersion.version ??
xcodeVersion.buildVersion ??
xcodeVersion.developerDir ??
xcodeVersion.xcodebuildPath,
);
const axeVersion = await getAxeVersionMetadata(async (command) => {
const result = await commandExecutor(command, 'Get AXe Version');
return { success: result.success, output: result.output };
}, axeBinary?.path);
setSentryRuntimeContext({
...baseSentryRuntimeContext,
xcodeAvailable,
axeVersion,
xcodeDeveloperDir: xcodeVersion.developerDir,
xcodebuildPath: xcodeVersion.xcodebuildPath,
xcodeVersion: xcodeVersion.version,
xcodeBuildVersion: xcodeVersion.buildVersion,
});
};
const catalog = await buildDaemonToolCatalogFromManifest({
excludeWorkflows: excludedWorkflows,
});
log('info', `[Daemon] Loaded ${catalog.tools.length} tools`);
const startedAt = new Date().toISOString();
const idleTimeoutMs = resolveDaemonIdleTimeoutMs();
const configuredIdleTimeout = process.env[DAEMON_IDLE_TIMEOUT_ENV_KEY]?.trim();
if (configuredIdleTimeout) {
const parsedIdleTimeout = Number(configuredIdleTimeout);
if (!Number.isFinite(parsedIdleTimeout) || parsedIdleTimeout < 0) {
log(
'warn',
`[Daemon] Invalid ${DAEMON_IDLE_TIMEOUT_ENV_KEY}=${configuredIdleTimeout}; using default ${idleTimeoutMs}ms`,
);
}
}
if (idleTimeoutMs === 0) {
log('info', '[Daemon] Idle shutdown disabled');
} else {
log(
'info',
`[Daemon] Idle shutdown enabled: timeout=${idleTimeoutMs}ms interval=${DEFAULT_DAEMON_IDLE_CHECK_INTERVAL_MS}ms`,
);
}
recordDaemonGaugeMetric('idle_timeout_ms', idleTimeoutMs);
let isShuttingDown = false;
let inFlightRequests = 0;
let lastActivityAt = Date.now();
let idleCheckTimer: NodeJS.Timeout | null = null;
const markActivity = (): void => {
lastActivityAt = Date.now();
};
// Unified shutdown handler
const shutdown = (): void => {
if (isShuttingDown) {
return;
}
isShuttingDown = true;
if (idleCheckTimer) {
clearInterval(idleCheckTimer);
idleCheckTimer = null;
}
recordDaemonLifecycleMetric('shutdown');
log('info', '[Daemon] Shutting down...');
// Close the server
server.close(() => {
log('info', '[Daemon] Server closed');
// Remove registry entry and socket
removeDaemonRegistryEntry(workspaceKey);
removeStaleSocket(socketPath);
log('info', '[Daemon] Cleanup complete');
void flushAndCloseSentry(2000).finally(() => {
process.exit(0);
});
});
// Force exit if server doesn't close in time
setTimeout(() => {
log('warn', '[Daemon] Forced shutdown after timeout');
cleanupWorkspaceDaemonFiles(workspaceKey);
void flushAndCloseSentry(1000).finally(() => {
process.exit(1);
});
}, 5000);
};
const emitRequestGauges = (): void => {
recordDaemonGaugeMetric('inflight_requests', inFlightRequests);
recordDaemonGaugeMetric('active_sessions', getDaemonActivitySnapshot().activeOperationCount);
};
const server = startDaemonServer({
socketPath,
logPath: logPath ?? undefined,
startedAt,
enabledWorkflows: daemonWorkflows,
catalog,
workspaceRoot,
workspaceKey,
xcodeIdeWorkflowEnabled,
requestShutdown: shutdown,
onRequestStarted: () => {
inFlightRequests += 1;
markActivity();
emitRequestGauges();
},
onRequestFinished: () => {
inFlightRequests = Math.max(0, inFlightRequests - 1);
markActivity();
emitRequestGauges();
},
});
emitRequestGauges();
if (idleTimeoutMs > 0) {
idleCheckTimer = setInterval(() => {
if (isShuttingDown) {
return;
}
emitRequestGauges();
const idleForMs = Date.now() - lastActivityAt;
if (idleForMs < idleTimeoutMs) {
return;
}
if (inFlightRequests > 0) {
return;
}
if (hasActiveRuntimeSessions(getDaemonActivitySnapshot())) {
return;
}
log(
'info',
`[Daemon] Idle timeout reached (${idleForMs}ms >= ${idleTimeoutMs}ms); shutting down`,
);
shutdown();
}, DEFAULT_DAEMON_IDLE_CHECK_INTERVAL_MS);
idleCheckTimer.unref?.();
}
server.listen(socketPath, () => {
log('info', `[Daemon] Listening on ${socketPath}`);
// Write registry entry after successful listen
writeDaemonRegistryEntry({
workspaceKey,
workspaceRoot,
socketPath,
logPath: logPath ?? undefined,
pid: process.pid,
startedAt,
enabledWorkflows: daemonWorkflows,
version: String(version),
});
writeLine(`Daemon started (PID: ${process.pid})`);
writeLine(`Workspace: ${workspaceRoot}`);
writeLine(`Socket: ${socketPath}`);
writeLine(`Tools: ${catalog.tools.length}`);
recordBootstrapDurationMetric('cli-daemon', Date.now() - daemonBootstrapStart);
setImmediate(() => {
void enrichSentryMetadata().catch((error) => {
const message = error instanceof Error ? error.message : String(error);
log('warn', `[Daemon] Failed to enrich Sentry metadata: ${message}`);
});
});
});
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
}
main().catch(async (err) => {
recordDaemonLifecycleMetric('crash');
const message =
err == null ? 'Unknown daemon error' : err instanceof Error ? err.message : String(err);
log('error', `Daemon error: ${message}`, { sentry: true });
console.error('Daemon error:', message);
await flushAndCloseSentry(2000);
process.exit(1);
});