1use std::collections::BTreeMap;
4
5use serde_json::{json, Value};
6
7use crate::topology::Topology;
8
9pub const ROUTING_PROTOCOLS: [&str; 8] =
10 ["red", "reds", "grpc", "grpcs", "http", "https", "ws", "wss"];
11pub const FEATURE_TOPOLOGY: u32 = 0x0000_0002;
12pub const TOPOLOGY_TRANSPORT_METADATA_KEY: &str = "x-reddb-topology-transport";
13
14pub struct RoutingUri {
16 pub protocol: String,
17 pub path: String,
18 pub parameters: Vec<(String, String)>,
19}
20impl RoutingUri {
21 pub fn query_pairs(&self) -> impl Iterator<Item = (&str, &str)> {
22 self.parameters
23 .iter()
24 .map(|(key, value)| (key.as_str(), value.as_str()))
25 }
26 pub fn path(&self) -> &str {
27 &self.path
28 }
29}
30pub fn routing_uri(
31 uri: &str,
32 target: &crate::ConnectionTarget,
33) -> Result<RoutingUri, crate::ParseError> {
34 let mut parsed = url::Url::parse(match target {
35 crate::ConnectionTarget::GrpcCluster { primary, .. } => primary,
36 _ => uri,
37 })
38 .map_err(|_| crate::ParseError::new(crate::ParseErrorKind::InvalidUri, "invalid remote URI"))?;
39 if matches!(target, crate::ConnectionTarget::GrpcCluster { .. }) {
40 parsed.set_query(
41 uri.split_once('?')
42 .map(|(_, query)| query.split('#').next().unwrap_or_default()),
43 );
44 }
45 let parameters: Vec<_> = parsed
46 .query_pairs()
47 .map(|(key, value)| (key.into_owned(), value.into_owned()))
48 .collect();
49 let scheme = uri
50 .trim()
51 .split(':')
52 .next()
53 .unwrap_or_default()
54 .to_ascii_lowercase();
55 let protocol = match scheme.as_str() {
56 "red+ws" => "ws",
57 "red+wss" => "wss",
58 "red"
59 if parameters
60 .iter()
61 .any(|(key, value)| key == "tls" && matches!(value.as_str(), "true" | "1")) =>
62 {
63 "reds"
64 }
65 other => other,
66 }
67 .to_owned();
68 Ok(RoutingUri {
69 protocol,
70 path: parsed.path().to_owned(),
71 parameters,
72 })
73}
74pub fn websocket_routing_url(address: &str) -> Option<String> {
75 let mut parsed = url::Url::parse(address).ok()?;
76 if !matches!(parsed.scheme(), "ws" | "wss") {
77 return None;
78 }
79 if matches!(parsed.path(), "" | "/") {
80 parsed.set_path(crate::redwire::REDWIRE_WS_PATH);
81 }
82 Some(parsed.into())
83}
84
85pub type RoutingEndpoints = BTreeMap<String, String>;
86
87pub fn routing_endpoints(value: &Value) -> RoutingEndpoints {
90 ROUTING_PROTOCOLS
91 .iter()
92 .filter_map(|protocol| {
93 let address = value.get(*protocol)?.as_str()?;
94 let normalized = routing_endpoint(protocol, address)?;
95 Some((protocol.to_string(), normalized))
96 })
97 .collect()
98}
99
100pub fn routing_endpoint(protocol: &str, address: &str) -> Option<String> {
101 if !ROUTING_PROTOCOLS.contains(&protocol) || address.len() > 4096 || address.is_empty() {
102 return None;
103 }
104 let address = if address.contains("://") {
105 address.to_string()
106 } else {
107 format!("{protocol}://{address}")
108 };
109 let parsed = url::Url::parse(&address).ok()?;
110 if parsed.scheme() != protocol
111 || parsed.host_str().is_none()
112 || !parsed.username().is_empty()
113 || parsed.password().is_some()
114 || parsed.query().is_some()
115 || parsed.fragment().is_some()
116 {
117 return None;
118 }
119 Some(address.trim_end_matches('/').to_string())
120}
121
122pub fn topology_json(topology: &Topology) -> Value {
125 json!({
126 "version": 1,
127 "epoch": topology.epoch.to_string(),
128 "primary": { "addr": topology.primary.addr, "region": topology.primary.region },
129 "replicas": topology.replicas.iter().map(|replica| json!({
130 "addr": replica.addr,
131 "region": replica.region,
132 "healthy": replica.healthy,
133 "lag_ms": replica.lag_ms,
134 "last_applied_lsn": replica.last_applied_lsn.to_string(),
135 "rebootstrapping": replica.rebootstrapping,
136 })).collect::<Vec<_>>(),
137 })
138}
139
140pub fn topology_from_json(value: &Value) -> Option<Topology> {
141 use crate::topology::{Endpoint, ReplicaInfo};
142 if value.get("version")?.as_u64()? != 1 {
143 return None;
144 }
145 let integer = |value: &Value| value.as_u64().or_else(|| value.as_str()?.parse().ok());
146 let endpoint = value.get("primary")?;
147 let replicas = value.get("replicas")?.as_array()?;
148 if replicas.len() > 256 {
149 return None;
150 }
151 Some(Topology {
152 epoch: integer(value.get("epoch")?)?,
153 primary: Endpoint {
154 addr: endpoint.get("addr")?.as_str()?.to_string(),
155 region: endpoint
156 .get("region")
157 .and_then(Value::as_str)
158 .unwrap_or_default()
159 .to_string(),
160 },
161 replicas: replicas
162 .iter()
163 .map(|replica| {
164 Some(ReplicaInfo {
165 addr: replica.get("addr")?.as_str()?.to_string(),
166 region: replica
167 .get("region")
168 .and_then(Value::as_str)
169 .unwrap_or_default()
170 .to_string(),
171 healthy: replica.get("healthy")?.as_bool()?,
172 lag_ms: u32::try_from(replica.get("lag_ms")?.as_u64()?).ok()?,
173 last_applied_lsn: integer(replica.get("last_applied_lsn")?)?,
174 rebootstrapping: replica
175 .get("rebootstrapping")
176 .and_then(Value::as_bool)
177 .unwrap_or(false),
178 })
179 })
180 .collect::<Option<Vec<_>>>()?,
181 })
182}
183
184#[cfg(test)]
185mod tests {
186 use super::*;
187
188 #[test]
189 fn discovery_keeps_protocol_and_tls_boundaries() {
190 let endpoints = routing_endpoints(&json!({
191 "red": "node:5050",
192 "http": "http://node:5000",
193 "https": "http://node:5000",
194 "wss": "wss://node:8443/redwire",
195 "grpc": "grpc://secret:password@node:55055",
196 "reds": "reds://node:5051?token=secret",
197 "unknown": "anything",
198 }));
199 assert_eq!(endpoints.len(), 3);
200 assert_eq!(endpoints["red"], "red://node:5050");
201 assert_eq!(endpoints["wss"], "wss://node:8443/redwire");
202 }
203
204 #[test]
205 fn topology_count_is_validated_before_allocation() {
206 let mut body = vec![0; 20];
207 body[16..20].copy_from_slice(&u32::MAX.to_le_bytes());
208 let mut bytes = vec![1];
209 bytes.extend_from_slice(&20u32.to_le_bytes());
210 bytes.extend_from_slice(&body);
211 assert_eq!(
212 crate::decode_topology(&bytes),
213 Err(crate::TopologyError::Truncated)
214 );
215 }
216
217 #[test]
218 fn cluster_auth_preserves_distinct_ports_without_embedding_credentials_in_routes() {
219 let spec = crate::parse_with_auth(
220 "grpc://alice:password@primary:55055,replica:55056?route=primary",
221 )
222 .expect("cluster URI");
223 assert_eq!(
224 spec.auth,
225 crate::ConnectionAuth::Basic {
226 user: "alice".into(),
227 pass: "password".into()
228 }
229 );
230 assert_eq!(
231 spec.target,
232 crate::ConnectionTarget::GrpcCluster {
233 primary: "http://primary:55055".into(),
234 replicas: vec!["http://replica:55056".into()],
235 force_primary: true,
236 }
237 );
238 }
239}