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