use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::Path;
use hmac::{Hmac, KeyInit, Mac};
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use crate::adapters::mapper::Canonical;
use crate::apply::write_atomic;
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::model::applied::Scope;
pub const LEDGER_FILE: &str = "ledger.json";
pub const LEDGER_KEY_FILE: &str = "ledger.key";
pub(crate) const LEDGER_SCHEMA: u32 = 2;
const HASH_PREFIX: &str = "hmac-sha256:";
const KEY_LEN: usize = 32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EntryKind {
McpEntry,
ListMember,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Origin {
Created,
Adopted,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LedgerEntry {
pub kind: EntryKind,
pub client: String,
pub scope: Scope,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub project_id: Option<String>,
pub file: String,
pub container: String,
pub key: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub server_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<Origin>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub written_hash: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub written_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub store_commit: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delivery: Option<String>,
#[serde(flatten)]
pub extra: serde_json::Map<String, serde_json::Value>,
}
impl LedgerEntry {
pub fn slot(&self) -> LedgerSlot<'_> {
LedgerSlot {
scope: self.scope,
project_id: self.project_id.as_deref(),
file: &self.file,
container: &self.container,
}
}
fn is(&self, slot: &LedgerSlot<'_>, key: &str) -> bool {
self.slot() == *slot && self.key == key
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LedgerSlot<'a> {
pub scope: Scope,
pub project_id: Option<&'a str>,
pub file: &'a str,
pub container: &'a str,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Ledger {
pub schema: u32,
#[serde(default)]
pub entries: Vec<LedgerEntry>,
#[serde(flatten)]
pub extra: serde_json::Map<String, serde_json::Value>,
}
impl Default for Ledger {
fn default() -> Self {
Self {
schema: LEDGER_SCHEMA,
entries: Vec::new(),
extra: serde_json::Map::new(),
}
}
}
impl Ledger {
pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
let path = state_dir.join(LEDGER_FILE);
if !fs.exists(&path) {
return Ok(Self::default());
}
let text = fs.read_to_string(&path).map_err(|err| {
CoreError::new(ErrorCode::IoError, format!("cannot read the ledger: {err}"))
.with_path(&path)
})?;
let mut ledger: Self = serde_json::from_str(&text).map_err(|err| {
CoreError::new(
ErrorCode::ParseError,
format!("the ledger does not parse: {err}"),
)
.with_path(&path)
})?;
if !(1..=LEDGER_SCHEMA).contains(&ledger.schema) {
return Err(CoreError::new(
ErrorCode::UnsupportedSchema,
format!(
"ledger schema {} is not supported; this build reads schema {LEDGER_SCHEMA}",
ledger.schema
),
)
.with_path(&path));
}
ledger.schema = LEDGER_SCHEMA;
Ok(ledger)
}
pub fn save(&self, fs: &dyn Fs, state_dir: &Path) -> Result<(), CoreError> {
let mut text = serde_json::to_string_pretty(self).map_err(|err| {
CoreError::new(
ErrorCode::InvalidValue,
format!("cannot serialize the ledger: {err}"),
)
})?;
text.push('\n');
write_atomic(fs, &state_dir.join(LEDGER_FILE), text.as_bytes())
}
pub fn get(&self, slot: &LedgerSlot<'_>, key: &str) -> Option<&LedgerEntry> {
self.entries.iter().find(|entry| entry.is(slot, key))
}
pub fn in_container<'a>(
&'a self,
slot: LedgerSlot<'a>,
) -> impl Iterator<Item = &'a LedgerEntry> + 'a {
self.entries
.iter()
.filter(move |entry| entry.slot() == slot)
}
pub fn upsert(&mut self, entry: LedgerEntry) {
match self
.entries
.iter_mut()
.find(|known| known.slot() == entry.slot() && known.key == entry.key)
{
Some(slot) => *slot = entry,
None => self.entries.push(entry),
}
}
pub fn remove(&mut self, slot: &LedgerSlot<'_>, key: &str) -> bool {
let before = self.entries.len();
self.entries.retain(|entry| !entry.is(slot, key));
self.entries.len() != before
}
pub fn slot_entries(&self, slot: &LedgerSlot<'_>) -> SlotEntries<'_> {
let entries: Vec<&LedgerEntry> = self
.entries
.iter()
.filter(|entry| entry.slot() == *slot)
.collect();
let mut by_key = HashMap::with_capacity(entries.len());
for entry in &entries {
by_key.entry(entry.key.as_str()).or_insert(*entry);
}
SlotEntries { entries, by_key }
}
pub fn update_slot(
&mut self,
slot: &LedgerSlot<'_>,
changes: Vec<(String, Option<LedgerEntry>)>,
) -> bool {
let mut at: HashMap<String, Vec<usize>> = HashMap::new();
for (index, entry) in self.entries.iter().enumerate() {
if entry.slot() == *slot {
at.entry(entry.key.clone()).or_default().push(index);
}
}
let mut dropped: HashSet<usize> = HashSet::new();
let mut changed = false;
for (key, change) in changes {
match change {
Some(entry) => {
debug_assert!(entry.slot() == *slot && entry.key == key);
match at.get(&key).and_then(|indices| indices.first()) {
Some(&index) => self.entries[index] = entry,
None => {
at.insert(key, vec![self.entries.len()]);
self.entries.push(entry);
}
}
changed = true;
}
None => {
if let Some(indices) = at.remove(&key) {
changed = true;
dropped.extend(indices);
}
}
}
}
if !dropped.is_empty() {
let mut index = 0;
self.entries.retain(|_| {
index += 1;
!dropped.contains(&(index - 1))
});
}
changed
}
}
#[derive(Debug)]
pub struct SlotEntries<'a> {
entries: Vec<&'a LedgerEntry>,
by_key: HashMap<&'a str, &'a LedgerEntry>,
}
impl<'a> SlotEntries<'a> {
pub fn get(&self, key: &str) -> Option<&'a LedgerEntry> {
self.by_key.get(key).copied()
}
pub fn iter(&self) -> impl Iterator<Item = &'a LedgerEntry> + '_ {
self.entries.iter().copied()
}
}
#[derive(Clone)]
pub struct LedgerKey([u8; KEY_LEN]);
impl fmt::Debug for LedgerKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("LedgerKey(..)")
}
}
impl LedgerKey {
pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Option<Self>, CoreError> {
let path = state_dir.join(LEDGER_KEY_FILE);
if !fs.exists(&path) {
return Ok(None);
}
let bytes = fs.read(&path).map_err(|err| {
CoreError::new(
ErrorCode::IoError,
format!("cannot read the ledger key: {err}"),
)
.with_path(&path)
})?;
let key: [u8; KEY_LEN] = bytes.try_into().map_err(|_| {
CoreError::new(
ErrorCode::InvalidValue,
format!("the ledger key must be {KEY_LEN} bytes"),
)
.with_path(&path)
})?;
Ok(Some(Self(key)))
}
pub fn load_or_create(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
if let Some(key) = Self::load(fs, state_dir)? {
return Ok(key);
}
let path = state_dir.join(LEDGER_KEY_FILE);
let mut key = [0u8; KEY_LEN];
getrandom::fill(&mut key).map_err(|err| {
CoreError::new(
ErrorCode::IoError,
format!("cannot read random bytes for the ledger key: {err}"),
)
})?;
fs.create_dir_all(state_dir).map_err(|err| {
CoreError::new(
ErrorCode::IoError,
format!("cannot create directory: {err}"),
)
.with_path(state_dir)
})?;
fs.write_private(&path, &key).map_err(|err| {
CoreError::new(
ErrorCode::IoError,
format!("cannot write the ledger key: {err}"),
)
.with_path(&path)
})?;
Ok(Self(key))
}
pub fn from_bytes(bytes: [u8; KEY_LEN]) -> Self {
Self(bytes)
}
pub fn hash(&self, canonical: &Canonical) -> String {
let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(&self.0)
.expect("HMAC accepts any key length");
mac.update(canonical.as_str().as_bytes());
let digest = mac.finalize().into_bytes();
let mut text = String::with_capacity(HASH_PREFIX.len() + digest.len() * 2);
text.push_str(HASH_PREFIX);
for byte in digest {
text.push_str(&format!("{byte:02x}"));
}
text
}
}
pub fn container_pointer<S: AsRef<str>>(keys: &[S]) -> String {
keys.iter()
.map(|key| format!("/{}", key.as_ref().replace('~', "~0").replace('/', "~1")))
.collect()
}