use std::sync::Arc;
use serde_json::{Value, json};
use crate::binding::ProjectBinding;
use crate::jsonrpc::{ConnectionContext, Router, RpcError};
pub fn register(router: &mut Router, binding: ProjectBinding) {
router.register("ping", ping);
let binding = Arc::new(binding);
router.register("health", move |params: Value, ctx: ConnectionContext| {
let binding = binding.clone();
async move { health(&binding, params, ctx).await }
});
}
async fn ping(_params: Value, _ctx: ConnectionContext) -> Result<Value, RpcError> {
Ok(json!({"pong": true}))
}
async fn health(
binding: &ProjectBinding,
_params: Value,
_ctx: ConnectionContext,
) -> Result<Value, RpcError> {
Ok(health_payload(binding))
}
pub(crate) fn health_payload(binding: &ProjectBinding) -> Value {
let drops = trusty_common::search_index::index_drop_stats();
json!({
"server": "tcode",
"version": crate::VERSION,
"build": crate::build_info::GIT_HASH,
"status": "ok",
"pid": std::process::id(),
"binding": binding.to_json(),
"incremental_index": {
"dropped_batches": drops.dropped_batches,
"seconds_since_last_drop": drops.seconds_since_last_drop,
"truncated_batches": drops.truncated_batches,
"seconds_since_last_truncation": drops.seconds_since_last_truncation,
},
})
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::sync::mpsc;
fn test_ctx() -> ConnectionContext {
let (tx, _rx) = mpsc::unbounded_channel();
ConnectionContext::new(tx)
}
#[tokio::test]
async fn ping_returns_pong_true() {
let result = ping(Value::Null, test_ctx())
.await
.expect("ping must not fail");
assert_eq!(result, json!({"pong": true}));
}
#[tokio::test]
async fn health_returns_server_identity() {
let result = health(&ProjectBinding::None, Value::Null, test_ctx())
.await
.expect("health must not fail");
assert_eq!(result["server"], "tcode");
assert_eq!(result["status"], "ok");
assert_eq!(result["version"], crate::VERSION);
}
#[test]
fn health_payload_has_expected_shape() {
let v = health_payload(&ProjectBinding::None);
assert_eq!(v["server"], "tcode");
assert_eq!(v["status"], "ok");
assert_eq!(v["version"], crate::VERSION);
assert_eq!(v["pid"], std::process::id());
assert_eq!(v["binding"]["state"], crate::binding::STATE_PROJECTLESS);
assert!(v["binding"]["root"].is_null());
}
#[test]
fn health_payload_reports_the_daemon_build_sha() {
let v = health_payload(&ProjectBinding::None);
assert_eq!(v["build"], crate::build_info::GIT_HASH);
assert!(
v["build"].as_str().is_some_and(|s| !s.is_empty()),
"the build field must always carry a value, got {v}"
);
}
#[test]
fn health_payload_reports_incremental_index_drops() {
let v = health_payload(&ProjectBinding::None);
let drops = &v["incremental_index"];
assert_eq!(
drops["dropped_batches"], 0,
"no test in this crate submits to the pool, so nothing can have been \
dropped, got {drops}"
);
assert!(
drops["seconds_since_last_drop"].is_null(),
"with no drops the age must be null, never a misleading 0, got {drops}"
);
}
#[test]
fn health_payload_reports_incremental_index_truncations() {
let v = health_payload(&ProjectBinding::None);
let drops = &v["incremental_index"];
assert_eq!(
drops["truncated_batches"], 0,
"no test in this crate runs a batch, so nothing can have been \
truncated, got {drops}"
);
assert!(
drops["seconds_since_last_truncation"].is_null(),
"with no truncations the age must be null, never a misleading 0, got {drops}"
);
let keys: Vec<&String> = drops
.as_object()
.expect("incremental_index must be an object")
.keys()
.collect();
assert!(
keys.contains(&&"dropped_batches".to_string())
&& keys.contains(&&"truncated_batches".to_string()),
"the two losses must be separate fields, never one summed number, got {keys:?}"
);
}
#[test]
fn health_payload_reports_a_bound_project_root() {
let dir = tempfile::tempdir().expect("tempdir");
let binding = ProjectBinding::resolve(Some(dir.path().to_path_buf())).expect("must bind");
let v = health_payload(&binding);
assert_eq!(
v["binding"]["root"],
json!(binding.label().expect("a bound binding has a root"))
);
}
#[tokio::test]
async fn health_reports_the_daemons_project_binding() {
let dir = tempfile::tempdir().expect("tempdir");
let binding = ProjectBinding::resolve(Some(dir.path().to_path_buf())).expect("must bind");
let result = health(&binding, Value::Null, test_ctx())
.await
.expect("health must not fail");
assert_eq!(result["binding"], binding.to_json());
}
#[tokio::test]
async fn methods_register_wires_ping_and_health() {
use trusty_mcp::Request;
let mut router = Router::new();
register(&mut router, ProjectBinding::None);
for method in ["ping", "health"] {
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(json!(1)),
method: method.to_string(),
params: None,
};
let resp = router.dispatch(req, &test_ctx()).await;
assert!(
resp.error.is_none(),
"{method} should be registered, got {:?}",
resp.error
);
}
}
}