use std::path::Path;
use anyhow::Context;
use rho_providers::credentials::CredentialStore;
use serde::{de::DeserializeOwned, Serialize};
use crate::{
credential_store::UntrackedCredentialStore,
daemon::{account_lock_path, lock_account_file},
};
const LOCK_FILE: &str = ".rho-mcp-tokens.lock";
const GUARDED: &str = "MCP server credentials";
pub(crate) trait StoredSet: Default + Serialize + DeserializeOwned {
const ACCOUNT: &'static str;
const WHAT: &'static str;
}
pub(crate) fn load<S: StoredSet>(store: &dyn CredentialStore) -> anyhow::Result<S> {
let Some(saved) = store
.get_secret_fresh(S::ACCOUNT)
.with_context(|| format!("could not read the {} from the credential store", S::WHAT))?
else {
return Ok(S::default());
};
serde_json::from_str(&saved).with_context(|| format!("the saved {} do not parse", S::WHAT))
}
pub(crate) fn save<S: StoredSet>(set: &S, store: &dyn CredentialStore) -> anyhow::Result<()> {
let encoded = serde_json::to_string(set)?;
store
.set_secret(S::ACCOUNT, &encoded)
.with_context(|| format!("could not save the {} in the credential store", S::WHAT))
}
pub(crate) fn update<S: StoredSet, T>(
change: impl FnOnce(&mut S) -> anyhow::Result<T>,
) -> anyhow::Result<T> {
update_at(
&UntrackedCredentialStore,
&account_lock_path(LOCK_FILE, GUARDED)?,
change,
)
}
fn update_at<S: StoredSet, T>(
store: &dyn CredentialStore,
lock_path: &Path,
change: impl FnOnce(&mut S) -> anyhow::Result<T>,
) -> anyhow::Result<T> {
let _lock = lock_account_file(lock_path, GUARDED)?;
let mut set = load::<S>(store)?;
let result = change(&mut set)?;
save(&set, store)?;
Ok(result)
}
#[cfg(test)]
#[path = "token_store_tests.rs"]
mod tests;