1use std::sync::Once;
25
26use super::profile::DeployProfile;
27
28pub const MEMORY_BUDGET_ENV: &str = "REDDB_MEMORY_BUDGET";
32
33pub const CGROUP_V2_MEMORY_MAX_PATH: &str = "/sys/fs/cgroup/memory.max";
36
37pub const CGROUP_V1_MEMORY_LIMIT_PATH: &str = "/sys/fs/cgroup/memory/memory.limit_in_bytes";
40
41pub const PHYSICAL_RAM_BUDGET_PERCENT: u64 = 70;
50
51pub const SERVERLESS_PROFILE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;
56
57pub const MINIMUM_DETECTED_BUDGET_BYTES: u64 = 64 * 1024 * 1024;
65
66const CGROUP_V1_UNLIMITED_SENTINEL: u64 = 0x7FFF_FFFF_FFFF_F000;
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74pub enum MemoryBudgetSource {
75 Config,
77 ProfileDefault,
79 CgroupV2,
81 CgroupV1,
83 PhysicalFraction,
85}
86
87impl MemoryBudgetSource {
88 pub const fn as_str(self) -> &'static str {
90 match self {
91 Self::Config => "config",
92 Self::ProfileDefault => "profile-default",
93 Self::CgroupV2 => "cgroup-v2",
94 Self::CgroupV1 => "cgroup-v1",
95 Self::PhysicalFraction => "physical-fraction",
96 }
97 }
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub struct MemoryBudget {
103 pub resolved_bytes: u64,
104 pub source: MemoryBudgetSource,
105}
106
107#[derive(Debug, Clone, PartialEq, Eq)]
110pub struct InvalidMemoryBudget {
111 pub raw: String,
112}
113
114impl std::fmt::Display for InvalidMemoryBudget {
115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116 write!(
117 f,
118 "invalid memory budget `{}`: expected a positive byte count with an optional \
119 unit suffix (`536870912`, `512MiB`, `2GiB`, `2GB`); RedDB has no unlimited \
120 mode — omit the setting to use the detected default",
121 self.raw
122 )
123 }
124}
125
126impl std::error::Error for InvalidMemoryBudget {}
127
128#[derive(Debug, Clone, Default, PartialEq, Eq)]
131pub struct MemoryBudgetInputs {
132 pub configured: Option<String>,
134 pub profile: Option<DeployProfile>,
136 pub cgroup_v2_memory_max: Option<String>,
138 pub cgroup_v1_memory_limit: Option<String>,
140 pub physical_ram_bytes: u64,
142}
143
144pub fn resolve(inputs: &MemoryBudgetInputs) -> Result<MemoryBudget, InvalidMemoryBudget> {
150 if let Some(raw) = inputs.configured.as_deref() {
151 let resolved_bytes = parse_budget_bytes(raw).ok_or_else(|| InvalidMemoryBudget {
152 raw: raw.to_string(),
153 })?;
154 return Ok(MemoryBudget {
155 resolved_bytes,
156 source: MemoryBudgetSource::Config,
157 });
158 }
159
160 if let Some(resolved_bytes) = inputs.profile.and_then(profile_default_bytes) {
161 return Ok(MemoryBudget {
162 resolved_bytes,
163 source: MemoryBudgetSource::ProfileDefault,
164 });
165 }
166
167 if let Some(resolved_bytes) = inputs
168 .cgroup_v2_memory_max
169 .as_deref()
170 .and_then(parse_cgroup_v2_limit)
171 {
172 return Ok(MemoryBudget {
173 resolved_bytes,
174 source: MemoryBudgetSource::CgroupV2,
175 });
176 }
177
178 if let Some(resolved_bytes) = inputs
179 .cgroup_v1_memory_limit
180 .as_deref()
181 .and_then(parse_cgroup_v1_limit)
182 {
183 return Ok(MemoryBudget {
184 resolved_bytes,
185 source: MemoryBudgetSource::CgroupV1,
186 });
187 }
188
189 Ok(MemoryBudget {
190 resolved_bytes: physical_fraction_bytes(inputs.physical_ram_bytes),
191 source: MemoryBudgetSource::PhysicalFraction,
192 })
193}
194
195pub fn host_inputs(profile: DeployProfile, configured_bytes: Option<u64>) -> MemoryBudgetInputs {
198 let configured = configured_bytes
201 .map(|bytes| bytes.to_string())
202 .or_else(|| std::env::var(MEMORY_BUDGET_ENV).ok())
203 .filter(|raw| !raw.trim().is_empty());
204
205 MemoryBudgetInputs {
206 configured,
207 profile: Some(profile),
208 cgroup_v2_memory_max: read_cgroup_file(CGROUP_V2_MEMORY_MAX_PATH),
209 cgroup_v1_memory_limit: read_cgroup_file(CGROUP_V1_MEMORY_LIMIT_PATH),
210 physical_ram_bytes: physical_ram_bytes(),
211 }
212}
213
214pub fn resolve_for_boot(
217 profile: DeployProfile,
218 configured_bytes: Option<u64>,
219) -> Result<MemoryBudget, InvalidMemoryBudget> {
220 resolve(&host_inputs(profile, configured_bytes))
221}
222
223pub fn log_resolved_once(budget: &MemoryBudget) {
226 static LOGGED: Once = Once::new();
227 LOGGED.call_once(|| {
228 tracing::info!(
229 resolved_bytes = budget.resolved_bytes,
230 source = budget.source.as_str(),
231 "memory budget resolved"
232 );
233 });
234}
235
236fn profile_default_bytes(profile: DeployProfile) -> Option<u64> {
238 match profile {
239 DeployProfile::Serverless => Some(SERVERLESS_PROFILE_BUDGET_BYTES),
240 DeployProfile::Embedded | DeployProfile::PrimaryReplica | DeployProfile::Cluster => None,
241 }
242}
243
244fn parse_budget_bytes(raw: &str) -> Option<u64> {
248 let trimmed = raw.trim();
249 let digits_end = trimmed
250 .char_indices()
251 .find(|(_, ch)| !ch.is_ascii_digit())
252 .map_or(trimmed.len(), |(idx, _)| idx);
253 if digits_end == 0 {
254 return None;
255 }
256
257 let value = trimmed[..digits_end].parse::<u64>().ok()?;
258 let multiplier = match trimmed[digits_end..].trim().to_ascii_lowercase().as_str() {
259 "" | "b" => 1,
260 "kb" => 1_000,
261 "mb" => 1_000_000,
262 "gb" => 1_000_000_000,
263 "tb" => 1_000_000_000_000,
264 "kib" => 1 << 10,
265 "mib" => 1 << 20,
266 "gib" => 1 << 30,
267 "tib" => 1 << 40,
268 _ => return None,
269 };
270
271 let bytes = value.checked_mul(multiplier)?;
272 (bytes > 0).then_some(bytes)
273}
274
275fn parse_cgroup_v2_limit(raw: &str) -> Option<u64> {
277 let trimmed = raw.trim();
278 if trimmed.eq_ignore_ascii_case("max") {
279 return None;
280 }
281 trimmed.parse::<u64>().ok().filter(|bytes| *bytes > 0)
282}
283
284fn parse_cgroup_v1_limit(raw: &str) -> Option<u64> {
286 raw.trim()
287 .parse::<u64>()
288 .ok()
289 .filter(|bytes| *bytes > 0 && *bytes < CGROUP_V1_UNLIMITED_SENTINEL)
290}
291
292fn physical_fraction_bytes(physical_ram_bytes: u64) -> u64 {
294 (physical_ram_bytes / 100)
297 .saturating_mul(PHYSICAL_RAM_BUDGET_PERCENT)
298 .max(MINIMUM_DETECTED_BUDGET_BYTES)
299}
300
301fn read_cgroup_file(path: &str) -> Option<String> {
304 std::fs::read_to_string(path).ok()
305}
306
307#[cfg(target_os = "linux")]
308fn physical_ram_bytes() -> u64 {
309 std::fs::read_to_string("/proc/meminfo")
310 .ok()
311 .and_then(|meminfo| {
312 meminfo
313 .lines()
314 .find(|line| line.starts_with("MemTotal:"))
315 .and_then(|line| line.split_whitespace().nth(1))
316 .and_then(|kb| kb.parse::<u64>().ok())
317 })
318 .map_or(0, |kb| kb.saturating_mul(1024))
319}
320
321#[cfg(not(target_os = "linux"))]
322fn physical_ram_bytes() -> u64 {
323 0
324}
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329
330 const GIB: u64 = 1 << 30;
331
332 fn inputs() -> MemoryBudgetInputs {
333 MemoryBudgetInputs {
334 profile: Some(DeployProfile::Embedded),
335 physical_ram_bytes: 16 * GIB,
336 ..MemoryBudgetInputs::default()
337 }
338 }
339
340 #[test]
341 fn explicit_configuration_wins_over_every_other_tier() {
342 let resolved = resolve(&MemoryBudgetInputs {
343 configured: Some("512MiB".to_string()),
344 profile: Some(DeployProfile::Serverless),
345 cgroup_v2_memory_max: Some("1073741824".to_string()),
346 cgroup_v1_memory_limit: Some("2147483648".to_string()),
347 ..inputs()
348 })
349 .expect("configured budget resolves");
350
351 assert_eq!(resolved.source, MemoryBudgetSource::Config);
352 assert_eq!(resolved.resolved_bytes, 512 * 1024 * 1024);
353 }
354
355 #[test]
356 fn configured_budget_accepts_bare_bytes_and_unit_suffixes() {
357 let cases = [
358 ("536870912", 536_870_912),
359 (" 536870912 ", 536_870_912),
360 ("1024b", 1024),
361 ("2KiB", 2048),
362 ("512MiB", 512 * 1024 * 1024),
363 ("2GiB", 2 * GIB),
364 ("1TiB", 1 << 40),
365 ("2GB", 2_000_000_000),
366 ("500mb", 500_000_000),
367 ];
368
369 for (raw, expected) in cases {
370 assert_eq!(parse_budget_bytes(raw), Some(expected), "parsing {raw}");
371 }
372 }
373
374 #[test]
375 fn nonsensical_configured_budget_is_rejected_not_replaced() {
376 for raw in [
377 "0",
378 "0MiB",
379 "-1",
380 "unlimited",
381 "max",
382 "",
383 " ",
384 "12 apples",
385 "MiB",
386 "1.5GiB",
387 ] {
388 let err = resolve(&MemoryBudgetInputs {
389 configured: Some(raw.to_string()),
390 ..inputs()
391 })
392 .expect_err("nonsensical configured budget must fail boot");
393
394 let message = err.to_string();
395 assert!(
396 message.contains("expected a positive byte count"),
397 "{message}"
398 );
399 assert!(
400 message.contains("512MiB"),
401 "error names the valid form: {message}"
402 );
403 assert!(message.contains("no unlimited mode"), "{message}");
404 }
405 }
406
407 #[test]
408 fn serverless_profile_ships_a_strict_default() {
409 let resolved = resolve(&MemoryBudgetInputs {
410 profile: Some(DeployProfile::Serverless),
411 cgroup_v2_memory_max: Some("34359738368".to_string()),
412 ..inputs()
413 })
414 .expect("profile default resolves");
415
416 assert_eq!(resolved.source, MemoryBudgetSource::ProfileDefault);
417 assert_eq!(resolved.resolved_bytes, SERVERLESS_PROFILE_BUDGET_BYTES);
418 }
419
420 #[test]
421 fn detection_profiles_fall_through_to_the_cgroup() {
422 for profile in [
423 DeployProfile::Embedded,
424 DeployProfile::PrimaryReplica,
425 DeployProfile::Cluster,
426 ] {
427 let resolved = resolve(&MemoryBudgetInputs {
428 profile: Some(profile),
429 cgroup_v2_memory_max: Some("1073741824\n".to_string()),
430 ..inputs()
431 })
432 .expect("cgroup budget resolves");
433
434 assert_eq!(resolved.source, MemoryBudgetSource::CgroupV2);
435 assert_eq!(resolved.resolved_bytes, GIB);
436 }
437 }
438
439 #[test]
440 fn cgroup_v2_max_falls_through_to_v1_then_physical() {
441 let to_v1 = resolve(&MemoryBudgetInputs {
442 cgroup_v2_memory_max: Some("max\n".to_string()),
443 cgroup_v1_memory_limit: Some("2147483648".to_string()),
444 ..inputs()
445 })
446 .expect("v1 fallback resolves");
447 assert_eq!(to_v1.source, MemoryBudgetSource::CgroupV1);
448 assert_eq!(to_v1.resolved_bytes, 2 * GIB);
449
450 let to_physical = resolve(&MemoryBudgetInputs {
451 cgroup_v2_memory_max: Some("MAX".to_string()),
452 ..inputs()
453 })
454 .expect("physical fallback resolves");
455 assert_eq!(to_physical.source, MemoryBudgetSource::PhysicalFraction);
456 }
457
458 #[test]
459 fn cgroup_v1_unlimited_sentinel_falls_through_to_physical() {
460 let resolved = resolve(&MemoryBudgetInputs {
461 cgroup_v1_memory_limit: Some(CGROUP_V1_UNLIMITED_SENTINEL.to_string()),
462 ..inputs()
463 })
464 .expect("sentinel falls through");
465
466 assert_eq!(resolved.source, MemoryBudgetSource::PhysicalFraction);
467 assert_eq!(resolved.resolved_bytes, 16 * GIB / 100 * 70);
468 }
469
470 #[test]
471 fn physical_fraction_is_the_last_tier_and_never_zero() {
472 let detected = resolve(&inputs()).expect("physical fraction resolves");
473 assert_eq!(detected.source, MemoryBudgetSource::PhysicalFraction);
474 assert_eq!(detected.resolved_bytes, 16 * GIB / 100 * 70);
475
476 let undetectable = resolve(&MemoryBudgetInputs {
478 physical_ram_bytes: 0,
479 ..inputs()
480 })
481 .expect("undetectable physical RAM resolves");
482 assert_eq!(undetectable.source, MemoryBudgetSource::PhysicalFraction);
483 assert_eq!(undetectable.resolved_bytes, MINIMUM_DETECTED_BUDGET_BYTES);
484 }
485
486 #[test]
487 fn every_resolved_budget_is_strictly_positive() {
488 let profiles = [
489 None,
490 Some(DeployProfile::Embedded),
491 Some(DeployProfile::Serverless),
492 Some(DeployProfile::PrimaryReplica),
493 Some(DeployProfile::Cluster),
494 ];
495 let cgroup_v2 = [None, Some("max"), Some("0"), Some("1"), Some("garbage")];
496 let cgroup_v1 = [None, Some("0"), Some("1"), Some("9223372036854771712")];
497 let physical = [0, 1, 1024, 16 * GIB, u64::MAX];
498 let configured = [None, Some("1"), Some("1TiB")];
499
500 for profile in profiles {
501 for v2 in cgroup_v2 {
502 for v1 in cgroup_v1 {
503 for ram in physical {
504 for config in configured {
505 let resolved = resolve(&MemoryBudgetInputs {
506 configured: config.map(str::to_string),
507 profile,
508 cgroup_v2_memory_max: v2.map(str::to_string),
509 cgroup_v1_memory_limit: v1.map(str::to_string),
510 physical_ram_bytes: ram,
511 })
512 .expect("valid inputs always resolve");
513 assert!(resolved.resolved_bytes > 0);
514 }
515 }
516 }
517 }
518 }
519 }
520
521 #[test]
522 fn source_labels_are_the_documented_tier_names() {
523 assert_eq!(MemoryBudgetSource::Config.as_str(), "config");
524 assert_eq!(
525 MemoryBudgetSource::ProfileDefault.as_str(),
526 "profile-default"
527 );
528 assert_eq!(MemoryBudgetSource::CgroupV2.as_str(), "cgroup-v2");
529 assert_eq!(MemoryBudgetSource::CgroupV1.as_str(), "cgroup-v1");
530 assert_eq!(
531 MemoryBudgetSource::PhysicalFraction.as_str(),
532 "physical-fraction"
533 );
534 }
535}