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, and a static `"ok"` status.
14//! Test: `methods::tests::*`.
15
16use serde_json::{Value, json};
17
18use crate::jsonrpc::{ConnectionContext, Router, RpcError};
19
20/// Register every proof-of-life method onto `router`.
21///
22/// Why: keeps `crate::serve::build_router` a one-line call as more method
23/// groups (session/task/harness) register themselves the same way later.
24/// What: registers `"ping"` and `"health"`.
25/// Test: `methods_register_wires_ping_and_health`.
26pub fn register(router: &mut Router) {
27 router.register("ping", ping);
28 router.register("health", health);
29}
30
31/// `ping` — returns `{"pong": true}` regardless of `params`.
32///
33/// Why: the cheapest possible round-trip proof that a transport and the
34/// router are wired correctly.
35/// What: ignores `params` and the connection context, never fails.
36/// Test: `ping_returns_pong_true`.
37async fn ping(_params: Value, _ctx: ConnectionContext) -> Result<Value, RpcError> {
38 Ok(json!({"pong": true}))
39}
40
41/// `health` — returns server identity, crate version, and status.
42///
43/// Why: a slightly richer proof-of-life than `ping` that a caller can use to
44/// confirm which build of `tcode` it is talking to.
45/// What: ignores `params` and the connection context, never fails; the
46/// payload is [`health_payload`].
47/// Test: `health_returns_server_identity`.
48async fn health(_params: Value, _ctx: ConnectionContext) -> Result<Value, RpcError> {
49 Ok(health_payload())
50}
51
52/// The shared `health` payload: `{"server","version","status"}`.
53///
54/// Why: pulled out of the `health` JSON-RPC handler so
55/// `crate::serve::http::health_handler` (`GET /health`) can return the
56/// identical shape without duplicating the `json!` literal — one source of
57/// truth for what "healthy" means over either transport.
58/// What: `server = "tcode"`, `version = crate::VERSION`
59/// (`CARGO_PKG_VERSION`), `status = "ok"`. Never fails — there is no
60/// fallible state to check yet; a future ticket that adds real readiness
61/// checks (e.g. project root validity) will extend this function.
62/// Test: `health_payload_has_expected_shape`.
63pub(crate) fn health_payload() -> Value {
64 json!({
65 "server": "tcode",
66 "version": crate::VERSION,
67 "status": "ok",
68 })
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74 use tokio::sync::mpsc;
75
76 fn test_ctx() -> ConnectionContext {
77 let (tx, _rx) = mpsc::unbounded_channel();
78 ConnectionContext::new(tx)
79 }
80
81 /// `ping` must return `{"pong": true}` and never fail.
82 #[tokio::test]
83 async fn ping_returns_pong_true() {
84 let result = ping(Value::Null, test_ctx())
85 .await
86 .expect("ping must not fail");
87 assert_eq!(result, json!({"pong": true}));
88 }
89
90 /// `health` must report the server name, version, and "ok" status.
91 #[tokio::test]
92 async fn health_returns_server_identity() {
93 let result = health(Value::Null, test_ctx())
94 .await
95 .expect("health must not fail");
96 assert_eq!(result["server"], "tcode");
97 assert_eq!(result["status"], "ok");
98 assert_eq!(result["version"], crate::VERSION);
99 }
100
101 /// `health_payload` (shared with the HTTP `GET /health` route) must
102 /// carry the same three fields.
103 #[test]
104 fn health_payload_has_expected_shape() {
105 let v = health_payload();
106 assert_eq!(v["server"], "tcode");
107 assert_eq!(v["status"], "ok");
108 assert_eq!(v["version"], crate::VERSION);
109 }
110
111 /// `register` must wire both methods so the router recognises them
112 /// (rather than returning method-not-found).
113 #[tokio::test]
114 async fn methods_register_wires_ping_and_health() {
115 use trusty_common::mcp::Request;
116
117 let mut router = Router::new();
118 register(&mut router);
119
120 for method in ["ping", "health"] {
121 let req = Request {
122 jsonrpc: Some("2.0".to_string()),
123 id: Some(json!(1)),
124 method: method.to_string(),
125 params: None,
126 };
127 let resp = router.dispatch(req, &test_ctx()).await;
128 assert!(
129 resp.error.is_none(),
130 "{method} should be registered, got {:?}",
131 resp.error
132 );
133 }
134 }
135}