use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use super::authority::PublicationIdentity;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OwnerIdentity(std::num::NonZeroU64);
static NEXT_OWNER: AtomicU64 = AtomicU64::new(1);
impl OwnerIdentity {
pub fn fresh() -> Self {
let raw = NEXT_OWNER.fetch_add(1, Ordering::Relaxed);
Self(std::num::NonZeroU64::new(raw).expect("owner counter starts at 1"))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PoolIdentity(std::num::NonZeroU64);
static NEXT_POOL: AtomicU64 = AtomicU64::new(1);
impl PoolIdentity {
fn fresh() -> Self {
let raw = NEXT_POOL.fetch_add(1, Ordering::Relaxed);
Self(std::num::NonZeroU64::new(raw).expect("pool counter starts at 1"))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CapacityRefusal {
Exhausted {
requested: u64,
available: u64,
},
ExceedsParent {
requested: u64,
available: u64,
},
HasChildren {
children: usize,
},
UnknownOwner,
ForeignGrant,
}
#[derive(Debug)]
pub struct CapacityGrant {
owner: OwnerIdentity,
bytes: u64,
charge: PublicationIdentity,
pool: PoolIdentity,
ledger: Arc<ProcessCapacityPool>,
redeemed: bool,
}
impl CapacityGrant {
pub fn owner(&self) -> OwnerIdentity {
self.owner
}
pub fn bytes(&self) -> u64 {
self.bytes
}
pub fn charge(&self) -> PublicationIdentity {
self.charge
}
}
impl Drop for CapacityGrant {
fn drop(&mut self) {
if !self.redeemed {
self.ledger.refund(self.owner, self.charge, self.bytes);
}
}
}
#[derive(Debug)]
pub struct CapacityPermit {
owner: OwnerIdentity,
bytes: u64,
charge: PublicationIdentity,
ledger: Arc<ProcessCapacityPool>,
refunded: bool,
}
impl CapacityPermit {
pub fn bytes(&self) -> u64 {
self.bytes
}
pub fn charge(&self) -> PublicationIdentity {
self.charge
}
pub fn release(mut self) -> u64 {
let refunded = self.ledger.refund(self.owner, self.charge, self.bytes);
self.refunded = true;
refunded
}
}
impl Drop for CapacityPermit {
fn drop(&mut self) {
if !self.refunded {
self.ledger.refund(self.owner, self.charge, self.bytes);
}
}
}
#[derive(Debug, Default)]
struct OwnerRow {
limit: u64,
charged: u64,
outstanding: HashMap<PublicationIdentity, u64>,
parent: Option<OwnerIdentity>,
}
#[derive(Debug)]
pub struct ProcessCapacityPool {
identity: PoolIdentity,
rows: std::sync::Mutex<BTreeMap<OwnerIdentity, OwnerRow>>,
unknown_refunds: AtomicU64,
}
impl Default for ProcessCapacityPool {
fn default() -> Self {
Self {
identity: PoolIdentity::fresh(),
rows: std::sync::Mutex::new(BTreeMap::new()),
unknown_refunds: AtomicU64::new(0),
}
}
}
impl ProcessCapacityPool {
pub fn new() -> Arc<Self> {
Arc::new(Self::default())
}
pub fn identity(&self) -> PoolIdentity {
self.identity
}
pub fn root(self: &Arc<Self>, limit: u64) -> OwnerIdentity {
let identity = OwnerIdentity::fresh();
self.rows.lock().expect("capacity ledger mutex").insert(
identity,
OwnerRow {
limit,
parent: None,
..OwnerRow::default()
},
);
identity
}
pub fn child(
self: &Arc<Self>,
parent: OwnerIdentity,
limit: u64,
) -> Result<OwnerIdentity, CapacityRefusal> {
let mut rows = self.rows.lock().expect("capacity ledger mutex");
let available = rows
.get(&parent)
.map(|row| row.limit.saturating_sub(row.charged))
.unwrap_or(0);
if limit > available {
return Err(CapacityRefusal::ExceedsParent {
requested: limit,
available,
});
}
if let Some(row) = rows.get_mut(&parent) {
row.charged += limit;
}
let identity = OwnerIdentity::fresh();
rows.insert(
identity,
OwnerRow {
limit,
parent: Some(parent),
..OwnerRow::default()
},
);
Ok(identity)
}
pub fn reserve(
self: &Arc<Self>,
owner: OwnerIdentity,
bytes: u64,
) -> Result<CapacityGrant, CapacityRefusal> {
let mut rows = self.rows.lock().expect("capacity ledger mutex");
let row = rows.get_mut(&owner).ok_or(CapacityRefusal::UnknownOwner)?;
let available = row.limit.saturating_sub(row.charged);
if bytes > available {
return Err(CapacityRefusal::Exhausted {
requested: bytes,
available,
});
}
let charge = PublicationIdentity::fresh();
row.charged += bytes;
row.outstanding.insert(charge, bytes);
drop(rows);
Ok(CapacityGrant {
owner,
bytes,
charge,
pool: self.identity,
ledger: Arc::clone(self),
redeemed: false,
})
}
pub fn redeem(
self: &Arc<Self>,
mut grant: CapacityGrant,
) -> Result<CapacityPermit, CapacityRefusal> {
if grant.pool != self.identity {
return Err(CapacityRefusal::ForeignGrant);
}
grant.redeemed = true;
Ok(CapacityPermit {
owner: grant.owner,
bytes: grant.bytes,
charge: grant.charge,
ledger: Arc::clone(self),
refunded: false,
})
}
pub fn charged(&self, owner: OwnerIdentity) -> u64 {
self.rows
.lock()
.expect("capacity ledger mutex")
.get(&owner)
.map(|row| row.charged)
.unwrap_or(0)
}
pub fn available(&self, owner: OwnerIdentity) -> u64 {
self.rows
.lock()
.expect("capacity ledger mutex")
.get(&owner)
.map(|row| row.limit.saturating_sub(row.charged))
.unwrap_or(0)
}
pub fn outstanding_charges(&self, owner: OwnerIdentity) -> usize {
self.rows
.lock()
.expect("capacity ledger mutex")
.get(&owner)
.map(|row| row.outstanding.len())
.unwrap_or(0)
}
pub fn unknown_refunds(&self) -> u64 {
self.unknown_refunds.load(Ordering::Relaxed)
}
pub fn release_owner(self: &Arc<Self>, owner: OwnerIdentity) -> Result<u64, CapacityRefusal> {
let mut rows = self.rows.lock().expect("capacity ledger mutex");
let Some(row) = rows.get(&owner) else {
return Err(CapacityRefusal::UnknownOwner);
};
if !row.outstanding.is_empty() {
return Err(CapacityRefusal::Exhausted {
requested: 0,
available: row.limit.saturating_sub(row.charged),
});
}
let children = rows
.values()
.filter(|candidate| candidate.parent == Some(owner))
.count();
if children > 0 {
return Err(CapacityRefusal::HasChildren { children });
}
let limit = row.limit;
let parent = row.parent;
if let Some(parent) = parent
&& !rows.contains_key(&parent)
{
return Err(CapacityRefusal::UnknownOwner);
}
rows.remove(&owner);
if let Some(parent) = parent
&& let Some(parent_row) = rows.get_mut(&parent)
{
parent_row.charged = parent_row.charged.saturating_sub(limit);
}
Ok(limit)
}
fn refund(&self, owner: OwnerIdentity, charge: PublicationIdentity, bytes: u64) -> u64 {
let mut rows = self.rows.lock().expect("capacity ledger mutex");
let Some(row) = rows.get_mut(&owner) else {
self.unknown_refunds.fetch_add(1, Ordering::Relaxed);
return 0;
};
match row.outstanding.remove(&charge) {
Some(recorded) => {
debug_assert_eq!(
recorded, bytes,
"charge size changed between reserve and refund"
);
row.charged = row.charged.saturating_sub(recorded);
recorded
}
None => {
self.unknown_refunds.fetch_add(1, Ordering::Relaxed);
0
}
}
}
}