use std::time::Duration;
const FORK_HEADROOM: f32 = 0.9;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ContextPolicy {
pub compact_at: f32,
pub pause_at: f32,
pub restore_budget: f32,
pub idle_compact_before_expiry: Duration,
}
impl Default for ContextPolicy {
fn default() -> Self {
Self {
compact_at: 0.6,
pause_at: 0.9,
restore_budget: 0.15,
idle_compact_before_expiry: Duration::from_secs(6 * 60),
}
}
}
impl ContextPolicy {
#[must_use]
pub fn should_compact(&self, usage: f32) -> bool {
usage >= self.compact_at
}
#[must_use]
pub fn fork_limit(&self) -> f32 {
self.compact_at * FORK_HEADROOM
}
#[must_use]
pub fn allows_fork(&self, usage: f32) -> bool {
usage < self.fork_limit()
}
#[must_use]
pub fn should_pause(&self, usage: f32) -> bool {
usage >= self.pause_at
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_thresholds_are_ordered() {
let policy = ContextPolicy::default();
assert!(policy.compact_at < policy.pause_at);
assert!(policy.pause_at < 1.0);
assert!(policy.restore_budget < policy.compact_at);
}
#[test]
fn a_fork_is_refused_within_a_tenth_of_the_compaction_point() {
let policy = ContextPolicy::default();
assert!(policy.allows_fork(0.53));
assert!(!policy.allows_fork(0.54));
assert!(!policy.allows_fork(0.7));
}
#[test]
fn thresholds_are_inclusive() {
let policy = ContextPolicy::default();
assert!(policy.should_compact(0.6));
assert!(!policy.should_compact(0.59));
assert!(policy.should_pause(0.9));
assert!(!policy.should_pause(0.89));
}
}