use std::sync::Arc;
use axum::Router as AxumRouter;
use axum::extract::{Path, State};
use axum::routing::get;
use serde_json::json;
use crate::jsonrpc::Router;
use super::{RestResult, respond};
#[derive(Clone)]
struct AgentsState {
router: Arc<Router>,
}
pub fn routes(router: Arc<Router>) -> AxumRouter {
AxumRouter::new()
.route("/sessions/{id}/agents", get(get_agents))
.with_state(AgentsState { router })
}
async fn get_agents(State(state): State<AgentsState>, Path(id): Path<String>) -> RestResult {
respond(
&state.router,
"session.get_agents",
json!({"session_id": id}),
)
.await
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::{Body, to_bytes};
use axum::http::{Request, StatusCode};
use serde_json::Value;
use tower::util::ServiceExt;
async fn app_and_registry() -> (AxumRouter, Arc<crate::session::SessionRegistry>) {
let sessions = Arc::new(crate::session::SessionRegistry::new());
let mut router = Router::new();
crate::session::protocol::register(
&mut router,
sessions.clone(),
crate::workstreams::test_shared_store().await,
);
let app = routes(Arc::new(router));
(app, sessions)
}
async fn body_json(response: axum::response::Response) -> Value {
let bytes = to_bytes(response.into_body(), 1024 * 1024).await.unwrap();
serde_json::from_slice(&bytes).unwrap()
}
async fn get(app: &AxumRouter, uri: &str) -> axum::response::Response {
app.clone()
.oneshot(
Request::builder()
.method("GET")
.uri(uri)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap()
}
#[tokio::test]
async fn get_agents_found_returns_200_with_empty_roster() {
let (app, sessions) = app_and_registry().await;
let session = sessions.create("t".to_string(), None, crate::binding::ProjectBinding::None);
let resp = get(&app, &format!("/sessions/{}/agents", session.id)).await;
assert_eq!(resp.status(), StatusCode::OK);
let v = body_json(resp).await;
assert_eq!(v["agents"].as_array().unwrap().len(), 0);
}
#[tokio::test]
async fn get_agents_missing_returns_404_session_not_found() {
let (app, _sessions) = app_and_registry().await;
let resp = get(&app, "/sessions/does-not-exist/agents").await;
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let v = body_json(resp).await;
assert_eq!(v["error"]["code"], -32007);
}
}