use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use super::authority::BindingAuthority;
use super::capacity::OwnerIdentity;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SlotIdentity(std::num::NonZeroU64);
static NEXT_SLOT: AtomicU64 = AtomicU64::new(1);
impl SlotIdentity {
pub fn fresh() -> Self {
let raw = NEXT_SLOT.fetch_add(1, Ordering::Relaxed);
Self(std::num::NonZeroU64::new(raw).expect("slot counter starts at 1"))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ProjectKey(String);
impl ProjectKey {
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RegistryRefusal {
Tombstoned {
slot: SlotIdentity,
},
NotAdmitted,
ProtectedWithoutAuthorization,
StillPending,
RootMismatch {
joined: super::physical_root::PhysicalRootIdentity,
presented: super::physical_root::PhysicalRootIdentity,
},
PlacementMismatch {
joined: StatePlacement,
presented: StatePlacement,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatePlacement {
ProjectLocal,
UserLocal,
MemoryOnly,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RootProtection {
Normal,
Protected,
}
#[derive(Debug)]
pub struct PendingProjectAdmission {
slot: SlotIdentity,
key: ProjectKey,
binding: BindingAuthority,
placement: StatePlacement,
joiners: usize,
}
impl PendingProjectAdmission {
pub fn slot(&self) -> SlotIdentity {
self.slot
}
pub fn key(&self) -> &ProjectKey {
&self.key
}
pub fn placement(&self) -> StatePlacement {
self.placement
}
pub fn joiners(&self) -> usize {
self.joiners
}
pub fn binding(&self) -> &BindingAuthority {
&self.binding
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AdmissionJoin {
CreatedPending,
JoinedPending,
JoinedLive,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AdmissionAttempt {
slot: SlotIdentity,
join: AdmissionJoin,
}
impl AdmissionAttempt {
pub fn slot(self) -> SlotIdentity {
self.slot
}
pub fn join(self) -> AdmissionJoin {
self.join
}
pub fn cleanup_candidate(self) -> bool {
matches!(
self.join,
AdmissionJoin::CreatedPending | AdmissionJoin::JoinedPending
)
}
}
#[derive(Debug)]
pub struct LiveProjectSlot {
slot: SlotIdentity,
key: ProjectKey,
binding: BindingAuthority,
placement: StatePlacement,
owner: Option<OwnerIdentity>,
revoked: std::sync::atomic::AtomicBool,
}
impl LiveProjectSlot {
pub fn slot(&self) -> SlotIdentity {
self.slot
}
pub fn key(&self) -> &ProjectKey {
&self.key
}
pub fn placement(&self) -> StatePlacement {
self.placement
}
pub fn is_live(&self) -> bool {
!self.revoked.load(Ordering::Acquire)
}
pub fn binding(&self) -> Result<&BindingAuthority, RegistryRefusal> {
if self.is_live() {
Ok(&self.binding)
} else {
Err(RegistryRefusal::Tombstoned { slot: self.slot })
}
}
pub fn capacity_owner(&self) -> Result<Option<OwnerIdentity>, RegistryRefusal> {
if self.is_live() {
Ok(self.owner)
} else {
Err(RegistryRefusal::Tombstoned { slot: self.slot })
}
}
fn revoke(&self) {
self.binding.revoke();
self.revoked.store(true, Ordering::Release);
}
}
#[derive(Debug)]
enum Occupancy {
Pending(PendingProjectAdmission),
Live(Arc<LiveProjectSlot>),
}
#[derive(Debug, Default)]
pub struct ProjectRegistry {
occupancy: std::sync::Mutex<RegistryState>,
}
#[derive(Debug, Default)]
struct RegistryState {
keys: HashMap<ProjectKey, Occupancy>,
tombstones: HashMap<SlotIdentity, ProjectKey>,
}
impl ProjectRegistry {
pub fn new() -> Arc<Self> {
Arc::new(Self::default())
}
pub fn admit(
self: &Arc<Self>,
key: ProjectKey,
binding: BindingAuthority,
protection: RootProtection,
authorized: bool,
placement: StatePlacement,
) -> Result<SlotIdentity, RegistryRefusal> {
self.admit_with_outcome(key, binding, protection, authorized, placement)
.map(AdmissionAttempt::slot)
}
pub fn admit_with_outcome(
self: &Arc<Self>,
key: ProjectKey,
binding: BindingAuthority,
protection: RootProtection,
authorized: bool,
placement: StatePlacement,
) -> Result<AdmissionAttempt, RegistryRefusal> {
if protection == RootProtection::Protected {
if !authorized {
return Err(RegistryRefusal::ProtectedWithoutAuthorization);
}
if placement == StatePlacement::ProjectLocal {
return Err(RegistryRefusal::ProtectedWithoutAuthorization);
}
}
let mut state = self.occupancy.lock().expect("registry mutex");
match state.keys.get_mut(&key) {
Some(Occupancy::Pending(pending)) => {
if pending.binding.physical_root() != binding.physical_root() {
return Err(RegistryRefusal::RootMismatch {
joined: pending.binding.physical_root(),
presented: binding.physical_root(),
});
}
if pending.placement != placement {
return Err(RegistryRefusal::PlacementMismatch {
joined: pending.placement,
presented: placement,
});
}
pending.joiners += 1;
Ok(AdmissionAttempt {
slot: pending.slot,
join: AdmissionJoin::JoinedPending,
})
}
Some(Occupancy::Live(live)) => {
if live.binding.physical_root() != binding.physical_root() {
return Err(RegistryRefusal::RootMismatch {
joined: live.binding.physical_root(),
presented: binding.physical_root(),
});
}
if live.placement != placement {
return Err(RegistryRefusal::PlacementMismatch {
joined: live.placement,
presented: placement,
});
}
Ok(AdmissionAttempt {
slot: live.slot(),
join: AdmissionJoin::JoinedLive,
})
}
None => {
let slot = SlotIdentity::fresh();
state.keys.insert(
key.clone(),
Occupancy::Pending(PendingProjectAdmission {
slot,
key,
binding,
placement,
joiners: 1,
}),
);
Ok(AdmissionAttempt {
slot,
join: AdmissionJoin::CreatedPending,
})
}
}
}
pub fn pending_joiners(&self, key: &ProjectKey) -> Option<usize> {
match self.occupancy.lock().expect("registry mutex").keys.get(key) {
Some(Occupancy::Pending(pending)) => Some(pending.joiners),
_ => None,
}
}
pub fn install(
self: &Arc<Self>,
key: &ProjectKey,
owner: Option<OwnerIdentity>,
) -> Result<Arc<LiveProjectSlot>, RegistryRefusal> {
let mut state = self.occupancy.lock().expect("registry mutex");
let pending = match state.keys.remove(key) {
Some(Occupancy::Pending(pending)) => pending,
Some(other) => {
state.keys.insert(key.clone(), other);
return Err(RegistryRefusal::NotAdmitted);
}
None => return Err(RegistryRefusal::NotAdmitted),
};
let live = Arc::new(LiveProjectSlot {
slot: pending.slot,
key: pending.key.clone(),
binding: pending.binding,
placement: pending.placement,
owner,
revoked: std::sync::atomic::AtomicBool::new(false),
});
state
.keys
.insert(pending.key, Occupancy::Live(Arc::clone(&live)));
Ok(live)
}
pub fn cancel(self: &Arc<Self>, key: &ProjectKey) -> Result<SlotIdentity, RegistryRefusal> {
let mut state = self.occupancy.lock().expect("registry mutex");
let pending = match state.keys.remove(key) {
Some(Occupancy::Pending(pending)) => pending,
Some(other) => {
state.keys.insert(key.clone(), other);
return Err(RegistryRefusal::NotAdmitted);
}
None => return Err(RegistryRefusal::NotAdmitted),
};
state.tombstones.insert(pending.slot, pending.key);
Ok(pending.slot)
}
pub fn stop(self: &Arc<Self>, key: &ProjectKey) -> Result<SlotIdentity, RegistryRefusal> {
let mut state = self.occupancy.lock().expect("registry mutex");
let live = match state.keys.remove(key) {
Some(Occupancy::Live(live)) => live,
Some(other) => {
state.keys.insert(key.clone(), other);
return Err(RegistryRefusal::NotAdmitted);
}
None => return Err(RegistryRefusal::NotAdmitted),
};
live.revoke();
let slot = live.slot();
state.tombstones.insert(slot, live.key().clone());
Ok(slot)
}
pub fn stop_if_unheld(
self: &Arc<Self>,
key: &ProjectKey,
slot: SlotIdentity,
) -> Result<SlotIdentity, RegistryRefusal> {
let mut state = self.occupancy.lock().expect("registry mutex");
match state.keys.get(key) {
Some(Occupancy::Live(live)) if live.slot() == slot => {
if Arc::strong_count(live) > 1 {
return Err(RegistryRefusal::StillPending);
}
}
Some(Occupancy::Live(_)) => return Err(RegistryRefusal::NotAdmitted),
Some(Occupancy::Pending(_)) => return Err(RegistryRefusal::StillPending),
None => return Err(RegistryRefusal::NotAdmitted),
};
let Some(Occupancy::Live(live)) = state.keys.remove(key) else {
return Err(RegistryRefusal::NotAdmitted);
};
live.revoke();
let stopped = live.slot();
state.tombstones.insert(stopped, live.key().clone());
Ok(stopped)
}
pub fn is_current(&self, key: &ProjectKey, slot: SlotIdentity) -> bool {
let state = self.occupancy.lock().expect("registry mutex");
if state.tombstones.contains_key(&slot) {
return false;
}
match state.keys.get(key) {
Some(Occupancy::Live(live)) => live.slot() == slot,
_ => false,
}
}
pub fn is_tombstoned(&self, slot: SlotIdentity) -> bool {
self.occupancy
.lock()
.expect("registry mutex")
.tombstones
.contains_key(&slot)
}
pub fn live(&self, key: &ProjectKey) -> Result<Arc<LiveProjectSlot>, RegistryRefusal> {
match self.occupancy.lock().expect("registry mutex").keys.get(key) {
Some(Occupancy::Live(live)) => Ok(Arc::clone(live)),
Some(Occupancy::Pending(_)) => Err(RegistryRefusal::StillPending),
None => Err(RegistryRefusal::NotAdmitted),
}
}
pub fn tombstone_count(&self) -> usize {
self.occupancy
.lock()
.expect("registry mutex")
.tombstones
.len()
}
}