Skip to main content

trusty_code/serve/
discovery.rs

1//! `tcode serve --http` daemon discovery file (issue #3415, DOC-50 §3.4).
2//!
3//! Why: `tcode tui` (`crate::tui_client::CodeEngine`) needs to find a running
4//! `tcode serve --http` daemon without the operator copying a port number by
5//! hand. DOC-50 §3.4's prose sketched a NEW, tcode-specific JSON file
6//! (`~/.trusty-code/daemon.json`, `{daemon_url, pid, started_at}`) for this —
7//! but this crate's siblings already solve the identical problem, and their
8//! convention is different: `trusty-memory` (which wrote one until #6286 retired both the file and its listener)
9//! and `trusty-search` (`crates/trusty-search/src/service/daemon.rs`) both
10//! write the bound `host:port` as PLAIN TEXT to a file named `http_addr`
11//! under `trusty_common::resolve_data_dir(<app_name>)`, atomically (tmp +
12//! rename) so a reader never observes a half-written value. This module
13//! follows THAT established convention for tcode instead of inventing a
14//! second, JSON-shaped one: `pid`/`started_at` have no consumer anywhere in
15//! this codebase yet, and a plain-text `host:port` is exactly what
16//! `discover_daemon_url` (`crate::tui_client::discovery`) needs to build
17//! `http://{addr}`.
18//! What: [`http_addr_path`] resolves `{resolve_data_dir("trusty-code")}/http_addr`
19//! (server AND client side share this one path-resolution function so they
20//! can never drift onto two different locations); [`write_http_addr_file`]
21//! (called from `crate::serve::http::run_http` after binding) atomically
22//! writes the bound address; [`remove_http_addr_file`] (called on graceful
23//! shutdown) clears it so a stopped daemon doesn't leave a stale pointer for
24//! the next reader; [`read_http_addr_file`] (called from
25//! `crate::tui_client::discovery`) reads and trims it back. Every operation
26//! is best-effort: a write/remove failure only degrades discovery to the
27//! `TCODE_DAEMON_URL` env var; a read failure (file absent, stale content,
28//! unreadable) means "no candidate from this source," not a hard error — the
29//! caller's overall discovery still fails with a clear, actionable message
30//! when no source yields a live daemon.
31//! Test: `discovery_tests::*`.
32
33use std::io;
34use std::net::SocketAddr;
35use std::path::{Path, PathBuf};
36
37/// Filename of the discovery file, written under
38/// `resolve_data_dir("trusty-code")` — mirrors what `trusty-memory`'s
39/// `http_addr` convention exactly (same filename, same directory-resolution
40/// helper, same plain-text `host:port` content).
41pub const HTTP_ADDR_FILENAME: &str = "http_addr";
42
43/// Resolve `{resolve_data_dir("trusty-code")}/http_addr`, or `None` if the
44/// data directory cannot be resolved (matches
45/// retired `http_addr_path` did: the degrade-gracefully
46/// contract — a resolution failure here is never fatal, only a missing
47/// discovery source).
48pub fn http_addr_path() -> Option<PathBuf> {
49    trusty_common::resolve_data_dir("trusty-code")
50        .ok()
51        .map(|d| d.join(HTTP_ADDR_FILENAME))
52}
53
54/// Atomically write `addr` to `path` (tmp + rename).
55///
56/// Why: a client reading this file mid-write must never observe a partial
57/// value; writing to a `.addr.tmp` sibling and renaming over the target
58/// gives POSIX atomicity. Mirrors
59/// trusty-memory's retired `write_http_addr_file` byte-for-byte in
60/// behaviour — duplicated here (rather than adding a cross-product
61/// dependency on trusty-memory for one ~10-line helper) since both crates
62/// are independent binaries with no other shared coupling.
63/// What: creates the parent directory if missing; writes `addr` followed by
64/// a trailing newline; renames the tmp file over `path`.
65/// Test: `discovery_tests::write_then_read_round_trips_bound_addr`.
66pub(crate) fn write_http_addr_file(path: &Path, addr: &SocketAddr) -> io::Result<()> {
67    use std::io::Write;
68    if let Some(parent) = path.parent() {
69        std::fs::create_dir_all(parent)?;
70    }
71    let tmp = path.with_extension("addr.tmp");
72    {
73        let mut f = std::fs::File::create(&tmp)?;
74        writeln!(f, "{addr}")?;
75        f.sync_all()?;
76    }
77    std::fs::rename(&tmp, path)?;
78    Ok(())
79}
80
81/// Best-effort remove of the discovery file.
82///
83/// Why: called on graceful `tcode serve --http` shutdown so a stopped
84/// daemon doesn't leave a stale `http_addr` pointing at a dead port for the
85/// next `CodeEngine::discover` call — a reader would otherwise pass the
86/// "candidate found" step and only fail at the liveness ping, which is a
87/// worse error message than "no daemon found" for the common
88/// stop-then-later-reconnect case.
89/// What: `std::fs::remove_file`, ignoring any error (already-absent is the
90/// common case, e.g. `write_http_addr_file` itself failed earlier).
91/// Test: `discovery_tests::remove_is_best_effort_on_missing_file`.
92pub(crate) fn remove_http_addr_file(path: &Path) {
93    let _ = std::fs::remove_file(path);
94}
95
96/// Read and trim the discovery file's contents (just `host:port`), or
97/// `None` if it's absent/unreadable/empty.
98///
99/// Why: the client side of discovery — deliberately infallible (`Option`,
100/// not `Result`) since "no file" and "unreadable file" are both just "no
101/// candidate from this source" to the caller, not distinct error states
102/// worth surfacing.
103/// Test: `discovery_tests::write_then_read_round_trips_bound_addr`,
104/// `discovery_tests::read_missing_file_returns_none`.
105pub(crate) fn read_http_addr_file(path: &Path) -> Option<String> {
106    let raw = std::fs::read_to_string(path).ok()?;
107    let trimmed = raw.trim();
108    if trimmed.is_empty() {
109        None
110    } else {
111        Some(trimmed.to_string())
112    }
113}
114
115#[cfg(test)]
116mod discovery_tests {
117    use super::*;
118
119    /// The write/read round trip must recover exactly the address that was
120    /// written, with no surrounding whitespace.
121    #[test]
122    fn write_then_read_round_trips_bound_addr() {
123        let dir = tempfile::tempdir().expect("tempdir");
124        let path = dir.path().join(HTTP_ADDR_FILENAME);
125        let addr: SocketAddr = "127.0.0.1:7882".parse().expect("parse addr");
126        write_http_addr_file(&path, &addr).expect("write");
127        assert_eq!(
128            read_http_addr_file(&path).as_deref(),
129            Some("127.0.0.1:7882")
130        );
131    }
132
133    /// A missing file is "no candidate," not an error.
134    #[test]
135    fn read_missing_file_returns_none() {
136        let dir = tempfile::tempdir().expect("tempdir");
137        let path = dir.path().join(HTTP_ADDR_FILENAME);
138        assert_eq!(read_http_addr_file(&path), None);
139    }
140
141    /// An empty (or whitespace-only) file must also read back as "no
142    /// candidate" — a truncated write mid-crash should never hand the
143    /// client an empty daemon URL.
144    #[test]
145    fn read_blank_file_returns_none() {
146        let dir = tempfile::tempdir().expect("tempdir");
147        let path = dir.path().join(HTTP_ADDR_FILENAME);
148        std::fs::write(&path, "   \n").expect("write blank");
149        assert_eq!(read_http_addr_file(&path), None);
150    }
151
152    /// Removing an already-absent file must not panic or return an
153    /// observable error — this is the common case (daemon exits after a
154    /// write failure, or two shutdown paths race).
155    #[test]
156    fn remove_is_best_effort_on_missing_file() {
157        let dir = tempfile::tempdir().expect("tempdir");
158        let path = dir.path().join(HTTP_ADDR_FILENAME);
159        remove_http_addr_file(&path); // must not panic
160        assert!(!path.exists());
161    }
162
163    /// `remove_http_addr_file` must actually delete an existing file (not
164    /// just no-op on the missing case).
165    #[test]
166    fn remove_deletes_an_existing_file() {
167        let dir = tempfile::tempdir().expect("tempdir");
168        let path = dir.path().join(HTTP_ADDR_FILENAME);
169        let addr: SocketAddr = "127.0.0.1:7882".parse().expect("parse addr");
170        write_http_addr_file(&path, &addr).expect("write");
171        assert!(path.exists());
172        remove_http_addr_file(&path);
173        assert!(!path.exists());
174    }
175
176    /// `http_addr_path` must join the filename onto whatever base
177    /// `resolve_data_dir` returns — not asserting the exact OS-standard base
178    /// (platform-dependent), only that the join is correct when resolution
179    /// succeeds.
180    #[test]
181    fn http_addr_path_ends_with_filename() {
182        if let Some(p) = http_addr_path() {
183            assert_eq!(
184                p.file_name().and_then(|f| f.to_str()),
185                Some(HTTP_ADDR_FILENAME)
186            );
187        }
188    }
189}