use std::collections::HashMap;
use std::sync::Mutex;
use adk_core::{Result, ToolContext};
use async_trait::async_trait;
use sha2::{Digest as _, Sha256};
pub(crate) const READ_SCOPE_CAPACITY: usize = 1024;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct ReadScope {
pub app: String,
pub user: String,
pub session: String,
pub agent: String,
}
impl ReadScope {
pub fn new(
app: impl Into<String>,
user: impl Into<String>,
session: impl Into<String>,
agent: impl Into<String>,
) -> Self {
Self { app: app.into(), user: user.into(), session: session.into(), agent: agent.into() }
}
pub fn of(ctx: &dyn ToolContext) -> Option<Self> {
let session = ctx.session_id();
if session.is_empty() {
return None;
}
Some(Self::new(ctx.app_name(), ctx.user_id(), session, ctx.agent_name()))
}
}
#[async_trait]
pub trait ReadLedger: Send + Sync {
async fn record(&self, scope: &ReadScope, path: &str, sha256: &str) -> Result<()>;
async fn digest(&self, scope: &ReadScope, path: &str) -> Result<Option<String>>;
async fn forget(&self, scope: &ReadScope, path: &str) -> Result<()>;
}
#[derive(Default)]
pub struct InMemoryReadLedger {
inner: Mutex<Scopes>,
}
#[derive(Default)]
struct Scopes {
scoped: HashMap<ReadScope, (u64, HashMap<String, String>)>,
tick: u64,
}
impl Scopes {
fn files(&mut self, scope: &ReadScope) -> &mut HashMap<String, String> {
self.tick += 1;
if !self.scoped.contains_key(scope)
&& self.scoped.len() >= READ_SCOPE_CAPACITY
&& let Some(oldest) = self
.scoped
.iter()
.min_by_key(|(_, (used, _))| *used)
.map(|(oldest, _)| oldest.clone())
{
self.scoped.remove(&oldest);
}
let entry = self.scoped.entry(scope.clone()).or_default();
entry.0 = self.tick;
&mut entry.1
}
fn existing(&mut self, scope: &ReadScope) -> Option<&mut HashMap<String, String>> {
self.tick += 1;
let tick = self.tick;
self.scoped.get_mut(scope).map(|entry| {
entry.0 = tick;
&mut entry.1
})
}
}
impl InMemoryReadLedger {
pub fn new() -> Self {
Self::default()
}
#[cfg(test)]
pub(crate) fn scopes(&self) -> usize {
self.inner.lock().map(|inner| inner.scoped.len()).unwrap_or_default()
}
}
#[async_trait]
impl ReadLedger for InMemoryReadLedger {
async fn record(&self, scope: &ReadScope, path: &str, sha256: &str) -> Result<()> {
let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
inner.files(scope).insert(path.to_string(), sha256.to_string());
Ok(())
}
async fn digest(&self, scope: &ReadScope, path: &str) -> Result<Option<String>> {
let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
Ok(inner.existing(scope).and_then(|files| files.get(path).cloned()))
}
async fn forget(&self, scope: &ReadScope, path: &str) -> Result<()> {
let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
if let Some(files) = inner.existing(scope) {
files.remove(path);
}
Ok(())
}
}
pub fn sha256_hex(bytes: &[u8]) -> String {
use std::fmt::Write as _;
let mut out = String::with_capacity(64);
for byte in Sha256::digest(bytes) {
let _ = write!(out, "{byte:02x}");
}
out
}