Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions src/daemon/app-log-android.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import { AppError } from '../utils/errors.ts';
import { runCmd } from '../utils/exec.ts';
import { clearPidFile, writePidFile, type AppLogResult } from './app-log-process.ts';
import { attachChildToStream, createLineWriter, sleep, waitForChildExit } from './app-log-stream.ts';

export function assertAndroidPackageArgSafe(appBundleId: string): void {
if (!/^[a-zA-Z0-9._:-]+$/.test(appBundleId)) {
throw new AppError('INVALID_ARGS', `Invalid Android package name for logs: ${appBundleId}`);
}
}

async function resolveAndroidPid(deviceId: string, appBundleId: string): Promise<string | null> {
const pidResult = await runCmd('adb', ['-s', deviceId, 'shell', 'pidof', appBundleId], {
allowFailure: true,
});
const pid = pidResult.stdout.trim().split(/\s+/)[0];
if (!pid || !/^\d+$/.test(pid)) return null;
return pid;
}

export async function startAndroidAppLog(
deviceId: string,
appBundleId: string,
stream: fs.WriteStream,
redactionPatterns: RegExp[],
pidPath?: string,
): Promise<AppLogResult> {
let state: 'active' | 'failed' = 'active';
let stopped = false;
let activeChild: ReturnType<typeof spawn> | undefined;
let activeWait: ReturnType<typeof attachChildToStream> | undefined;

const wait = (async () => {
try {
while (!stopped) {
const pid = await resolveAndroidPid(deviceId, appBundleId);
if (!pid) {
await sleep(1_000);
continue;
}
const child = spawn('adb', ['-s', deviceId, 'logcat', '-v', 'time', '--pid', pid], {
stdio: ['ignore', 'pipe', 'pipe'],
});
activeChild = child;
const writer = createLineWriter(stream, { redactionPatterns });
activeWait = attachChildToStream(child, stream, { endStreamOnClose: false, writer });
if (typeof child.pid === 'number') {
writePidFile(pidPath, child.pid);
}
const result = await activeWait;
clearPidFile(pidPath);
activeChild = undefined;
activeWait = undefined;
if (stopped) return { stdout: '', stderr: '', exitCode: 0 };
if (result.exitCode !== 0) {
state = 'failed';
}
await sleep(500);
}
return { stdout: '', stderr: '', exitCode: 0 };
} finally {
stream.end();
clearPidFile(pidPath);
}
})();

return {
backend: 'android',
getState: () => state,
startedAt: Date.now(),
wait,
stop: async () => {
stopped = true;
if (activeChild && !activeChild.killed) {
activeChild.kill('SIGINT');
}
if (activeWait) await waitForChildExit(activeWait);
if (activeChild && !activeChild.killed) {
activeChild.kill('SIGKILL');
}
await waitForChildExit(wait);
clearPidFile(pidPath);
},
};
}
85 changes: 85 additions & 0 deletions src/daemon/app-log-ios.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import { clearPidFile, writePidFile, type AppLogResult } from './app-log-process.ts';
import { attachChildToStream, createLineWriter, waitForChildExit } from './app-log-stream.ts';

export function buildIosLogPredicate(appBundleId: string): string {
return [
`subsystem == "${appBundleId}"`,
`processImagePath ENDSWITH[c] "/${appBundleId}"`,
`senderImagePath ENDSWITH[c] "/${appBundleId}"`,
`eventMessage CONTAINS[c] "${appBundleId}"`,
].join(' OR ');
}

export function buildIosDeviceLogStreamArgs(deviceId: string): string[] {
return ['devicectl', 'device', 'log', 'stream', '--device', deviceId];
}

export async function startIosSimulatorAppLog(
appBundleId: string,
stream: fs.WriteStream,
redactionPatterns: RegExp[],
pidPath?: string,
): Promise<AppLogResult> {
let state: 'active' | 'failed' = 'active';
const child = spawn('log', ['stream', '--style', 'compact', '--predicate', buildIosLogPredicate(appBundleId)], {
stdio: ['ignore', 'pipe', 'pipe'],
});
const writer = createLineWriter(stream, { redactionPatterns });
if (typeof child.pid === 'number') {
writePidFile(pidPath, child.pid);
}
const wait = attachChildToStream(child, stream, { endStreamOnClose: true, writer }).then((result) => {
if (result.exitCode !== 0) state = 'failed';
clearPidFile(pidPath);
return result;
});
return {
backend: 'ios-simulator',
getState: () => state,
startedAt: Date.now(),
wait,
stop: async () => {
if (!child.killed) child.kill('SIGINT');
await waitForChildExit(wait);
if (!child.killed) child.kill('SIGKILL');
await waitForChildExit(wait);
clearPidFile(pidPath);
},
};
}

export async function startIosDeviceAppLog(
deviceId: string,
stream: fs.WriteStream,
redactionPatterns: RegExp[],
pidPath?: string,
): Promise<AppLogResult> {
let state: 'active' | 'failed' = 'active';
const child = spawn('xcrun', buildIosDeviceLogStreamArgs(deviceId), {
stdio: ['ignore', 'pipe', 'pipe'],
});
const writer = createLineWriter(stream, { redactionPatterns });
if (typeof child.pid === 'number') {
writePidFile(pidPath, child.pid);
}
const wait = attachChildToStream(child, stream, { endStreamOnClose: true, writer }).then((result) => {
if (result.exitCode !== 0) state = 'failed';
clearPidFile(pidPath);
return result;
});
return {
backend: 'ios-device',
getState: () => state,
startedAt: Date.now(),
wait,
stop: async () => {
if (!child.killed) child.kill('SIGINT');
await waitForChildExit(wait);
if (!child.killed) child.kill('SIGKILL');
await waitForChildExit(wait);
clearPidFile(pidPath);
},
};
}
96 changes: 96 additions & 0 deletions src/daemon/app-log-process.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import fs from 'node:fs';
import path from 'node:path';
import { readProcessCommand, readProcessStartTime } from '../utils/process-identity.ts';

export const APP_LOG_PID_FILENAME = 'app-log.pid';

export type AppLogResult = {
backend: 'ios-simulator' | 'ios-device' | 'android';
getState: () => 'active' | 'failed';
startedAt: number;
stop: () => Promise<void>;
wait: Promise<{ stdout: string; stderr: string; exitCode: number }>;
};

type StoredAppLogProcessMeta = {
pid: number;
startTime?: string;
command?: string;
};

function parsePidFile(raw: string): StoredAppLogProcessMeta | null {
const trimmed = raw.trim();
if (!trimmed) return null;
if (/^\d+$/.test(trimmed)) {
return { pid: Number.parseInt(trimmed, 10) };
}
try {
const parsed = JSON.parse(trimmed) as StoredAppLogProcessMeta;
if (!Number.isInteger(parsed.pid) || parsed.pid <= 0) return null;
return parsed;
} catch {
return null;
}
}

function isManagedAppLogCommand(command: string): boolean {
const normalized = command.toLowerCase().replaceAll('\\', '/');
return normalized.includes('log stream')
|| normalized.includes('logcat')
|| normalized.includes('devicectl device log stream');
}

function shouldTerminateStoredProcess(meta: StoredAppLogProcessMeta): boolean {
const currentStartTime = readProcessStartTime(meta.pid);
if (!currentStartTime) return false;
if (meta.startTime && currentStartTime !== meta.startTime) return false;
const currentCommand = readProcessCommand(meta.pid);
if (!currentCommand || !isManagedAppLogCommand(currentCommand)) return false;
if (meta.command && currentCommand !== meta.command) return false;
return true;
}

export function writePidFile(pidPath: string | undefined, pid: number): void {
if (!pidPath) return;
const dir = path.dirname(pidPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
const metadata: StoredAppLogProcessMeta = {
pid,
startTime: readProcessStartTime(pid) ?? undefined,
command: readProcessCommand(pid) ?? undefined,
};
fs.writeFileSync(pidPath, `${JSON.stringify(metadata)}\n`);
}

export function clearPidFile(pidPath: string | undefined): void {
if (!pidPath || !fs.existsSync(pidPath)) return;
try {
fs.unlinkSync(pidPath);
} catch {
// best-effort cleanup
}
}

export function cleanupStaleAppLogProcesses(sessionsDir: string): void {
if (!fs.existsSync(sessionsDir)) return;
const entries = fs.readdirSync(sessionsDir, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const pidPath = path.join(sessionsDir, entry.name, APP_LOG_PID_FILENAME);
if (!fs.existsSync(pidPath)) continue;
try {
const meta = parsePidFile(fs.readFileSync(pidPath, 'utf8'));
if (meta && shouldTerminateStoredProcess(meta)) {
try {
process.kill(meta.pid, 'SIGTERM');
} catch {
// process already gone
}
}
} catch {
// ignore malformed pid files
} finally {
clearPidFile(pidPath);
}
}
}
82 changes: 82 additions & 0 deletions src/daemon/app-log-stream.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import type { ExecResult } from '../utils/exec.ts';

export async function waitForChildExit(wait: Promise<ExecResult>, timeoutMs = 2_000): Promise<void> {
await Promise.race([
wait.then(() => undefined).catch(() => undefined),
new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),
]);
}

export async function sleep(ms: number): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, ms));
}

function redactChunk(chunk: string, patterns: RegExp[]): string {
if (patterns.length === 0) return chunk;
let output = chunk;
for (const pattern of patterns) {
output = output.replace(pattern, '[REDACTED]');
}
return output;
}

export function createLineWriter(
stream: fs.WriteStream,
options: { redactionPatterns: RegExp[]; includeTokens?: string[] },
): { onChunk: (chunk: string) => void; flush: () => void } {
const includeTokens = options.includeTokens?.filter((token) => token.length > 0) ?? [];
let pending = '';

const writeLine = (line: string): void => {
if (includeTokens.length > 0) {
const shouldInclude = includeTokens.some((token) => line.includes(token));
if (!shouldInclude) return;
}
stream.write(redactChunk(line, options.redactionPatterns));
};

return {
onChunk: (chunk: string) => {
const combined = `${pending}${chunk}`;
const lines = combined.split('\n');
pending = lines.pop() ?? '';
for (const line of lines) {
writeLine(`${line}\n`);
}
},
flush: () => {
if (!pending) return;
writeLine(pending);
pending = '';
},
};
}

export function attachChildToStream(
child: ReturnType<typeof spawn>,
stream: fs.WriteStream,
options: { endStreamOnClose: boolean; writer: { onChunk: (chunk: string) => void; flush: () => void } },
): Promise<ExecResult> {
const stdout = child.stdout;
const stderr = child.stderr;
if (!stdout || !stderr) {
return Promise.resolve({ stdout: '', stderr: 'missing stdio pipes', exitCode: 1 });
}
stdout.setEncoding('utf8');
stderr.setEncoding('utf8');
stdout.on('data', options.writer.onChunk);
stderr.on('data', options.writer.onChunk);
stream.on('error', () => {
if (!child.killed) child.kill('SIGKILL');
});
child.on('error', () => stream.destroy());
return new Promise<ExecResult>((resolve) => {
child.on('close', (code) => {
options.writer.flush();
if (options.endStreamOnClose) stream.end();
resolve({ stdout: '', stderr: '', exitCode: code ?? 1 });
});
});
}
Loading
Loading