Skip to main content

waratah_router/
config.rs

1//! Static five-process cluster addresses (MVP; gossip/etcd later).
2//!
3//! Two independent tables. Hexastore addresses are keyed by
4//! [`PartitionAxis`], the axis chosen by [`crate::Router::route_pattern`].
5//! Registry addresses are keyed by [`RegistryNodeId`] and are **not** part of
6//! axis routing: a hashed term reaches a registry node through
7//! `murmur3(StrHash) % registry_node_count`, which is a single endpoint at MVP.
8
9use std::collections::BTreeMap;
10use std::fmt;
11use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
12
13use serde::Deserialize;
14use waratah_storage::{PartitionAxis, StrHash, shard_id_for_hash};
15
16use crate::error::RouterError;
17use crate::{NodeId, RoutedNode, Router, RoutingSnapshot, RoutingTable};
18
19/// Identifier of a string-registry process. MVP clusters run node `0` only.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub struct RegistryNodeId(pub u32);
22
23impl fmt::Display for RegistryNodeId {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        write!(f, "registry-{}", self.0)
26    }
27}
28
29/// Default compute id when TOML omits `[[computes]]`.
30pub const DEFAULT_COMPUTE_ID: &str = "compute-0";
31/// Default advertised RDF4J base URL for local_dev.
32pub const DEFAULT_RDF4J_URL: &str = "http://127.0.0.1:8080/rdf4j/";
33/// Default advertised Waratah HTTP (`/waratah`) base URL for local_dev.
34pub const DEFAULT_ADMIN_URL: &str = "http://127.0.0.1:8080/waratah/";
35
36/// One compute coordinator in the static membership list.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct ComputeSpec {
39    /// Stable id (`compute-0`).
40    pub id: String,
41    /// gRPC Describe/Health listen address.
42    pub grpc: SocketAddr,
43    /// Advertised RDF4J HTTP prefix (may differ from the bind address).
44    pub rdf4j_url: String,
45    /// Advertised Waratah admin HTTP prefix (`/waratah`).
46    pub admin_url: String,
47}
48
49impl ComputeSpec {
50    /// Local-dev spec with default advertised HTTP URLs.
51    pub fn local(id: impl Into<String>, grpc: SocketAddr) -> Self {
52        Self {
53            id: id.into(),
54            grpc,
55            rdf4j_url: DEFAULT_RDF4J_URL.to_owned(),
56            admin_url: DEFAULT_ADMIN_URL.to_owned(),
57        }
58    }
59}
60
61/// Addresses of the five MVP processes: S, P, O, string-registry, compute.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct ClusterConfig {
64    hexastore: BTreeMap<&'static str, SocketAddr>,
65    registry: BTreeMap<RegistryNodeId, SocketAddr>,
66    compute: SocketAddr,
67    self_id: String,
68    computes: Vec<ComputeSpec>,
69}
70
71impl ClusterConfig {
72    /// Build from explicit tables, rejecting an incomplete cluster.
73    pub fn new(
74        hexastore: impl IntoIterator<Item = (PartitionAxis, SocketAddr)>,
75        registry: impl IntoIterator<Item = (RegistryNodeId, SocketAddr)>,
76        compute: SocketAddr,
77    ) -> Result<Self, RouterError> {
78        let config = Self {
79            hexastore: hexastore
80                .into_iter()
81                .map(|(axis, addr)| (axis.as_str(), addr))
82                .collect(),
83            registry: registry.into_iter().collect(),
84            compute,
85            self_id: DEFAULT_COMPUTE_ID.to_owned(),
86            computes: vec![ComputeSpec::local(DEFAULT_COMPUTE_ID, compute)],
87        };
88        config.validate()?;
89        Ok(config)
90    }
91
92    /// Default local cluster: S/P/O on `:7001`–`:7003`, registry `:7004`, compute `:7005`.
93    pub fn local_dev() -> Self {
94        Self {
95            hexastore: PartitionAxis::ALL
96                .into_iter()
97                .zip(7001..)
98                .map(|(axis, port)| (axis.as_str(), localhost(port)))
99                .collect(),
100            registry: BTreeMap::from([(RegistryNodeId(0), localhost(7004))]),
101            compute: localhost(7005),
102            self_id: DEFAULT_COMPUTE_ID.to_owned(),
103            computes: vec![ComputeSpec::local(DEFAULT_COMPUTE_ID, localhost(7005))],
104        }
105    }
106
107    /// Parse the static config `waratah_bin` injects into compute.
108    ///
109    /// ```toml
110    /// compute = "127.0.0.1:7005"
111    ///
112    /// [hexastore]
113    /// s = "127.0.0.1:7001"
114    /// p = "127.0.0.1:7002"
115    /// o = "127.0.0.1:7003"
116    ///
117    /// [registry]
118    /// 0 = "127.0.0.1:7004"
119    /// ```
120    pub fn from_toml_str(toml: &str) -> Result<Self, RouterError> {
121        let raw: RawConfig =
122            toml::from_str(toml).map_err(|e| RouterError::Config(e.to_string()))?;
123
124        let mut hexastore = Vec::new();
125        for (axis, addr) in raw.hexastore {
126            let axis: PartitionAxis = axis
127                .parse()
128                .map_err(|e: waratah_storage::StorageError| RouterError::Config(e.to_string()))?;
129            hexastore.push((axis, addr));
130        }
131
132        let mut registry = Vec::new();
133        for (id, addr) in raw.registry {
134            let id: u32 = id.parse().map_err(|_| {
135                RouterError::Config(format!("registry node id must be a number, got {id:?}"))
136            })?;
137            registry.push((RegistryNodeId(id), addr));
138        }
139
140        Self::from_parts(hexastore, registry, raw.compute, raw.self_id, raw.computes)
141    }
142
143    fn from_parts(
144        hexastore: Vec<(PartitionAxis, SocketAddr)>,
145        registry: Vec<(RegistryNodeId, SocketAddr)>,
146        compute: Option<SocketAddr>,
147        self_id: Option<String>,
148        raw_computes: Vec<RawCompute>,
149    ) -> Result<Self, RouterError> {
150        let computes = build_compute_list(compute, raw_computes)?;
151        let self_id = self_id
152            .filter(|id| !id.is_empty())
153            .unwrap_or_else(|| computes[0].id.clone());
154        if !computes.iter().any(|c| c.id == self_id) {
155            return Err(RouterError::UnknownCompute(self_id));
156        }
157        let compute = computes
158            .iter()
159            .find(|c| c.id == self_id)
160            .map(|c| c.grpc)
161            .expect("self_id checked above");
162        let config = Self {
163            hexastore: hexastore
164                .into_iter()
165                .map(|(axis, addr)| (axis.as_str(), addr))
166                .collect(),
167            registry: registry.into_iter().collect(),
168            compute,
169            self_id,
170            computes,
171        };
172        config.validate()?;
173        Ok(config)
174    }
175
176    /// Every hexastore axis is addressed and at least one registry node exists.
177    pub fn validate(&self) -> Result<(), RouterError> {
178        for axis in PartitionAxis::ALL {
179            if !self.hexastore.contains_key(axis.as_str()) {
180                return Err(RouterError::MissingAxis(axis));
181            }
182        }
183        if self.registry.is_empty() {
184            return Err(RouterError::NoRegistryNodes);
185        }
186        Ok(())
187    }
188
189    /// Address of the hexastore partition owning `axis`.
190    pub fn hexastore(&self, axis: PartitionAxis) -> Result<SocketAddr, RouterError> {
191        self.hexastore
192            .get(axis.as_str())
193            .copied()
194            .ok_or(RouterError::MissingAxis(axis))
195    }
196
197    /// Address of a specific registry node.
198    pub fn registry(&self, node: RegistryNodeId) -> Result<SocketAddr, RouterError> {
199        self.registry
200            .get(&node)
201            .copied()
202            .ok_or(RouterError::UnknownRegistryNode(node))
203    }
204
205    /// Every configured registry node and its address (MVP: a single entry).
206    pub fn registry_nodes(&self) -> impl Iterator<Item = (RegistryNodeId, SocketAddr)> + '_ {
207        self.registry.iter().map(|(&id, &addr)| (id, addr))
208    }
209
210    /// Registry node owning `hash` (`murmur3(StrHash) % registry_node_count`).
211    ///
212    /// MVP has a single registry process, so this always resolves to node `0`;
213    /// the sharding stays here so splitting the registry later is a config
214    /// change rather than a call-site change.
215    pub fn registry_for_hash(&self, hash: StrHash) -> Result<SocketAddr, RouterError> {
216        if self.registry.is_empty() {
217            return Err(RouterError::NoRegistryNodes);
218        }
219        let shard = shard_id_for_hash(hash, self.registry.len());
220        self.registry
221            .values()
222            .nth(shard)
223            .copied()
224            .ok_or(RouterError::NoRegistryNodes)
225    }
226
227    /// Address of this process's compute gRPC listener.
228    pub fn compute(&self) -> SocketAddr {
229        self.compute
230    }
231
232    /// Id of this process in [`Self::computes`].
233    pub fn self_id(&self) -> &str {
234        &self.self_id
235    }
236
237    /// Static compute membership (includes this process).
238    pub fn computes(&self) -> &[ComputeSpec] {
239        &self.computes
240    }
241
242    /// This process's [`ComputeSpec`].
243    pub fn self_spec(&self) -> Result<&ComputeSpec, RouterError> {
244        self.computes
245            .iter()
246            .find(|c| c.id == self.self_id)
247            .ok_or_else(|| RouterError::UnknownCompute(self.self_id.clone()))
248    }
249
250    /// Replace advertised HTTP URLs on this process's spec.
251    pub fn with_advertised_urls(mut self, rdf4j_url: String, admin_url: String) -> Self {
252        if let Some(spec) = self.computes.iter_mut().find(|c| c.id == self.self_id) {
253            spec.rdf4j_url = rdf4j_url;
254            spec.admin_url = admin_url;
255        }
256        self
257    }
258
259    /// Total processes described: hexastore axes, registries, and compute nodes.
260    pub fn process_count(&self) -> usize {
261        self.hexastore.len() + self.registry.len() + self.computes.len()
262    }
263
264    /// Build a pattern [`Router`] over one node per axis, addressed from this config.
265    ///
266    /// Node ids follow `<axis>-0`; multi-node axes arrive with real sharding.
267    pub fn router(&self, vnodes_per_node: u32) -> Result<Router, RouterError> {
268        let mut table = RoutingTable::new();
269        let mut nodes = Vec::new();
270        for axis in PartitionAxis::ALL {
271            let node = NodeId::new(format!("{axis}-0"));
272            table.insert(node.clone(), self.hexastore(axis)?);
273            nodes.push(node);
274        }
275        let [s, p, o] = <[NodeId; 3]>::try_from(nodes).expect("one node per axis");
276        Ok(Router::new([s], [p], [o], vnodes_per_node, table))
277    }
278
279    /// Murmur3 hexastore rings plus registry addresses.
280    pub fn routing_snapshot(&self, router: &Router) -> Result<RoutingSnapshot, RouterError> {
281        let hexastore = router.hexastore_nodes()?;
282        let registry = self
283            .registry_nodes()
284            .map(|(id, grpc)| RoutedNode {
285                node_id: NodeId::new(id.to_string()),
286                grpc,
287                axis: None,
288            })
289            .collect();
290        Ok(RoutingSnapshot {
291            hexastore,
292            registry,
293            vnodes_per_node: router.vnodes_per_node(),
294        })
295    }
296}
297
298fn localhost(port: u16) -> SocketAddr {
299    SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port))
300}
301
302fn build_compute_list(
303    compute: Option<SocketAddr>,
304    raw_computes: Vec<RawCompute>,
305) -> Result<Vec<ComputeSpec>, RouterError> {
306    if raw_computes.is_empty() {
307        let grpc = compute.ok_or_else(|| {
308            RouterError::Config("cluster config needs `compute` or `[[computes]]`".to_owned())
309        })?;
310        return Ok(vec![ComputeSpec::local(DEFAULT_COMPUTE_ID, grpc)]);
311    }
312    let mut seen = BTreeMap::new();
313    let mut computes = Vec::new();
314    for raw in raw_computes {
315        if seen.insert(raw.id.clone(), ()).is_some() {
316            return Err(RouterError::DuplicateComputeId(raw.id));
317        }
318        computes.push(ComputeSpec {
319            id: raw.id,
320            grpc: raw.grpc,
321            rdf4j_url: raw.rdf4j.unwrap_or_else(|| DEFAULT_RDF4J_URL.to_owned()),
322            admin_url: raw.admin.unwrap_or_else(|| DEFAULT_ADMIN_URL.to_owned()),
323        });
324    }
325    Ok(computes)
326}
327
328#[derive(Deserialize)]
329struct RawConfig {
330    compute: Option<SocketAddr>,
331    #[serde(rename = "self", default)]
332    self_id: Option<String>,
333    #[serde(default)]
334    computes: Vec<RawCompute>,
335    #[serde(default)]
336    hexastore: BTreeMap<String, SocketAddr>,
337    #[serde(default)]
338    registry: BTreeMap<String, SocketAddr>,
339}
340
341#[derive(Deserialize)]
342struct RawCompute {
343    id: String,
344    grpc: SocketAddr,
345    rdf4j: Option<String>,
346    admin: Option<String>,
347}
348
349#[cfg(test)]
350mod tests {
351    use super::*;
352    use pretty_assertions::assert_eq;
353
354    const FIVE_PROCESS_TOML: &str = r#"
355compute = "127.0.0.1:7005"
356
357[hexastore]
358s = "127.0.0.1:7001"
359p = "127.0.0.1:7002"
360o = "127.0.0.1:7003"
361
362[registry]
3630 = "127.0.0.1:7004"
364"#;
365
366    #[test]
367    fn five_process_address_map_loads() {
368        let config = ClusterConfig::from_toml_str(FIVE_PROCESS_TOML).unwrap();
369        assert_eq!(config.process_count(), 5);
370        assert_eq!(config.hexastore(PartitionAxis::S).unwrap().port(), 7001);
371        assert_eq!(config.hexastore(PartitionAxis::P).unwrap().port(), 7002);
372        assert_eq!(config.hexastore(PartitionAxis::O).unwrap().port(), 7003);
373        assert_eq!(config.registry(RegistryNodeId(0)).unwrap().port(), 7004);
374        assert_eq!(config.compute().port(), 7005);
375        assert_eq!(config, ClusterConfig::local_dev());
376    }
377
378    #[test]
379    fn missing_axis_is_rejected() {
380        let toml = r#"
381compute = "127.0.0.1:7005"
382
383[hexastore]
384s = "127.0.0.1:7001"
385p = "127.0.0.1:7002"
386
387[registry]
3880 = "127.0.0.1:7004"
389"#;
390        assert_eq!(
391            ClusterConfig::from_toml_str(toml),
392            Err(RouterError::MissingAxis(PartitionAxis::O))
393        );
394    }
395
396    #[test]
397    fn registry_table_is_required_and_separate_from_axis_routing() {
398        let toml = r#"
399compute = "127.0.0.1:7005"
400
401[hexastore]
402s = "127.0.0.1:7001"
403p = "127.0.0.1:7002"
404o = "127.0.0.1:7003"
405"#;
406        assert_eq!(
407            ClusterConfig::from_toml_str(toml),
408            Err(RouterError::NoRegistryNodes)
409        );
410
411        // The registry endpoint is not any hexastore axis endpoint.
412        let config = ClusterConfig::local_dev();
413        let registry = config.registry(RegistryNodeId(0)).unwrap();
414        for axis in PartitionAxis::ALL {
415            assert_ne!(config.hexastore(axis).unwrap(), registry);
416        }
417    }
418
419    #[test]
420    fn unknown_registry_node_errors() {
421        let config = ClusterConfig::local_dev();
422        assert_eq!(
423            config.registry(RegistryNodeId(3)),
424            Err(RouterError::UnknownRegistryNode(RegistryNodeId(3)))
425        );
426    }
427
428    #[test]
429    fn single_registry_node_owns_every_hash() {
430        let config = ClusterConfig::local_dev();
431        let expected = config.registry(RegistryNodeId(0)).unwrap();
432        for term in ["http://ex/alice", "Sunny", "http://ex/livesIn"] {
433            assert_eq!(
434                config.registry_for_hash(StrHash::new(term)).unwrap(),
435                expected
436            );
437        }
438    }
439
440    #[test]
441    fn malformed_config_is_a_typed_error() {
442        assert!(matches!(
443            ClusterConfig::from_toml_str("compute = \"not-an-address\""),
444            Err(RouterError::Config(_))
445        ));
446
447        let bad_axis = r#"
448compute = "127.0.0.1:7005"
449
450[hexastore]
451g = "127.0.0.1:7001"
452
453[registry]
4540 = "127.0.0.1:7004"
455"#;
456        assert!(matches!(
457            ClusterConfig::from_toml_str(bad_axis),
458            Err(RouterError::Config(_))
459        ));
460    }
461
462    #[test]
463    fn router_built_from_config_resolves_axis_addresses() {
464        let config = ClusterConfig::local_dev();
465        let router = config.router(16).unwrap();
466        for axis in PartitionAxis::ALL {
467            let node = NodeId::new(format!("{axis}-0"));
468            assert_eq!(
469                router.table().lookup(&node).unwrap(),
470                config.hexastore(axis).unwrap()
471            );
472        }
473        let snap = config.routing_snapshot(&router).unwrap();
474        assert_eq!(snap.vnodes_per_node, 16);
475        assert_eq!(snap.hexastore.len(), 3);
476        assert_eq!(snap.registry.len(), 1);
477        assert_eq!(snap.registry[0].node_id.as_str(), "registry-0");
478        let ids: Vec<_> = snap.hexastore.iter().map(|n| n.node_id.as_str()).collect();
479        assert_eq!(ids, ["s-0", "p-0", "o-0"]);
480        let router_only = router.snapshot().unwrap();
481        assert_eq!(router_only.hexastore, snap.hexastore);
482        assert!(router_only.registry.is_empty());
483        assert_eq!(router_only.vnodes_per_node, 16);
484    }
485
486    #[test]
487    fn toml_compute_pool_lists_peers() {
488        let toml = r#"
489self = "compute-0"
490
491[[computes]]
492id = "compute-0"
493grpc = "127.0.0.1:7005"
494rdf4j = "http://127.0.0.1:8080/rdf4j/"
495admin = "http://127.0.0.1:8080/waratah/"
496
497[[computes]]
498id = "compute-1"
499grpc = "127.0.0.1:7015"
500rdf4j = "http://127.0.0.1:8081/rdf4j/"
501admin = "http://127.0.0.1:8081/waratah/"
502
503[hexastore]
504s = "127.0.0.1:7001"
505p = "127.0.0.1:7002"
506o = "127.0.0.1:7003"
507
508[registry]
5090 = "127.0.0.1:7004"
510"#;
511        let config = ClusterConfig::from_toml_str(toml).unwrap();
512        assert_eq!(config.process_count(), 6);
513        assert_eq!(config.self_id(), "compute-0");
514        assert_eq!(config.computes().len(), 2);
515        assert_eq!(config.computes()[1].grpc.port(), 7015);
516        assert_eq!(config.compute().port(), 7005);
517    }
518}