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/// Test: `health_payload_has_expected_shape`,
113/// `health_payload_reports_a_bound_project_root`,
114/// `health_payload_reports_incremental_index_drops`,
115/// `health_payload_reports_incremental_index_truncations`.
116/// The whole of what an UNAUTHENTICATED `GET /health` caller may learn
117/// (#6472).
118///
119/// Why: [`health_payload`] answers `pid`, the bound project's absolute root
120/// path, the daemon's version, and its index counters. Those are process and
121/// filesystem facts about the operator's machine, and until #6472 any local
122/// process — including a page in the operator's browser — could read them
123/// without presenting anything. A liveness poller needs none of it: it needs
124/// to know the daemon answered. This payload is deliberately not derived from
125/// [`health_payload`] by filtering, because a filter grows a hole every time a
126/// field is added upstream; a field added to `health_payload` cannot leak here.
127/// What: `{"status": "ok"}`. Nothing conditional, nothing derived.
128/// Test: `liveness_payload_discloses_only_status`, and end-to-end in
129/// `http_tests::http_health_anonymous_discloses_only_liveness`.
130pub(crate) fn liveness_payload() -> Value {
131    json!({ "status": "ok" })
132}
133
134pub(crate) fn health_payload(binding: &ProjectBinding) -> Value {
135    // #2798: publish the background-index loss counters where a health check
136    // already looks, so a saturated pool is not invisible.
137    let drops = trusty_common::search_index::index_drop_stats();
138    json!({
139        "server": "tcode",
140        "version": crate::VERSION,
141        "status": "ok",
142        "pid": std::process::id(),
143        "binding": binding.to_json(),
144        "incremental_index": {
145            "dropped_batches": drops.dropped_batches,
146            "seconds_since_last_drop": drops.seconds_since_last_drop,
147            "truncated_batches": drops.truncated_batches,
148            "seconds_since_last_truncation": drops.seconds_since_last_truncation,
149        },
150    })
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156    use tokio::sync::mpsc;
157
158    fn test_ctx() -> ConnectionContext {
159        let (tx, _rx) = mpsc::unbounded_channel();
160        ConnectionContext::new(tx)
161    }
162
163    /// `ping` must return `{"pong": true}` and never fail.
164    #[tokio::test]
165    async fn ping_returns_pong_true() {
166        let result = ping(Value::Null, test_ctx())
167            .await
168            .expect("ping must not fail");
169        assert_eq!(result, json!({"pong": true}));
170    }
171
172    /// `health` must report the server name, version, and "ok" status.
173    #[tokio::test]
174    async fn health_returns_server_identity() {
175        let result = health(&ProjectBinding::None, Value::Null, test_ctx())
176            .await
177            .expect("health must not fail");
178        assert_eq!(result["server"], "tcode");
179        assert_eq!(result["status"], "ok");
180        assert_eq!(result["version"], crate::VERSION);
181    }
182
183    /// The anonymous payload must carry `status` and NOTHING else — the
184    /// #6472 regression. Asserting the key SET (not just the absence of
185    /// `pid`/`binding`) is what makes a future field addition fail here
186    /// rather than leak.
187    #[test]
188    fn liveness_payload_discloses_only_status() {
189        let payload = liveness_payload();
190        let obj = payload.as_object().expect("liveness payload is an object");
191        assert_eq!(obj["status"], "ok");
192        assert_eq!(
193            obj.keys().collect::<Vec<_>>(),
194            vec!["status"],
195            "an anonymous /health caller must learn only that the daemon is up"
196        );
197    }
198
199    /// `health_payload` (shared with the HTTP `GET /health` route) must carry
200    /// the original three fields UNCHANGED plus #4512's additive `pid` and
201    /// `binding` — pinned so the backward-compatible promise in this
202    /// function's docs can't be broken by a later edit.
203    #[test]
204    fn health_payload_has_expected_shape() {
205        let v = health_payload(&ProjectBinding::None);
206        assert_eq!(v["server"], "tcode");
207        assert_eq!(v["status"], "ok");
208        assert_eq!(v["version"], crate::VERSION);
209        assert_eq!(v["pid"], std::process::id());
210        assert_eq!(v["binding"]["state"], crate::binding::STATE_PROJECTLESS);
211        assert!(v["binding"]["root"].is_null());
212    }
213
214    /// The background-index drop counters must be on the wire, and a process
215    /// that has dropped nothing must say so distinguishably (#2798).
216    ///
217    /// Why: dropping a batch when the pool saturates is only an acceptable
218    /// trade because the loss is visible somewhere a health check reads. This
219    /// pins that it IS on the wire — the field existing is the whole fix, and a
220    /// later edit that quietly removes it would restore the blind spot.
221    /// What: nothing in this crate's tests submits to the shared index pool, so
222    /// `dropped_batches` is provably `0` here — asserted exactly, not merely as
223    /// "numeric". The age is then asserted STRICTLY `null`: a `|| is_u64()`
224    /// disjunction would pass just as happily if a later edit reported a
225    /// misleading `0`, which is the regression this test exists to catch.
226    /// Test: this test.
227    #[test]
228    fn health_payload_reports_incremental_index_drops() {
229        let v = health_payload(&ProjectBinding::None);
230        let drops = &v["incremental_index"];
231        assert_eq!(
232            drops["dropped_batches"], 0,
233            "no test in this crate submits to the pool, so nothing can have been \
234             dropped, got {drops}"
235        );
236        assert!(
237            drops["seconds_since_last_drop"].is_null(),
238            "with no drops the age must be null, never a misleading 0, got {drops}"
239        );
240    }
241
242    /// The budget-truncation counters must be on the wire too, and must be
243    /// their own fields rather than folded into the drop counters (#2798).
244    ///
245    /// Why: a batch the pool ACCEPTS and then cuts short at the 30s budget is a
246    /// different fault from one the pool refuses — different cause, different
247    /// fix — and an operator who cannot tell them apart cannot act on either.
248    /// Summing them, or publishing only the drop pair, would leave an episode
249    /// of repeated truncations reading as a perfectly healthy `0`.
250    /// What: asserts both truncation fields are present under
251    /// `incremental_index` and are NOT the same JSON values as the drop pair's
252    /// keys; as with drops, a fresh test process has truncated nothing, so the
253    /// count is exactly `0` and the age is strictly `null`.
254    /// Test: this test.
255    #[test]
256    fn health_payload_reports_incremental_index_truncations() {
257        let v = health_payload(&ProjectBinding::None);
258        let drops = &v["incremental_index"];
259        assert_eq!(
260            drops["truncated_batches"], 0,
261            "no test in this crate runs a batch, so nothing can have been \
262             truncated, got {drops}"
263        );
264        assert!(
265            drops["seconds_since_last_truncation"].is_null(),
266            "with no truncations the age must be null, never a misleading 0, got {drops}"
267        );
268        let keys: Vec<&String> = drops
269            .as_object()
270            .expect("incremental_index must be an object")
271            .keys()
272            .collect();
273        assert!(
274            keys.contains(&&"dropped_batches".to_string())
275                && keys.contains(&&"truncated_batches".to_string()),
276            "the two losses must be separate fields, never one summed number, got {keys:?}"
277        );
278    }
279
280    /// A BOUND daemon must publish its project root, since that is the field
281    /// `cli::daemon_autospawn` compares against the client's own project
282    /// before attaching (#4512).
283    #[test]
284    fn health_payload_reports_a_bound_project_root() {
285        let dir = tempfile::tempdir().expect("tempdir");
286        let binding = ProjectBinding::resolve(Some(dir.path().to_path_buf())).expect("must bind");
287        let v = health_payload(&binding);
288        assert_eq!(
289            v["binding"]["root"],
290            json!(binding.label().expect("a bound binding has a root"))
291        );
292    }
293
294    /// The `health` METHOD (not just the payload helper) must carry the
295    /// daemon's binding, so the STDIO transport reports it too.
296    #[tokio::test]
297    async fn health_reports_the_daemons_project_binding() {
298        let dir = tempfile::tempdir().expect("tempdir");
299        let binding = ProjectBinding::resolve(Some(dir.path().to_path_buf())).expect("must bind");
300        let result = health(&binding, Value::Null, test_ctx())
301            .await
302            .expect("health must not fail");
303        assert_eq!(result["binding"], binding.to_json());
304    }
305
306    /// `register` must wire both methods so the router recognises them
307    /// (rather than returning method-not-found).
308    #[tokio::test]
309    async fn methods_register_wires_ping_and_health() {
310        use trusty_mcp::Request;
311
312        let mut router = Router::new();
313        register(&mut router, ProjectBinding::None);
314
315        for method in ["ping", "health"] {
316            let req = Request {
317                jsonrpc: Some("2.0".to_string()),
318                id: Some(json!(1)),
319                method: method.to_string(),
320                params: None,
321            };
322            let resp = router.dispatch(req, &test_ctx()).await;
323            assert!(
324                resp.error.is_none(),
325                "{method} should be registered, got {:?}",
326                resp.error
327            );
328        }
329    }
330}