1use std::collections::BTreeMap;
8use std::fmt;
9use std::path::Path;
10use std::time::Duration;
11
12use datumesh_core::json::{self, Value};
13use datumesh_core::lexical;
14
15use crate::apikeys::ApiKeys;
16
17pub const DEFAULT_BUDGET: Duration = Duration::from_secs(1);
19pub const DEFAULT_POOL_SIZE: usize = 32;
22pub const DEFAULT_BATCH_MAX: usize = 1000;
24pub const DEFAULT_SLICE_PAGE: usize = 1000;
26pub const MAX_SLICE_PAGE: usize = 10_000;
28pub const MAX_SLICE_MEMBERS: usize = 1_048_576;
30
31#[non_exhaustive]
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct RateLimits {
36 pub enabled: bool,
38 pub per_ip: u32,
40 pub ip_burst: u32,
42 pub per_key: u32,
45 pub verify_per_ip: u32,
47 pub batch_cells_per_token: u32,
50}
51
52impl Default for RateLimits {
53 fn default() -> Self {
54 RateLimits {
55 enabled: true,
56 per_ip: 60,
57 ip_burst: 120,
58 per_key: 600,
59 verify_per_ip: 60,
60 batch_cells_per_token: 50,
61 }
62 }
63}
64
65#[non_exhaustive]
68#[derive(Clone, Debug, PartialEq, Eq)]
69pub struct Ttls {
70 pub key_doc: Duration,
73 pub key_refetch: Duration,
75 pub mesh_doc: Duration,
77 pub binding: Duration,
80 pub current: Duration,
83 pub latest_max_age: Duration,
85 pub job: Duration,
88}
89
90impl Default for Ttls {
91 fn default() -> Self {
92 Ttls {
93 key_doc: Duration::from_secs(300),
94 key_refetch: Duration::from_secs(10),
95 mesh_doc: Duration::from_secs(300),
96 binding: Duration::from_secs(60),
97 current: Duration::from_secs(60),
98 latest_max_age: Duration::from_secs(10),
99 job: Duration::from_secs(300),
100 }
101 }
102}
103
104#[non_exhaustive]
106#[derive(Clone, Debug, PartialEq, Eq)]
107pub enum Rule {
108 Principals(Vec<String>),
111 Price {
114 amount: String,
116 currency: String,
118 },
119}
120
121#[non_exhaustive]
123#[derive(Clone, Debug, Default, PartialEq, Eq)]
124pub struct Policy {
125 pub rules: BTreeMap<String, Rule>,
127}
128
129impl Policy {
130 pub fn rule(&self, fn_name: &str) -> Option<&Rule> {
132 self.rules.get(fn_name)
133 }
134
135 pub fn from_json(bytes: &[u8]) -> Result<Policy, ConfigError> {
137 let v = json::parse(bytes).map_err(|e| ConfigError::new("policy", e.to_string()))?;
138 let mut rules = BTreeMap::new();
139 for (name, r) in v.as_object().ok_or_else(|| ConfigError::new("policy", "not an object"))? {
140 lexical::check_function_name(name, "$").map_err(|e| ConfigError::new("policy", e.to_string()))?;
141 let rule = if let Some(Value::Array(ps)) = r.get("principals") {
142 Rule::Principals(
143 ps.iter()
144 .map(|p| p.as_str().map(str::to_string).ok_or_else(|| ConfigError::new("policy", "principal")))
145 .collect::<Result<_, _>>()?,
146 )
147 } else if let Some(p) = r.get("price") {
148 let amount =
149 p.get("amount").and_then(Value::as_str).ok_or_else(|| ConfigError::new("policy", "amount"))?;
150 let currency =
151 p.get("currency").and_then(Value::as_str).ok_or_else(|| ConfigError::new("policy", "currency"))?;
152 lexical::check_number(amount, "$").map_err(|e| ConfigError::new("policy", e.to_string()))?;
153 if amount.starts_with('-') || amount == "0" || !lexical::is_currency(currency) {
154 return Err(ConfigError::new("policy", format!("price of {name}")));
155 }
156 Rule::Price { amount: amount.to_string(), currency: currency.to_string() }
157 } else {
158 return Err(ConfigError::new("policy", format!("rule of {name}")));
159 };
160 rules.insert(name.clone(), rule);
161 }
162 Ok(Policy { rules })
163 }
164}
165
166#[non_exhaustive]
168#[derive(Clone, Debug)]
169pub struct Config {
170 pub host: String,
173 pub namespaces: Vec<String>,
176 pub budget: Duration,
178 pub pool_size: usize,
180 pub batch_max: usize,
182 pub slice_page: usize,
184 pub slice_max: usize,
186 pub explain_depth: usize,
188 pub max_jobs: usize,
190 pub rate: RateLimits,
192 pub ttl: Ttls,
194 pub trust_proxy: bool,
197 pub cross_mesh: bool,
199 pub cross_mesh_hosts: Option<Vec<String>>,
202 pub peers: BTreeMap<String, String>,
205 pub peer_timeout: Duration,
207 pub aliases: BTreeMap<String, String>,
209 pub policy: Policy,
211 pub catalog: BTreeMap<String, String>,
213 pub api_keys: ApiKeys,
215}
216
217impl Config {
218 pub fn new(host: impl Into<String>) -> Config {
220 let host = host.into();
221 Config {
222 namespaces: vec![host.clone()],
223 host,
224 budget: DEFAULT_BUDGET,
225 pool_size: DEFAULT_POOL_SIZE,
226 batch_max: DEFAULT_BATCH_MAX,
227 slice_page: DEFAULT_SLICE_PAGE,
228 slice_max: MAX_SLICE_MEMBERS,
229 explain_depth: 4,
230 max_jobs: 10_000,
231 rate: RateLimits::default(),
232 ttl: Ttls::default(),
233 trust_proxy: false,
234 cross_mesh: true,
235 cross_mesh_hosts: None,
236 peers: BTreeMap::new(),
237 peer_timeout: Duration::from_secs(10),
238 aliases: BTreeMap::new(),
239 policy: Policy::default(),
240 catalog: BTreeMap::new(),
241 api_keys: ApiKeys::default(),
242 }
243 }
244
245 pub fn from_env() -> Result<Config, ConfigError> {
249 Config::from_vars(|k| std::env::var(k).ok())
250 }
251
252 pub fn from_vars(get: impl Fn(&str) -> Option<String>) -> Result<Config, ConfigError> {
254 let host = get("DATUMESH_HOST").ok_or_else(|| ConfigError::new("DATUMESH_HOST", "not set"))?;
255 let mut c = Config::new(host);
256 if let Some(v) = get("DATUMESH_NAMESPACES") {
257 c.namespaces = v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
258 }
259 let ms = |k: &str, d: Duration| -> Result<Duration, ConfigError> {
260 match get(k) {
261 Some(v) => v.parse::<u64>().map(Duration::from_millis).map_err(|e| ConfigError::new(k, e.to_string())),
262 None => Ok(d),
263 }
264 };
265 let secs = |k: &str, d: Duration| -> Result<Duration, ConfigError> {
266 match get(k) {
267 Some(v) => v.parse::<u64>().map(Duration::from_secs).map_err(|e| ConfigError::new(k, e.to_string())),
268 None => Ok(d),
269 }
270 };
271 let num = |k: &str, d: usize| -> Result<usize, ConfigError> {
272 match get(k) {
273 Some(v) => v.parse::<usize>().map_err(|e| ConfigError::new(k, e.to_string())),
274 None => Ok(d),
275 }
276 };
277 let flag = |k: &str, d: bool| -> Result<bool, ConfigError> {
278 match get(k).as_deref() {
279 None => Ok(d),
280 Some("1" | "true" | "yes") => Ok(true),
281 Some("0" | "false" | "no") => Ok(false),
282 Some(v) => Err(ConfigError::new(k, format!("not a boolean: {v}"))),
283 }
284 };
285 c.budget = ms("DATUMESH_BUDGET_MS", c.budget)?;
286 c.pool_size = num("DATUMESH_POOL_SIZE", c.pool_size)?;
287 c.batch_max = num("DATUMESH_BATCH_MAX", c.batch_max)?;
288 c.slice_page = num("DATUMESH_SLICE_PAGE", c.slice_page)?;
289 c.slice_max = num("DATUMESH_SLICE_MAX", c.slice_max)?;
290 c.explain_depth = num("DATUMESH_EXPLAIN_DEPTH", c.explain_depth)?;
291 c.max_jobs = num("DATUMESH_MAX_JOBS", c.max_jobs)?;
292 c.trust_proxy = flag("DATUMESH_TRUST_PROXY", c.trust_proxy)?;
293 c.cross_mesh = flag("DATUMESH_CROSS_MESH", c.cross_mesh)?;
294 c.rate.enabled = flag("DATUMESH_RATE_LIMITS", c.rate.enabled)?;
295 c.rate.per_ip = num("DATUMESH_RATE_PER_IP", c.rate.per_ip as usize)? as u32;
296 c.rate.ip_burst = num("DATUMESH_RATE_IP_BURST", c.rate.ip_burst as usize)? as u32;
297 c.rate.per_key = num("DATUMESH_RATE_PER_KEY", c.rate.per_key as usize)? as u32;
298 c.rate.verify_per_ip = num("DATUMESH_RATE_VERIFY_PER_IP", c.rate.verify_per_ip as usize)? as u32;
299 c.ttl.key_doc = secs("DATUMESH_TTL_KEY_DOC", c.ttl.key_doc)?;
300 c.ttl.mesh_doc = secs("DATUMESH_TTL_MESH_DOC", c.ttl.mesh_doc)?;
301 c.ttl.binding = secs("DATUMESH_TTL_BINDING", c.ttl.binding)?;
302 c.ttl.current = secs("DATUMESH_TTL_CURRENT", c.ttl.current)?;
303 c.ttl.latest_max_age = secs("DATUMESH_LATEST_MAX_AGE", c.ttl.latest_max_age)?;
304 c.ttl.job = secs("DATUMESH_JOB_TTL", c.ttl.job)?;
305 c.peer_timeout = ms("DATUMESH_PEER_TIMEOUT_MS", c.peer_timeout)?;
306 if let Some(v) = get("DATUMESH_CROSS_MESH_HOSTS") {
307 c.cross_mesh_hosts = Some(v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect());
308 }
309 if let Some(v) = get("DATUMESH_PEERS") {
310 for pair in v.split(',').map(str::trim).filter(|s| !s.is_empty()) {
311 let (h, o) =
312 pair.split_once('=').ok_or_else(|| ConfigError::new("DATUMESH_PEERS", "host=origin pairs"))?;
313 c.peers.insert(h.trim().to_string(), o.trim().trim_end_matches('/').to_string());
314 }
315 }
316 if let Some(p) = get("DATUMESH_ALIASES_FILE") {
317 c.aliases = string_map(&read_file(&p)?, "DATUMESH_ALIASES_FILE")?;
318 }
319 if let Some(p) = get("DATUMESH_CATALOG_FILE") {
320 c.catalog = string_map(&read_file(&p)?, "DATUMESH_CATALOG_FILE")?;
321 }
322 if let Some(p) = get("DATUMESH_POLICY_FILE") {
323 c.policy = Policy::from_json(&read_file(&p)?)?;
324 }
325 if let Some(p) = get("DATUMESH_API_KEYS_FILE") {
326 c.api_keys = ApiKeys::parse(&read_secret_file(Path::new(&p))?)?;
327 }
328 c.check()?;
329 Ok(c)
330 }
331
332 pub fn check(&self) -> Result<(), ConfigError> {
334 lexical::check_dns_name(&self.host, "$").map_err(|e| ConfigError::new("host", e.to_string()))?;
335 for h in &self.namespaces {
336 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("namespaces", e.to_string()))?;
337 }
338 for (h, o) in &self.peers {
339 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("peers", e.to_string()))?;
340 if !(o.starts_with("http://") || o.starts_with("https://")) {
341 return Err(ConfigError::new("peers", format!("{o}: not an http(s) origin")));
342 }
343 }
344 for (a, n) in &self.aliases {
345 lexical::check_function_name(n, "$").map_err(|e| ConfigError::new("aliases", format!("{a}: {e}")))?;
346 }
347 if self.pool_size == 0 || self.batch_max == 0 || self.slice_page == 0 || self.slice_max == 0 {
348 return Err(ConfigError::new("sizes", "the pool, batch and slice bounds must be positive"));
349 }
350 if self.ttl.job < Duration::from_secs(300) {
351 return Err(ConfigError::new("job TTL", "at least 300 s (SPEC 5.5)"));
352 }
353 if self.budget.is_zero() {
354 return Err(ConfigError::new("budget", "must be positive"));
355 }
356 Ok(())
357 }
358
359 pub fn owns(&self, host: &str) -> bool {
361 self.namespaces.iter().any(|h| h == host)
362 }
363
364 pub fn origin(&self) -> String {
366 format!("https://{}", self.host)
367 }
368}
369
370fn string_map(bytes: &[u8], what: &str) -> Result<BTreeMap<String, String>, ConfigError> {
371 let v = json::parse(bytes).map_err(|e| ConfigError::new(what, e.to_string()))?;
372 let mut out = BTreeMap::new();
373 for (k, x) in v.as_object().ok_or_else(|| ConfigError::new(what, "not an object"))? {
374 let s = x.as_str().ok_or_else(|| ConfigError::new(what, format!("{k}: not a string")))?;
375 out.insert(k.clone(), s.to_string());
376 }
377 Ok(out)
378}
379
380fn read_file(path: &str) -> Result<Vec<u8>, ConfigError> {
381 std::fs::read(path).map_err(|e| ConfigError::new(path, e.to_string()))
382}
383
384pub fn read_secret_file(path: &Path) -> Result<Vec<u8>, ConfigError> {
387 let what = path.display().to_string();
388 let meta = std::fs::metadata(path).map_err(|e| ConfigError::new(&what, e.to_string()))?;
389 #[cfg(unix)]
390 {
391 use std::os::unix::fs::PermissionsExt;
392 let mode = meta.permissions().mode() & 0o777;
393 if mode & 0o077 != 0 {
394 return Err(ConfigError::new(&what, format!("mode {mode:o}: a secret file must be 0600")));
395 }
396 }
397 #[cfg(not(unix))]
398 let _ = meta;
399 std::fs::read(path).map_err(|e| ConfigError::new(&what, e.to_string()))
400}
401
402#[derive(Clone, Debug, PartialEq, Eq)]
404pub struct ConfigError {
405 what: String,
406 detail: String,
407}
408
409impl ConfigError {
410 pub(crate) fn new(what: &str, detail: impl Into<String>) -> ConfigError {
411 ConfigError { what: what.to_string(), detail: detail.into() }
412 }
413}
414
415impl fmt::Display for ConfigError {
416 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417 write!(f, "configuration: {}: {}", self.what, self.detail)
418 }
419}
420
421impl std::error::Error for ConfigError {}