Skip to content
Open
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
67 changes: 55 additions & 12 deletions packages/daemon-client/src/autostart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ export async function ensureDaemon(
// wait — releasing early lets it spawn a twin that clobbers the socket path
// and orphans the first daemon forever.
try {
if (!spawnDaemon(bin.path, dir, debug)) return null;
const pid = spawnDaemon(bin.path, dir, debug);
if (pid === null) return null;
writeSpawnLockPid(lockPath, pid);
return await waitForSocket(waitMs, debug);
} finally {
releaseSpawnLock(lockPath);
Expand Down Expand Up @@ -176,7 +178,9 @@ async function replaceStaleDaemon(
}
debug?.("stale devkitd stopped");
}
if (!spawnDaemon(bin.path, dir, debug)) return null;
const pid = spawnDaemon(bin.path, dir, debug);
if (pid === null) return null;
writeSpawnLockPid(lockPath, pid);
return await waitForSocket(waitMs, debug);
} finally {
releaseSpawnLock(lockPath);
Expand All @@ -193,7 +197,7 @@ function isNewerVersion(a: string, b: string): boolean {
return false;
}

function spawnDaemon(bin: string, dir: string, debug?: (msg: string) => void): boolean {
function spawnDaemon(bin: string, dir: string, debug?: (msg: string) => void): number | null {
try {
const logPath = path.join(dir, "daemon.log");
capDaemonLog(logPath);
Expand All @@ -204,14 +208,45 @@ function spawnDaemon(bin: string, dir: string, debug?: (msg: string) => void): b
});
child.unref();
fs.closeSync(logFd);
if (child.pid === undefined) {
debug?.("devkitd spawn failed (no pid)");
return null;
}
debug?.(`spawned devkitd (pid ${child.pid}) from ${bin}; waiting for socket`);
return true;
return child.pid;
} catch {
debug?.("devkitd spawn failed");
return null;
}
}

function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}

function writeSpawnLockPid(lockPath: string, pid: number): void {
try {
fs.writeFileSync(lockPath, String(pid));
} catch {
/* best effort — mtime-based reclaim still applies */
}
}

function readSpawnLockPid(lockPath: string): number | undefined {
try {
const text = fs.readFileSync(lockPath, "utf8").trim();
const pid = Number(text);
return Number.isInteger(pid) && pid > 0 ? pid : undefined;
} catch {
return undefined;
}
}

/** daemon.log is append-only per spawn — rotate to .1 past 1 MiB. */
const MAX_LOG_BYTES = 1 << 20;

Expand All @@ -233,23 +268,31 @@ function releaseSpawnLock(lockPath: string): void {
}
}

function spawnLockIsStale(lockPath: string, staleMs: number): boolean {
try {
const age = Date.now() - fs.statSync(lockPath).mtimeMs;
if (age > staleMs) return true;
const pid = readSpawnLockPid(lockPath);
return pid !== undefined && !isProcessAlive(pid);
} catch {
return false;
}
}

function acquireSpawnLock(lockPath: string, staleMs: number): boolean {
try {
fs.closeSync(fs.openSync(lockPath, "wx", 0o600));
return true;
} catch {
// Lock held — reclaim it only if the holder plausibly died.
if (!spawnLockIsStale(lockPath, staleMs)) return false;
try {
const age = Date.now() - fs.statSync(lockPath).mtimeMs;
if (age > staleMs) {
fs.unlinkSync(lockPath);
fs.closeSync(fs.openSync(lockPath, "wx", 0o600));
return true;
}
fs.unlinkSync(lockPath);
fs.closeSync(fs.openSync(lockPath, "wx", 0o600));
return true;
} catch {
/* races with the holder are fine — losing means we wait */
return false;
}
return false;
}
}

Expand Down
142 changes: 142 additions & 0 deletions packages/daemon-client/tests/autostart-spawn-lock.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import { daemonSocketPath } from "../src/client.js";
import { ensureDaemon } from "../src/autostart.js";
import type { DaemonBinary } from "../src/binary.js";

const testDir = path.dirname(fileURLToPath(import.meta.url));

/** Fake devkitd that sleeps before binding — reproduces client wait timeout (#495). */
function makeSlowFakeBin(dir: string, delayMs: number): string {
const file = path.join(dir, "slow-devkitd");
fs.writeFileSync(
file,
`#!/usr/bin/env node
const fs = require("node:fs");
const net = require("node:net");
const path = require("node:path");
const os = require("node:os");
const delay = ${delayMs};
if (process.argv[2] === "version") {
console.log(JSON.stringify({ version: "0.1.0", buildVersion: "9.9.9" }));
process.exit(0);
}
const dir = path.join(os.homedir(), ".ai-devkit");
const sock = path.join(dir, "daemon.sock");
fs.mkdirSync(dir, { recursive: true });
fs.appendFileSync(path.join(dir, "slow-pids"), process.pid + "\\n");
setTimeout(() => {
const server = net.createServer((conn) => {
let buf = "";
conn.on("data", (d) => {
buf += d;
let i;
while ((i = buf.indexOf("\\n")) >= 0) {
const req = JSON.parse(buf.slice(0, i));
buf = buf.slice(i + 1);
conn.write(JSON.stringify({ id: req.id, result: { pong: true } }) + "\\n");
}
});
});
server.listen(sock);
}, delay);
`,
);
fs.chmodSync(file, 0o755);
return file;
}

describe("ensureDaemon spawn lock", () => {
let home: string;
let binDir: string;
const saved: Record<string, string | undefined> = {};

beforeEach(() => {
home = fs.mkdtempSync(path.join(os.tmpdir(), "aidk-spawnlock-home-"));
binDir = fs.mkdtempSync(path.join(os.tmpdir(), "aidk-spawnlock-bin-"));
for (const k of ["HOME", "DEVKITD_BIN", "AI_DEVKIT_NO_DAEMON", "VITEST"])
saved[k] = process.env[k];
process.env.HOME = home;
delete process.env.AI_DEVKIT_NO_DAEMON;
delete process.env.VITEST;
});

afterEach(() => {
const pids = path.join(home, ".ai-devkit", "slow-pids");
if (fs.existsSync(pids)) {
for (const pid of fs.readFileSync(pids, "utf8").split("\n").filter(Boolean)) {
try {
process.kill(Number(pid), "SIGKILL");
} catch {
/* already gone */
}
}
}
for (const [k, v] of Object.entries(saved)) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
fs.rmSync(home, { recursive: true, force: true });
fs.rmSync(binDir, { recursive: true, force: true });
});

it("releases spawn lock when the socket wait times out", async () => {
const bin = makeSlowFakeBin(binDir, 5000);
const lockPath = `${daemonSocketPath()}.spawn.lock`;
const resolveBinary = (): DaemonBinary => ({ path: bin, version: "9.9.9" });

const client = await ensureDaemon({ resolveBinary, waitMs: 200 });
expect(client).toBeNull();
expect(fs.existsSync(lockPath)).toBe(false);
});

it("reclaims spawn lock when the recorded devkitd pid has exited", async () => {
const lockPath = `${daemonSocketPath()}.spawn.lock`;
fs.mkdirSync(path.dirname(lockPath), { recursive: true });
fs.writeFileSync(lockPath, "999999999");

const bin = makeSlowFakeBin(binDir, 50);
const resolveBinary = (): DaemonBinary => ({ path: bin, version: "9.9.9" });
const client = await ensureDaemon({ resolveBinary, waitMs: 3000 });
expect(client).not.toBeNull();
client?.close();
expect(fs.existsSync(lockPath)).toBe(false);
});

it("short-lived caller subprocess exits promptly when devkitd binds slowly", async () => {
const bin = makeSlowFakeBin(binDir, 8000);
const runner = path.join(home, "run-ensure-once.mjs");
const autostart = path.join(testDir, "../dist/autostart.js");
fs.writeFileSync(
runner,
`import { ensureDaemon } from ${JSON.stringify(autostart)};
await ensureDaemon({
waitMs: 250,
resolveBinary: () => ({ path: process.env.BIN, version: "9.9.9" }),
});
`,
);

const start = Date.now();
await new Promise<void>((resolve, reject) => {
const child = spawn(process.execPath, [runner], {
env: { ...process.env, HOME: home, BIN: bin, VITEST: undefined },
stdio: "ignore",
});
const killTimer = setTimeout(() => {
child.kill("SIGKILL");
reject(new Error("subprocess hung (event loop kept alive)"));
}, 2500);
child.on("exit", (code) => {
clearTimeout(killTimer);
if (code === 0) resolve();
else reject(new Error(`subprocess exited ${code}`));
});
});
expect(Date.now() - start).toBeLessThan(2000);
}, 15000);
});
5 changes: 3 additions & 2 deletions rust/crates/devkitd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ async fn main() -> Result<()> {
let cmd = std::env::args().nth(1).unwrap_or_else(|| "serve".into());
match cmd.as_str() {
"serve" => {
let daemon = Arc::new(Daemon::new(&data_dir(), socket_path(), dirs_home())?);
daemon.apply_sweep(); // warm the cache before accepting clients
let dir = data_dir();
let _instance = server::acquire_instance_lock(&dir)?;
let daemon = Arc::new(Daemon::new(&dir, socket_path(), dirs_home())?);
server::serve(daemon).await
}
"install" => {
Expand Down
56 changes: 52 additions & 4 deletions rust/crates/devkitd/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,33 @@ fn peer_is_same_user(_stream: &UnixStream) -> bool {
/// apart (#376) — clients compare `buildVersion` to detect a stale daemon.
pub const BUILD_VERSION: Option<&str> = option_env!("DEVKITD_BUILD_VERSION");

/// Kernel-released singleton lock — held for the process lifetime so two
/// `devkitd serve` invocations cannot both sweep `daemon.db` or race on the
/// socket path. Must be taken before `Daemon::new()` / SQLite work.
pub fn acquire_instance_lock(data_dir: &std::path::Path) -> Result<InstanceLock> {
std::fs::create_dir_all(data_dir)?;
let path = data_dir.join("daemon.lock");
let file = std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(false)
.open(&path)?;
let fd = std::os::unix::io::AsRawFd::as_raw_fd(&file);
let rc = unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) };
if rc != 0 {
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::EWOULDBLOCK) {
anyhow::bail!("devkitd already running");
}
return Err(err.into());
}
Ok(InstanceLock { _file: file })
}

pub struct InstanceLock {
_file: std::fs::File,
}

/// Shared by `daemon.status` and `devkitd version` so a client can compare
/// the running daemon against the binary it would spawn.
pub fn identity() -> Value {
Expand All @@ -428,15 +455,21 @@ pub async fn serve(daemon: Arc<Daemon>) -> Result<()> {
// Refuse to displace a live daemon: unlinking the socket file leaves
// the old process sweeping and writing daemon.db invisibly — two
// daemons, one reachable. Only a dead owner's file is unlinked.
match std::os::unix::net::UnixStream::connect(&daemon.socket_path) {
Ok(_) => anyhow::bail!("devkitd already running"),
Err(_) => std::fs::remove_file(&daemon.socket_path)?,
if std::os::unix::net::UnixStream::connect(&daemon.socket_path).is_ok() {
anyhow::bail!("devkitd already running");
}
if daemon.socket_path.exists() {
std::fs::remove_file(&daemon.socket_path)?;
}
}
let listener = UnixListener::bind(&daemon.socket_path)?;
std::fs::set_permissions(&daemon.socket_path, std::fs::Permissions::from_mode(0o600))?;
tracing::info!("listening on {}", daemon.socket_path.display());

// Warm the cache after the socket is visible so clients don't time out
// while SQLite + the first sweep run (#495).
daemon.apply_sweep();

// Discovery loop: one sweep per interval for all subscribers.
{
let d = daemon.clone();
Expand Down Expand Up @@ -610,7 +643,6 @@ mod tests {

async fn test_daemon() -> (Arc<Daemon>, PathBuf) {
let (d, sock) = unserved_daemon();
d.apply_sweep(); // warm the cache like main() does before serving
let d2 = d.clone();
tokio::spawn(async move {
let _ = serve(d2).await;
Expand Down Expand Up @@ -699,6 +731,22 @@ mod tests {
assert_eq!(r["pid"], std::process::id());
}

#[test]
fn instance_lock_allows_one_holder() {
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let dir = std::env::temp_dir().join(format!(
"aidk-instlock-{}-{}",
std::process::id(),
N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
));
std::fs::create_dir_all(&dir).unwrap();
let _a = acquire_instance_lock(&dir).unwrap();
match acquire_instance_lock(&dir) {
Err(e) => assert!(e.to_string().contains("already running")),
Ok(_) => panic!("expected lock contention"),
}
}

#[tokio::test]
async fn serve_refuses_to_displace_a_live_daemon() {
let (d, sock) = test_daemon().await;
Expand Down
Loading