use std::collections::HashMap;
use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::{Arc, Mutex, PoisonError};
use async_lock::OnceCell;
use crate::binding::Instance;
use crate::error::LookupError;
use crate::graph::BindingId;
use crate::key::KeyName;
use crate::redact::Redactor;
use crate::transport::enhancer::ClosureId;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum Slot {
Binding(BindingId),
Closure(ClosureId),
}
pub(crate) struct OnceCells {
cells: Mutex<Option<HashMap<Slot, Arc<OnceCell<Instance>>>>>,
}
impl Default for OnceCells {
fn default() -> Self {
OnceCells { cells: Mutex::new(Some(HashMap::new())) }
}
}
impl OnceCells {
pub(crate) async fn get_or_build<F, Fut>(&self, slot: Slot, key: KeyName, build: F) -> Result<Instance, LookupError>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<Instance, LookupError>>,
{
let cell = {
let mut cells = self.cells.lock().unwrap_or_else(PoisonError::into_inner);
let Some(cells) = cells.as_mut() else {
return Err(LookupError::ExecutionEnded { key });
};
Arc::clone(cells.entry(slot).or_default())
};
let instance = cell.get_or_try_init(build).await?;
Ok(Arc::clone(instance))
}
pub(crate) fn release(&self, redactor: &Redactor) {
let released = self.cells.lock().unwrap_or_else(PoisonError::into_inner).take();
let mut first = None;
for (_, cell) in released.into_iter().flatten() {
if let Err(payload) = catch_unwind(AssertUnwindSafe(move || drop(cell))) {
first.get_or_insert(payload);
}
}
if let Some(payload) = first {
let message = redactor.panic(payload);
tracing::warn!(%message, "an execution-scoped instance panicked while it was dropped at the end of its execution");
}
}
}