MCPcopy Create free account
hub / github.com/colbymchenry/codegraph / tryAcquireDaemonLock

Function tryAcquireDaemonLock

src/mcp/daemon.ts:844–895  ·  view source on GitHub ↗
(projectRoot: string)

Source from the content-addressed store, hash-verified

842 * drive that's strictly better than the daemon never starting at all.
843 */
844export function tryAcquireDaemonLock(projectRoot: string): AcquireResult {
845 const pidPath = getDaemonPidPath(projectRoot);
846 // Make sure the .codegraph/ directory exists — the daemon may be the first
847 // thing to touch it on a fresh-clone-but-already-initialized checkout.
848 fs.mkdirSync(path.dirname(pidPath), { recursive: true });
849
850 const info: DaemonLockInfo = {
851 pid: process.pid,
852 version: CodeGraphPackageVersion,
853 socketPath: getDaemonSocketPath(projectRoot),
854 startedAt: Date.now(),
855 };
856
857 // Temp name is pid-scoped so racing candidates never collide on it.
858 const tmp = `${pidPath}.${process.pid}.tmp`;
859 let acquired = false;
860 try {
861 fs.writeFileSync(tmp, encodeLockInfo(info), { mode: 0o600 });
862 try {
863 fs.linkSync(tmp, pidPath); // atomic + exclusive (race-free; see must-fix 1)
864 acquired = true;
865 } catch (err: unknown) {
866 if ((err as NodeJS.ErrnoException).code === 'EEXIST') {
867 // Lost the race — another candidate already holds it. Fall through to read.
868 } else {
869 // link() failed for a non-conflict reason — nearly always "this filesystem
870 // has no hard links" (ExFAT/FAT external volumes, some network mounts),
871 // which surfaces as a DIFFERENT errno on every OS: ENOTSUP on macOS, EPERM
872 // on Linux, EISDIR on Windows (#997). Enumerating them is whack-a-mole and
873 // unnecessary: the `tmp` write above already proved this directory is
874 // writable, so an O_EXCL create is a valid atomic+exclusive substitute. If
875 // IT fails too, that's a genuine error and propagates. EEXIST ⇒ taken.
876 acquired = acquireLockViaExclusiveOpen(pidPath, info);
877 }
878 }
879 } finally {
880 try { fs.unlinkSync(tmp); } catch { /* temp already gone */ }
881 }
882
883 if (acquired) return { kind: 'acquired', pidPath, info };
884
885 // Taken. Because the pidfile was link'd atomically it always holds a complete
886 // record — `existing` is null only for a genuinely corrupt leftover, never a
887 // mid-write race.
888 let existing: DaemonLockInfo | null = null;
889 let lockContents: string | null = null;
890 try {
891 lockContents = fs.readFileSync(pidPath, 'utf8');
892 existing = decodeLockInfo(lockContents);
893 } catch { /* unreadable lockfile — treat as malformed */ }
894 return { kind: 'taken', existing, lockContents, pidPath };
895}
896
897/**
898 * Exclusive-create the pidfile (O_CREAT|O_EXCL via the `wx` flag) and write the

Calls 5

getDaemonPidPathFunction · 0.90
getDaemonSocketPathFunction · 0.90
encodeLockInfoFunction · 0.90
decodeLockInfoFunction · 0.90

Tested by

no test coverage detected