use std::fmt;
use futures::future::BoxFuture;
use crate::store::{StoreError, StoreResult};
pub const MAX_KEY_BYTES: usize = 512;
pub const MAX_VALUE_BYTES: usize = 1024 * 1024;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Versioned {
pub value: Vec<u8>,
pub version: u64,
}
pub trait CoordinationStore: Send + Sync + fmt::Debug {
fn create_if_absent<'a>(&'a self, key: &'a str, value: Vec<u8>) -> BoxFuture<'a, StoreResult<u64>>;
fn compare_and_swap<'a>(
&'a self,
key: &'a str,
expected_version: u64,
value: Vec<u8>,
) -> BoxFuture<'a, StoreResult<u64>>;
fn get_object<'a>(&'a self, key: &'a str) -> BoxFuture<'a, StoreResult<Option<Versioned>>>;
fn list_objects<'a>(&'a self, prefix: &'a str) -> BoxFuture<'a, StoreResult<Vec<(String, Versioned)>>>;
fn delete_object<'a>(&'a self, key: &'a str, expected_version: u64) -> BoxFuture<'a, StoreResult<bool>>;
}
pub fn validate_key(key: &str) -> StoreResult<()> {
let segment_ok = |segment: &str| {
!segment.is_empty()
&& segment != "."
&& segment != ".."
&& segment.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | ':' | '='))
};
if !key.is_empty() && key.len() <= MAX_KEY_BYTES && key.split('/').all(segment_ok) {
Ok(())
} else {
Err(StoreError::InvalidId(key.chars().take(64).collect()))
}
}
pub fn validate_value(value: &[u8]) -> StoreResult<()> {
if value.len() <= MAX_VALUE_BYTES {
Ok(())
} else {
Err(StoreError::Conflict(format!("coordination value of {} bytes exceeds {MAX_VALUE_BYTES}", value.len())))
}
}
pub fn deployment_key(deployment: &str, kind: &str, id: &str) -> String {
format!("d/{deployment}/{kind}/{id}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keys_are_validated() {
for good in ["d/shop/runs/run-1", "a", "d/x/cron/daily/2026-11-22T00:00:00Z", "k=v"] {
assert!(validate_key(good).is_ok(), "{good}");
}
let long = "x".repeat(MAX_KEY_BYTES + 1);
for bad in ["", "/a", "a/", "a//b", "a/../b", "./a", "a b", "a\\b", &long] {
assert!(validate_key(bad).is_err(), "{bad}");
}
assert_eq!(deployment_key("shop", "runs", "r1"), "d/shop/runs/r1");
assert!(validate_value(&vec![0; MAX_VALUE_BYTES]).is_ok());
assert!(validate_value(&vec![0; MAX_VALUE_BYTES + 1]).is_err());
}
}