Skip to main content

ursula_config/
config.rs

1use std::path::PathBuf;
2
3use serde::Deserialize;
4use serde::Serialize;
5
6use crate::human::HumanDuration;
7use crate::human::HumanSize;
8
9/// Cold-storage backend selector.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
11#[serde(rename_all = "lowercase")]
12pub enum ColdBackend {
13    #[default]
14    #[serde(alias = "disabled", alias = "off")]
15    None,
16    #[serde(alias = "mem", alias = "inmem")]
17    Memory,
18    S3,
19}
20
21/// Raft WAL persistence backend selector.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
23#[serde(rename_all = "lowercase")]
24pub enum WalBackend {
25    #[default]
26    Memory,
27    Disk,
28}
29
30/// Raft snapshot store backend selector.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
32#[serde(rename_all = "lowercase")]
33pub enum RaftSnapshotBackend {
34    #[default]
35    #[serde(alias = "default", alias = "")]
36    Inline,
37    S3,
38}
39
40/// Top-level Ursula server configuration.
41///
42/// Populated from a TOML config file, an optional preset, and CLI overrides.
43#[derive(Debug, Clone, Default, Deserialize, Serialize)]
44#[serde(default, deny_unknown_fields)]
45pub struct UrsulaConfig {
46    pub server: ServerConfig,
47    pub runtime: RuntimeConfig,
48    pub raft: RaftConfig,
49    pub storage: StorageConfig,
50    pub governance: GovernanceConfig,
51    pub observability: ObservabilityConfig,
52}
53
54/// HTTP server binding and admission settings.
55#[derive(Debug, Clone, Deserialize, Serialize)]
56#[serde(default, deny_unknown_fields)]
57pub struct ServerConfig {
58    /// Public HTTP client API bind address.
59    pub listen: String,
60    /// Optional separate bind for the cluster / Raft gRPC plane.
61    /// When omitted, both planes share `listen`.
62    pub cluster_listen: Option<String>,
63    /// Admin-plane bind for mutating operator endpoints (raft ops,
64    /// maintenance drain, cold-flush trigger). Loopback by default so nodes
65    /// expose no cluster-mutation surface on the network; operator tooling
66    /// reaches it through an SSH/SSM/port-forward tunnel.
67    pub admin_listen: String,
68    /// Process-wide cap on accepted write body bytes held by the HTTP layer.
69    pub http_inflight_body_size: HumanSize,
70}
71
72impl Default for ServerConfig {
73    fn default() -> Self {
74        Self {
75            listen: "127.0.0.1:4437".to_string(),
76            cluster_listen: None,
77            admin_listen: "127.0.0.1:4438".to_string(),
78            http_inflight_body_size: HumanSize::mib(256),
79        }
80    }
81}
82
83/// Per-core runtime sizing and admission controls.
84#[derive(Debug, Clone, Deserialize, Serialize)]
85#[serde(default, deny_unknown_fields)]
86pub struct RuntimeConfig {
87    /// Number of CPU cores / tokio worker threads to use.
88    pub core_count: usize,
89    /// Soft RSS cap. When the process RSS exceeds this value, new writes are
90    /// rejected with HTTP 503. `None` disables the monitor.
91    pub node_memory_abort_cap_size: Option<HumanSize>,
92    /// Minimum payload size that triggers external cold-store staging instead
93    /// of inline hot-ring storage. `None` uses the default (1 MiB).
94    pub external_payload_min_size: Option<HumanSize>,
95    /// Max live-read waiters per core. `None` or `0` disables the limit.
96    pub live_read_max_waiters_per_core: Option<usize>,
97}
98
99impl Default for RuntimeConfig {
100    fn default() -> Self {
101        Self {
102            core_count: std::thread::available_parallelism()
103                .map(|n| n.get())
104                .unwrap_or(4),
105            node_memory_abort_cap_size: None,
106            external_payload_min_size: None,
107            live_read_max_waiters_per_core: Some(65_536),
108        }
109    }
110}
111
112/// Raft consensus and static-cluster networking configuration.
113#[derive(Debug, Clone, Deserialize, Serialize)]
114#[serde(default, deny_unknown_fields)]
115pub struct RaftConfig {
116    /// Unique node ID within the static gRPC Raft cluster.
117    /// Must be present in `peers` and must be non-zero.
118    pub node_id: u64,
119    /// Number of Raft groups (shards). Defaults to `core_count * 16`.
120    pub group_count: usize,
121    /// Per-group cap on raft-submitted-but-not-yet-applied payload bytes.
122    /// `None` or `0` disables the admission. Catches raft replication lag before
123    /// in-memory queues grow unbounded.
124    pub max_uncommitted_size_per_group: Option<HumanSize>,
125    /// Bootstrap the initial Raft membership once on startup.
126    pub init_membership: bool,
127    /// Bootstrap per-group Raft membership on startup.
128    pub init_membership_per_group: bool,
129    /// Raft WAL configuration.
130    pub wal: WalConfig,
131    /// Static gRPC Raft peers. Each entry maps a `node_id` to its gRPC URL.
132    pub peers: Vec<RaftPeerConfig>,
133    /// Optional per-group voter assignments.
134    ///
135    /// When empty (the default), every Raft group uses all peers as voters.
136    /// When supplied, every group in `0..group_count` must have an entry and
137    /// each entry's voters must be a non-empty subset of `peers`.
138    #[serde(default)]
139    pub groups: Vec<RaftGroupConfig>,
140    /// How long a restarting node waits to observe an already-established
141    /// (or freshly re-elected) leader before deciding the group is truly new
142    /// and bootstrapping it. Must exceed the election window.
143    pub rejoin_probe: HumanDuration,
144    /// Timeout for probing static peers during bootstrap before logging a
145    /// warning. Continues retrying indefinitely.
146    pub bootstrap_peer_probe: HumanDuration,
147    /// Interval between static-peer reachability probes during bootstrap.
148    pub bootstrap_peer_probe_interval: HumanDuration,
149    /// gRPC connect timeout when probing static peers.
150    pub bootstrap_peer_connect: HumanDuration,
151    /// OpenRaft's `install_snapshot_timeout` covers the whole FullSnapshot RPC.
152    /// The receiver downloads and installs the referenced object before
153    /// replying, so this must be comfortably above the S3 per-attempt timeout
154    /// plus retries.
155    pub install_snapshot_timeout: HumanDuration,
156    /// Directory for memory-bootstrap marker files. When set, each group
157    /// writes a marker after successful membership initialization. On restart,
158    /// a marked memory group rejoins an observed leader or reinitializes
159    /// volatile membership if no leader exists.
160    pub memory_bootstrap_marker_dir: Option<PathBuf>,
161    /// Consecutive gRPC RPC failures before forcing a transport reconnect.
162    pub grpc_reconnect_after_failures: usize,
163    /// Max concurrent snapshot builds across all groups on this node.
164    pub snapshot_build_max_concurrency: usize,
165    /// Max concurrent snapshot installs across all groups on this node.
166    pub snapshot_install_max_concurrency: usize,
167    /// Committed Raft log entries per group between automatic snapshots.
168    /// Larger values reduce full-state snapshot CPU and tail-latency spikes at
169    /// the cost of retaining more log entries for recovery.
170    pub snapshot_logs_since_last: u64,
171    /// Maximum number of payload-bearing Raft log entries retained per group
172    /// after they are covered by a snapshot.
173    pub max_in_snapshot_log_to_keep: u64,
174}
175
176impl Default for RaftConfig {
177    fn default() -> Self {
178        Self {
179            node_id: 0,
180            group_count: std::thread::available_parallelism()
181                .map(|n| n.get().saturating_mul(16).max(1))
182                .unwrap_or(16),
183            max_uncommitted_size_per_group: None,
184            init_membership: false,
185            init_membership_per_group: false,
186            wal: WalConfig::default(),
187            peers: Vec::new(),
188            groups: Vec::new(),
189            rejoin_probe: HumanDuration::sec(6),
190            bootstrap_peer_probe: HumanDuration::sec(60),
191            bootstrap_peer_probe_interval: HumanDuration::milli(250),
192            bootstrap_peer_connect: HumanDuration::milli(500),
193            install_snapshot_timeout: HumanDuration::sec(120),
194            memory_bootstrap_marker_dir: None,
195            grpc_reconnect_after_failures: 8,
196            snapshot_build_max_concurrency: 1,
197            snapshot_install_max_concurrency: 1,
198            snapshot_logs_since_last: 5_000,
199            max_in_snapshot_log_to_keep: 64,
200        }
201    }
202}
203
204/// Raft write-ahead log configuration.
205#[derive(Debug, Clone, Deserialize, Serialize)]
206#[serde(default, deny_unknown_fields)]
207pub struct WalConfig {
208    /// WAL persistence backend.
209    pub backend: WalBackend,
210    /// Directory for on-disk WAL files. Required when `backend` is `Disk`.
211    pub path: Option<PathBuf>,
212}
213
214impl WalConfig {
215    /// Resolved on-disk log directory for the Raft WAL.
216    ///
217    /// When `backend` is `Disk` and `path` is set, appends the legacy
218    /// `raft-log` subdirectory so that existing data directories continue
219    /// to work after the config refactor.
220    pub fn resolved_path(&self) -> Option<PathBuf> {
221        match self.backend {
222            WalBackend::Memory => None,
223            WalBackend::Disk => self.path.as_ref().map(|p| p.join("raft-log")),
224        }
225    }
226}
227
228impl Default for WalConfig {
229    fn default() -> Self {
230        Self {
231            backend: WalBackend::Memory,
232            path: None,
233        }
234    }
235}
236
237/// A single static gRPC Raft peer.
238#[derive(Debug, Clone, Deserialize, Serialize)]
239#[serde(deny_unknown_fields)]
240pub struct RaftPeerConfig {
241    /// Peer node ID.
242    pub node_id: u64,
243    /// Peer gRPC URL.
244    pub url: String,
245}
246
247/// Per-group voter assignment for heterogeneous static clusters.
248///
249/// When omitted (the default), every group uses all peers as voters.
250#[derive(Debug, Clone, Deserialize, Serialize)]
251#[serde(deny_unknown_fields)]
252pub struct RaftGroupConfig {
253    /// Raft group ID.
254    pub raft_group_id: u32,
255    /// Node IDs that are voters for this group.
256    pub voters: Vec<u64>,
257}
258
259/// Storage tier configuration.
260#[derive(Debug, Clone, Default, Deserialize, Serialize)]
261#[serde(default, deny_unknown_fields)]
262pub struct StorageConfig {
263    /// Cold-tier (opendal-backed object store) configuration.
264    pub cold: ColdConfig,
265    /// Raft snapshot store configuration.
266    pub snapshot: RaftSnapshotConfig,
267}
268
269/// Cold-tier flush, GC, and cache configuration.
270#[derive(Debug, Clone, Deserialize, Serialize)]
271#[serde(default, deny_unknown_fields)]
272pub struct ColdConfig {
273    /// Cold-storage backend.
274    pub backend: ColdBackend,
275    /// Root prefix for cold-storage objects (e.g. S3 prefix or local dir).
276    pub root: Option<String>,
277    /// S3-specific connection and credential settings.
278    /// Required when `backend` is `S3`.
279    pub s3: Option<S3Config>,
280    /// Optional cold-read cache.
281    pub cache: Option<ColdCacheConfig>,
282    /// Interval between periodic cold-flush passes. Must be non-zero.
283    pub flush_interval: HumanDuration,
284    /// Target number of hot bytes to flush per group per pass.
285    pub flush_size: HumanSize,
286    /// Minimum hot bytes a group must have before it is eligible for flush.
287    /// Falls back to [`flush_size`](Self::flush_size) when unset.
288    pub flush_min_hot_size: Option<HumanSize>,
289    /// Upper bound on bytes flushed per group per pass.
290    /// Falls back to [`flush_size`](Self::flush_size) when unset.
291    pub flush_max_size: Option<HumanSize>,
292    /// Max groups flushed concurrently.
293    pub flush_max_concurrency: usize,
294    /// Enable background same-stream cold chunk compaction.
295    pub compaction_enabled: bool,
296    /// Interval between cold chunk compaction discovery passes.
297    pub compaction_interval: HumanDuration,
298    /// Preferred compacted object size.
299    pub compaction_target_size: HumanSize,
300    /// Hard maximum compacted object size.
301    pub compaction_max_size: HumanSize,
302    /// Maximum streams compacted per pass.
303    pub compaction_max_streams_per_pass: usize,
304    /// Grace period before compacted input objects are physically deleted.
305    pub compaction_gc_grace: HumanDuration,
306    /// Per-group hot-size cap. When a group's hot bytes exceed this, new
307    /// writes are rejected with HTTP 503. `None` or `0` disables the admission.
308    pub max_hot_size_per_group: Option<HumanSize>,
309    /// Interval between periodic cold-gc passes. Must be non-zero.
310    pub gc_interval: HumanDuration,
311    /// Max GC entries to process per group per pass.
312    pub gc_max_entries: usize,
313}
314
315impl ColdConfig {
316    /// Minimum hot bytes a group must have before it is eligible for flush.
317    ///
318    /// Falls back to [`flush_size`](Self::flush_size) when the user does not
319    /// supply an explicit value.
320    pub fn flush_min_hot_size(&self) -> HumanSize {
321        self.flush_min_hot_size.unwrap_or(self.flush_size)
322    }
323
324    /// Upper bound on bytes flushed per group per pass.
325    ///
326    /// Falls back to [`flush_size`](Self::flush_size) when the user does not
327    /// supply an explicit value.
328    pub fn flush_max_size(&self) -> HumanSize {
329        self.flush_max_size.unwrap_or(self.flush_size)
330    }
331}
332
333impl Default for ColdConfig {
334    fn default() -> Self {
335        Self {
336            backend: ColdBackend::None,
337            root: None,
338            s3: None,
339            cache: None,
340            flush_interval: HumanDuration::sec(1),
341            flush_size: HumanSize::mib(8),
342            flush_min_hot_size: None,
343            flush_max_size: None,
344            flush_max_concurrency: 4,
345            compaction_enabled: false,
346            compaction_interval: HumanDuration::sec(30),
347            compaction_target_size: HumanSize::mib(8),
348            compaction_max_size: HumanSize::mib(16),
349            compaction_max_streams_per_pass: 16,
350            compaction_gc_grace: HumanDuration::sec(300),
351            max_hot_size_per_group: Some(HumanSize::mib(64)),
352            gc_interval: HumanDuration::sec(5),
353            gc_max_entries: 256,
354        }
355    }
356}
357
358/// S3 connection and credential settings.
359#[derive(Debug, Clone, Deserialize, Serialize)]
360#[serde(default, deny_unknown_fields)]
361pub struct S3Config {
362    /// S3 bucket name.
363    pub bucket: Option<String>,
364    /// S3 region.
365    pub region: Option<String>,
366    /// Custom S3 endpoint (for MinIO, etc.).
367    pub endpoint: Option<String>,
368    /// S3 access key ID.
369    pub access_key_id: Option<String>,
370    /// S3 secret access key.
371    pub secret_access_key: Option<String>,
372    /// Optional S3 session token.
373    pub session_token: Option<String>,
374    /// Server-side encryption requested on every cold-tier object write.
375    ///
376    /// Defaults to `aes256` (SSE-S3): free on AWS S3 and the baseline for any
377    /// shared deployment. MinIO only honors it when a KMS/KES is configured —
378    /// set `none` explicitly for a MinIO deployment without one. `aws-kms`
379    /// uses the AWS-managed KMS key unless `kms_key_id` names a customer
380    /// managed key.
381    pub server_side_encryption: S3ServerSideEncryption,
382    /// Customer managed KMS key for `server_side_encryption = "aws-kms"`.
383    pub kms_key_id: Option<String>,
384    /// Per-S3-operation timeout.
385    pub timeout: HumanDuration,
386    /// Max retries per S3 operation.
387    pub max_retries: usize,
388    /// Timeout for S3 health probes.
389    pub probe_timeout: HumanDuration,
390    /// Consecutive probe failures before marking S3 unhealthy.
391    pub unhealthy_ticks: usize,
392    /// Consecutive probe successes before marking S3 healthy again.
393    pub heal_ticks: usize,
394}
395
396impl Default for S3Config {
397    fn default() -> Self {
398        Self {
399            bucket: None,
400            region: None,
401            endpoint: None,
402            access_key_id: None,
403            secret_access_key: None,
404            session_token: None,
405            server_side_encryption: S3ServerSideEncryption::default(),
406            kms_key_id: None,
407            timeout: HumanDuration::sec(10),
408            max_retries: 3,
409            probe_timeout: HumanDuration::sec(2),
410            unhealthy_ticks: 1,
411            heal_ticks: 2,
412        }
413    }
414}
415
416/// Server-side encryption mode for cold-tier S3 writes.
417#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
418#[serde(rename_all = "kebab-case")]
419pub enum S3ServerSideEncryption {
420    /// SSE-S3 (`x-amz-server-side-encryption: AES256`). The default.
421    #[default]
422    #[serde(rename = "aes256")]
423    Aes256,
424    /// SSE-KMS; uses the AWS managed key unless `kms_key_id` is set.
425    AwsKms,
426    /// No server-side encryption header. Required for object stores that
427    /// reject the header (for example MinIO without a configured KMS).
428    None,
429}
430
431/// Cold-read cache sizing.
432#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
433#[serde(default, deny_unknown_fields)]
434pub struct ColdCacheConfig {
435    /// Max cache size in bytes.
436    pub max_size: HumanSize,
437    /// Cache block size in bytes.
438    pub block_size: HumanSize,
439    /// Number of blocks to read ahead on cache miss.
440    pub readahead_blocks: usize,
441}
442
443impl Default for ColdCacheConfig {
444    fn default() -> Self {
445        Self {
446            max_size: HumanSize::mib(256),
447            block_size: HumanSize::mib(1),
448            readahead_blocks: 4,
449        }
450    }
451}
452
453/// Raft snapshot store configuration.
454#[derive(Debug, Clone, Deserialize, Serialize)]
455#[serde(default, deny_unknown_fields)]
456pub struct RaftSnapshotConfig {
457    /// Snapshot store backend.
458    pub backend: RaftSnapshotBackend,
459    /// S3 namespace for snapshot objects, relative to the cold-storage root.
460    /// Used only when `backend` is `S3`.
461    pub s3_prefix: Option<String>,
462    /// Interval for the manual snapshot driver.
463    ///
464    /// When omitted, inline snapshot stores keep the manual driver disabled and
465    /// external snapshot stores use a 5s manual-driver default. Explicit `0s`
466    /// disables the manual driver and keeps openraft's default auto-policy.
467    pub drive_interval: Option<HumanDuration>,
468    /// Retained for configuration compatibility. Snapshot driving no longer
469    /// forces cold flushes; the cold worker owns flush concurrency.
470    pub drive_flush_concurrency: usize,
471}
472
473impl Default for RaftSnapshotConfig {
474    fn default() -> Self {
475        Self {
476            backend: RaftSnapshotBackend::Inline,
477            s3_prefix: None,
478            drive_interval: None,
479            drive_flush_concurrency: 4,
480        }
481    }
482}
483
484/// Cluster governance and health-gate configuration.
485#[derive(Debug, Clone, Default, Deserialize, Serialize)]
486#[serde(default, deny_unknown_fields)]
487pub struct GovernanceConfig {
488    /// Leadership balancing configuration.
489    pub leadership_balance: LeadershipBalanceConfig,
490    /// Cluster egress probe configuration.
491    pub cluster_probe: ClusterProbeConfig,
492    /// Commit-stall watchdog configuration.
493    pub commit_stall: CommitStallConfig,
494    /// Cold-storage health gate configuration.
495    pub cold_health: ColdHealthConfig,
496}
497
498/// Leadership balancer tuning.
499#[derive(Debug, Clone, Deserialize, Serialize)]
500#[serde(default, deny_unknown_fields)]
501pub struct LeadershipBalanceConfig {
502    /// Tick interval for the leadership balancer.
503    pub interval: HumanDuration,
504    /// Max leader handoffs to attempt per tick.
505    pub max_per_tick: usize,
506    /// Timeout when querying peer shed state.
507    pub peer_timeout: HumanDuration,
508}
509
510impl Default for LeadershipBalanceConfig {
511    fn default() -> Self {
512        Self {
513            interval: HumanDuration::sec(5),
514            max_per_tick: 4,
515            peer_timeout: HumanDuration::milli(500),
516        }
517    }
518}
519
520/// Cluster egress probe tuning.
521#[derive(Debug, Clone, Deserialize, Serialize)]
522#[serde(default, deny_unknown_fields)]
523pub struct ClusterProbeConfig {
524    /// Tick interval for egress probes.
525    pub interval: HumanDuration,
526    /// Payload size for egress probe messages.
527    pub probe_size: HumanSize,
528    /// Timeout for individual egress probes.
529    pub timeout: HumanDuration,
530    /// Consecutive failed ticks before marking egress unhealthy.
531    pub unhealthy_ticks: usize,
532    /// Consecutive healthy ticks before clearing egress unhealthy.
533    pub heal_ticks: usize,
534}
535
536impl Default for ClusterProbeConfig {
537    fn default() -> Self {
538        Self {
539            interval: HumanDuration::milli(500),
540            probe_size: HumanSize::kib(64),
541            timeout: HumanDuration::milli(200),
542            unhealthy_ticks: 2,
543            heal_ticks: 6,
544        }
545    }
546}
547
548/// Commit-stall watchdog tuning.
549#[derive(Debug, Clone, Deserialize, Serialize)]
550#[serde(default, deny_unknown_fields)]
551pub struct CommitStallConfig {
552    /// Tick interval for the commit-stall watchdog.
553    pub interval: HumanDuration,
554    /// Duration a group must be stalled (`last_log_index > committed_index`)
555    /// before triggering a leader transfer.
556    pub threshold: HumanDuration,
557}
558
559impl Default for CommitStallConfig {
560    fn default() -> Self {
561        Self {
562            interval: HumanDuration::sec(2),
563            threshold: HumanDuration::sec(15),
564        }
565    }
566}
567
568/// Cold-storage health gate tuning.
569#[derive(Debug, Clone, Deserialize, Serialize)]
570#[serde(default, deny_unknown_fields)]
571pub struct ColdHealthConfig {
572    /// Tick interval for the cold-health gate.
573    pub interval: HumanDuration,
574    /// Consecutive unhealthy ticks before shedding leadership.
575    pub unhealthy_ticks: usize,
576    /// Consecutive healthy ticks before re-allowing leadership.
577    pub heal_ticks: usize,
578    /// High watermark for per-group hot bytes. Exceeding this contributes to
579    /// unhealthy.
580    pub hot_size_high: HumanSize,
581    /// Low watermark for per-group hot bytes. Dropping below this contributes
582    /// to healthy.
583    pub hot_size_low: HumanSize,
584    /// Error-count threshold per tick that marks cold as unhealthy.
585    pub errors_per_tick_high: usize,
586}
587
588impl Default for ColdHealthConfig {
589    fn default() -> Self {
590        Self {
591            interval: HumanDuration::sec(2),
592            unhealthy_ticks: 3,
593            heal_ticks: 5,
594            // Leave the normal 8 MiB cold-flush threshold enough room to run.
595            // The old 7 MiB watermark forced leadership shedding before a
596            // group became eligible for its first flush.
597            hot_size_high: HumanSize::mib(48),
598            hot_size_low: HumanSize::mib(32),
599            errors_per_tick_high: 1,
600        }
601    }
602}
603
604/// Observability and debugging features.
605#[derive(Debug, Clone, Default, Deserialize, Serialize)]
606#[serde(default, deny_unknown_fields)]
607pub struct ObservabilityConfig {
608    /// Enable tokio-console integration.
609    pub tokio_console: bool,
610}