Skip to main content

waratah_compute/
cluster.rs

1//! Cluster snapshot: this compute is coordinator for one HTTP/gRPC request.
2//!
3//! No gossip. Membership is the static [`ClusterConfig`] compute list. This
4//! process probes its configured hexastore/registry and peer compute Describe
5//! RPCs, then returns a JSON-serializable view for `/waratah/cluster`.
6//! Each compute in that view carries `cors_proxy`: this coordinator's HTTP
7//! origin plus `/cors_proxy`, so a browser can reach other computes without
8//! calling their origins directly.
9
10use std::time::{Duration, SystemTime, UNIX_EPOCH};
11
12use serde::Serialize;
13use tokio::time::timeout;
14use waratah_proto::pb;
15use waratah_proto::{ComputeClient, GRPC_MAX_MESSAGE_SIZE};
16use waratah_router::{ClusterConfig, ComputeSpec, DEFAULT_RDF4J_URL, RoutingSnapshot};
17use waratah_stats::StatsProfile;
18use waratah_storage::PartitionAxis;
19
20use crate::clients::{HexastoreAdmin, RegistryAdmin};
21use crate::describe::DescribeMode;
22
23/// Per-peer / per-partition probe budget so one down node cannot stall HTTP.
24pub const CLUSTER_PROBE_TIMEOUT: Duration = Duration::from_secs(1);
25
26/// JSON body of `GET /waratah/cluster`.
27#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
28pub struct ClusterSnapshot {
29    /// Id of the compute that assembled this view.
30    pub coordinator_id: String,
31    /// Unix milliseconds when probing finished.
32    pub probed_at_ms: u64,
33    /// Configured compute pool (this process plus static peers).
34    pub computes: Vec<ComputeView>,
35    /// Live probes of this coordinator's hexastore + registry.
36    pub storage: Vec<StorageView>,
37    /// Summarized planner cache (not the full sketch blob).
38    pub planner: PlannerSummary,
39}
40
41/// Notebook service capability block on a compute entry.
42///
43/// `available` means the feature is enabled on that compute **and** the
44/// jupyter sidecar answered readiness when the view was assembled. v1
45/// populates this only for the serving compute itself; peer propagation
46/// via the Describe proto is deferred (ARCH.md §11).
47#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
48pub struct NotebooksCapability {
49    /// Feature enabled and sidecar ready.
50    pub available: bool,
51    /// Same-origin proxy path prefix (`/jupyter`).
52    pub path: String,
53}
54
55/// One compute coordinator as seen by this request.
56#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
57pub struct ComputeView {
58    /// Stable id from cluster config.
59    pub id: String,
60    /// Whether this is the process that served the snapshot.
61    #[serde(rename = "self")]
62    pub is_self: bool,
63    /// `up` or `down`.
64    pub status: NodeStatus,
65    /// gRPC Describe/Health address.
66    pub grpc: String,
67    /// True when this process opened S/P/O + registry in-process (`waratah standalone`).
68    pub standalone: bool,
69    /// Build version (`semver+git-describe`, `waratah_buildinfo`) reported by
70    /// this compute's Describe RPC; the self row carries the local build.
71    /// Omitted for peers that did not answer their probe.
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub version: Option<String>,
74    /// Advertised RDF4J HTTP prefix.
75    pub rdf4j: String,
76    /// Advertised Waratah HTTP prefix.
77    pub admin: String,
78    /// Same-origin proxy base for browser calls aimed at another compute.
79    ///
80    /// Every compute in one snapshot carries this coordinator's origin plus
81    /// `/cors_proxy` (for example `http://127.0.0.1:8080/cors_proxy`). The
82    /// console appends `/{compute_id}/rdf4j/…` or `/{compute_id}/waratah/…`.
83    pub cors_proxy: String,
84    /// Repositories this compute exposes.
85    pub repositories: Vec<RepoInfo>,
86    /// SPARQL DESCRIBE algorithm.
87    pub describe_mode: String,
88    /// SPARQL default-graph union flag.
89    pub default_union: bool,
90    /// Routing table this compute is configured to use.
91    pub routing: RoutingView,
92    /// Notebook sidecar capability (`--with-notebooks`); self row only in v1.
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub notebooks: Option<NotebooksCapability>,
95    /// Probe error when `status` is `down`.
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub error: Option<String>,
98}
99
100/// Hexastore partition or string-registry process.
101#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
102pub struct StorageView {
103    /// `hexastore` or `registry`.
104    pub kind: &'static str,
105    /// Routing id (`s-0`, `registry-0`).
106    pub id: String,
107    /// Hexastore axis, omitted for registry.
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub axis: Option<String>,
110    /// gRPC listen address when this store is a separate process.
111    ///
112    /// Omitted when the coordinator opened storage in-process (`waratah standalone`).
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub grpc: Option<String>,
115    /// `up` or `down`.
116    pub status: NodeStatus,
117    /// Build version (`semver+git-describe`, `waratah_buildinfo`) from the
118    /// partition's / registry's Describe RPC. Omitted when the probe failed.
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub version: Option<String>,
121    /// `memory` or `rocksdb`.
122    #[serde(skip_serializing_if = "Option::is_none")]
123    pub backend: Option<String>,
124    /// Data directory from Describe.
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub data_dir: Option<String>,
127    /// LSM / process counters.
128    #[serde(skip_serializing_if = "Option::is_none")]
129    pub metrics: Option<LsmMetricsView>,
130    /// Probe error when `status` is `down`.
131    #[serde(skip_serializing_if = "Option::is_none")]
132    pub error: Option<String>,
133}
134
135/// Cheap planner-cache summary (no CMS/HLL).
136#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
137pub struct PlannerSummary {
138    /// Approximate Put observations on the preferred rolled-up axis.
139    pub total_puts: u64,
140    /// Distinct named-node predicates in the exact map.
141    pub predicate_count: u64,
142    /// Distinct `rdf:type` classes in the exact map.
143    pub class_count: u64,
144    /// S-axis named-graph catalog count copied onto the rollup.
145    pub named_graph_count: u64,
146}
147
148/// One RDF repository this HTTP server exposes.
149#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
150pub struct RepoInfo {
151    /// Repository id (`main`).
152    pub id: String,
153    /// SPARQL reads are enabled.
154    pub readable: bool,
155    /// Ingest / writes are enabled.
156    pub writable: bool,
157}
158
159/// Routing table dump for one compute.
160#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
161pub struct RoutingView {
162    /// Physical hexastore nodes.
163    pub hexastore: Vec<RoutingNodeView>,
164    /// Registry processes.
165    pub registry: Vec<RoutingNodeView>,
166    /// Virtual nodes per physical node.
167    pub vnodes_per_node: u32,
168}
169
170/// One node in a routing dump.
171#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
172pub struct RoutingNodeView {
173    /// `s-0`, `registry-0`, …
174    pub node_id: String,
175    /// gRPC address.
176    pub grpc: String,
177    /// Hexastore axis when applicable.
178    #[serde(skip_serializing_if = "Option::is_none")]
179    pub axis: Option<String>,
180}
181
182/// Optional LSM counters (absent on memory backends).
183#[derive(Debug, Clone, Serialize, PartialEq, Eq, Default)]
184pub struct LsmMetricsView {
185    /// `rocksdb.estimate-live-data-size`.
186    #[serde(skip_serializing_if = "Option::is_none")]
187    pub estimate_live_data_bytes: Option<u64>,
188    /// `rocksdb.estimate-num-keys`.
189    #[serde(skip_serializing_if = "Option::is_none")]
190    pub estimate_num_keys: Option<u64>,
191    /// `rocksdb.total-sst-files-size`.
192    #[serde(skip_serializing_if = "Option::is_none")]
193    pub total_sst_bytes: Option<u64>,
194    /// `rocksdb.cur-size-all-mem-tables`.
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub memtable_bytes: Option<u64>,
197    /// `rocksdb.num-running-compactions`.
198    #[serde(skip_serializing_if = "Option::is_none")]
199    pub num_running_compactions: Option<u64>,
200    /// `rocksdb.num-running-flushes`.
201    #[serde(skip_serializing_if = "Option::is_none")]
202    pub num_running_flushes: Option<u64>,
203    /// Write-path open overlay Put count (hexastore).
204    #[serde(skip_serializing_if = "Option::is_none")]
205    pub open_total_puts: Option<u64>,
206    /// Listener-observed compaction completions (hexastore).
207    #[serde(skip_serializing_if = "Option::is_none")]
208    pub compaction_event_count: Option<u64>,
209    /// S-axis named-graph catalog count.
210    #[serde(skip_serializing_if = "Option::is_none")]
211    pub named_graph_count: Option<u64>,
212    /// Registry dictionary entry count / estimate.
213    #[serde(skip_serializing_if = "Option::is_none")]
214    pub entry_count: Option<u64>,
215    /// Process-wide block cache capacity (absent on memory backends).
216    #[serde(skip_serializing_if = "Option::is_none")]
217    pub block_cache_capacity_bytes: Option<u64>,
218    /// Bytes currently charged to cached blocks.
219    #[serde(skip_serializing_if = "Option::is_none")]
220    pub block_cache_usage_bytes: Option<u64>,
221}
222
223/// Probe outcome.
224#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
225#[serde(rename_all = "lowercase")]
226pub enum NodeStatus {
227    /// RPC succeeded and `serving` was true.
228    Up,
229    /// Timeout, transport error, or `serving` false / axis mismatch.
230    Down,
231}
232
233/// Knobs copied onto self / Compute Describe.
234#[derive(Debug, Clone)]
235pub struct ClusterKnobs {
236    /// SPARQL DESCRIBE algorithm.
237    pub describe_mode: DescribeMode,
238    /// SPARQL default-graph union.
239    pub default_union: bool,
240    /// Repositories this HTTP catalog exposes.
241    pub repositories: Vec<RepoInfo>,
242    /// In-process S/P/O + registry (`waratah standalone`).
243    pub standalone: bool,
244}
245
246impl ClusterKnobs {
247    /// MVP catalog: repository `main`, readable and writable (ingest).
248    pub fn main_only(describe_mode: DescribeMode, default_union: bool) -> Self {
249        Self {
250            describe_mode,
251            default_union,
252            repositories: vec![RepoInfo {
253                id: waratah_storage::MAIN_REPOSITORY_ID.to_owned(),
254                readable: true,
255                writable: true,
256            }],
257            standalone: false,
258        }
259    }
260
261    /// Mark this coordinator as in-process storage (`waratah standalone`).
262    pub fn with_standalone(mut self, standalone: bool) -> Self {
263        self.standalone = standalone;
264        self
265    }
266}
267
268/// Scheme and authority of an advertised HTTP URL (`http://host:port`).
269///
270/// `http://127.0.0.1:8080/rdf4j/` becomes `http://127.0.0.1:8080`.
271pub fn http_origin(url: &str) -> Option<String> {
272    let url = url.trim();
273    let (scheme, rest) = if let Some(rest) = url.strip_prefix("https://") {
274        ("https", rest)
275    } else if let Some(rest) = url.strip_prefix("http://") {
276        ("http", rest)
277    } else {
278        return None;
279    };
280    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
281    if authority.is_empty() || authority.contains([' ', '\\', '\0']) {
282        return None;
283    }
284    Some(format!("{scheme}://{authority}"))
285}
286
287/// Console proxy base advertised on every compute in a cluster snapshot.
288///
289/// Derived from this coordinator's RDF4J URL so the browser stays on this
290/// origin. `http://127.0.0.1:8080/rdf4j/` becomes `http://127.0.0.1:8080/cors_proxy`.
291pub fn cors_proxy_base(rdf4j_url: &str) -> String {
292    let origin = http_origin(rdf4j_url).unwrap_or_else(|| {
293        http_origin(DEFAULT_RDF4J_URL).unwrap_or_else(|| "http://127.0.0.1:8080".to_owned())
294    });
295    format!("{origin}/cors_proxy")
296}
297
298/// Assemble a snapshot: self without RPC, peers via Compute gRPC, storage via Describe.
299pub async fn assemble_cluster_snapshot<H, R>(
300    config: &ClusterConfig,
301    knobs: &ClusterKnobs,
302    hexastore: &H,
303    registry: &R,
304    planner: &StatsProfile,
305) -> ClusterSnapshot
306where
307    H: HexastoreAdmin,
308    R: RegistryAdmin,
309{
310    let router = match config.router(16) {
311        Ok(router) => router,
312        Err(_) => {
313            return ClusterSnapshot {
314                coordinator_id: config.self_id().to_owned(),
315                probed_at_ms: now_ms(),
316                computes: Vec::new(),
317                storage: Vec::new(),
318                planner: planner_summary(planner),
319            };
320        }
321    };
322    let self_routing = routing_view(
323        &config.routing_snapshot(&router).unwrap_or(RoutingSnapshot {
324            hexastore: Vec::new(),
325            registry: Vec::new(),
326            vnodes_per_node: 16,
327        }),
328    );
329
330    let cors_proxy = config
331        .self_spec()
332        .ok()
333        .map(|spec| cors_proxy_base(&spec.rdf4j_url))
334        .unwrap_or_else(|| cors_proxy_base(DEFAULT_RDF4J_URL));
335
336    let mut computes = Vec::new();
337    for spec in config.computes() {
338        if spec.id == config.self_id() {
339            computes.push(self_compute_view(
340                spec,
341                knobs,
342                self_routing.clone(),
343                &cors_proxy,
344            ));
345        } else {
346            computes.push(probe_peer_compute(spec.clone(), &cors_proxy).await);
347        }
348    }
349
350    let mut storage = Vec::new();
351    for axis in PartitionAxis::ALL {
352        let addr = config.hexastore(axis).ok();
353        storage.push(probe_hexastore(hexastore, axis, addr, knobs.standalone).await);
354    }
355    for (id, addr) in config.registry_nodes() {
356        storage.push(probe_registry(registry, id, addr.to_string(), knobs.standalone).await);
357    }
358
359    ClusterSnapshot {
360        coordinator_id: config.self_id().to_owned(),
361        probed_at_ms: now_ms(),
362        computes,
363        storage,
364        planner: planner_summary(planner),
365    }
366}
367
368/// Identity payload for this process's Compute gRPC Describe (no storage probes).
369pub fn self_describe_response(
370    spec: &ComputeSpec,
371    knobs: &ClusterKnobs,
372    routing: &RoutingSnapshot,
373) -> pb::ComputeDescribeResponse {
374    pb::ComputeDescribeResponse {
375        id: spec.id.clone(),
376        grpc: spec.grpc.to_string(),
377        rdf4j_url: spec.rdf4j_url.clone(),
378        admin_url: spec.admin_url.clone(),
379        repositories: knobs
380            .repositories
381            .iter()
382            .map(|r| pb::RepositoryInfo {
383                id: r.id.clone(),
384                readable: r.readable,
385                writable: r.writable,
386            })
387            .collect(),
388        describe_mode: knobs.describe_mode.to_string(),
389        default_union: knobs.default_union,
390        routing: Some(routing_to_proto(routing)),
391        version: waratah_buildinfo::version_string(),
392        serving: true,
393        standalone: knobs.standalone,
394    }
395}
396
397fn self_compute_view(
398    spec: &ComputeSpec,
399    knobs: &ClusterKnobs,
400    routing: RoutingView,
401    cors_proxy: &str,
402) -> ComputeView {
403    ComputeView {
404        id: spec.id.clone(),
405        is_self: true,
406        status: NodeStatus::Up,
407        grpc: spec.grpc.to_string(),
408        standalone: knobs.standalone,
409        version: Some(waratah_buildinfo::version_string()),
410        rdf4j: spec.rdf4j_url.clone(),
411        admin: spec.admin_url.clone(),
412        cors_proxy: cors_proxy.to_owned(),
413        repositories: knobs.repositories.clone(),
414        describe_mode: knobs.describe_mode.to_string(),
415        default_union: knobs.default_union,
416        routing,
417        notebooks: None,
418        error: None,
419    }
420}
421
422async fn probe_peer_compute(spec: ComputeSpec, cors_proxy: &str) -> ComputeView {
423    let url = format!("http://{}", spec.grpc);
424    let result = timeout(CLUSTER_PROBE_TIMEOUT, async {
425        let endpoint = tonic::transport::Endpoint::from_shared(url)
426            .map_err(|e| tonic::Status::unavailable(e.to_string()))?
427            .tcp_nodelay(true);
428        let mut client = ComputeClient::connect(endpoint)
429            .await
430            .map_err(|e| tonic::Status::unavailable(e.to_string()))?
431            .max_decoding_message_size(GRPC_MAX_MESSAGE_SIZE);
432        let health = client.health(pb::HealthRequest {}).await?.into_inner();
433        if !health.serving {
434            return Err(tonic::Status::unavailable(if health.detail.is_empty() {
435                "not serving".to_owned()
436            } else {
437                health.detail
438            }));
439        }
440        let desc = client
441            .describe(pb::ComputeDescribeRequest {})
442            .await?
443            .into_inner();
444        Ok::<_, tonic::Status>(desc)
445    })
446    .await;
447    match result {
448        Ok(Ok(desc)) => ComputeView {
449            id: if desc.id.is_empty() {
450                spec.id.clone()
451            } else {
452                desc.id
453            },
454            is_self: false,
455            status: if desc.serving {
456                NodeStatus::Up
457            } else {
458                NodeStatus::Down
459            },
460            grpc: if desc.grpc.is_empty() {
461                spec.grpc.to_string()
462            } else {
463                desc.grpc
464            },
465            standalone: desc.standalone,
466            version: empty_to_none(desc.version),
467            rdf4j: nonempty_or(desc.rdf4j_url, &spec.rdf4j_url),
468            admin: nonempty_or(desc.admin_url, &spec.admin_url),
469            cors_proxy: cors_proxy.to_owned(),
470            repositories: desc
471                .repositories
472                .into_iter()
473                .map(|r| RepoInfo {
474                    id: r.id,
475                    readable: r.readable,
476                    writable: r.writable,
477                })
478                .collect(),
479            describe_mode: desc.describe_mode,
480            default_union: desc.default_union,
481            routing: desc
482                .routing
483                .map(routing_from_proto)
484                .unwrap_or_else(|| RoutingView {
485                    hexastore: Vec::new(),
486                    registry: Vec::new(),
487                    vnodes_per_node: 0,
488                }),
489            notebooks: None,
490            error: if desc.serving {
491                None
492            } else {
493                Some("not serving".to_owned())
494            },
495        },
496        Ok(Err(status)) => down_compute(&spec, status.to_string(), cors_proxy),
497        Err(_) => down_compute(&spec, "probe timed out".to_owned(), cors_proxy),
498    }
499}
500
501fn down_compute(spec: &ComputeSpec, error: String, cors_proxy: &str) -> ComputeView {
502    ComputeView {
503        id: spec.id.clone(),
504        is_self: false,
505        status: NodeStatus::Down,
506        grpc: spec.grpc.to_string(),
507        standalone: false,
508        version: None,
509        rdf4j: spec.rdf4j_url.clone(),
510        admin: spec.admin_url.clone(),
511        cors_proxy: cors_proxy.to_owned(),
512        repositories: Vec::new(),
513        describe_mode: String::new(),
514        default_union: false,
515        routing: RoutingView {
516            hexastore: Vec::new(),
517            registry: Vec::new(),
518            vnodes_per_node: 0,
519        },
520        notebooks: None,
521        error: Some(error),
522    }
523}
524
525async fn probe_hexastore<H: HexastoreAdmin>(
526    hexastore: &H,
527    axis: PartitionAxis,
528    addr: Option<std::net::SocketAddr>,
529    standalone: bool,
530) -> StorageView {
531    let configured = addr.map(|a| a.to_string()).unwrap_or_default();
532    let id = format!("{axis}-0");
533    match timeout(CLUSTER_PROBE_TIMEOUT, hexastore.describe(axis)).await {
534        Ok(Ok(desc)) => {
535            let mismatch = desc.axis != axis;
536            let up = desc.serving && !mismatch;
537            StorageView {
538                kind: "hexastore",
539                id: if desc.node_id.is_empty() {
540                    id
541                } else {
542                    desc.node_id
543                },
544                axis: Some(axis.as_str().to_owned()),
545                grpc: advertised_storage_grpc(desc.listen, &configured, standalone),
546                status: if up { NodeStatus::Up } else { NodeStatus::Down },
547                version: empty_to_none(desc.version),
548                backend: Some(desc.backend),
549                data_dir: empty_to_none(desc.data_dir),
550                metrics: Some(desc.metrics),
551                error: if mismatch {
552                    Some(format!(
553                        "axis_mismatch: configured {axis}, describe reported {}",
554                        desc.axis
555                    ))
556                } else if desc.serving {
557                    None
558                } else {
559                    Some("not serving".to_owned())
560                },
561            }
562        }
563        Ok(Err(status)) => StorageView {
564            kind: "hexastore",
565            id,
566            axis: Some(axis.as_str().to_owned()),
567            grpc: advertised_storage_grpc(String::new(), &configured, standalone),
568            status: NodeStatus::Down,
569            version: None,
570            backend: None,
571            data_dir: None,
572            metrics: None,
573            error: Some(status.to_string()),
574        },
575        Err(_) => StorageView {
576            kind: "hexastore",
577            id,
578            axis: Some(axis.as_str().to_owned()),
579            grpc: advertised_storage_grpc(String::new(), &configured, standalone),
580            status: NodeStatus::Down,
581            version: None,
582            backend: None,
583            data_dir: None,
584            metrics: None,
585            error: Some("probe timed out".to_owned()),
586        },
587    }
588}
589
590async fn probe_registry<R: RegistryAdmin>(
591    registry: &R,
592    id: waratah_router::RegistryNodeId,
593    configured: String,
594    standalone: bool,
595) -> StorageView {
596    let label = id.to_string();
597    match timeout(CLUSTER_PROBE_TIMEOUT, registry.describe(id)).await {
598        Ok(Ok(desc)) => StorageView {
599            kind: "registry",
600            id: if desc.node_id.is_empty() {
601                label.clone()
602            } else {
603                desc.node_id
604            },
605            axis: None,
606            grpc: advertised_storage_grpc(desc.listen, &configured, standalone),
607            status: if desc.serving {
608                NodeStatus::Up
609            } else {
610                NodeStatus::Down
611            },
612            version: empty_to_none(desc.version),
613            backend: Some(desc.backend),
614            data_dir: empty_to_none(desc.data_dir),
615            metrics: {
616                let mut m = desc.metrics;
617                m.entry_count = desc.entry_count.or(m.entry_count);
618                Some(m)
619            },
620            error: if desc.serving {
621                None
622            } else {
623                Some("not serving".to_owned())
624            },
625        },
626        Ok(Err(status)) => StorageView {
627            kind: "registry",
628            id: label.clone(),
629            axis: None,
630            grpc: advertised_storage_grpc(String::new(), &configured, standalone),
631            status: NodeStatus::Down,
632            version: None,
633            backend: None,
634            data_dir: None,
635            metrics: None,
636            error: Some(status.to_string()),
637        },
638        Err(_) => StorageView {
639            kind: "registry",
640            id: label,
641            axis: None,
642            grpc: advertised_storage_grpc(String::new(), &configured, standalone),
643            status: NodeStatus::Down,
644            version: None,
645            backend: None,
646            data_dir: None,
647            metrics: None,
648            error: Some("probe timed out".to_owned()),
649        },
650    }
651}
652
653fn planner_summary(profile: &StatsProfile) -> PlannerSummary {
654    PlannerSummary {
655        total_puts: profile.total_puts,
656        predicate_count: profile.predicate_counts.len() as u64,
657        class_count: profile.class_counts.len() as u64,
658        named_graph_count: profile.named_graph_count,
659    }
660}
661
662fn routing_view(snap: &RoutingSnapshot) -> RoutingView {
663    RoutingView {
664        hexastore: snap
665            .hexastore
666            .iter()
667            .map(|n| RoutingNodeView {
668                node_id: n.node_id.to_string(),
669                grpc: n.grpc.to_string(),
670                axis: n.axis.map(|a| a.as_str().to_owned()),
671            })
672            .collect(),
673        registry: snap
674            .registry
675            .iter()
676            .map(|n| RoutingNodeView {
677                node_id: n.node_id.to_string(),
678                grpc: n.grpc.to_string(),
679                axis: None,
680            })
681            .collect(),
682        vnodes_per_node: snap.vnodes_per_node,
683    }
684}
685
686fn routing_to_proto(snap: &RoutingSnapshot) -> pb::RoutingSnapshot {
687    let map_node = |n: &waratah_router::RoutedNode| pb::RoutingNode {
688        node_id: n.node_id.to_string(),
689        grpc: n.grpc.to_string(),
690        axis: n
691            .axis
692            .map(waratah_proto::axis_to_proto)
693            .unwrap_or(pb::PartitionAxis::Unspecified)
694            .into(),
695    };
696    pb::RoutingSnapshot {
697        hexastore: snap.hexastore.iter().map(map_node).collect(),
698        registry: snap.registry.iter().map(map_node).collect(),
699        vnodes_per_node: snap.vnodes_per_node,
700    }
701}
702
703fn routing_from_proto(snap: pb::RoutingSnapshot) -> RoutingView {
704    let map_node = |n: pb::RoutingNode| {
705        let axis = waratah_proto::axis_from_proto(
706            pb::PartitionAxis::try_from(n.axis).unwrap_or(pb::PartitionAxis::Unspecified),
707        )
708        .map(|a| a.as_str().to_owned());
709        RoutingNodeView {
710            node_id: n.node_id,
711            grpc: n.grpc,
712            axis,
713        }
714    };
715    RoutingView {
716        hexastore: snap.hexastore.into_iter().map(map_node).collect(),
717        registry: snap.registry.into_iter().map(map_node).collect(),
718        vnodes_per_node: snap.vnodes_per_node,
719    }
720}
721
722fn now_ms() -> u64 {
723    SystemTime::now()
724        .duration_since(UNIX_EPOCH)
725        .map(|d| d.as_millis() as u64)
726        .unwrap_or(0)
727}
728
729fn nonempty_or(value: String, fallback: &str) -> String {
730    if value.is_empty() {
731        fallback.to_owned()
732    } else {
733        value
734    }
735}
736
737/// Live storage listen, or the configured address. Standalone has no storage gRPC.
738fn advertised_storage_grpc(listen: String, configured: &str, standalone: bool) -> Option<String> {
739    if standalone {
740        empty_to_none(listen)
741    } else if listen.is_empty() {
742        empty_to_none(configured.to_owned())
743    } else {
744        Some(listen)
745    }
746}
747
748fn empty_to_none(value: String) -> Option<String> {
749    if value.is_empty() { None } else { Some(value) }
750}
751
752#[cfg(test)]
753mod tests {
754    use super::*;
755    use std::net::SocketAddr;
756    use waratah_router::RegistryNodeId;
757
758    use crate::clients::{HexastoreDescribe, RegistryDescribe};
759
760    struct TimeoutHexastore;
761
762    impl HexastoreAdmin for TimeoutHexastore {
763        async fn describe(&self, _axis: PartitionAxis) -> Result<HexastoreDescribe, tonic::Status> {
764            tokio::time::sleep(Duration::from_secs(5)).await;
765            unreachable!("should time out")
766        }
767    }
768
769    struct OkRegistry;
770
771    impl RegistryAdmin for OkRegistry {
772        async fn describe(
773            &self,
774            _node: waratah_router::RegistryNodeId,
775        ) -> Result<RegistryDescribe, tonic::Status> {
776            Ok(RegistryDescribe {
777                node_id: "registry-0".to_owned(),
778                listen: String::new(),
779                data_dir: String::new(),
780                backend: "memory".to_owned(),
781                version: "0.1.0".to_owned(),
782                repository_id: "main".to_owned(),
783                shard_count: 1,
784                entry_count: Some(0),
785                serving: true,
786                metrics: LsmMetricsView::default(),
787            })
788        }
789    }
790
791    fn cfg() -> ClusterConfig {
792        let hexastore = PartitionAxis::ALL
793            .into_iter()
794            .zip(7001u16..)
795            .map(|(axis, port)| {
796                (
797                    axis,
798                    format!("127.0.0.1:{port}").parse::<SocketAddr>().unwrap(),
799                )
800            });
801        ClusterConfig::new(
802            hexastore,
803            [(RegistryNodeId(0), "127.0.0.1:7004".parse().unwrap())],
804            "127.0.0.1:7005".parse().unwrap(),
805        )
806        .unwrap()
807    }
808
809    #[tokio::test]
810    async fn storage_timeout_is_down_not_http_error() {
811        let config = cfg();
812        let knobs = ClusterKnobs::main_only(DescribeMode::Star, false);
813        let snap = assemble_cluster_snapshot(
814            &config,
815            &knobs,
816            &TimeoutHexastore,
817            &OkRegistry,
818            &StatsProfile::default(),
819        )
820        .await;
821        assert_eq!(snap.coordinator_id, "compute-0");
822        let hex = snap
823            .storage
824            .iter()
825            .filter(|s| s.kind == "hexastore")
826            .collect::<Vec<_>>();
827        assert_eq!(hex.len(), 3);
828        for node in hex {
829            assert_eq!(node.status, NodeStatus::Down);
830            assert_eq!(node.error.as_deref(), Some("probe timed out"));
831            assert!(node.grpc.is_some());
832        }
833    }
834
835    struct OkHexastore;
836
837    impl HexastoreAdmin for OkHexastore {
838        async fn describe(&self, axis: PartitionAxis) -> Result<HexastoreDescribe, tonic::Status> {
839            Ok(HexastoreDescribe {
840                axis,
841                node_id: format!("{axis}-0"),
842                listen: String::new(),
843                data_dir: String::new(),
844                backend: "memory".to_owned(),
845                version: "0.1.0".to_owned(),
846                repository_id: "main".to_owned(),
847                serving: true,
848                metrics: LsmMetricsView::default(),
849                geo_index_epoch: None,
850                temporal_index_epoch: None,
851                temporal_rebuild_in_progress: false,
852                geo_rebuild_in_progress: false,
853                text_index_epoch: None,
854                text_index_fingerprint: String::new(),
855                text_index_terms: 0,
856                text_rebuild_in_progress: false,
857            })
858        }
859    }
860
861    #[tokio::test]
862    async fn standalone_omits_storage_grpc() {
863        let config = cfg();
864        let knobs = ClusterKnobs::main_only(DescribeMode::Star, false).with_standalone(true);
865        let snap = assemble_cluster_snapshot(
866            &config,
867            &knobs,
868            &OkHexastore,
869            &OkRegistry,
870            &StatsProfile::default(),
871        )
872        .await;
873        assert!(snap.computes[0].is_self);
874        assert!(snap.computes[0].standalone);
875        assert_eq!(snap.computes[0].grpc, "127.0.0.1:7005");
876        assert_eq!(
877            snap.computes[0].cors_proxy,
878            "http://127.0.0.1:8080/cors_proxy"
879        );
880        for node in &snap.storage {
881            assert_eq!(node.status, NodeStatus::Up);
882            assert_eq!(node.grpc, None);
883        }
884        let json = serde_json::to_value(&snap).unwrap();
885        assert_eq!(json["computes"][0]["self"], true);
886        assert_eq!(json["computes"][0]["standalone"], true);
887        assert_eq!(
888            json["computes"][0]["cors_proxy"],
889            "http://127.0.0.1:8080/cors_proxy"
890        );
891        // Self compute row carries the local build string; storage rows echo
892        // the version their (mocked) Describe RPC returned.
893        assert!(
894            snap.computes[0]
895                .version
896                .as_deref()
897                .is_some_and(|v| v.starts_with(waratah_buildinfo::PKG_VERSION)),
898            "self version should start with the package version: {:?}",
899            snap.computes[0].version
900        );
901        for node in &snap.storage {
902            assert_eq!(node.version.as_deref(), Some("0.1.0"));
903        }
904        for node in json["storage"].as_array().unwrap() {
905            assert!(node.get("grpc").is_none(), "standalone omits storage grpc");
906        }
907    }
908
909    #[tokio::test]
910    async fn down_peer_does_not_fail_snapshot() {
911        let toml = r#"
912self = "compute-0"
913
914[[computes]]
915id = "compute-0"
916grpc = "127.0.0.1:7005"
917rdf4j = "http://127.0.0.1:8080/rdf4j/"
918
919[[computes]]
920id = "compute-1"
921grpc = "127.0.0.1:1"
922rdf4j = "http://10.1.2.3:9090/rdf4j/"
923
924[hexastore]
925s = "127.0.0.1:7001"
926p = "127.0.0.1:7002"
927o = "127.0.0.1:7003"
928
929[registry]
9300 = "127.0.0.1:7004"
931"#;
932        let config = ClusterConfig::from_toml_str(toml).unwrap();
933        let knobs = ClusterKnobs::main_only(DescribeMode::Star, false);
934        let snap = assemble_cluster_snapshot(
935            &config,
936            &knobs,
937            &TimeoutHexastore,
938            &OkRegistry,
939            &StatsProfile::default(),
940        )
941        .await;
942        assert_eq!(snap.computes.len(), 2);
943        assert!(snap.computes[0].is_self);
944        assert_eq!(snap.computes[0].status, NodeStatus::Up);
945        assert!(!snap.computes[1].is_self);
946        assert_eq!(snap.computes[1].status, NodeStatus::Down);
947        assert!(snap.computes[1].error.is_some());
948        // A peer that did not answer reports no version.
949        assert_eq!(snap.computes[1].version, None);
950        assert_eq!(snap.computes[1].rdf4j, "http://10.1.2.3:9090/rdf4j/");
951        assert_eq!(
952            snap.computes[0].cors_proxy, snap.computes[1].cors_proxy,
953            "every compute advertises this coordinator's proxy"
954        );
955        assert_eq!(
956            snap.computes[0].cors_proxy,
957            "http://127.0.0.1:8080/cors_proxy"
958        );
959    }
960
961    #[test]
962    fn http_origin_strips_path() {
963        assert_eq!(
964            http_origin("http://127.0.0.1:8080/rdf4j/").as_deref(),
965            Some("http://127.0.0.1:8080")
966        );
967        assert_eq!(
968            cors_proxy_base("https://compute.example:8443/rdf4j"),
969            "https://compute.example:8443/cors_proxy"
970        );
971        assert!(http_origin("not a url").is_none());
972    }
973}