Skip to main content

run_http_foreground

Function run_http_foreground 

Source
pub async fn run_http_foreground(state: AppState) -> Result<()>
Expand description

The canonical serve --foreground entry point used by launchd and systemd supervisors (issue #787).

Why (issue #787): previously serve --foreground shared the same run_http_dynamic path used by ad-hoc CLI invocations. That path silently port-walked (7070→7071→…→7079→OS-assigned) on bind collision, producing hidden second instances that never appeared in the http_addr discovery file at the expected port. This function replaces that path for the supervised case with three explicit guarantees:

  1. Lock file ownership (Fix A): writes daemon.lock containing the current PID before binding. The RAII guard removes the file on any exit (graceful shutdown, panic, launchd SIGTERM). start and the single-instance guard read this file as a second detection layer when http_addr is absent or stale.

  2. http_addr written on bind (Fix B): run_http_on writes both the OS-standard http_addr file and the legacy dotfile path (~/.trusty-memory/http_addr) immediately after binding, before accepting the first request. Both files are removed on clean shutdown. This ensures trusty-memory port and the MCP bridge always find the running daemon.

  3. Abort on port collision (Fix C): uses bind_foreground_port (binds exactly port 7070, returns Err on EADDRINUSE) instead of the port-walking bind_dynamic_port. If 7070 is already taken the function returns Err with a clear message; the caller (main.rs) exits non-zero, launchd logs the error, applies ThrottleInterval, and the single-instance guard prevents a respawn storm.

What: acquires the daemon lock, binds 127.0.0.1:7070 (aborts on collision), then runs run_http_on which writes the addr file and serves until graceful shutdown. The lock guard is dropped after run_http_on returns, removing daemon.lock best-effort.

Test: bind_foreground_port_refuses_collision (unit), plus the integration path trusty-memory service start followed by a second trusty-memory serve --foreground which should exit immediately with the “already in use” error.