1use std::collections::{HashMap, HashSet};
7use std::fmt;
8use std::path::Path;
9
10use hmac::{Hmac, KeyInit, Mac};
11use serde::{Deserialize, Serialize};
12use sha2::Sha256;
13
14use crate::adapters::mapper::Canonical;
15use crate::apply::write_atomic;
16use crate::error::{CoreError, ErrorCode};
17use crate::fs::Fs;
18use crate::model::applied::Scope;
19
20pub const LEDGER_FILE: &str = "ledger.json";
22pub const LEDGER_KEY_FILE: &str = "ledger.key";
24
25pub(crate) const LEDGER_SCHEMA: u32 = 2;
27const HASH_PREFIX: &str = "hmac-sha256:";
28const KEY_LEN: usize = 32;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(rename_all = "snake_case")]
33pub enum EntryKind {
34 McpEntry,
36 ListMember,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum Origin {
44 Created,
46 Adopted,
49}
50
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
53pub struct LedgerEntry {
54 pub kind: EntryKind,
55 pub client: String,
56 pub scope: Scope,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub project_id: Option<String>,
59 pub file: String,
61 pub container: String,
64 pub key: String,
66 #[serde(default, skip_serializing_if = "Option::is_none")]
67 pub server_id: Option<String>,
68 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub origin: Option<Origin>,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
73 pub written_hash: Option<String>,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub written_at: Option<String>,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub store_commit: Option<String>,
80 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub delivery: Option<String>,
83 #[serde(flatten)]
85 pub extra: serde_json::Map<String, serde_json::Value>,
86}
87
88impl LedgerEntry {
89 pub fn slot(&self) -> LedgerSlot<'_> {
91 LedgerSlot {
92 scope: self.scope,
93 project_id: self.project_id.as_deref(),
94 file: &self.file,
95 container: &self.container,
96 }
97 }
98
99 fn is(&self, slot: &LedgerSlot<'_>, key: &str) -> bool {
100 self.slot() == *slot && self.key == key
101 }
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub struct LedgerSlot<'a> {
110 pub scope: Scope,
111 pub project_id: Option<&'a str>,
112 pub file: &'a str,
113 pub container: &'a str,
115}
116
117#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
119pub struct Ledger {
120 pub schema: u32,
121 #[serde(default)]
122 pub entries: Vec<LedgerEntry>,
123 #[serde(flatten)]
124 pub extra: serde_json::Map<String, serde_json::Value>,
125}
126
127impl Default for Ledger {
128 fn default() -> Self {
129 Self {
130 schema: LEDGER_SCHEMA,
131 entries: Vec::new(),
132 extra: serde_json::Map::new(),
133 }
134 }
135}
136
137impl Ledger {
138 pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
142 let path = state_dir.join(LEDGER_FILE);
143 if !fs.exists(&path) {
144 return Ok(Self::default());
145 }
146 let text = fs.read_to_string(&path).map_err(|err| {
147 CoreError::new(ErrorCode::IoError, format!("cannot read the ledger: {err}"))
148 .with_path(&path)
149 })?;
150 let mut ledger: Self = serde_json::from_str(&text).map_err(|err| {
151 CoreError::new(
152 ErrorCode::ParseError,
153 format!("the ledger does not parse: {err}"),
154 )
155 .with_path(&path)
156 })?;
157 if !(1..=LEDGER_SCHEMA).contains(&ledger.schema) {
160 return Err(CoreError::new(
161 ErrorCode::UnsupportedSchema,
162 format!(
163 "ledger schema {} is not supported; this build reads schema {LEDGER_SCHEMA}",
164 ledger.schema
165 ),
166 )
167 .with_path(&path));
168 }
169 ledger.schema = LEDGER_SCHEMA;
170 Ok(ledger)
171 }
172
173 pub fn save(&self, fs: &dyn Fs, state_dir: &Path) -> Result<(), CoreError> {
175 let mut text = serde_json::to_string_pretty(self).map_err(|err| {
176 CoreError::new(
177 ErrorCode::InvalidValue,
178 format!("cannot serialize the ledger: {err}"),
179 )
180 })?;
181 text.push('\n');
182 write_atomic(fs, &state_dir.join(LEDGER_FILE), text.as_bytes())
183 }
184
185 pub fn get(&self, slot: &LedgerSlot<'_>, key: &str) -> Option<&LedgerEntry> {
186 self.entries.iter().find(|entry| entry.is(slot, key))
187 }
188
189 pub fn in_container<'a>(
191 &'a self,
192 slot: LedgerSlot<'a>,
193 ) -> impl Iterator<Item = &'a LedgerEntry> + 'a {
194 self.entries
195 .iter()
196 .filter(move |entry| entry.slot() == slot)
197 }
198
199 pub fn upsert(&mut self, entry: LedgerEntry) {
201 match self
202 .entries
203 .iter_mut()
204 .find(|known| known.slot() == entry.slot() && known.key == entry.key)
205 {
206 Some(slot) => *slot = entry,
207 None => self.entries.push(entry),
208 }
209 }
210
211 pub fn remove(&mut self, slot: &LedgerSlot<'_>, key: &str) -> bool {
213 let before = self.entries.len();
214 self.entries.retain(|entry| !entry.is(slot, key));
215 self.entries.len() != before
216 }
217
218 pub fn slot_entries(&self, slot: &LedgerSlot<'_>) -> SlotEntries<'_> {
222 let entries: Vec<&LedgerEntry> = self
223 .entries
224 .iter()
225 .filter(|entry| entry.slot() == *slot)
226 .collect();
227 let mut by_key = HashMap::with_capacity(entries.len());
228 for entry in &entries {
229 by_key.entry(entry.key.as_str()).or_insert(*entry);
230 }
231 SlotEntries { entries, by_key }
232 }
233
234 pub fn update_slot(
239 &mut self,
240 slot: &LedgerSlot<'_>,
241 changes: Vec<(String, Option<LedgerEntry>)>,
242 ) -> bool {
243 let mut at: HashMap<String, Vec<usize>> = HashMap::new();
245 for (index, entry) in self.entries.iter().enumerate() {
246 if entry.slot() == *slot {
247 at.entry(entry.key.clone()).or_default().push(index);
248 }
249 }
250 let mut dropped: HashSet<usize> = HashSet::new();
251 let mut changed = false;
252 for (key, change) in changes {
253 match change {
254 Some(entry) => {
255 debug_assert!(entry.slot() == *slot && entry.key == key);
256 match at.get(&key).and_then(|indices| indices.first()) {
257 Some(&index) => self.entries[index] = entry,
258 None => {
259 at.insert(key, vec![self.entries.len()]);
260 self.entries.push(entry);
261 }
262 }
263 changed = true;
264 }
265 None => {
266 if let Some(indices) = at.remove(&key) {
267 changed = true;
268 dropped.extend(indices);
269 }
270 }
271 }
272 }
273 if !dropped.is_empty() {
274 let mut index = 0;
275 self.entries.retain(|_| {
276 index += 1;
277 !dropped.contains(&(index - 1))
278 });
279 }
280 changed
281 }
282}
283
284#[derive(Debug)]
286pub struct SlotEntries<'a> {
287 entries: Vec<&'a LedgerEntry>,
288 by_key: HashMap<&'a str, &'a LedgerEntry>,
289}
290
291impl<'a> SlotEntries<'a> {
292 pub fn get(&self, key: &str) -> Option<&'a LedgerEntry> {
294 self.by_key.get(key).copied()
295 }
296
297 pub fn iter(&self) -> impl Iterator<Item = &'a LedgerEntry> + '_ {
299 self.entries.iter().copied()
300 }
301}
302
303#[derive(Clone)]
307pub struct LedgerKey([u8; KEY_LEN]);
308
309impl fmt::Debug for LedgerKey {
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 f.write_str("LedgerKey(..)")
312 }
313}
314
315impl LedgerKey {
316 pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Option<Self>, CoreError> {
320 let path = state_dir.join(LEDGER_KEY_FILE);
321 if !fs.exists(&path) {
322 return Ok(None);
323 }
324 let bytes = fs.read(&path).map_err(|err| {
325 CoreError::new(
326 ErrorCode::IoError,
327 format!("cannot read the ledger key: {err}"),
328 )
329 .with_path(&path)
330 })?;
331 let key: [u8; KEY_LEN] = bytes.try_into().map_err(|_| {
332 CoreError::new(
333 ErrorCode::InvalidValue,
334 format!("the ledger key must be {KEY_LEN} bytes"),
335 )
336 .with_path(&path)
337 })?;
338 Ok(Some(Self(key)))
339 }
340
341 pub fn load_or_create(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
344 if let Some(key) = Self::load(fs, state_dir)? {
345 return Ok(key);
346 }
347 let path = state_dir.join(LEDGER_KEY_FILE);
348 let mut key = [0u8; KEY_LEN];
349 getrandom::fill(&mut key).map_err(|err| {
350 CoreError::new(
351 ErrorCode::IoError,
352 format!("cannot read random bytes for the ledger key: {err}"),
353 )
354 })?;
355 fs.create_dir_all(state_dir).map_err(|err| {
356 CoreError::new(
357 ErrorCode::IoError,
358 format!("cannot create directory: {err}"),
359 )
360 .with_path(state_dir)
361 })?;
362 fs.write_private(&path, &key).map_err(|err| {
363 CoreError::new(
364 ErrorCode::IoError,
365 format!("cannot write the ledger key: {err}"),
366 )
367 .with_path(&path)
368 })?;
369 Ok(Self(key))
370 }
371
372 pub fn from_bytes(bytes: [u8; KEY_LEN]) -> Self {
374 Self(bytes)
375 }
376
377 pub fn hash(&self, canonical: &Canonical) -> String {
379 let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(&self.0)
380 .expect("HMAC accepts any key length");
381 mac.update(canonical.as_str().as_bytes());
382 let digest = mac.finalize().into_bytes();
383 let mut text = String::with_capacity(HASH_PREFIX.len() + digest.len() * 2);
384 text.push_str(HASH_PREFIX);
385 for byte in digest {
386 text.push_str(&format!("{byte:02x}"));
387 }
388 text
389 }
390}
391
392pub fn container_pointer<S: AsRef<str>>(keys: &[S]) -> String {
395 keys.iter()
396 .map(|key| format!("/{}", key.as_ref().replace('~', "~0").replace('/', "~1")))
397 .collect()
398}