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:
51
akode-rs/utils/cache/src/initialization_tests.rs
vendored
Normal file
51
akode-rs/utils/cache/src/initialization_tests.rs
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
//! Checks that initialization releases the global lock and survives LRU eviction.
|
||||
|
||||
use crate::BlockingLruCache;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn initialization_keeps_other_keys_available_through_eviction() {
|
||||
let cache = BlockingLruCache::new(NonZeroUsize::new(/*n*/ 2).expect("capacity"));
|
||||
assert_eq!(cache.get_or_init("hot", || 3), 3);
|
||||
let handle = tokio::runtime::Handle::current();
|
||||
let (started_tx, started_rx) = mpsc::channel();
|
||||
let (release_tx, release_rx) = mpsc::channel();
|
||||
|
||||
std::thread::scope(|scope| {
|
||||
let cache = &cache;
|
||||
let initializing = scope.spawn(move || {
|
||||
let _entered = handle.enter();
|
||||
cache.get_or_init("busy", || {
|
||||
started_tx.send(()).expect("signal initialization");
|
||||
release_rx
|
||||
.recv_timeout(Duration::from_secs(/*secs*/ 5))
|
||||
.expect("other keys should finish before initialization is released");
|
||||
7
|
||||
})
|
||||
});
|
||||
started_rx
|
||||
.recv_timeout(Duration::from_secs(/*secs*/ 5))
|
||||
.expect("initialization should start");
|
||||
|
||||
assert_eq!(cache.get_or_init("hot", || panic!("cached value")), 3);
|
||||
assert_eq!(cache.get_or_init("other", || 5), 5);
|
||||
assert!(cache.get(&"busy").is_none());
|
||||
|
||||
// The evicted initializer still owns its cell. A new resident cell can
|
||||
// independently initialize the same deterministic value for this key.
|
||||
assert_eq!(cache.get_or_init("busy", || 7), 7);
|
||||
release_tx.send(()).expect("release initialization");
|
||||
assert_eq!(initializing.join().expect("initialization thread"), 7);
|
||||
assert_eq!(
|
||||
cache.with_mut(|entries| {
|
||||
entries
|
||||
.iter()
|
||||
.map(|(key, value)| (*key, *value.get().expect("initialized value")))
|
||||
.collect::<Vec<_>>()
|
||||
}),
|
||||
vec![("busy", 7), ("other", 5)]
|
||||
);
|
||||
});
|
||||
}
|
||||
167
akode-rs/utils/cache/src/lib.rs
vendored
Normal file
167
akode-rs/utils/cache/src/lib.rs
vendored
Normal file
@@ -0,0 +1,167 @@
|
||||
use std::borrow::Borrow;
|
||||
use std::hash::Hash;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use lru::LruCache;
|
||||
use sha1::Digest;
|
||||
use sha1::Sha1;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::MutexGuard;
|
||||
|
||||
/// A minimal LRU cache protected by a Tokio mutex.
|
||||
/// Calls outside a Tokio runtime are no-ops.
|
||||
pub struct BlockingLruCache<K, V> {
|
||||
inner: Mutex<LruCache<K, V>>,
|
||||
}
|
||||
|
||||
impl<K, V> BlockingLruCache<K, V>
|
||||
where
|
||||
K: Eq + Hash,
|
||||
{
|
||||
/// Creates a cache with the provided non-zero capacity.
|
||||
#[must_use]
|
||||
pub fn new(capacity: NonZeroUsize) -> Self {
|
||||
Self {
|
||||
inner: Mutex::new(LruCache::new(capacity)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a clone of the cached value for `key`, or computes and inserts it.
|
||||
pub fn get_or_insert_with(&self, key: K, value: impl FnOnce() -> V) -> V
|
||||
where
|
||||
V: Clone,
|
||||
{
|
||||
if let Some(mut guard) = lock_if_runtime(&self.inner) {
|
||||
if let Some(v) = guard.get(&key) {
|
||||
return v.clone();
|
||||
}
|
||||
let v = value();
|
||||
// Insert and return a clone to keep ownership in the cache.
|
||||
guard.put(key, v.clone());
|
||||
return v;
|
||||
}
|
||||
value()
|
||||
}
|
||||
|
||||
/// Like `get_or_insert_with`, but the value factory may fail.
|
||||
pub fn get_or_try_insert_with<E>(
|
||||
&self,
|
||||
key: K,
|
||||
value: impl FnOnce() -> Result<V, E>,
|
||||
) -> Result<V, E>
|
||||
where
|
||||
V: Clone,
|
||||
{
|
||||
if let Some(mut guard) = lock_if_runtime(&self.inner) {
|
||||
if let Some(v) = guard.get(&key) {
|
||||
return Ok(v.clone());
|
||||
}
|
||||
let v = value()?;
|
||||
guard.put(key, v.clone());
|
||||
return Ok(v);
|
||||
}
|
||||
value()
|
||||
}
|
||||
|
||||
/// Builds a cache if `capacity` is non-zero, returning `None` otherwise.
|
||||
#[must_use]
|
||||
pub fn try_with_capacity(capacity: usize) -> Option<Self> {
|
||||
NonZeroUsize::new(capacity).map(Self::new)
|
||||
}
|
||||
|
||||
/// Returns a clone of the cached value corresponding to `key`, if present.
|
||||
pub fn get<Q>(&self, key: &Q) -> Option<V>
|
||||
where
|
||||
K: Borrow<Q>,
|
||||
Q: Hash + Eq + ?Sized,
|
||||
V: Clone,
|
||||
{
|
||||
let mut guard = lock_if_runtime(&self.inner)?;
|
||||
guard.get(key).cloned()
|
||||
}
|
||||
|
||||
/// Inserts `value` for `key`, returning the previous entry if it existed.
|
||||
pub fn insert(&self, key: K, value: V) -> Option<V> {
|
||||
let mut guard = lock_if_runtime(&self.inner)?;
|
||||
guard.put(key, value)
|
||||
}
|
||||
|
||||
/// Removes the entry for `key` if it exists, returning it.
|
||||
pub fn remove<Q>(&self, key: &Q) -> Option<V>
|
||||
where
|
||||
K: Borrow<Q>,
|
||||
Q: Hash + Eq + ?Sized,
|
||||
{
|
||||
let mut guard = lock_if_runtime(&self.inner)?;
|
||||
guard.pop(key)
|
||||
}
|
||||
|
||||
/// Clears all entries from the cache.
|
||||
pub fn clear(&self) {
|
||||
if let Some(mut guard) = lock_if_runtime(&self.inner) {
|
||||
guard.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes `callback` with a mutable reference to the underlying cache.
|
||||
pub fn with_mut<R>(&self, callback: impl FnOnce(&mut LruCache<K, V>) -> R) -> R {
|
||||
if let Some(mut guard) = lock_if_runtime(&self.inner) {
|
||||
callback(&mut guard)
|
||||
} else {
|
||||
let mut disabled = LruCache::unbounded();
|
||||
callback(&mut disabled)
|
||||
}
|
||||
}
|
||||
|
||||
/// Provides direct access to the cache guard when a Tokio runtime is available.
|
||||
pub fn blocking_lock(&self) -> Option<MutexGuard<'_, LruCache<K, V>>> {
|
||||
lock_if_runtime(&self.inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V> BlockingLruCache<K, Arc<OnceLock<V>>>
|
||||
where
|
||||
K: Eq + Hash,
|
||||
V: Clone,
|
||||
{
|
||||
/// Returns the cached value, initializing it outside the global cache lock.
|
||||
///
|
||||
/// Concurrent callers share initialization while the entry remains cached.
|
||||
/// An in-flight entry can be evicted and initialized again, so factories must
|
||||
/// be deterministic. Initialization and same-key waits use a blocking region.
|
||||
pub fn get_or_init(&self, key: K, value: impl FnOnce() -> V) -> V {
|
||||
let entry = self.get_or_insert_with(key, || Arc::new(OnceLock::new()));
|
||||
if let Some(value) = entry.get() {
|
||||
return value.clone();
|
||||
}
|
||||
tokio::task::block_in_place(|| entry.get_or_init(value).clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn lock_if_runtime<K, V>(m: &Mutex<LruCache<K, V>>) -> Option<MutexGuard<'_, LruCache<K, V>>>
|
||||
where
|
||||
K: Eq + Hash,
|
||||
{
|
||||
tokio::runtime::Handle::try_current().ok()?;
|
||||
Some(tokio::task::block_in_place(|| m.blocking_lock()))
|
||||
}
|
||||
|
||||
/// Computes the SHA-1 digest of `bytes`.
|
||||
///
|
||||
/// Useful for content-based cache keys when you want to avoid staleness
|
||||
/// caused by path-only keys.
|
||||
#[must_use]
|
||||
pub fn sha1_digest(bytes: &[u8]) -> [u8; 20] {
|
||||
let mut hasher = Sha1::new();
|
||||
hasher.update(bytes);
|
||||
let result = hasher.finalize();
|
||||
let mut out = [0; 20];
|
||||
out.copy_from_slice(&result);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lib_tests.rs"]
|
||||
mod tests;
|
||||
54
akode-rs/utils/cache/src/lib_tests.rs
vendored
Normal file
54
akode-rs/utils/cache/src/lib_tests.rs
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
#![cfg(test)]
|
||||
|
||||
//! Unit tests for the crate and its related test suites.
|
||||
|
||||
use super::BlockingLruCache;
|
||||
use std::num::NonZeroUsize;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn stores_and_retrieves_values() {
|
||||
let cache = BlockingLruCache::new(NonZeroUsize::new(2).expect("capacity"));
|
||||
|
||||
assert!(cache.get(&"first").is_none());
|
||||
cache.insert("first", /*value*/ 1);
|
||||
assert_eq!(cache.get(&"first"), Some(1));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn evicts_least_recently_used() {
|
||||
let cache = BlockingLruCache::new(NonZeroUsize::new(2).expect("capacity"));
|
||||
cache.insert("a", /*value*/ 1);
|
||||
cache.insert("b", /*value*/ 2);
|
||||
assert_eq!(cache.get(&"a"), Some(1));
|
||||
|
||||
cache.insert("c", /*value*/ 3);
|
||||
|
||||
assert!(cache.get(&"b").is_none());
|
||||
assert_eq!(cache.get(&"a"), Some(1));
|
||||
assert_eq!(cache.get(&"c"), Some(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_without_runtime() {
|
||||
let cache = BlockingLruCache::new(NonZeroUsize::new(2).expect("capacity"));
|
||||
cache.insert("first", /*value*/ 1);
|
||||
assert!(cache.get(&"first").is_none());
|
||||
|
||||
assert_eq!(cache.get_or_insert_with("first", || 2), 2);
|
||||
assert!(cache.get(&"first").is_none());
|
||||
|
||||
assert!(cache.remove(&"first").is_none());
|
||||
cache.clear();
|
||||
|
||||
let result = cache.with_mut(|inner| {
|
||||
inner.put("tmp", 3);
|
||||
inner.get(&"tmp").cloned()
|
||||
});
|
||||
assert_eq!(result, Some(3));
|
||||
assert!(cache.get(&"tmp").is_none());
|
||||
|
||||
assert!(cache.blocking_lock().is_none());
|
||||
}
|
||||
|
||||
#[path = "initialization_tests.rs"]
|
||||
mod initialization_tests;
|
||||
Reference in New Issue
Block a user