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"))
}
pub(crate) fn raw(&self) -> u64 {
self.0.get()
}
}
#[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),
_not_unwind_safe: std::marker::PhantomData,
})
}
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,
_not_unwind_safe: super::public_api::NotUnwindSafe,
}
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 begin_close(&self) -> SourceCloseReceipt {
let performed = if self.closed.swap(true, Ordering::AcqRel) {
false
} else {
let (performed, _final_owner) = self.registration.close_one(&self.key, self.identity);
performed
};
SourceCloseReceipt {
identity: self.identity,
performed_shutdown: performed,
_not_unwind_safe: std::marker::PhantomData,
}
}
pub fn runtime_view(&self) -> super::public_api::SourceRuntimeView {
let phase = if self.closed.load(Ordering::Acquire) {
super::public_api::SourceRuntimePhase::Stopped
} else {
super::public_api::SourceRuntimePhase::Loading
};
super::public_api::SourceRuntimeView {
binding_identity: format!("source-{}", self.identity.raw()),
current_publication_identity: None,
observer_epoch: 0,
phase,
source_version: 0,
}
}
pub fn search_symbols(
&self,
request: &super::public_api::SymbolSearchRequest,
) -> Result<
super::public_api::EmbedClaim<super::public_api::SymbolSearchResult>,
super::public_api::EmbedSourceRefusal,
> {
let _ = request;
Err(super::public_api::dark_unbound_refusal(
crate::lifecycle_identity::OperationKind::SearchSymbols,
))
}
pub fn search_text(
&self,
request: &super::public_api::TextSearchRequest,
) -> Result<
super::public_api::EmbedClaim<super::public_api::TextSearchResult>,
super::public_api::EmbedSourceRefusal,
> {
let _ = request;
Err(super::public_api::dark_unbound_refusal(
crate::lifecycle_identity::OperationKind::SearchText,
))
}
pub fn request_refresh(
&self,
) -> Result<super::public_api::EmbedRefreshTicket, super::public_api::EmbedSourceRefusal> {
Err(super::public_api::dark_unbound_refusal(
crate::lifecycle_identity::OperationKind::RefreshSource,
))
}
#[cfg(all(test, feature = "server"))]
pub fn self_wait_probe_for_test(&self) -> Result<SourceCloseReport, ReceiptWaitError> {
let receipt = self.begin_close();
self.finalize(|| receipt.wait_for_test())
}
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()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReceiptWaitError {
DeadlineElapsed,
WouldSelfWait,
}
impl std::fmt::Display for ReceiptWaitError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::DeadlineElapsed => {
write!(f, "the deadline passed before the wait completed")
}
Self::WouldSelfWait => write!(
f,
"waiting on this receipt from inside its own source's finalizer \
would wait on the calling thread itself"
),
}
}
}
impl std::error::Error for ReceiptWaitError {}
#[derive(Debug)]
pub struct SourceCloseReceipt {
identity: EmbeddedIdentity,
performed_shutdown: bool,
_not_unwind_safe: super::public_api::NotUnwindSafe,
}
impl SourceCloseReceipt {
pub fn wait(
&self,
deadline: std::time::Instant,
) -> Result<super::public_api::SourceCloseReport, ReceiptWaitError> {
let _ = deadline;
if FINALIZING.with(std::cell::Cell::get) == Some(self.identity) {
return Err(ReceiptWaitError::WouldSelfWait);
}
Ok(super::public_api::SourceCloseReport {
already_terminal: !self.performed_shutdown,
terminal_source_version: 0,
})
}
#[cfg(all(test, feature = "server"))]
pub fn wait_for_test(&self) -> Result<SourceCloseReport, ReceiptWaitError> {
if FINALIZING.with(std::cell::Cell::get) == Some(self.identity) {
return Err(ReceiptWaitError::WouldSelfWait);
}
Ok(SourceCloseReport {
finalized: true,
performed_shutdown: self.performed_shutdown,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SourceCloseReport {
finalized: bool,
performed_shutdown: bool,
}
impl SourceCloseReport {
pub fn finalized(&self) -> bool {
self.finalized
}
pub fn performed_shutdown(&self) -> bool {
self.performed_shutdown
}
}
impl Drop for EmbeddedSourceHandle {
fn drop(&mut self) {
if !self.closed.swap(true, Ordering::AcqRel) {
self.registration.close_one(&self.key, self.identity);
}
}
}