use std::sync::Arc;
use adk_core::subject::{StoreErasure, StoreSupport, SubjectDataStore, SubjectScope};
use async_trait::async_trait;
use serde_json::{Value, json};
use crate::filter::{Field, Filter};
use crate::scope::Scope;
use crate::vectorstore::VectorStore;
pub const SUBJECT_METADATA_KEY: &str = "adk_subject";
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SubjectPartition {
Tagged {
scopes: Vec<Scope>,
},
ScopePerUser,
}
pub struct RagSubjectData {
store: Arc<dyn VectorStore>,
collections: Vec<String>,
partition: SubjectPartition,
support: StoreSupport,
}
impl RagSubjectData {
pub fn new<I, S>(
store: Arc<dyn VectorStore>,
collections: I,
partition: SubjectPartition,
) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self {
store,
collections: collections.into_iter().map(Into::into).collect(),
partition,
support: StoreSupport::Hard,
}
}
#[must_use]
pub fn with_support(mut self, support: StoreSupport) -> Self {
self.support = support;
self
}
fn targets(&self, subject: &SubjectScope) -> adk_core::Result<Vec<(Scope, Option<Filter>)>> {
match &self.partition {
SubjectPartition::Tagged { scopes } => {
let ids: Vec<String> = subject.user_ids().into_iter().map(str::to_owned).collect();
let tagged = Filter::In(Field::metadata(SUBJECT_METADATA_KEY), ids);
Ok(scopes.iter().map(|scope| (scope.clone(), Some(tagged.clone()))).collect())
}
SubjectPartition::ScopePerUser => {
let mut targets = Vec::new();
for app_name in &subject.app_names {
for user_id in subject.user_ids() {
targets.push((Scope::from_parts([app_name.as_str(), user_id])?, None));
}
}
Ok(targets)
}
}
}
}
impl std::fmt::Debug for RagSubjectData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RagSubjectData")
.field("collections", &self.collections)
.field("partition", &self.partition)
.finish_non_exhaustive()
}
}
#[async_trait]
impl SubjectDataStore for RagSubjectData {
fn name(&self) -> &str {
"rag"
}
fn support(&self) -> StoreSupport {
self.support
}
async fn export(&self, subject: &SubjectScope) -> adk_core::Result<Value> {
let mut held = Vec::new();
for collection in &self.collections {
for (scope, filter) in self.targets(subject)? {
let chunks = self.store.count(collection, &scope, filter.as_ref()).await?;
if chunks > 0 {
held.push(json!({
"collection": collection,
"scope": scope.as_str(),
"chunks": chunks,
}));
}
}
}
Ok(json!({ "collections": held }))
}
async fn erase(&self, subject: &SubjectScope) -> adk_core::Result<StoreErasure> {
let mut deleted = 0;
for collection in &self.collections {
for (scope, filter) in self.targets(subject)? {
deleted += match &filter {
Some(filter) => self.store.delete_where(collection, &scope, filter).await?,
None => self.store.purge_scope(collection, &scope).await?,
};
}
}
Ok(StoreErasure::deleted(deleted))
}
}