tower_memlim/
memory.rs

1//! Memory determination and thresholds
2
3use cgroup_memory::memory_available;
4
5use crate::error::BoxError;
6
7/// Memory threshold.
8/// 
9/// Requests are limited once the threshold is exceeded. The concrete
10/// definition of exceeded depends on Threshold's enum variant.
11#[derive(Clone, Debug)]
12pub enum Threshold {
13    /// Threshold is exceeded when the available memory is less than the given number of bytes.
14    MinAvailableBytes(u64),
15}
16
17pub trait AvailableMemory
18where
19    Self: Clone + Send + 'static,
20{
21    fn available_memory(&self) -> Result<usize, BoxError>;
22}
23
24/// Implements [AvailableMemory] with help of Linux `/sys/fs/cgroup` files / the `cgroup-memory` crate.
25#[derive(Clone)]
26pub struct LinuxCgroupMemory;
27
28impl AvailableMemory for LinuxCgroupMemory {
29    fn available_memory(&self) -> Result<usize, BoxError> {
30        match memory_available() {
31            Ok(Some(m)) => Ok(m as usize),
32            Ok(None) => Err("Memory cannot be determined".into()),
33            Err(e) => Err(e.into()),
34        }
35    }
36}