use std::{
fs::File,
io,
path::{Path, PathBuf},
sync::Mutex,
};
use artifactize_foundation::platform::private::{PrivateTempDir, private_tempdir_in};
use super::Inventory;
use crate::{
auth::{Location, storage::Storage},
platform::{credential_files, paths_equal},
};
const ROOT: &str = "active-redaction";
const WATCH: &str = "watch-";
const LEASE: &str = "lease";
const VALUES: &str = "redaction.json";
const COORDINATOR: &str = "redaction.lock";
#[derive(Default)]
pub(crate) struct History {
values: Mutex<Inventory>,
watches: Vec<Watch>,
}
struct Watch {
store: Storage,
marker: Option<Marker>,
}
struct Marker {
_lock: File,
_directory: PrivateTempDir,
}
impl History {
pub(crate) fn watch(
providers: Option<&Location>,
codex: Option<&Location>,
) -> Result<Self, String> {
let mut history = Self::default();
for location in [providers, codex]
.into_iter()
.flatten()
.filter(|location| !location.is_refused())
{
if history
.watches
.iter()
.any(|watch| paths_equal(&watch.store.directory, location.path()))
{
continue;
}
history.watches.push(Watch::new(location)?);
}
Ok(history)
}
pub(crate) fn update(&self, observed: Inventory) -> Inventory {
let mut known = self.values.lock().unwrap();
known.merge(observed);
for watch in &self.watches {
match watch.store.read::<Vec<String>>(VALUES) {
Ok(Some(values)) => known.merge(Inventory::new(values)),
Ok(None) => {}
Err(_) => return Inventory::withheld(),
}
}
known.clone()
}
}
impl Watch {
fn new(location: &Location) -> Result<Self, String> {
let store = Storage::new(location)?;
let _coordination = lock(&store.directory)?;
let root = store.directory.join(ROOT);
crate::platform::create_private_dir_all(&root).map_err(|error| error.to_string())?;
if !has_live_watch(&root)? {
store.remove(VALUES)?;
}
let directory = private_tempdir_in(WATCH, &root).map_err(|error| error.to_string())?;
let lock = credential_files::exclusive(&directory.path().join(LEASE))
.map_err(|error| error.to_string())?;
Ok(Self {
store,
marker: Some(Marker {
_lock: lock,
_directory: directory,
}),
})
}
}
impl Drop for Watch {
fn drop(&mut self) {
if let Ok(_coordination) = lock(&self.store.directory) {
drop(self.marker.take());
if has_live_watch(&self.store.directory.join(ROOT)).is_ok_and(|live| !live) {
let _ = self.store.remove(VALUES);
}
}
}
}
fn lock(directory: &Path) -> Result<File, String> {
credential_files::exclusive(&directory.join(COORDINATOR)).map_err(|error| error.to_string())
}
fn has_live_watch(root: &Path) -> Result<bool, String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
Err(error) => return Err(error.to_string()),
};
let mut live = false;
for entry in entries {
let entry = entry.map_err(|error| error.to_string())?;
if !entry
.file_name()
.to_str()
.is_some_and(|name| name.starts_with(WATCH))
|| !entry
.file_type()
.map_err(|error| error.to_string())?
.is_dir()
{
continue;
}
let path: PathBuf = entry.path();
match credential_files::held(&path.join(LEASE)) {
Ok(true) => live = true,
Ok(false) => retire(&path)?,
Err(error) if error.kind() == io::ErrorKind::NotFound => retire(&path)?,
Err(error) => return Err(error.to_string()),
}
}
Ok(live)
}
fn retire(path: &Path) -> Result<(), String> {
match crate::platform::remove_tree(path) {
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
result => result.map_err(|error| error.to_string()),
}
}
pub(crate) fn publish<'a>(
store: &Storage,
values: impl IntoIterator<Item = &'a str>,
) -> Result<(), String> {
let _coordination = lock(&store.directory)?;
if !has_live_watch(&store.directory.join(ROOT))? {
return store.remove(VALUES);
}
let mut known: std::collections::BTreeSet<String> = store.read(VALUES)?.unwrap_or_default();
let initial = known.len();
known.extend(
values
.into_iter()
.filter(|value| !value.is_empty())
.map(str::to_owned),
);
if known.len() != initial {
let bytes = serde_json::to_vec(&known).map_err(|_| "Cannot encode redaction history.")?;
if bytes.len() > crate::auth::storage::MAX_CREDENTIAL_BYTES {
return Err("Active provider redaction history exceeds its storage limit.".into());
}
store.save(VALUES, &known)?;
}
Ok(())
}