use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use rmcp::model::{CallToolResult, ContentBlock};
use lean_ctx::core::archive::authority::ArchiveAuthority;
use lean_ctx::core::context_admission::carrier::Withheld;
const CAPACITY: usize = 4_096;
#[derive(Debug)]
struct CallScope {
key: Option<String>,
lineage: Mutex<Option<Lineage>>,
}
tokio::task_local! {
static CALL: Arc<CallScope>;
}
#[derive(Debug, Clone, Copy, Default)]
pub(in crate::server::call_tool) struct Declaration {
pub publishes_every_source: bool,
pub attests_source_free: bool,
}
#[derive(Debug, Clone)]
enum Lineage {
Sources(Box<ArchiveAuthority>),
AttestedSourceFree,
Unknown,
}
impl Lineage {
fn of(authority: Option<&ArchiveAuthority>, declared: Declaration) -> Self {
match authority {
Some(authority) if authority.is_incomplete() => Self::Unknown,
Some(authority) if declared.publishes_every_source => {
Self::Sources(Box::new(authority.clone()))
}
None if declared.attests_source_free => Self::AttestedSourceFree,
Some(_) | None => Self::Unknown,
}
}
fn reauthorized(&self) -> Result<(), Withheld> {
match self {
Self::Sources(authority) => {
let admitted =
lean_ctx::core::policy::runtime::with_source_view(|| authority.admitted())
.unwrap_or(false);
if admitted {
Ok(())
} else {
Err(Withheld::source_unavailable())
}
}
Self::AttestedSourceFree => Ok(()),
Self::Unknown => Err(Withheld::no_source_authority()),
}
}
}
#[derive(Debug, Clone)]
struct Entry {
lineage: Lineage,
dispatches: u32,
gateway_digest: Option<String>,
}
struct Store {
order: VecDeque<String>,
entries: HashMap<String, Entry>,
}
fn store() -> &'static Mutex<Store> {
static STORE: OnceLock<Mutex<Store>> = OnceLock::new();
STORE.get_or_init(|| {
Mutex::new(Store {
order: VecDeque::new(),
entries: HashMap::new(),
})
})
}
pub(in crate::server::call_tool) async fn scope<T>(
key: Option<String>,
call: impl std::future::Future<Output = T>,
) -> T {
let call_scope = Arc::new(CallScope {
key,
lineage: Mutex::new(None),
});
CALL.scope(call_scope, call).await
}
fn current_call() -> Option<Arc<CallScope>> {
CALL.try_with(Clone::clone).ok()
}
pub(in crate::server::call_tool) fn record(
authority: Option<&ArchiveAuthority>,
declared: Declaration,
) {
let Some(call) = current_call() else {
return;
};
let lineage = Lineage::of(authority, declared);
if let Some(key) = &call.key {
record_for(key, lineage.clone(), None);
}
*call.lineage.lock().unwrap_or_else(PoisonError::into_inner) = Some(lineage);
}
fn record_for(key: &str, lineage: Lineage, gateway_digest: Option<String>) {
let mut store = store().lock().unwrap_or_else(PoisonError::into_inner);
if let Some(entry) = store.entries.get_mut(key) {
entry.lineage = lineage;
entry.gateway_digest = gateway_digest;
entry.dispatches = entry.dispatches.saturating_add(1);
return;
}
store.entries.insert(
key.to_owned(),
Entry {
lineage,
dispatches: 1,
gateway_digest,
},
);
store.order.push_back(key.to_owned());
if store.order.len() > CAPACITY
&& let Some(oldest) = store.order.pop_front()
{
store.entries.remove(&oldest);
}
}
pub(in crate::server::call_tool) fn denial() -> Option<CallToolResult> {
let key = current_call()?.key.clone()?;
denial_text_for(&key).map(|text| CallToolResult::error(vec![ContentBlock::text(text)]))
}
pub(in crate::server::call_tool) const COMPLETED_NOT_RELEASED: &str =
"replay.completed_result_not_released";
fn denial_text_for(key: &str) -> Option<String> {
let withheld = denial_for(key)?;
Some(if dispatches_for(key) > 0 {
format!(
"operation already executed under this idempotency key and not executed again; \
its original result is not released ({COMPLETED_NOT_RELEASED}, {})",
withheld.codes().join(", ")
)
} else {
withheld.message("replayed result")
})
}
fn entry(key: &str) -> Option<Entry> {
store()
.lock()
.unwrap_or_else(PoisonError::into_inner)
.entries
.get(key)
.cloned()
}
fn denial_for(key: &str) -> Option<Withheld> {
match entry(key).map(|entry| entry.lineage) {
Some(lineage @ Lineage::Sources(_)) => lineage.reauthorized().err(),
Some(Lineage::AttestedSourceFree) => None,
Some(Lineage::Unknown) | None => {
lean_ctx::core::context_admission::stored::source_authority_required()
.then(Withheld::no_source_authority)
}
}
}
fn cache_entry_key(cache_id: &str) -> String {
format!("response-cache:{cache_id}")
}
fn current_gateway_digest() -> String {
lean_ctx::core::context_admission::stores::StoreAdmission::current()
.digest()
.to_owned()
}
pub(in crate::server::call_tool) fn bind_cache_entry(cache_id: &str) -> bool {
let lineage = current_call().and_then(|call| {
call.lineage
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
});
bind_cache_entry_to(cache_id, lineage)
}
fn bind_cache_entry_to(cache_id: &str, lineage: Option<Lineage>) -> bool {
match lineage {
Some(lineage @ (Lineage::Sources(_) | Lineage::AttestedSourceFree)) => {
record_for(
&cache_entry_key(cache_id),
lineage,
Some(current_gateway_digest()),
);
true
}
Some(Lineage::Unknown) | None => false,
}
}
pub(in crate::server::call_tool) fn cache_entry_current(cache_id: &str) -> bool {
entry(&cache_entry_key(cache_id)).is_some_and(|entry| {
entry.gateway_digest.as_deref() == Some(current_gateway_digest().as_str())
&& entry.lineage.reauthorized().is_ok()
})
}
fn dispatches_for(key: &str) -> u32 {
store()
.lock()
.unwrap_or_else(PoisonError::into_inner)
.entries
.get(key)
.map_or(0, |entry| entry.dispatches)
}
#[cfg(test)]
mod tests;