Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
203
akode-rs/akode-mcp/src/client_tool_catalog.rs
Normal file
203
akode-rs/akode-mcp/src/client_tool_catalog.rs
Normal file
@@ -0,0 +1,203 @@
|
||||
//! Client-local catalog revisions and synchronization for MCP calls.
|
||||
//!
|
||||
//! Only active readers, calls, and frozen model bindings pin earlier snapshots.
|
||||
//! Servers coalesce list-change notifications and publish only a stable listing.
|
||||
//! Notifications update discovery without waiting for admitted calls to finish.
|
||||
//! Failed refreshes retain the last catalog and share a short retry cooldown.
|
||||
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use akode_rmcp_client::ToolListRevision;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio::time::Instant;
|
||||
|
||||
use crate::tools::ToolInfo;
|
||||
|
||||
const NOTIFICATION_REFRESH_COOLDOWN: Duration = Duration::from_secs(5);
|
||||
|
||||
pub(crate) struct ClientToolCatalog {
|
||||
current: RwLock<CatalogState>,
|
||||
/// Serialize fetches and retain the next retry time after failure or cancellation.
|
||||
refresh_lock: Mutex<Option<Instant>>,
|
||||
/// Starts at zero so notifications during the initial listing stay pending.
|
||||
listed_notification_revision: AtomicU64,
|
||||
}
|
||||
|
||||
struct CatalogState {
|
||||
revision: u64,
|
||||
tools: Arc<[ToolInfo]>,
|
||||
meta: Option<Arc<serde_json::Value>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ToolCatalogSnapshot {
|
||||
pub(crate) revision: u64,
|
||||
pub(crate) tools: Arc<[ToolInfo]>,
|
||||
pub(crate) meta: Option<Arc<serde_json::Value>>,
|
||||
}
|
||||
|
||||
impl ClientToolCatalog {
|
||||
pub(crate) fn new(
|
||||
tools: impl Into<Arc<[ToolInfo]>>,
|
||||
meta: Option<Arc<serde_json::Value>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
current: RwLock::new(CatalogState {
|
||||
revision: 0,
|
||||
tools: tools.into(),
|
||||
meta,
|
||||
}),
|
||||
refresh_lock: Mutex::new(None),
|
||||
listed_notification_revision: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn read<R>(&self, read: impl FnOnce(ToolCatalogSnapshot) -> R) -> R {
|
||||
let current = self.current.read().await;
|
||||
let snapshot = ToolCatalogSnapshot {
|
||||
revision: current.revision,
|
||||
tools: Arc::clone(¤t.tools),
|
||||
meta: current.meta.clone(),
|
||||
};
|
||||
drop(current);
|
||||
read(snapshot)
|
||||
}
|
||||
|
||||
pub(crate) fn notifications_current(&self, notifications: &ToolListRevision) -> bool {
|
||||
self.listed_notification_revision.load(Ordering::Acquire) == notifications.current()
|
||||
}
|
||||
|
||||
/// Refresh ordinary server catalogs, coalescing concurrent readers. Never mark a
|
||||
/// listing current if another notification arrived while fetching its pages.
|
||||
/// Retry once; persistent churn stays pending until the retry cooldown expires.
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "refreshes must remain serialized through fetching and catalog publication"
|
||||
)]
|
||||
pub(crate) async fn refresh_after_notifications<F, Fut>(
|
||||
&self,
|
||||
notifications: &ToolListRevision,
|
||||
timeout: Duration,
|
||||
mut fetch: F,
|
||||
) -> Result<()>
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: Future<Output = Result<(Vec<ToolInfo>, Option<Arc<serde_json::Value>>)>>,
|
||||
{
|
||||
if self.notifications_current(notifications) {
|
||||
return Ok(());
|
||||
}
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut retry_after = tokio::time::timeout_at(deadline, self.refresh_lock.lock())
|
||||
.await
|
||||
.context("MCP tool catalog refresh timed out")?;
|
||||
if self.notifications_current(notifications)
|
||||
|| retry_after.is_some_and(|deadline| Instant::now() < deadline)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
// Also bound retries if the caller cancels this future during the fetch.
|
||||
*retry_after = Some(deadline + NOTIFICATION_REFRESH_COOLDOWN);
|
||||
let result = tokio::time::timeout_at(deadline, async {
|
||||
for _ in 0..2 {
|
||||
let revision = notifications.current();
|
||||
let tools = fetch().await;
|
||||
let mut current = self.current.write().await;
|
||||
if notifications.current() != revision {
|
||||
continue;
|
||||
}
|
||||
let (tools, meta) = tools?;
|
||||
current.tools = tools.into();
|
||||
current.meta = meta;
|
||||
current.revision += 1;
|
||||
self.listed_notification_revision
|
||||
.store(revision, Ordering::Release);
|
||||
return Ok(());
|
||||
}
|
||||
bail!("MCP tool list changed during catalog refresh")
|
||||
})
|
||||
.await
|
||||
.context("MCP tool catalog refresh timed out")
|
||||
.and_then(std::convert::identity);
|
||||
*retry_after = result
|
||||
.is_err()
|
||||
.then(|| Instant::now() + NOTIFICATION_REFRESH_COOLDOWN);
|
||||
result
|
||||
}
|
||||
|
||||
/// Installs a new catalog as a list-change refresh would.
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn replace_for_test(&self, tools: Vec<ToolInfo>) {
|
||||
let mut current = self.current.write().await;
|
||||
current.tools = tools.into();
|
||||
current.revision += 1;
|
||||
}
|
||||
|
||||
/// Reject stale calls before preparation. List-change notifications may publish while an
|
||||
/// admitted call runs.
|
||||
pub(crate) async fn run_with_snapshot<R, F, Fut>(
|
||||
&self,
|
||||
expected: &ToolCatalogSnapshot,
|
||||
run: F,
|
||||
) -> Option<R>
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
Fut: Future<Output = R>,
|
||||
{
|
||||
let current = self.read(|snapshot| snapshot).await;
|
||||
if current.revision != expected.revision
|
||||
&& !catalogs_match(¤t.tools, &expected.tools)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(run().await)
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares complete definitions independently of tool-list order. Stable sorting keeps
|
||||
/// conflicting duplicate identities in their original order, since deduplication can pick the
|
||||
/// first definition. This slow path runs only after the client's revision has changed.
|
||||
fn catalogs_match(left: &[ToolInfo], right: &[ToolInfo]) -> bool {
|
||||
if left == right {
|
||||
return true;
|
||||
}
|
||||
if left.len() != right.len() {
|
||||
return false;
|
||||
}
|
||||
let mut left = left.iter().collect::<Vec<_>>();
|
||||
let mut right = right.iter().collect::<Vec<_>>();
|
||||
for tools in [&mut left, &mut right] {
|
||||
tools.sort_by_key(|tool| {
|
||||
(
|
||||
tool.server_name.as_str(),
|
||||
tool.tool.name.as_ref(),
|
||||
tool.callable_namespace.as_str(),
|
||||
tool.callable_name.as_str(),
|
||||
)
|
||||
});
|
||||
}
|
||||
left == right
|
||||
}
|
||||
|
||||
/// A binding cache key includes client identity, since new clients start at zero.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ClientToolCatalogRevision {
|
||||
pub(crate) catalog: Arc<ClientToolCatalog>,
|
||||
pub(crate) revision: u64,
|
||||
}
|
||||
|
||||
impl PartialEq for ClientToolCatalogRevision {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
Arc::ptr_eq(&self.catalog, &other.catalog) && self.revision == other.revision
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for ClientToolCatalogRevision {}
|
||||
Reference in New Issue
Block a user