use std::fmt;
use crate::error::{BlobError, Result};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ServePrefix(String);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct QueryPrefix(String);
fn validate_shape(prefix: &str) -> Result<()> {
if prefix.is_empty() {
return Err(BlobError::InvalidPrefix("empty key prefix".into()));
}
if prefix.starts_with('/') || prefix.ends_with('/') {
return Err(BlobError::InvalidPrefix(format!(
"key prefix {prefix:?} must not start or end with '/'"
)));
}
if prefix.split('/').any(|seg| seg == "**") {
return Err(BlobError::InvalidPrefix(format!(
"key prefix {prefix:?} must not contain '**' — ids are resolved \
positionally, so no server can answer past an unbounded span"
)));
}
zenoh::key_expr::KeyExpr::try_from(prefix)
.map_err(|e| BlobError::InvalidPrefix(format!("invalid key prefix {prefix:?}: {e}")))?;
zenoh::key_expr::KeyExpr::try_from(format!("{prefix}/id/**"))
.map_err(|e| BlobError::InvalidPrefix(format!("unusable key prefix {prefix:?}: {e}")))?;
Ok(())
}
fn has_wildcard(prefix: &str) -> bool {
prefix.split('/').any(|seg| seg.contains('*'))
}
impl ServePrefix {
pub fn new(prefix: impl Into<String>) -> Result<Self> {
let prefix = prefix.into();
validate_shape(&prefix)?;
if has_wildcard(&prefix) {
return Err(BlobError::InvalidPrefix(format!(
"key prefix {prefix:?} must not contain wildcards when serving or publishing"
)));
}
zenoh::key_expr::KeyExpr::try_from(format!("{prefix}/**")).map_err(|e| {
BlobError::InvalidPrefix(format!("undeclarable key prefix {prefix:?}: {e}"))
})?;
Ok(ServePrefix(prefix))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl QueryPrefix {
pub fn new(prefix: impl Into<String>) -> Result<Self> {
let prefix = prefix.into();
validate_shape(&prefix)?;
Ok(QueryPrefix(prefix))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn is_concrete(&self) -> bool {
!has_wildcard(&self.0)
}
}
impl From<ServePrefix> for QueryPrefix {
fn from(p: ServePrefix) -> Self {
QueryPrefix(p.0)
}
}
impl From<&ServePrefix> for QueryPrefix {
fn from(p: &ServePrefix) -> Self {
QueryPrefix(p.0.clone())
}
}
impl TryFrom<QueryPrefix> for ServePrefix {
type Error = BlobError;
fn try_from(p: QueryPrefix) -> Result<Self> {
ServePrefix::new(p.0)
}
}
macro_rules! prefix_common {
($t:ty) => {
impl fmt::Display for $t {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<str> for $t {
fn as_ref(&self) -> &str {
&self.0
}
}
impl std::str::FromStr for $t {
type Err = BlobError;
fn from_str(s: &str) -> Result<Self> {
Self::new(s)
}
}
impl TryFrom<&str> for $t {
type Error = BlobError;
fn try_from(s: &str) -> Result<Self> {
Self::new(s)
}
}
impl TryFrom<String> for $t {
type Error = BlobError;
fn try_from(s: String) -> Result<Self> {
Self::new(s)
}
}
};
}
prefix_common!(ServePrefix);
prefix_common!(QueryPrefix);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_server_cannot_be_built_on_a_wildcard() {
assert!(ServePrefix::new("v1/host-a/@blob/artifact").is_ok());
assert!(ServePrefix::new("v1/*/@blob/artifact").is_err());
assert!(ServePrefix::new("v1/**/artifact").is_err());
}
#[test]
fn a_client_may_wildcard_an_origin_but_never_span() {
assert!(QueryPrefix::new("v1/host-a/@blob/artifact").is_ok());
assert!(QueryPrefix::new("v1/*/@blob/artifact").is_ok());
assert!(QueryPrefix::new("v1/**/artifact").is_err());
}
#[test]
fn the_role_rules_hold_over_the_whole_corpus() {
for good in [
"demo/blobs",
"v1/h-0011223344ff/@blob/artifact",
"a",
"a/b/c",
] {
QueryPrefix::new(good).unwrap_or_else(|e| panic!("{good:?} rejected: {e}"));
ServePrefix::new(good).unwrap_or_else(|e| panic!("{good:?} rejected: {e}"));
}
for bad in ["", "/leading", "trailing/", "a//b"] {
assert!(QueryPrefix::new(bad).is_err(), "{bad:?} should be rejected");
assert!(ServePrefix::new(bad).is_err(), "{bad:?} should be rejected");
}
for wild in ["v1/*/@blob/artifact", "wild/*/card", "v1/host$*/x"] {
let q = QueryPrefix::new(wild)
.unwrap_or_else(|e| panic!("{wild:?} must be queryable: {e}"));
assert!(!q.is_concrete(), "{wild:?} names more than one origin");
assert!(
ServePrefix::new(wild).is_err(),
"{wild:?} must not be servable"
);
}
for span in ["wild/**", "**", "a/**/b"] {
assert!(
QueryPrefix::new(span).is_err(),
"{span:?} must not be queryable"
);
assert!(
ServePrefix::new(span).is_err(),
"{span:?} must not be servable"
);
assert_eq!(
crate::keys::parse_id(span, &format!("{span}/A/manifest")),
None,
"parse_id must not resolve an id past '**'"
);
}
}
#[test]
fn serving_implies_querying() {
let serve = ServePrefix::new("v1/host-a/@blob/artifact").unwrap();
let query: QueryPrefix = serve.clone().into();
assert_eq!(query.as_str(), serve.as_str());
assert!(query.is_concrete());
let wide = QueryPrefix::new("v1/*/@blob/artifact").unwrap();
assert!(!wide.is_concrete());
assert!(ServePrefix::try_from(wide).is_err());
assert!(ServePrefix::try_from(query).is_ok());
}
#[test]
fn every_conversion_preserves_the_prefix_and_its_role() {
use std::str::FromStr;
let serve = ServePrefix::new("v1/host-a/@blob/art").unwrap();
assert_eq!(serve.as_str(), "v1/host-a/@blob/art");
assert_eq!(serve.to_string(), "v1/host-a/@blob/art");
assert_eq!(serve.as_ref() as &str, "v1/host-a/@blob/art");
assert_eq!(
QueryPrefix::from(serve.clone()).as_str(),
"v1/host-a/@blob/art"
);
assert_eq!(QueryPrefix::from(&serve).as_str(), "v1/host-a/@blob/art");
let concrete = QueryPrefix::new("v1/host-a/@blob/art").unwrap();
assert!(concrete.is_concrete());
assert_eq!(
ServePrefix::try_from(concrete).unwrap().as_str(),
"v1/host-a/@blob/art"
);
let wild = QueryPrefix::new("v1/*/@blob/art").unwrap();
assert!(!wild.is_concrete());
assert!(ServePrefix::try_from(wild).is_err());
for good in ["p/q", "v1/host-a/@blob/art"] {
assert_eq!(ServePrefix::from_str(good).unwrap().as_str(), good);
assert_eq!(ServePrefix::try_from(good).unwrap().as_str(), good);
assert_eq!(
ServePrefix::try_from(String::from(good)).unwrap().as_str(),
good
);
assert_eq!(QueryPrefix::from_str(good).unwrap().as_str(), good);
assert_eq!(QueryPrefix::try_from(good).unwrap().as_str(), good);
assert_eq!(
QueryPrefix::try_from(String::from(good)).unwrap().as_str(),
good
);
}
for bad in ["", "p/*", "p/**"] {
assert!(ServePrefix::from_str(bad).is_err(), "{bad:?}");
assert!(ServePrefix::try_from(bad).is_err(), "{bad:?}");
assert!(ServePrefix::try_from(String::from(bad)).is_err(), "{bad:?}");
}
assert!(QueryPrefix::from_str("p/*").is_ok());
assert!(QueryPrefix::from_str("p/**").is_err());
assert!(QueryPrefix::from_str("").is_err());
}
#[test]
fn prefix_rejections_are_classified_as_usage() {
for bad in ["", "p/**", "p/*"] {
let e = ServePrefix::new(bad).unwrap_err();
assert!(matches!(e, BlobError::InvalidPrefix(_)), "{bad:?}: {e}");
assert_eq!(e.kind(), crate::error::ErrorKind::Usage);
assert!(!e.is_retriable(), "a bad prefix is never worth retrying");
}
}
}