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 calc_per_ip: u32,
50 pub batch_cells_per_token: u32,
53 pub series_per_ip: u32,
56}
57
58impl Default for RateLimits {
59 fn default() -> Self {
60 RateLimits {
61 enabled: true,
62 per_ip: 60,
63 ip_burst: 120,
64 per_key: 600,
65 verify_per_ip: 60,
66 calc_per_ip: 30,
67 batch_cells_per_token: 50,
68 series_per_ip: 30,
69 }
70 }
71}
72
73#[non_exhaustive]
76#[derive(Clone, Debug, PartialEq, Eq)]
77pub struct Ttls {
78 pub key_doc: Duration,
81 pub key_refetch: Duration,
83 pub mesh_doc: Duration,
85 pub binding: Duration,
88 pub current: Duration,
91 pub latest_max_age: Duration,
93 pub job: Duration,
96}
97
98impl Default for Ttls {
99 fn default() -> Self {
100 Ttls {
101 key_doc: Duration::from_secs(300),
102 key_refetch: Duration::from_secs(10),
103 mesh_doc: Duration::from_secs(300),
104 binding: Duration::from_secs(60),
105 current: Duration::from_secs(60),
106 latest_max_age: Duration::from_secs(10),
107 job: Duration::from_secs(300),
108 }
109 }
110}
111
112#[non_exhaustive]
114#[derive(Clone, Debug, PartialEq, Eq)]
115pub enum Rule {
116 Principals(Vec<String>),
119 Price {
122 amount: String,
124 currency: String,
126 },
127}
128
129#[non_exhaustive]
131#[derive(Clone, Debug, Default, PartialEq, Eq)]
132pub struct Policy {
133 pub rules: BTreeMap<String, Rule>,
135}
136
137impl Policy {
138 pub fn rule(&self, fn_name: &str) -> Option<&Rule> {
140 self.rules.get(fn_name)
141 }
142
143 pub fn from_json(bytes: &[u8]) -> Result<Policy, ConfigError> {
145 let v = json::parse(bytes).map_err(|e| ConfigError::new("policy", e.to_string()))?;
146 let mut rules = BTreeMap::new();
147 for (name, r) in v.as_object().ok_or_else(|| ConfigError::new("policy", "not an object"))? {
148 lexical::check_function_name(name, "$").map_err(|e| ConfigError::new("policy", e.to_string()))?;
149 let rule = if let Some(Value::Array(ps)) = r.get("principals") {
150 Rule::Principals(
151 ps.iter()
152 .map(|p| p.as_str().map(str::to_string).ok_or_else(|| ConfigError::new("policy", "principal")))
153 .collect::<Result<_, _>>()?,
154 )
155 } else if let Some(p) = r.get("price") {
156 let amount =
157 p.get("amount").and_then(Value::as_str).ok_or_else(|| ConfigError::new("policy", "amount"))?;
158 let currency =
159 p.get("currency").and_then(Value::as_str).ok_or_else(|| ConfigError::new("policy", "currency"))?;
160 lexical::check_number(amount, "$").map_err(|e| ConfigError::new("policy", e.to_string()))?;
161 if amount.starts_with('-') || amount == "0" || !lexical::is_currency(currency) {
162 return Err(ConfigError::new("policy", format!("price of {name}")));
163 }
164 Rule::Price { amount: amount.to_string(), currency: currency.to_string() }
165 } else {
166 return Err(ConfigError::new("policy", format!("rule of {name}")));
167 };
168 rules.insert(name.clone(), rule);
169 }
170 Ok(Policy { rules })
171 }
172}
173
174#[non_exhaustive]
176#[derive(Clone, Debug)]
177pub struct Config {
178 pub host: String,
181 pub base_url: Option<String>,
200 pub namespaces: Vec<String>,
203 pub budget: Duration,
205 pub pool_size: usize,
207 pub batch_max: usize,
209 pub test_cells: bool,
212 pub slice_page: usize,
214 pub slice_max: usize,
216 pub explain_depth: usize,
218 pub max_jobs: usize,
220 pub rate: RateLimits,
222 pub ttl: Ttls,
224 pub trust_proxy: bool,
227 pub cross_mesh: bool,
229 pub cross_mesh_hosts: Option<Vec<String>>,
232 pub peers: BTreeMap<String, String>,
235 pub peer_timeout: Duration,
237 pub aliases: BTreeMap<String, String>,
239 pub policy: Policy,
241 pub catalog: BTreeMap<String, String>,
243 pub embed_url: Option<String>,
246 pub api_keys: ApiKeys,
248 pub publish_domains: PublishDomains,
251 pub log_dir: Option<std::path::PathBuf>,
254 pub(crate) series: Vec<crate::series::SeriesPage>,
256}
257
258#[non_exhaustive]
262#[derive(Clone, Debug, PartialEq, Eq, Default)]
263pub enum PublishDomains {
264 #[default]
266 Own,
267 Hosts(Vec<String>),
269 Any,
271}
272
273impl PublishDomains {
274 pub fn parse(v: &str) -> Result<PublishDomains, ConfigError> {
277 let v = v.trim();
278 if v.is_empty() {
279 return Ok(PublishDomains::Own);
280 }
281 if v == "*" {
282 return Ok(PublishDomains::Any);
283 }
284 let mut hosts = Vec::new();
285 for h in v.split(',').map(str::trim).filter(|h| !h.is_empty()) {
286 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("DATUMESH_PUBLISH_DOMAINS", e.to_string()))?;
287 hosts.push(h.to_string());
288 }
289 Ok(if hosts.is_empty() { PublishDomains::Own } else { PublishDomains::Hosts(hosts) })
290 }
291
292 pub fn allows(&self, host: &str) -> bool {
294 match self {
295 PublishDomains::Own => false,
296 PublishDomains::Hosts(h) => h.iter().any(|x| x == host),
297 PublishDomains::Any => true,
298 }
299 }
300}
301
302impl Config {
303 pub fn new(host: impl Into<String>) -> Config {
305 let host = host.into();
306 Config {
307 namespaces: vec![host.clone()],
308 host,
309 base_url: None,
310 budget: DEFAULT_BUDGET,
311 pool_size: DEFAULT_POOL_SIZE,
312 batch_max: DEFAULT_BATCH_MAX,
313 test_cells: false,
314 slice_page: DEFAULT_SLICE_PAGE,
315 slice_max: MAX_SLICE_MEMBERS,
316 explain_depth: 4,
317 max_jobs: 10_000,
318 rate: RateLimits::default(),
319 ttl: Ttls::default(),
320 trust_proxy: false,
321 cross_mesh: true,
322 cross_mesh_hosts: None,
323 peers: BTreeMap::new(),
324 peer_timeout: Duration::from_secs(10),
325 aliases: BTreeMap::new(),
326 policy: Policy::default(),
327 catalog: BTreeMap::new(),
328 embed_url: None,
329 api_keys: ApiKeys::default(),
330 publish_domains: PublishDomains::Own,
331 log_dir: None,
332 series: Vec::new(),
333 }
334 }
335
336 pub fn with_base_url(mut self, url: impl Into<String>) -> Config {
339 self.base_url = Some(url.into());
340 self
341 }
342
343 pub fn from_env() -> Result<Config, ConfigError> {
347 Config::from_vars(|k| std::env::var(k).ok())
348 }
349
350 pub fn from_vars(get: impl Fn(&str) -> Option<String>) -> Result<Config, ConfigError> {
352 let host = get("DATUMESH_HOST").ok_or_else(|| ConfigError::new("DATUMESH_HOST", "not set"))?;
353 let mut c = Config::new(host);
354 if let Some(v) = get("DATUMESH_BASE_URL").filter(|v| !v.is_empty()) {
355 c.base_url = Some(v);
356 }
357 if let Some(v) = get("DATUMESH_NAMESPACES") {
358 c.namespaces = v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
359 }
360 let ms = |k: &str, d: Duration| -> Result<Duration, ConfigError> {
361 match get(k) {
362 Some(v) => v.parse::<u64>().map(Duration::from_millis).map_err(|e| ConfigError::new(k, e.to_string())),
363 None => Ok(d),
364 }
365 };
366 let secs = |k: &str, d: Duration| -> Result<Duration, ConfigError> {
367 match get(k) {
368 Some(v) => v.parse::<u64>().map(Duration::from_secs).map_err(|e| ConfigError::new(k, e.to_string())),
369 None => Ok(d),
370 }
371 };
372 let num = |k: &str, d: usize| -> Result<usize, ConfigError> {
373 match get(k) {
374 Some(v) => v.parse::<usize>().map_err(|e| ConfigError::new(k, e.to_string())),
375 None => Ok(d),
376 }
377 };
378 let flag = |k: &str, d: bool| -> Result<bool, ConfigError> {
379 match get(k).as_deref() {
380 None => Ok(d),
381 Some("1" | "true" | "yes") => Ok(true),
382 Some("0" | "false" | "no") => Ok(false),
383 Some(v) => Err(ConfigError::new(k, format!("not a boolean: {v}"))),
384 }
385 };
386 c.budget = ms("DATUMESH_BUDGET_MS", c.budget)?;
387 c.pool_size = num("DATUMESH_POOL_SIZE", c.pool_size)?;
388 c.batch_max = num("DATUMESH_BATCH_MAX", c.batch_max)?;
389 c.test_cells = flag("DATUMESH_TEST_CELLS", c.test_cells)?;
390 c.slice_page = num("DATUMESH_SLICE_PAGE", c.slice_page)?;
391 c.slice_max = num("DATUMESH_SLICE_MAX", c.slice_max)?;
392 c.explain_depth = num("DATUMESH_EXPLAIN_DEPTH", c.explain_depth)?;
393 c.max_jobs = num("DATUMESH_MAX_JOBS", c.max_jobs)?;
394 c.trust_proxy = flag("DATUMESH_TRUST_PROXY", c.trust_proxy)?;
395 c.cross_mesh = flag("DATUMESH_CROSS_MESH", c.cross_mesh)?;
396 c.rate.enabled = flag("DATUMESH_RATE_LIMITS", c.rate.enabled)?;
397 c.rate.per_ip = num("DATUMESH_RATE_PER_IP", c.rate.per_ip as usize)? as u32;
398 c.rate.ip_burst = num("DATUMESH_RATE_IP_BURST", c.rate.ip_burst as usize)? as u32;
399 c.rate.per_key = num("DATUMESH_RATE_PER_KEY", c.rate.per_key as usize)? as u32;
400 c.rate.verify_per_ip = num("DATUMESH_RATE_VERIFY_PER_IP", c.rate.verify_per_ip as usize)? as u32;
401 c.rate.series_per_ip = num("DATUMESH_RATE_SERIES_PER_IP", c.rate.series_per_ip as usize)? as u32;
402 c.rate.calc_per_ip = num("DATUMESH_RATE_CALC_PER_IP", c.rate.calc_per_ip as usize)? as u32;
403 c.ttl.key_doc = secs("DATUMESH_TTL_KEY_DOC", c.ttl.key_doc)?;
404 c.ttl.mesh_doc = secs("DATUMESH_TTL_MESH_DOC", c.ttl.mesh_doc)?;
405 c.ttl.binding = secs("DATUMESH_TTL_BINDING", c.ttl.binding)?;
406 c.ttl.current = secs("DATUMESH_TTL_CURRENT", c.ttl.current)?;
407 c.ttl.latest_max_age = secs("DATUMESH_LATEST_MAX_AGE", c.ttl.latest_max_age)?;
408 c.ttl.job = secs("DATUMESH_JOB_TTL", c.ttl.job)?;
409 c.peer_timeout = ms("DATUMESH_PEER_TIMEOUT_MS", c.peer_timeout)?;
410 if let Some(v) = get("DATUMESH_CROSS_MESH_HOSTS") {
411 c.cross_mesh_hosts = Some(v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect());
412 }
413 if let Some(v) = get("DATUMESH_PEERS") {
414 for pair in v.split(',').map(str::trim).filter(|s| !s.is_empty()) {
415 let (h, o) =
416 pair.split_once('=').ok_or_else(|| ConfigError::new("DATUMESH_PEERS", "host=origin pairs"))?;
417 c.peers.insert(h.trim().to_string(), o.trim().trim_end_matches('/').to_string());
418 }
419 }
420 if let Some(p) = get("DATUMESH_ALIASES_FILE") {
421 c.aliases = string_map(&read_file(&p)?, "DATUMESH_ALIASES_FILE")?;
422 }
423 if let Some(p) = get("DATUMESH_CATALOG_FILE") {
424 c.catalog = string_map(&read_file(&p)?, "DATUMESH_CATALOG_FILE")?;
425 }
426 if let Some(v) = get("DATUMESH_EMBED_URL").filter(|v| !v.trim().is_empty()) {
427 c.embed_url = Some(v.trim().trim_end_matches('/').to_string());
428 }
429 if let Some(p) = get("DATUMESH_POLICY_FILE") {
430 c.policy = Policy::from_json(&read_file(&p)?)?;
431 }
432 if let Some(p) = get("DATUMESH_API_KEYS_FILE") {
433 c.api_keys = ApiKeys::parse(&read_secret_file(Path::new(&p))?)?;
434 }
435 c.publish_domains = PublishDomains::parse(&get("DATUMESH_PUBLISH_DOMAINS").unwrap_or_default())?;
436 if let Some(p) = get("DATUMESH_SERIES_FILE").filter(|p| !p.trim().is_empty()) {
437 c.series = crate::series::parse(&read_file(&p)?)?;
438 }
439 if let Some(d) = get("DATUMESH_LOG_DIR").filter(|d| !d.trim().is_empty()) {
440 c.log_dir = Some(std::path::PathBuf::from(d));
441 }
442 c.check()?;
443 Ok(c)
444 }
445
446 pub fn check(&self) -> Result<(), ConfigError> {
449 lexical::check_dns_name(&self.host, "$").map_err(|e| ConfigError::new("host", e.to_string()))?;
450 if let Some(u) = &self.base_url {
451 check_base_url(&self.host, u).map_err(|e| ConfigError::new("base URL", format!("{u}: {e}")))?;
452 }
453 for h in &self.namespaces {
454 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("namespaces", e.to_string()))?;
455 }
456 for (h, o) in &self.peers {
457 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("peers", e.to_string()))?;
458 if !(o.starts_with("http://") || o.starts_with("https://")) {
459 return Err(ConfigError::new("peers", format!("{o}: not an http(s) origin")));
460 }
461 }
462 for (a, n) in &self.aliases {
463 lexical::check_function_name(n, "$").map_err(|e| ConfigError::new("aliases", format!("{a}: {e}")))?;
464 }
465 if self.pool_size == 0 || self.batch_max == 0 || self.slice_page == 0 || self.slice_max == 0 {
466 return Err(ConfigError::new("sizes", "the pool, batch and slice bounds must be positive"));
467 }
468 if self.ttl.job < Duration::from_secs(300) {
469 return Err(ConfigError::new("job TTL", "at least 300 s (SPEC 5.5)"));
470 }
471 if self.budget.is_zero() {
472 return Err(ConfigError::new("budget", "must be positive"));
473 }
474 Ok(())
475 }
476
477 pub fn owns(&self, host: &str) -> bool {
479 self.namespaces.iter().any(|h| h == host)
480 }
481
482 pub fn origin(&self) -> String {
484 format!("https://{}", self.host)
485 }
486
487 pub fn mesh_document_base(&self) -> String {
490 self.base_url.clone().unwrap_or_else(|| self.origin())
491 }
492}
493
494#[non_exhaustive]
496#[derive(Clone, Copy, Debug, PartialEq, Eq)]
497pub enum BaseUrlError {
498 Scheme,
500 HttpRootedHost,
503 HttpNotLoopback,
506 Host,
509 Port,
511 Path,
513 TrailingSlash,
515 Query,
517 Fragment,
519}
520
521impl fmt::Display for BaseUrlError {
522 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523 f.write_str(match self {
524 BaseUrlError::Scheme => "not an https:// or http:// URL",
525 BaseUrlError::HttpRootedHost => "http:// is for an unrooted host (under .invalid) only",
526 BaseUrlError::HttpNotLoopback => "http:// is for 127.0.0.1, [::1] and localhost only",
527 BaseUrlError::Host => "not a host name, IPv4 address or bracketed IPv6 address",
528 BaseUrlError::Port => "not a port from 1 to 65535",
529 BaseUrlError::Path => "a path (the base URL is a scheme, a host and a port)",
530 BaseUrlError::TrailingSlash => "a trailing slash",
531 BaseUrlError::Query => "a query",
532 BaseUrlError::Fragment => "a fragment",
533 })
534 }
535}
536
537impl std::error::Error for BaseUrlError {}
538
539pub fn check_base_url(host: &str, url: &str) -> Result<(), BaseUrlError> {
546 let mesh_host = host;
547 let (http, rest) = if let Some(r) = url.strip_prefix("https://") {
548 (false, r)
549 } else if let Some(r) = url.strip_prefix("http://") {
550 (true, r)
551 } else {
552 return Err(BaseUrlError::Scheme);
553 };
554 if rest.contains('#') {
555 return Err(BaseUrlError::Fragment);
556 }
557 if rest.contains('?') {
558 return Err(BaseUrlError::Query);
559 }
560 let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
561 match path {
562 "" => {}
563 "/" => return Err(BaseUrlError::TrailingSlash),
564 _ => return Err(BaseUrlError::Path),
565 }
566 if authority.contains('@') {
567 return Err(BaseUrlError::Host);
568 }
569 let (host, port) = if let Some(r) = authority.strip_prefix('[') {
570 let (inside, after) = r.split_once(']').ok_or(BaseUrlError::Host)?;
571 inside.parse::<std::net::Ipv6Addr>().map_err(|_| BaseUrlError::Host)?;
572 let port = match after {
573 "" => None,
574 p => Some(p.strip_prefix(':').ok_or(BaseUrlError::Host)?),
575 };
576 (&authority[..inside.len() + 2], port)
577 } else {
578 let (host, port) = match authority.split_once(':') {
579 Some((h, p)) => (h, Some(p)),
580 None => (authority, None),
581 };
582 if host.parse::<std::net::Ipv4Addr>().is_err() && !is_dns_name(host) {
583 return Err(BaseUrlError::Host);
584 }
585 (host, port)
586 };
587 if let Some(p) = port {
588 let ok = !p.is_empty() && p.len() <= 5 && p.bytes().all(|b| b.is_ascii_digit());
589 if !ok || !(1..=65535).contains(&p.parse::<u32>().unwrap_or(0)) {
590 return Err(BaseUrlError::Port);
591 }
592 }
593 if http && !is_unrooted(mesh_host) {
594 return Err(BaseUrlError::HttpRootedHost);
595 }
596 if http && !matches!(host, "127.0.0.1" | "[::1]" | "localhost") {
597 return Err(BaseUrlError::HttpNotLoopback);
598 }
599 Ok(())
600}
601
602pub fn is_unrooted(host: &str) -> bool {
605 host.rsplit('.').next() == Some("invalid")
606}
607
608fn is_dns_name(h: &str) -> bool {
611 !h.is_empty()
612 && h.len() <= 253
613 && h.split('.').all(|l| {
614 !l.is_empty()
615 && l.len() <= 63
616 && !l.starts_with('-')
617 && !l.ends_with('-')
618 && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
619 })
620}
621
622fn string_map(bytes: &[u8], what: &str) -> Result<BTreeMap<String, String>, ConfigError> {
623 let v = json::parse(bytes).map_err(|e| ConfigError::new(what, e.to_string()))?;
624 let mut out = BTreeMap::new();
625 for (k, x) in v.as_object().ok_or_else(|| ConfigError::new(what, "not an object"))? {
626 let s = x.as_str().ok_or_else(|| ConfigError::new(what, format!("{k}: not a string")))?;
627 out.insert(k.clone(), s.to_string());
628 }
629 Ok(out)
630}
631
632fn read_file(path: &str) -> Result<Vec<u8>, ConfigError> {
633 std::fs::read(path).map_err(|e| ConfigError::new(path, e.to_string()))
634}
635
636pub fn read_secret_file(path: &Path) -> Result<Vec<u8>, ConfigError> {
639 let what = path.display().to_string();
640 let meta = std::fs::metadata(path).map_err(|e| ConfigError::new(&what, e.to_string()))?;
641 #[cfg(unix)]
642 {
643 use std::os::unix::fs::PermissionsExt;
644 let mode = meta.permissions().mode() & 0o777;
645 if mode & 0o077 != 0 {
646 return Err(ConfigError::new(&what, format!("mode {mode:o}: a secret file must be 0600")));
647 }
648 }
649 #[cfg(not(unix))]
650 let _ = meta;
651 std::fs::read(path).map_err(|e| ConfigError::new(&what, e.to_string()))
652}
653
654#[derive(Clone, Debug, PartialEq, Eq)]
656pub struct ConfigError {
657 what: String,
658 detail: String,
659}
660
661impl ConfigError {
662 pub(crate) fn new(what: &str, detail: impl Into<String>) -> ConfigError {
663 ConfigError { what: what.to_string(), detail: detail.into() }
664 }
665}
666
667impl fmt::Display for ConfigError {
668 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
669 write!(f, "configuration: {}: {}", self.what, self.detail)
670 }
671}
672
673impl std::error::Error for ConfigError {}