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