aien-local-stack
aien-dev/aien-local-stack
Brought by drakestapleton
aien-local-stack / src / recipe.rs
| 1 | use aien_inference_protocol::ContextRecipeRef; |
| 2 | use aien_protocol_types::Digest32; |
| 3 | use aien_provenance::compute_canonical_json_digest; |
| 4 | use parking_lot::RwLock; |
| 5 | use serde::{Deserialize, Serialize}; |
| 6 | use std::collections::BTreeMap; |
| 7 | use std::fs; |
| 8 | use std::path::PathBuf; |
| 9 | use std::sync::Arc; |
| 10 | use uuid::Uuid; |
| 11 | |
| 12 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 13 | pub struct ContextRecipe { |
| 14 | pub recipe_id: Uuid, |
| 15 | pub root_prompt_tokens: Vec<u32>, |
| 16 | pub branch_deltas: BTreeMap<Uuid, Vec<u32>>, |
| 17 | } |
| 18 | |
| 19 | impl ContextRecipe { |
| 20 | pub fn new(root_prompt_tokens: Vec<u32>) -> Self { |
| 21 | Self { |
| 22 | recipe_id: Uuid::new_v4(), |
| 23 | root_prompt_tokens, |
| 24 | branch_deltas: BTreeMap::new(), |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | pub fn with_branch_delta(mut self, branch_id: Uuid, delta: Vec<u32>) -> Self { |
| 29 | self.branch_deltas.insert(branch_id, delta); |
| 30 | self |
| 31 | } |
| 32 | |
| 33 | pub fn compute_digest(&self) -> Digest32 { |
| 34 | compute_canonical_json_digest(self).unwrap_or(Digest32::ZERO) |
| 35 | } |
| 36 | |
| 37 | pub fn to_ref(&self) -> ContextRecipeRef { |
| 38 | ContextRecipeRef { |
| 39 | recipe_id: self.recipe_id, |
| 40 | recipe_digest: self.compute_digest(), |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | pub fn full_tokens_for_branch(&self, branch_id: &Uuid) -> Vec<u32> { |
| 45 | let mut tokens = self.root_prompt_tokens.clone(); |
| 46 | if let Some(delta) = self.branch_deltas.get(branch_id) { |
| 47 | tokens.extend_from_slice(delta); |
| 48 | } |
| 49 | tokens |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | pub struct RecipeStore { |
| 54 | storage_dir: Option<PathBuf>, |
| 55 | recipes: RwLock<BTreeMap<Uuid, ContextRecipe>>, |
| 56 | } |
| 57 | |
| 58 | impl RecipeStore { |
| 59 | pub fn new() -> Self { |
| 60 | Self { |
| 61 | storage_dir: None, |
| 62 | recipes: RwLock::new(BTreeMap::new()), |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | pub fn with_storage_dir(dir: impl Into<PathBuf>) -> Result<Self, std::io::Error> { |
| 67 | let path = dir.into(); |
| 68 | fs::create_dir_all(&path)?; |
| 69 | |
| 70 | let store = Self { |
| 71 | storage_dir: Some(path.clone()), |
| 72 | recipes: RwLock::new(BTreeMap::new()), |
| 73 | }; |
| 74 | |
| 75 | if let Ok(entries) = fs::read_dir(&path) { |
| 76 | for entry in entries.flatten() { |
| 77 | let p = entry.path(); |
| 78 | if p.extension().and_then(|s| s.to_str()) == Some("json") { |
| 79 | if let Ok(content) = fs::read_to_string(&p) { |
| 80 | if let Ok(recipe) = serde_json::from_str::<ContextRecipe>(&content) { |
| 81 | store.recipes.write().insert(recipe.recipe_id, recipe); |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | Ok(store) |
| 89 | } |
| 90 | |
| 91 | pub fn insert(&self, recipe: ContextRecipe) -> Result<(), std::io::Error> { |
| 92 | if let Some(dir) = &self.storage_dir { |
| 93 | let filename = format!("{}.json", recipe.recipe_id); |
| 94 | let file_path = dir.join(filename); |
| 95 | let temp_path = dir.join(format!("{}.tmp", recipe.recipe_id)); |
| 96 | let content = serde_json::to_string_pretty(&recipe) |
| 97 | .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; |
| 98 | fs::write(&temp_path, content)?; |
| 99 | fs::rename(&temp_path, &file_path)?; |
| 100 | } |
| 101 | self.recipes.write().insert(recipe.recipe_id, recipe); |
| 102 | Ok(()) |
| 103 | } |
| 104 | |
| 105 | pub fn verify_and_get(&self, recipe_ref: &ContextRecipeRef) -> Result<ContextRecipe, String> { |
| 106 | let in_memory = self.recipes.read().get(&recipe_ref.recipe_id).cloned(); |
| 107 | let recipe = match in_memory { |
| 108 | Some(r) => r, |
| 109 | None => { |
| 110 | if let Some(dir) = &self.storage_dir { |
| 111 | let file_path = dir.join(format!("{}.json", recipe_ref.recipe_id)); |
| 112 | if let Ok(content) = fs::read_to_string(&file_path) { |
| 113 | let r: ContextRecipe = serde_json::from_str(&content) |
| 114 | .map_err(|e| format!("Failed to parse recipe file: {}", e))?; |
| 115 | self.recipes.write().insert(r.recipe_id, r.clone()); |
| 116 | r |
| 117 | } else { |
| 118 | return Err(format!( |
| 119 | "Recipe {} not found in store or disk", |
| 120 | recipe_ref.recipe_id |
| 121 | )); |
| 122 | } |
| 123 | } else { |
| 124 | return Err(format!( |
| 125 | "Recipe {} not found in store", |
| 126 | recipe_ref.recipe_id |
| 127 | )); |
| 128 | } |
| 129 | } |
| 130 | }; |
| 131 | |
| 132 | let actual_digest = recipe.compute_digest(); |
| 133 | if actual_digest != recipe_ref.recipe_digest { |
| 134 | return Err(format!( |
| 135 | "Recipe digest mismatch: expected {:?}, actual {:?}", |
| 136 | recipe_ref.recipe_digest, actual_digest |
| 137 | )); |
| 138 | } |
| 139 | |
| 140 | Ok(recipe) |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | impl Default for RecipeStore { |
| 145 | fn default() -> Self { |
| 146 | Self::new() |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | pub type SharedRecipeStore = Arc<RecipeStore>; |