1use super::{AgentId, HostError, HostResult};
2use serde::Serialize;
3use std::{
4 collections::HashSet,
5 num::NonZeroUsize,
6 sync::{Arc, Mutex},
7};
8
9#[derive(Debug)]
10struct State {
11 limit: Option<NonZeroUsize>,
12 resident: HashSet<AgentId>,
13}
14
15#[derive(Clone, Debug)]
18pub struct Capacity(Arc<Mutex<State>>);
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
21pub struct CapacitySnapshot {
22 pub limit: Option<usize>,
23 pub resident: usize,
24 pub available: Option<usize>,
25}
26
27impl Capacity {
28 pub fn new(limit: Option<NonZeroUsize>) -> Self {
29 Self(Arc::new(Mutex::new(State {
30 limit,
31 resident: HashSet::new(),
32 })))
33 }
34
35 pub fn try_reserve(&self, agent_id: AgentId) -> HostResult<ResidentPermit> {
36 let mut state = self.0.lock().map_err(|_| HostError::Poisoned)?;
37 if state.resident.contains(&agent_id) {
38 return Err(HostError::AlreadyResident);
39 }
40 if let Some(limit) = state.limit {
41 if state.resident.len() >= limit.get() {
42 return Err(HostError::AtCapacity { limit: limit.get() });
43 }
44 }
45 state.resident.insert(agent_id);
46 Ok(ResidentPermit {
47 capacity: self.clone(),
48 agent_id,
49 })
50 }
51
52 pub fn set_limit(&self, limit: Option<NonZeroUsize>) -> HostResult<()> {
54 self.0.lock().map_err(|_| HostError::Poisoned)?.limit = limit;
55 Ok(())
56 }
57
58 pub fn snapshot(&self) -> HostResult<CapacitySnapshot> {
59 let state = self.0.lock().map_err(|_| HostError::Poisoned)?;
60 let limit = state.limit.map(NonZeroUsize::get);
61 Ok(CapacitySnapshot {
62 limit,
63 resident: state.resident.len(),
64 available: limit.map(|limit| limit.saturating_sub(state.resident.len())),
65 })
66 }
67}
68
69#[derive(Debug)]
73#[must_use = "retain the permit for the complete backend residency"]
74pub struct ResidentPermit {
75 capacity: Capacity,
76 agent_id: AgentId,
77}
78
79impl ResidentPermit {
80 pub fn agent_id(&self) -> AgentId {
81 self.agent_id
82 }
83}
84
85impl Drop for ResidentPermit {
86 fn drop(&mut self) {
87 self.capacity
90 .0
91 .lock()
92 .unwrap_or_else(|poison| poison.into_inner())
93 .resident
94 .remove(&self.agent_id);
95 }
96}