1use std::collections::{HashMap, HashSet};
2use std::fmt;
3use std::net::SocketAddr;
4use std::path::PathBuf;
5use std::str::FromStr;
6use std::time::Duration;
7
8use clap::Parser;
9use config::{Config, ConfigError, Environment, File, Value, ValueKind};
10use directories::ProjectDirs;
11use libp2p::Multiaddr;
12use serde::Deserialize;
13use sierradb::bucket::{BucketId, PartitionId};
14use sierradb::cache::BLOCK_SIZE;
15use thiserror::Error;
16
17#[derive(Parser, Debug)]
19#[command(version, about, long_about = None)]
20pub struct Args {
21 #[arg(long, short = 'd')]
23 pub dir: Option<String>,
24
25 #[arg(long)]
27 pub client_address: Option<String>,
28
29 #[arg(long)]
31 pub cluster_address: Option<String>,
32
33 #[arg(short = 'c', long)]
35 pub config: Option<PathBuf>,
36
37 #[arg(short = 'l', long)]
39 pub log: Option<String>,
40
41 #[arg(short = 'n', long)]
43 pub node_count: Option<u32>,
44
45 #[arg(short = 'i', long)]
47 pub node_index: Option<u32>,
48
49 #[arg(long)]
51 pub mdns: Option<bool>,
52}
53
54#[derive(Debug, Deserialize)]
55pub struct AppConfig {
56 pub append: AppendConfig,
57 pub bucket: BucketConfig,
58 pub cache: CacheConfig,
59 pub dir: PathBuf,
60 pub heartbeat: HeartbeatConfig,
61 pub network: NetworkConfig,
62 pub node: NodeConfig,
63 pub partition: PartitionConfig,
64 pub replication: ReplicationConfig,
65 pub segment: SegmentConfig,
66 pub sync: SyncConfig,
67 #[serde(default)]
68 pub threads: Threads,
69
70 pub nodes: Option<Vec<Value>>,
71}
72
73#[derive(Debug, Deserialize)]
74pub struct AppendConfig {
75 pub strict_versioning: bool,
76}
77
78#[derive(Debug, Deserialize)]
79pub struct BucketConfig {
80 pub count: u16,
81 pub ids: Option<Vec<BucketId>>,
82}
83
84#[derive(Debug, Deserialize)]
85pub struct CacheConfig {
86 pub capacity_bytes: usize,
87}
88
89#[derive(Debug, Deserialize)]
90pub struct HeartbeatConfig {
91 pub interval_ms: u64,
92 pub timeout_ms: u64,
93}
94
95#[derive(Debug, Deserialize)]
96pub struct NetworkConfig {
97 pub cluster_enabled: bool,
98 pub cluster_address: Multiaddr, pub client_address: String, pub mdns: bool,
101}
102
103#[derive(Debug, Deserialize)]
104pub struct NodeConfig {
105 pub count: Option<u32>,
106 pub index: u32,
107}
108
109#[derive(Debug, Deserialize)]
110pub struct PartitionConfig {
111 pub count: u16,
112 pub ids: Option<Vec<PartitionId>>,
113}
114
115#[derive(Debug, Deserialize)]
116pub struct ReplicationConfig {
117 pub buffer_size: usize,
118 pub buffer_timeout_ms: u64,
119 pub catchup_timeout_ms: u64,
120 pub factor: u8,
121}
122
123#[derive(Debug, Deserialize)]
124pub struct SegmentConfig {
125 pub size_bytes: usize,
126 pub compression: bool,
127}
128
129#[derive(Debug, Deserialize)]
130pub struct SyncConfig {
131 pub interval_ms: u64,
133 pub idle_interval_ms: Option<u64>,
135 pub max_batch_size: usize,
137 pub min_bytes: usize,
139}
140
141#[derive(Debug, Default, Deserialize)]
142pub struct Threads {
143 pub read: Option<u16>,
144 pub write: Option<u16>,
145}
146
147impl AppConfig {
148 pub fn load(args: Args) -> Result<Self, ConfigError> {
151 let project_dirs = ProjectDirs::from("io", "sierradb", "sierradb");
152
153 let mut builder = Config::builder();
154
155 if let Some(dirs) = &project_dirs {
156 builder = builder.set_default(
163 "dir",
164 dirs.data_dir().join("db").to_string_lossy().into_owned(),
165 )?
166 }
167
168 if let Some(config_path) = args.config {
170 builder = builder.add_source(File::from(config_path));
171 } else {
172 builder = builder.add_source(File::with_name("sierra").required(false));
174 if let Some(dirs) = &project_dirs {
175 builder = builder
184 .add_source(File::from(dirs.config_dir().join("sierra")).required(false));
185 }
186 }
187
188 let overrides = builder.build_cloned()?;
189
190 builder = builder
191 .set_default("append.strict_versioning", true)?
192 .set_default("bucket.count", 4)?
193 .set_default("cache.capacity_bytes", 256 * 1024 * 1024)?
194 .set_default("heartbeat.interval_ms", 1000)?
195 .set_default("heartbeat.timeout_ms", 6000)?
196 .set_default("network.cluster_enabled", true)?
197 .set_default("network.cluster_address", "/ip4/0.0.0.0/tcp/0")?
198 .set_default("network.client_address", "0.0.0.0:9090")?
199 .set_default("network.mdns", false)?
200 .set_default("partition.count", 32)?
201 .set_default("replication.buffer_size", 1000)?
202 .set_default("replication.buffer_timeout_ms", 8000)?
203 .set_default("replication.catchup_timeout_ms", 2000)?
204 .set_default("segment.size_bytes", 256 * 1024 * 1024)?
205 .set_default("segment.compression", true)?
206 .set_default("sync.interval_ms", 5)?
207 .set_default("sync.max_batch_size", 50)?
208 .set_default("sync.min_bytes", 4096)?;
209
210 {
212 let mut nodes = overrides.get_array("nodes").ok().unwrap_or_default();
213 let nodes_count = if nodes.is_empty() {
214 1
215 } else {
216 nodes.len() as u32
217 };
218 builder = builder.set_default("node.count", nodes_count)?;
219
220 let node_index = args
221 .node_index
222 .or_else(|| overrides.get_int("node.index").map(|n| n as u32).ok());
223 if let Some(node_index) = node_index
224 && (node_index as usize) < nodes.len()
225 {
226 let overrides = nodes.remove(node_index as usize);
227 for (key, value) in flatten_value(overrides) {
228 builder = builder.set_override(key, value)?;
229 }
230 }
231 }
232
233 builder = builder.add_source(Environment::with_prefix("SIERRA"));
235
236 builder = builder
238 .set_override_option("dir", args.dir)?
239 .set_override_option("network.cluster_address", args.cluster_address)?
240 .set_override_option("network.client_address", args.client_address)?
241 .set_override_option("network.mdns", args.mdns)?
242 .set_override_option("node.index", args.node_index)?
243 .set_override_option("node.count", args.node_count)?;
244
245 {
246 let temp_config = builder.build_cloned()?;
248 let node_count = temp_config.get::<u32>("node.count").unwrap_or(1);
249 builder = builder.set_default("replication.factor", node_count.clamp(1, 3))?;
250
251 let node_index_set =
253 args.node_index.is_some() || temp_config.get::<u32>("node.index").is_ok();
254
255 if node_count == 1 && !node_index_set {
256 builder = builder.set_override("node.index", 0)?;
258 } else if node_count > 1 && !node_index_set {
259 return Err(ConfigError::Message(
261 "node.index is required when node.count > 1 (use --node-index or set in config file)".to_string(),
262 ));
263 }
264 }
265
266 let config: AppConfig = builder.build()?.try_deserialize()?;
267
268 Ok(config)
269 }
270
271 pub fn validate(&self) -> Result<Vec<ValidationError>, ConfigError> {
272 let mut errs = Vec::new();
273
274 if self.bucket.count == 0 {
276 errs.push(ValidationError::BucketCountZero);
277 }
278 if let Some(ids) = &self.bucket.ids {
279 if ids.len() != self.bucket.count as usize {
280 errs.push(ValidationError::BucketIdCountMismatch {
281 expected: self.bucket.count,
282 actual: ids.len(),
283 });
284 }
285 let unique_ids: HashSet<_> = ids.iter().collect();
286 if unique_ids.len() != ids.len() {
287 errs.push(ValidationError::DuplicateBucketIds);
288 }
289 }
290
291 if self.heartbeat.interval_ms == 0 {
293 errs.push(ValidationError::HeartbeatIntervalZero);
294 }
295 if self.heartbeat.timeout_ms == 0 {
296 errs.push(ValidationError::HeartbeatTimeoutZero);
297 }
298 if self.heartbeat.timeout_ms <= self.heartbeat.interval_ms {
299 errs.push(ValidationError::HeartbeatTimeoutTooShort {
300 interval: self.heartbeat.interval_ms,
301 timeout: self.heartbeat.timeout_ms,
302 });
303 }
304
305 if SocketAddr::from_str(&self.network.client_address).is_err() {
307 errs.push(ValidationError::InvalidClientAddress {
308 address: self.network.client_address.clone(),
309 });
310 }
311
312 if let Some(count) = self.node.count {
314 if count == 0 {
315 errs.push(ValidationError::NodeCountZero);
316 }
317 if self.node.index >= count {
318 errs.push(ValidationError::NodeIndexOutOfBounds {
319 index: self.node.index,
320 count,
321 });
322 }
323 }
324
325 if !self.network.cluster_enabled {
327 if let Some(count) = self.node.count
329 && count > 1
330 {
331 errs.push(ValidationError::MultipleNodesWithoutCluster { count });
332 }
333 }
334
335 if self.partition.count == 0 {
337 errs.push(ValidationError::PartitionCountZero);
338 }
339 if let Some(ids) = &self.partition.ids {
340 if ids.len() != self.partition.count as usize {
341 errs.push(ValidationError::PartitionIdCountMismatch {
342 expected: self.partition.count,
343 actual: ids.len(),
344 });
345 }
346 let unique_ids: HashSet<_> = ids.iter().collect();
347 if unique_ids.len() != ids.len() {
348 errs.push(ValidationError::DuplicatePartitionIds);
349 }
350 }
351
352 if self.replication.factor == 0 {
354 errs.push(ValidationError::ReplicationFactorZero);
355 }
356 if self.replication.buffer_size == 0 {
357 errs.push(ValidationError::ReplicationBufferSizeZero);
358 }
359 if self.replication.buffer_timeout_ms == 0 {
360 errs.push(ValidationError::ReplicationBufferTimeoutZero);
361 }
362 if self.replication.catchup_timeout_ms == 0 {
363 errs.push(ValidationError::ReplicationCatchupTimeoutZero);
364 }
365
366 let node_count = self.node_count()?;
368 if self.replication.factor as usize > node_count {
369 errs.push(ValidationError::ReplicationFactorExceedsNodeCount {
370 factor: self.replication.factor,
371 node_count,
372 });
373 }
374
375 if self.segment.size_bytes == 0 {
377 errs.push(ValidationError::SegmentSizeZero);
378 }
379 const MIN_SEGMENT_SIZE: usize = BLOCK_SIZE * 2; const MAX_SEGMENT_SIZE: usize = 1024 * 1024 * 1024 * 10; if self.segment.size_bytes < MIN_SEGMENT_SIZE {
382 errs.push(ValidationError::SegmentSizeTooSmall {
383 size: self.segment.size_bytes,
384 min: MIN_SEGMENT_SIZE,
385 });
386 }
387 if self.segment.size_bytes > MAX_SEGMENT_SIZE {
388 errs.push(ValidationError::SegmentSizeTooLarge {
389 size: self.segment.size_bytes,
390 max: MAX_SEGMENT_SIZE,
391 });
392 }
393
394 if let Some(idle_interval_ms) = self.sync.idle_interval_ms
396 && self.sync.interval_ms <= idle_interval_ms
397 {
398 errs.push(ValidationError::SyncIdleIntervalTooSmall {
399 interval_ms: self.sync.interval_ms,
400 idle_interval_ms,
401 });
402 }
403
404 if let Some(read_threads) = self.threads.read {
406 if read_threads == 0 {
407 errs.push(ValidationError::ReadThreadsZero);
408 }
409 const MAX_THREADS: u16 = 1024;
410 if read_threads > MAX_THREADS {
411 errs.push(ValidationError::TooManyReadThreads {
412 count: read_threads,
413 max: MAX_THREADS,
414 });
415 }
416 }
417 if let Some(write_threads) = self.threads.write {
418 if write_threads == 0 {
419 errs.push(ValidationError::WriteThreadsZero);
420 }
421 const MAX_THREADS: u16 = 1024;
422 if write_threads > MAX_THREADS {
423 errs.push(ValidationError::TooManyWriteThreads {
424 count: write_threads,
425 max: MAX_THREADS,
426 });
427 }
428 }
429
430 if (self.partition.count as usize) < node_count {
432 errs.push(ValidationError::TooFewPartitionsForNodes {
433 partitions: self.partition.count,
434 nodes: node_count,
435 });
436 }
437 if self.partition.count < self.bucket.count {
438 errs.push(ValidationError::TooFewPartitionsForBuckets {
439 buckets: self.bucket.count,
440 partitions: self.partition.count,
441 });
442 }
443
444 Ok(errs)
445 }
446
447 pub fn assigned_buckets(&self) -> Result<HashSet<BucketId>, ConfigError> {
448 match &self.bucket.ids {
449 Some(ids) => Ok(ids.iter().copied().collect()),
450 None => {
451 let node_count = self.node_count()?;
452 let effective_replication_factor =
453 (self.replication.factor as usize).min(node_count);
454 let mut assigned = HashSet::new();
455
456 let buckets_per_node = self.bucket.count as usize / node_count;
457 let extra_buckets = self.bucket.count as usize % node_count;
458
459 for replica_offset in 0..effective_replication_factor {
461 let primary_node =
463 (self.node.index as usize + node_count - replica_offset) % node_count;
464
465 let start = primary_node * buckets_per_node + primary_node.min(extra_buckets);
467 let extra = if primary_node < extra_buckets { 1 } else { 0 };
468 let count = buckets_per_node + extra;
469
470 for bucket_id in start..(start + count) {
472 assigned.insert(bucket_id.try_into().unwrap());
473 }
474 }
475
476 Ok(assigned)
477 }
478 }
479 }
480
481 pub fn assigned_partitions(&self, bucket_ids: &HashSet<BucketId>) -> HashSet<PartitionId> {
482 match &self.partition.ids {
483 Some(ids) => ids.iter().copied().collect(),
484 None => (0..self.partition.count)
485 .filter(|p| bucket_ids.contains(&(p % self.bucket.count)))
486 .collect(),
487 }
488 }
489
490 pub fn node_count(&self) -> Result<usize, ConfigError> {
491 self.node
492 .count
493 .map(|node_count| node_count as usize)
494 .or(self.nodes.as_ref().map(|nodes| nodes.len()))
495 .ok_or_else(|| ConfigError::Message("node.count not specified".to_string()))
496 }
497
498 pub fn effective_idle_interval(&self) -> Duration {
499 let active_interval = Duration::from_millis(self.sync.interval_ms);
500 self.sync
501 .idle_interval_ms
502 .map(Duration::from_millis)
503 .unwrap_or_else(|| {
504 (active_interval * 10).min(Duration::from_secs(1))
506 })
507 }
508}
509
510impl fmt::Display for AppConfig {
511 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512 writeln!(
513 f,
514 "append.strict_versioning = {}",
515 self.append.strict_versioning
516 )?;
517
518 writeln!(f, "bucket.count = {}", self.bucket.count)?;
519 match &self.bucket.ids {
520 Some(ids) => writeln!(
521 f,
522 "bucket.ids = [{}]",
523 ids.iter()
524 .map(|id| id.to_string())
525 .collect::<Vec<_>>()
526 .join(", ")
527 )?,
528 None => writeln!(f, "bucket.ids = <none>")?,
529 }
530
531 writeln!(f, "cache.capacity_bytes = {}", self.cache.capacity_bytes)?;
532
533 writeln!(f, "dir = {}", self.dir.to_string_lossy())?;
534
535 writeln!(f, "heartbeat.interval_ms = {}", self.heartbeat.interval_ms)?;
536 writeln!(f, "heartbeat.timeout_ms = {}", self.heartbeat.timeout_ms)?;
537
538 writeln!(
539 f,
540 "network.cluster_enabled = {}",
541 self.network.cluster_enabled
542 )?;
543 writeln!(
544 f,
545 "network.cluster_address = {}",
546 self.network.cluster_address
547 )?;
548 writeln!(
549 f,
550 "network.client_address = {}",
551 self.network.client_address
552 )?;
553 writeln!(f, "network.mdns = {}", self.network.mdns)?;
554
555 match self.node_count() {
556 Ok(count) => writeln!(f, "node.count = {count}")?,
557 Err(_) => writeln!(f, "node.count = <none>")?,
558 }
559 writeln!(f, "node.index = {}", self.node.index)?;
560
561 writeln!(f, "partition.count = {}", self.partition.count)?;
562 match &self.partition.ids {
563 Some(ids) => writeln!(
564 f,
565 "partition.ids = [{}]",
566 ids.iter()
567 .map(|id| id.to_string())
568 .collect::<Vec<_>>()
569 .join(", ")
570 )?,
571 None => writeln!(f, "partition.ids = <none>")?,
572 }
573
574 writeln!(
575 f,
576 "replication.buffer_size = {}",
577 self.replication.buffer_size
578 )?;
579 writeln!(
580 f,
581 "replication.buffer_timeout_ms = {}",
582 self.replication.buffer_timeout_ms
583 )?;
584 writeln!(f, "replication.factor = {}", self.replication.factor)?;
585
586 writeln!(f, "segment.size_bytes = {}", self.segment.size_bytes)?;
587 writeln!(f, "segment.compression = {}", self.segment.compression)?;
588
589 writeln!(f, "sync.interval_ms = {}", self.sync.interval_ms)?;
590 writeln!(
591 f,
592 "sync.idle_interval_ms = {}",
593 self.effective_idle_interval().as_millis()
594 )?;
595 writeln!(f, "sync.max_batch_size = {}", self.sync.max_batch_size)?;
596 writeln!(f, "sync.min_bytes = {}", self.sync.min_bytes)?;
597
598 match self.threads.read {
599 Some(count) => writeln!(f, "threads.read = {count}")?,
600 None => writeln!(f, "threads.read = <none>")?,
601 }
602 match self.threads.write {
603 Some(count) => write!(f, "threads.write = {count}")?,
604 None => write!(f, "threads.write = <none>")?,
605 }
606
607 Ok(())
608 }
609}
610
611fn flatten_value(value: Value) -> HashMap<String, Value> {
612 let mut result = HashMap::new();
613 flatten_value_recursive(value, "", &mut result);
614 result
615}
616
617fn flatten_value_recursive(value: Value, prefix: &str, result: &mut HashMap<String, Value>) {
618 match value.kind {
619 ValueKind::Table(table) => {
620 for (key, val) in table {
621 let new_prefix = if prefix.is_empty() {
622 key
623 } else {
624 format!("{prefix}.{key}")
625 };
626
627 match val.kind {
628 ValueKind::Table(_) => {
629 flatten_value_recursive(val, &new_prefix, result);
630 }
631 _ => {
632 result.insert(new_prefix, val);
633 }
634 }
635 }
636 }
637 _ => {
638 if !prefix.is_empty() {
639 result.insert(prefix.to_string(), value);
640 }
641 }
642 }
643}
644
645#[derive(Clone, Debug, Error)]
646pub enum ValidationError {
647 #[error("bucket count cannot be zero")]
649 BucketCountZero,
650 #[error("bucket ID count mismatch: expected {expected}, got {actual}")]
651 BucketIdCountMismatch { expected: u16, actual: usize },
652 #[error("duplicate bucket IDs found")]
653 DuplicateBucketIds,
654
655 #[error("heartbeat interval cannot be zero")]
657 HeartbeatIntervalZero,
658 #[error("heartbeat timeout cannot be zero")]
659 HeartbeatTimeoutZero,
660 #[error("heartbeat timeout ({timeout}ms) must be greater than interval ({interval}ms)")]
661 HeartbeatTimeoutTooShort { interval: u64, timeout: u64 },
662
663 #[error("invalid client address: {address}")]
665 InvalidClientAddress { address: String },
666
667 #[error("node count cannot be zero")]
669 NodeCountZero,
670 #[error("node index {index} is out of bounds for count {count}")]
671 NodeIndexOutOfBounds { index: u32, count: u32 },
672 #[error("multiple nodes ({count}) configured but cluster is disabled")]
673 MultipleNodesWithoutCluster { count: u32 },
674
675 #[error("partition count cannot be zero")]
677 PartitionCountZero,
678 #[error("partition ID count mismatch: expected {expected}, got {actual}")]
679 PartitionIdCountMismatch { expected: u16, actual: usize },
680 #[error("duplicate partition IDs found")]
681 DuplicatePartitionIds,
682
683 #[error("replication factor cannot be zero")]
685 ReplicationFactorZero,
686 #[error("replication factor {factor} exceeds node count {node_count}")]
687 ReplicationFactorExceedsNodeCount { factor: u8, node_count: usize },
688 #[error("replication buffer size cannot be zero")]
689 ReplicationBufferSizeZero,
690 #[error("replication buffer timeout cannot be zero")]
691 ReplicationBufferTimeoutZero,
692 #[error("replication catchup timeout cannot be zero")]
693 ReplicationCatchupTimeoutZero,
694
695 #[error("segment size cannot be zero")]
697 SegmentSizeZero,
698 #[error("segment size {size} is too small (minimum: {min} bytes)")]
699 SegmentSizeTooSmall { size: usize, min: usize },
700 #[error("segment size {size} is too large (maximum: {max} bytes)")]
701 SegmentSizeTooLarge { size: usize, max: usize },
702
703 #[error(
705 "idle sync interval {idle_interval_ms} cannot be less than sync interval {interval_ms}"
706 )]
707 SyncIdleIntervalTooSmall {
708 interval_ms: u64,
709 idle_interval_ms: u64,
710 },
711
712 #[error("read thread count cannot be zero")]
714 ReadThreadsZero,
715 #[error("write thread count cannot be zero")]
716 WriteThreadsZero,
717 #[error("too many read threads: {count} (maximum: {max})")]
718 TooManyReadThreads { count: u16, max: u16 },
719 #[error("too many write threads: {count} (maximum: {max})")]
720 TooManyWriteThreads { count: u16, max: u16 },
721
722 #[error("too few partitions ({partitions}) for {nodes} nodes")]
724 TooFewPartitionsForNodes { partitions: u16, nodes: usize },
725 #[error("too few partitions ({partitions}) for {buckets} buckets")]
726 TooFewPartitionsForBuckets { buckets: u16, partitions: u16 },
727}