Skip to main content

waratah_compute/
admin.rs

1//! gRPC `Compute` service: Health + Describe (identity/config only).
2
3use std::sync::Arc;
4
5use tonic::{Request, Response, Status};
6use waratah_proto::pb;
7use waratah_proto::{Compute, GRPC_MAX_MESSAGE_SIZE};
8use waratah_router::{ClusterConfig, RoutingSnapshot};
9use waratah_storage::MAIN_REPOSITORY_ID;
10
11use crate::cluster::{ClusterKnobs, self_describe_response};
12use crate::describe::DescribeMode;
13
14/// Identity advertised on the compute gRPC Describe RPC.
15#[derive(Debug, Clone)]
16pub struct ComputeAdminService {
17    config: Arc<ClusterConfig>,
18    knobs: ClusterKnobs,
19    routing: RoutingSnapshot,
20}
21
22impl ComputeAdminService {
23    /// Build from this process's cluster config and SPARQL knobs.
24    pub fn new(
25        config: Arc<ClusterConfig>,
26        describe_mode: DescribeMode,
27        default_union: bool,
28    ) -> Result<Self, waratah_router::RouterError> {
29        let router = config.router(16)?;
30        let routing = config.routing_snapshot(&router)?;
31        Ok(Self {
32            config,
33            knobs: ClusterKnobs::main_only(describe_mode, default_union),
34            routing,
35        })
36    }
37
38    /// Override repositories (defaults to `main`).
39    pub fn with_repositories(mut self, repositories: Vec<crate::cluster::RepoInfo>) -> Self {
40        self.knobs.repositories = repositories;
41        self
42    }
43
44    /// In-process S/P/O + registry (`waratah standalone`).
45    pub fn with_standalone(mut self, standalone: bool) -> Self {
46        self.knobs.standalone = standalone;
47        self
48    }
49}
50
51#[tonic::async_trait]
52impl Compute for ComputeAdminService {
53    async fn health(
54        &self,
55        _request: Request<pb::HealthRequest>,
56    ) -> Result<Response<pb::HealthResponse>, Status> {
57        Ok(Response::new(pb::HealthResponse {
58            serving: true,
59            detail: String::new(),
60            // Compute has no cache-warm walk and no block cache of its own.
61            warm_ready: true,
62            warm_pending: Vec::new(),
63            cache_capacity_bytes: 0,
64            cache_usage_bytes: 0,
65        }))
66    }
67
68    async fn describe(
69        &self,
70        _request: Request<pb::ComputeDescribeRequest>,
71    ) -> Result<Response<pb::ComputeDescribeResponse>, Status> {
72        let spec = self
73            .config
74            .self_spec()
75            .map_err(|e| Status::failed_precondition(e.to_string()))?;
76        Ok(Response::new(self_describe_response(
77            spec,
78            &self.knobs,
79            &self.routing,
80        )))
81    }
82}
83
84/// Bind the compute gRPC listener. Failure is returned to the caller so process
85/// startup can abort before HTTP is served.
86pub fn bind_compute_admin(
87    addr: std::net::SocketAddr,
88) -> Result<tonic::transport::server::TcpIncoming, std::io::Error> {
89    // NODELAY on accepted connections: `Server::builder().tcp_nodelay(..)`
90    // is IGNORED when serving via `serve_with_incoming` (both compute
91    // servers), so the flag must ride on the incoming. Without it a large
92    // response written after the headers sits in the Nagle buffer for the
93    // client's ~40ms delayed-ACK window.
94    Ok(tonic::transport::server::TcpIncoming::bind(addr)?.with_nodelay(Some(true)))
95}
96
97/// Serve `Compute` Health/Describe on an already-bound listener.
98pub async fn serve_compute_admin_incoming(
99    incoming: tonic::transport::server::TcpIncoming,
100    service: ComputeAdminService,
101) -> Result<(), std::io::Error> {
102    tonic::transport::Server::builder()
103        // NOTE: `.tcp_nodelay(true)` here is ignored for `serve_with_incoming`
104        // — the operative flag is on the `TcpIncoming` (see `bind_compute_admin`).
105        .add_service(
106            waratah_proto::ComputeServer::new(service)
107                .max_decoding_message_size(GRPC_MAX_MESSAGE_SIZE)
108                .max_encoding_message_size(GRPC_MAX_MESSAGE_SIZE),
109        )
110        .serve_with_incoming(incoming)
111        .await
112        .map_err(|e| std::io::Error::other(e.to_string()))?;
113    Ok(())
114}
115
116/// Bind `addr` and serve `Compute` Health/Describe until the future is dropped.
117pub async fn serve_compute_admin(
118    addr: std::net::SocketAddr,
119    service: ComputeAdminService,
120) -> Result<(), std::io::Error> {
121    let incoming = bind_compute_admin(addr)?;
122    serve_compute_admin_incoming(incoming, service).await
123}
124
125/// Default repository list for Describe when the HTTP catalog is `main` only.
126pub fn main_repository_info() -> crate::cluster::RepoInfo {
127    crate::cluster::RepoInfo {
128        id: MAIN_REPOSITORY_ID.to_owned(),
129        readable: true,
130        writable: true,
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137    use waratah_proto::ComputeClient;
138
139    #[tokio::test]
140    async fn health_and_describe_over_grpc() {
141        let incoming = tonic::transport::server::TcpIncoming::bind("127.0.0.1:0".parse().unwrap())
142            .expect("bind ephemeral compute port")
143            .with_nodelay(Some(true));
144        let addr = incoming.local_addr().expect("local addr");
145        let service = ComputeAdminService::new(
146            Arc::new(ClusterConfig::local_dev()),
147            DescribeMode::Star,
148            false,
149        )
150        .unwrap();
151        tokio::spawn(async move {
152            tonic::transport::Server::builder()
153                .add_service(waratah_proto::ComputeServer::new(service))
154                .serve_with_incoming(incoming)
155                .await
156                .unwrap();
157        });
158        let mut client = ComputeClient::connect(format!("http://{addr}"))
159            .await
160            .unwrap();
161        let health = client
162            .health(pb::HealthRequest {})
163            .await
164            .unwrap()
165            .into_inner();
166        assert!(health.serving);
167        let desc = client
168            .describe(pb::ComputeDescribeRequest {})
169            .await
170            .unwrap()
171            .into_inner();
172        assert_eq!(desc.id, "compute-0");
173        assert!(desc.serving);
174        assert_eq!(desc.describe_mode, "star");
175        assert!(!desc.default_union);
176        assert!(!desc.standalone);
177        assert_eq!(desc.repositories.len(), 1);
178        assert_eq!(desc.repositories[0].id, MAIN_REPOSITORY_ID);
179        let routing = desc.routing.expect("describe includes routing");
180        let ids: Vec<_> = routing
181            .hexastore
182            .iter()
183            .map(|n| n.node_id.as_str())
184            .collect();
185        assert_eq!(ids, ["s-0", "p-0", "o-0"]);
186    }
187
188    #[tokio::test]
189    async fn second_bind_on_the_same_addr_fails() {
190        let incoming = bind_compute_admin("127.0.0.1:0".parse().unwrap()).expect("bind ephemeral");
191        let addr = incoming.local_addr().expect("local addr");
192        let error = bind_compute_admin(addr).expect_err("port already held");
193        let message = error.to_string();
194        assert!(
195            message.contains("Address already in use") || message.contains("AddrInUse"),
196            "{message}"
197        );
198        drop(incoming);
199    }
200}