use crate::error::CoreError;
use crate::event::Usage;
use crate::ids::RunId;
use crate::message::Message;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Checkpoint {
pub run_id: RunId,
pub step: u64,
pub state: Value,
}
#[async_trait]
pub trait CheckpointStore: Send + Sync {
async fn save(&self, cp: Checkpoint) -> Result<(), CoreError>;
async fn latest(&self, run_id: RunId) -> Result<Option<Checkpoint>, CoreError>;
async fn history(&self, run_id: RunId) -> Result<Vec<Checkpoint>, CoreError> {
Ok(self.latest(run_id).await?.into_iter().collect())
}
async fn prune(&self, run_id: RunId, keep_last: u64) -> Result<u64, CoreError> {
let _ = run_id;
if keep_last == 0 {
return Err(CoreError::Store("prune keep_last must be at least 1".into()));
}
Ok(0)
}
}
#[async_trait]
pub trait MemoryLog: Send + Sync {
async fn append(&self, log: &str, expected_len: u64, entries: Vec<Message>) -> Result<u64, CoreError>;
async fn read(&self, log: &str) -> Result<Vec<Message>, CoreError>;
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VectorRecord {
pub id: String,
pub vector: Vec<f32>,
pub text: String,
pub meta: BTreeMap<String, String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Scored {
pub id: String,
pub score: f32,
pub text: String,
pub meta: BTreeMap<String, String>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Filter(pub BTreeMap<String, String>);
impl Filter {
pub fn matches(&self, meta: &BTreeMap<String, String>) -> bool {
self.0.iter().all(|(k, v)| meta.get(k) == Some(v))
}
}
#[async_trait]
pub trait VectorStore: Send + Sync {
fn dims(&self) -> usize;
async fn upsert(&self, records: Vec<VectorRecord>) -> Result<(), CoreError>;
async fn search(&self, query: &[f32], k: usize, filter: &Filter) -> Result<Vec<Scored>, CoreError>;
}
#[async_trait]
pub trait KeywordStore: Send + Sync {
async fn search_text(&self, query: &str, k: usize, filter: &Filter) -> Result<Vec<Scored>, CoreError>;
}
#[async_trait]
pub trait BlobStore: Send + Sync {
async fn put(&self, path: &str, bytes: Vec<u8>) -> Result<(), CoreError>;
async fn get(&self, path: &str) -> Result<Vec<u8>, CoreError>;
}
pub fn cosine(a: &[f32], b: &[f32]) -> f32 {
assert_eq!(a.len(), b.len(), "cosine of unequal lengths");
let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
let na = a.iter().map(|x| x * x).sum::<f32>().sqrt();
let nb = b.iter().map(|x| x * x).sum::<f32>().sqrt();
if na == 0.0 || nb == 0.0 {
return 0.0;
}
dot / (na * nb)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Lease {
pub run_id: RunId,
pub token: u64,
pub attempts: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JobState {
Pending {
due_ms: i64,
},
Leased {
token: u64,
until_ms: i64,
next_due_ms: Option<i64>,
},
Done,
Failed {
error: String,
},
}
#[async_trait]
pub trait JobQueue: Send + Sync {
async fn enqueue(&self, run_id: RunId, due_ms: i64) -> Result<(), CoreError>;
async fn claim_due(&self, limit: usize, lease_ms: i64) -> Result<Vec<Lease>, CoreError>;
async fn complete(&self, lease: &Lease) -> Result<(), CoreError>;
async fn fail(&self, lease: &Lease, error: &str) -> Result<(), CoreError>;
async fn reschedule(&self, lease: &Lease, due_ms: i64) -> Result<(), CoreError>;
}
#[async_trait]
pub trait UsageLedger: Send + Sync {
async fn period_total(&self, key: &str) -> Result<u64, CoreError>;
async fn record(&self, key: &str, usage: Usage) -> Result<(), CoreError>;
}