use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use super::registry::ProjectKey;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EmbeddedIdentity(std::num::NonZeroU64);
static NEXT_EMBEDDED: AtomicU64 = AtomicU64::new(1);
impl EmbeddedIdentity {
pub fn fresh() -> Self {
let raw = NEXT_EMBEDDED.fetch_add(1, Ordering::Relaxed);
Self(std::num::NonZeroU64::new(raw).expect("embedded counter starts at 1"))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EmbedRefusal {
SourceAlreadyOpen {
held_by: EmbeddedIdentity,
},
WouldSelfWait,
AlreadyClosed,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CloseReceipt {
identity: EmbeddedIdentity,
performed_shutdown: bool,
was_final_owner: bool,
}
impl CloseReceipt {
pub fn identity(&self) -> EmbeddedIdentity {
self.identity
}
pub fn performed_shutdown(&self) -> bool {
self.performed_shutdown
}
pub fn was_final_owner(&self) -> bool {
self.was_final_owner
}
}
thread_local! {
static FINALIZING: std::cell::Cell<Option<EmbeddedIdentity>> =
const { std::cell::Cell::new(None) };
}
#[derive(Debug, Default)]
pub struct EmbeddedSourceFactory {
open: std::sync::Mutex<HashMap<ProjectKey, EmbeddedIdentity>>,
shutdown: AtomicBool,
}
impl EmbeddedSourceFactory {
pub fn new() -> Arc<Self> {
Arc::new(Self::default())
}
pub fn open(self: &Arc<Self>, key: ProjectKey) -> Result<EmbeddedSourceHandle, EmbedRefusal> {
let mut open = self.open.lock().expect("embedded registration mutex");
if let Some(held_by) = open.get(&key) {
return Err(EmbedRefusal::SourceAlreadyOpen { held_by: *held_by });
}
let identity = EmbeddedIdentity::fresh();
open.insert(key.clone(), identity);
self.shutdown.store(false, Ordering::Release);
Ok(EmbeddedSourceHandle {
identity,
key,
registration: Arc::clone(self),
closed: AtomicBool::new(false),
})
}
pub fn open_count(&self) -> usize {
self.open.lock().expect("embedded registration mutex").len()
}
pub fn has_shut_down(&self) -> bool {
self.shutdown.load(Ordering::Acquire)
}
fn close_one(&self, key: &ProjectKey, identity: EmbeddedIdentity) -> (bool, bool) {
let mut open = self.open.lock().expect("embedded registration mutex");
let performed = open.get(key) == Some(&identity) && open.remove(key).is_some();
let final_owner = performed && open.is_empty();
if final_owner {
self.shutdown.store(true, Ordering::Release);
}
(performed, final_owner)
}
}
#[derive(Debug)]
pub struct EmbeddedSourceHandle {
identity: EmbeddedIdentity,
key: ProjectKey,
registration: Arc<EmbeddedSourceFactory>,
closed: AtomicBool,
}
impl EmbeddedSourceHandle {
pub fn identity(&self) -> EmbeddedIdentity {
self.identity
}
pub fn key(&self) -> &ProjectKey {
&self.key
}
pub fn is_open(&self) -> bool {
!self.closed.load(Ordering::Acquire)
}
pub fn close(&self) -> Result<CloseReceipt, EmbedRefusal> {
if FINALIZING.with(std::cell::Cell::get) == Some(self.identity) {
return Err(EmbedRefusal::WouldSelfWait);
}
if self.closed.swap(true, Ordering::AcqRel) {
return Err(EmbedRefusal::AlreadyClosed);
}
let (performed, final_owner) = self.registration.close_one(&self.key, self.identity);
Ok(CloseReceipt {
identity: self.identity,
performed_shutdown: performed,
was_final_owner: final_owner,
})
}
pub fn finalize<R>(&self, finalizer: impl FnOnce() -> R) -> R {
struct Guard(Option<EmbeddedIdentity>);
impl Drop for Guard {
fn drop(&mut self) {
FINALIZING.with(|flag| flag.set(self.0));
}
}
let _guard = Guard(FINALIZING.with(|flag| flag.replace(Some(self.identity))));
finalizer()
}
}
impl Drop for EmbeddedSourceHandle {
fn drop(&mut self) {
if !self.closed.swap(true, Ordering::AcqRel) {
self.registration.close_one(&self.key, self.identity);
}
}
}