Skip to main content

trusty_code/serve/
methods.rs

1//! Proof-of-life JSON-RPC methods for `tcode serve` (#2053).
2//!
3//! Why: the transport + router need at least one real method to prove the
4//! whole path works end-to-end without pulling in `session.*`/`task.*`/
5//! `harness.describe` scope (those land in #2054/#2056/#2066). `ping` and
6//! `health` are the minimal, side-effect-free pair for that job, shared
7//! verbatim across both transports: the STDIO `health` JSON-RPC method and
8//! the HTTP `GET /health` route (`crate::serve::http::health_handler`) both
9//! call [`health_payload`] so the two transports can never drift into
10//! different shapes.
11//! What: `register` wires both methods into a [`Router`]; `ping` returns
12//! `{"pong": true}`; `health` returns [`health_payload`]'s server name,
13//! crate version, static `"ok"` status, pid, and the daemon's project
14//! binding.
15//! Test: `methods::tests::*`.
16
17use std::sync::Arc;
18
19use serde_json::{Value, json};
20
21use crate::binding::ProjectBinding;
22use crate::jsonrpc::{ConnectionContext, Router, RpcError};
23
24/// Register every proof-of-life method onto `router`.
25///
26/// Why: keeps `crate::serve::build_router` a one-line call as more method
27/// groups (session/task/harness) register themselves the same way later.
28/// `binding` is taken here — rather than `health` staying a bare `fn` — so
29/// the daemon can REPORT which project it serves (#4512): a daemon binds
30/// exactly one `ProjectBinding` for its whole life, and a client that
31/// auto-attaches to a daemon it did not start has no other way to tell
32/// whether it is about to operate against the wrong project.
33/// What: registers `"ping"` and `"health"`; `binding` is shared into the
34/// `health` closure behind an `Arc` so answering a probe never clones a
35/// `PathBuf`.
36/// Test: `methods_register_wires_ping_and_health`,
37/// `health_reports_the_daemons_project_binding`.
38pub fn register(router: &mut Router, binding: ProjectBinding) {
39    router.register("ping", ping);
40    let binding = Arc::new(binding);
41    router.register("health", move |params: Value, ctx: ConnectionContext| {
42        let binding = binding.clone();
43        async move { health(&binding, params, ctx).await }
44    });
45}
46
47/// `ping` — returns `{"pong": true}` regardless of `params`.
48///
49/// Why: the cheapest possible round-trip proof that a transport and the
50/// router are wired correctly.
51/// What: ignores `params` and the connection context, never fails.
52/// Test: `ping_returns_pong_true`.
53async fn ping(_params: Value, _ctx: ConnectionContext) -> Result<Value, RpcError> {
54    Ok(json!({"pong": true}))
55}
56
57/// `health` — returns server identity, crate version, status, and binding.
58///
59/// Why: a slightly richer proof-of-life than `ping` that a caller can use to
60/// confirm which build of `tcode` — and, since #4512, which PROJECT — it is
61/// talking to.
62/// What: ignores `params` and the connection context, never fails; the
63/// payload is [`health_payload`].
64/// Test: `health_returns_server_identity`,
65/// `health_reports_the_daemons_project_binding`.
66async fn health(
67    binding: &ProjectBinding,
68    _params: Value,
69    _ctx: ConnectionContext,
70) -> Result<Value, RpcError> {
71    Ok(health_payload(binding))
72}
73
74/// The shared `health` payload:
75/// `{"server","version","status","pid","binding"}`.
76///
77/// Why: pulled out of the `health` JSON-RPC handler so
78/// `crate::serve::http::health_handler` (`GET /health`) can return the
79/// identical shape without duplicating the `json!` literal — one source of
80/// truth for what "healthy" means over either transport.
81///
82/// `pid` and `binding` are ADDITIVE (#4512) — every field that was here
83/// before is unchanged, so an older client that only reads
84/// `server`/`version`/`status` keeps working. They exist because a daemon
85/// binds exactly one `ProjectBinding` at `build_router` time and holds it for
86/// its whole life, while `tcode tui` now AUTO-ATTACHES to whatever daemon
87/// discovery finds. Without the binding on the wire, a TUI launched in
88/// project B silently drives project A's daemon; `pid` is what lets an
89/// operator (or a test) identify and signal the exact process it found.
90/// What: `server = "tcode"`, `version = crate::VERSION`
91/// (`CARGO_PKG_VERSION`), `status = "ok"`, `pid = std::process::id()`,
92/// `binding = ProjectBinding::to_json()` (the SAME `{state, root}` wire shape
93/// `Session` already serialises, not a second spelling). Never fails — there
94/// is no fallible state to check.
95///
96/// `incremental_index` is additive too (#2798). The write/edit tool executors
97/// hand every successful write to a BOUNDED background pool, which loses work
98/// two ways when a degraded trusty-search daemon backs it up. Both used to
99/// exist only as a `warn!` line, so a sustained episode — files silently not
100/// indexed for as long as it lasts — looked identical to a healthy daemon here.
101/// This is the same process that owns the counters, and the TUI already polls
102/// this payload, so it is where the loss becomes visible.
103///
104/// Each loss is a count plus an age, and the age (`null` until the first one)
105/// is what separates "happened once an hour ago" from "happening right now".
106/// The two losses stay separate numbers because they need different fixes:
107/// `dropped_batches` means the pool refused the batch outright and none of it
108/// ran, while `truncated_batches` means the pool accepted and started it and
109/// the 30s per-batch budget then cut it short partway, abandoning the files it
110/// had not reached. Reporting only drops would read `0` throughout an episode
111/// in which every batch is accepted and then truncated.
112/// `build` is additive too (#8164) — the short git SHA `build.rs` embeds,
113/// which is what `tcode tui`'s startup splash compares against its own to
114/// warn that the daemon it attached to is a different build.
115/// Test: `health_payload_has_expected_shape`,
116/// `health_payload_reports_a_bound_project_root`,
117/// `health_payload_reports_the_daemon_build_sha`,
118/// `health_payload_reports_incremental_index_drops`,
119/// `health_payload_reports_incremental_index_truncations`.
120/// The whole of what an UNAUTHENTICATED `GET /health` caller may learn
121/// (#6472).
122///
123/// Why: [`health_payload`] answers `pid`, the bound project's absolute root
124/// path, the daemon's version, and its index counters. Those are process and
125/// filesystem facts about the operator's machine, and until #6472 any local
126/// process — including a page in the operator's browser — could read them
127/// without presenting anything. A liveness poller needs none of it: it needs
128/// to know the daemon answered. This payload is deliberately not derived from
129/// [`health_payload`] by filtering, because a filter grows a hole every time a
130/// field is added upstream; a field added to `health_payload` cannot leak here.
131/// What: `{"status": "ok"}`. Nothing conditional, nothing derived.
132/// Test: `liveness_payload_discloses_only_status`, and end-to-end in
133/// `http_tests::http_health_anonymous_discloses_only_liveness`.
134pub(crate) fn liveness_payload() -> Value {
135    json!({ "status": "ok" })
136}
137
138pub(crate) fn health_payload(binding: &ProjectBinding) -> Value {
139    // #2798: publish the background-index loss counters where a health check
140    // already looks, so a saturated pool is not invisible.
141    let drops = trusty_common::search_index::index_drop_stats();
142    json!({
143        "server": "tcode",
144        "version": crate::VERSION,
145        // #8164: the SHA, not just the semver. A daemon started before a
146        // reinstall reports the same `version` as the fresh binary that
147        // replaced it, so a client had no way to see it was talking to a
148        // stale process — that gap reproduced #4602 after its fix shipped.
149        // Same constant `tcode --version` prints.
150        "build": crate::build_info::GIT_HASH,
151        "status": "ok",
152        "pid": std::process::id(),
153        "binding": binding.to_json(),
154        "incremental_index": {
155            "dropped_batches": drops.dropped_batches,
156            "seconds_since_last_drop": drops.seconds_since_last_drop,
157            "truncated_batches": drops.truncated_batches,
158            "seconds_since_last_truncation": drops.seconds_since_last_truncation,
159        },
160    })
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166    use tokio::sync::mpsc;
167
168    fn test_ctx() -> ConnectionContext {
169        let (tx, _rx) = mpsc::unbounded_channel();
170        ConnectionContext::new(tx)
171    }
172
173    /// `ping` must return `{"pong": true}` and never fail.
174    #[tokio::test]
175    async fn ping_returns_pong_true() {
176        let result = ping(Value::Null, test_ctx())
177            .await
178            .expect("ping must not fail");
179        assert_eq!(result, json!({"pong": true}));
180    }
181
182    /// `health` must report the server name, version, and "ok" status.
183    #[tokio::test]
184    async fn health_returns_server_identity() {
185        let result = health(&ProjectBinding::None, Value::Null, test_ctx())
186            .await
187            .expect("health must not fail");
188        assert_eq!(result["server"], "tcode");
189        assert_eq!(result["status"], "ok");
190        assert_eq!(result["version"], crate::VERSION);
191    }
192
193    /// The anonymous payload must carry `status` and NOTHING else — the
194    /// #6472 regression. Asserting the key SET (not just the absence of
195    /// `pid`/`binding`) is what makes a future field addition fail here
196    /// rather than leak.
197    #[test]
198    fn liveness_payload_discloses_only_status() {
199        let payload = liveness_payload();
200        let obj = payload.as_object().expect("liveness payload is an object");
201        assert_eq!(obj["status"], "ok");
202        assert_eq!(
203            obj.keys().collect::<Vec<_>>(),
204            vec!["status"],
205            "an anonymous /health caller must learn only that the daemon is up"
206        );
207    }
208
209    /// `health_payload` (shared with the HTTP `GET /health` route) must carry
210    /// the original three fields UNCHANGED plus #4512's additive `pid` and
211    /// `binding` — pinned so the backward-compatible promise in this
212    /// function's docs can't be broken by a later edit.
213    #[test]
214    fn health_payload_has_expected_shape() {
215        let v = health_payload(&ProjectBinding::None);
216        assert_eq!(v["server"], "tcode");
217        assert_eq!(v["status"], "ok");
218        assert_eq!(v["version"], crate::VERSION);
219        assert_eq!(v["pid"], std::process::id());
220        assert_eq!(v["binding"]["state"], crate::binding::STATE_PROJECTLESS);
221        assert!(v["binding"]["root"].is_null());
222    }
223
224    /// The daemon's own build SHA must be on the wire (#8164), and it must be
225    /// the SAME constant `tcode --version` prints.
226    ///
227    /// Why: a client can already read `version`, but two builds of the same
228    /// semver are indistinguishable by it — which is exactly the stale-daemon
229    /// case the splash's mismatch warning exists to catch. Asserting against
230    /// `build_info::GIT_HASH` (rather than merely "a non-empty string") is
231    /// what pins the two surfaces to one source; a second, independently
232    /// derived SHA here would satisfy a looser assertion while reporting a
233    /// different build.
234    /// What: the field is present and equals `build_info::GIT_HASH`, which is
235    /// the literal `"unknown"` outside a git checkout — a real, reportable
236    /// value, so no case is excluded.
237    /// Test: this test.
238    #[test]
239    fn health_payload_reports_the_daemon_build_sha() {
240        let v = health_payload(&ProjectBinding::None);
241        assert_eq!(v["build"], crate::build_info::GIT_HASH);
242        assert!(
243            v["build"].as_str().is_some_and(|s| !s.is_empty()),
244            "the build field must always carry a value, got {v}"
245        );
246    }
247
248    /// The background-index drop counters must be on the wire, and a process
249    /// that has dropped nothing must say so distinguishably (#2798).
250    ///
251    /// Why: dropping a batch when the pool saturates is only an acceptable
252    /// trade because the loss is visible somewhere a health check reads. This
253    /// pins that it IS on the wire — the field existing is the whole fix, and a
254    /// later edit that quietly removes it would restore the blind spot.
255    /// What: nothing in this crate's tests submits to the shared index pool, so
256    /// `dropped_batches` is provably `0` here — asserted exactly, not merely as
257    /// "numeric". The age is then asserted STRICTLY `null`: a `|| is_u64()`
258    /// disjunction would pass just as happily if a later edit reported a
259    /// misleading `0`, which is the regression this test exists to catch.
260    /// Test: this test.
261    #[test]
262    fn health_payload_reports_incremental_index_drops() {
263        let v = health_payload(&ProjectBinding::None);
264        let drops = &v["incremental_index"];
265        assert_eq!(
266            drops["dropped_batches"], 0,
267            "no test in this crate submits to the pool, so nothing can have been \
268             dropped, got {drops}"
269        );
270        assert!(
271            drops["seconds_since_last_drop"].is_null(),
272            "with no drops the age must be null, never a misleading 0, got {drops}"
273        );
274    }
275
276    /// The budget-truncation counters must be on the wire too, and must be
277    /// their own fields rather than folded into the drop counters (#2798).
278    ///
279    /// Why: a batch the pool ACCEPTS and then cuts short at the 30s budget is a
280    /// different fault from one the pool refuses — different cause, different
281    /// fix — and an operator who cannot tell them apart cannot act on either.
282    /// Summing them, or publishing only the drop pair, would leave an episode
283    /// of repeated truncations reading as a perfectly healthy `0`.
284    /// What: asserts both truncation fields are present under
285    /// `incremental_index` and are NOT the same JSON values as the drop pair's
286    /// keys; as with drops, a fresh test process has truncated nothing, so the
287    /// count is exactly `0` and the age is strictly `null`.
288    /// Test: this test.
289    #[test]
290    fn health_payload_reports_incremental_index_truncations() {
291        let v = health_payload(&ProjectBinding::None);
292        let drops = &v["incremental_index"];
293        assert_eq!(
294            drops["truncated_batches"], 0,
295            "no test in this crate runs a batch, so nothing can have been \
296             truncated, got {drops}"
297        );
298        assert!(
299            drops["seconds_since_last_truncation"].is_null(),
300            "with no truncations the age must be null, never a misleading 0, got {drops}"
301        );
302        let keys: Vec<&String> = drops
303            .as_object()
304            .expect("incremental_index must be an object")
305            .keys()
306            .collect();
307        assert!(
308            keys.contains(&&"dropped_batches".to_string())
309                && keys.contains(&&"truncated_batches".to_string()),
310            "the two losses must be separate fields, never one summed number, got {keys:?}"
311        );
312    }
313
314    /// A BOUND daemon must publish its project root, since that is the field
315    /// `cli::daemon_autospawn` compares against the client's own project
316    /// before attaching (#4512).
317    #[test]
318    fn health_payload_reports_a_bound_project_root() {
319        let dir = tempfile::tempdir().expect("tempdir");
320        let binding = ProjectBinding::resolve(Some(dir.path().to_path_buf())).expect("must bind");
321        let v = health_payload(&binding);
322        assert_eq!(
323            v["binding"]["root"],
324            json!(binding.label().expect("a bound binding has a root"))
325        );
326    }
327
328    /// The `health` METHOD (not just the payload helper) must carry the
329    /// daemon's binding, so the STDIO transport reports it too.
330    #[tokio::test]
331    async fn health_reports_the_daemons_project_binding() {
332        let dir = tempfile::tempdir().expect("tempdir");
333        let binding = ProjectBinding::resolve(Some(dir.path().to_path_buf())).expect("must bind");
334        let result = health(&binding, Value::Null, test_ctx())
335            .await
336            .expect("health must not fail");
337        assert_eq!(result["binding"], binding.to_json());
338    }
339
340    /// `register` must wire both methods so the router recognises them
341    /// (rather than returning method-not-found).
342    #[tokio::test]
343    async fn methods_register_wires_ping_and_health() {
344        use trusty_mcp::Request;
345
346        let mut router = Router::new();
347        register(&mut router, ProjectBinding::None);
348
349        for method in ["ping", "health"] {
350            let req = Request {
351                jsonrpc: Some("2.0".to_string()),
352                id: Some(json!(1)),
353                method: method.to_string(),
354                params: None,
355            };
356            let resp = router.dispatch(req, &test_ctx()).await;
357            assert!(
358                resp.error.is_none(),
359                "{method} should be registered, got {:?}",
360                resp.error
361            );
362        }
363    }
364}