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

Function tryAcquireDaemonLock

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

Source from the content-addressed store, hash-verified

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