ifc_lite_geometry/resource/
pool.rs

1// SPDX-License-Identifier: MPL-2.0
2use super::*;
3use std::sync::{Arc, Mutex};
4#[derive(Debug)]
5struct Pool {
6    limit: u64,
7    used: Mutex<u64>,
8}
9/// Model resident admission is independent of deterministic per-request quotas.
10/// Request quotas are reserved up front; no cache lock or partial request holds
11/// a permit while waiting for another. Hosts retry WaitingForCapacity on release.
12#[derive(Debug, Clone)]
13pub struct ModelResourcePool(Arc<Pool>);
14#[derive(Debug)]
15pub enum RequestAdmission {
16    Ready(ExecutionAccount),
17    WaitingForCapacity,
18}
19#[derive(Debug)]
20pub(super) struct PoolPermit {
21    pool: Arc<Pool>,
22    bytes: u64,
23}
24impl ModelResourcePool {
25    pub fn new(live_bytes: u64) -> Self {
26        Self(Arc::new(Pool {
27            limit: live_bytes,
28            used: Mutex::new(0),
29        }))
30    }
31    pub fn resident_bytes(&self) -> u64 {
32        *self.0.used.lock().unwrap_or_else(|e| e.into_inner())
33    }
34    /// A finite request live allowance is required for pooled execution. Opaque
35    /// allocations remain excluded even after a resident permit is granted.
36    pub fn admit(&self, limits: ResourceLimits) -> Result<RequestAdmission, ProgramStop> {
37        let Some(bytes) = limits.live_bytes else {
38            return Err(ProgramStop::ResourceRefused(ResourceFailure {
39                dimension: Dimension::LiveBytes,
40                requested: u64::MAX,
41                remaining: self.0.limit,
42                reason: RefusalReason::UnsupportedCoverage,
43            }));
44        };
45        if bytes > self.0.limit {
46            return Err(ProgramStop::ResourceRefused(ResourceFailure {
47                dimension: Dimension::LiveBytes,
48                requested: bytes,
49                remaining: self.0.limit,
50                reason: RefusalReason::Limit,
51            }));
52        }
53        let mut used = self.0.used.lock().unwrap_or_else(|e| e.into_inner());
54        if bytes > self.0.limit - *used {
55            return Ok(RequestAdmission::WaitingForCapacity);
56        }
57        *used += bytes;
58        drop(used);
59        Ok(RequestAdmission::Ready(ExecutionAccount::bounded(
60            limits,
61            Some(PoolPermit {
62                pool: Arc::clone(&self.0),
63                bytes,
64            }),
65        )))
66    }
67}
68impl Drop for PoolPermit {
69    fn drop(&mut self) {
70        let mut used = self.pool.used.lock().unwrap_or_else(|e| e.into_inner());
71        *used = used.saturating_sub(self.bytes);
72    }
73}