use crate::error::PulsarError;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[must_use]
pub struct PulsarTopic {
full: String,
}
fn valid_part(part: &str) -> bool {
!part.is_empty()
&& part
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
}
impl PulsarTopic {
fn of(scheme: &str, tenant: &str, namespace: &str, topic: &str) -> Result<Self, PulsarError> {
for (label, part) in [
("tenant", tenant),
("namespace", namespace),
("topic", topic),
] {
if !valid_part(part) {
return Err(PulsarError::Invalid(format!(
"{label} '{part}' must be non-empty and contain only alphanumerics, '-', '_', '.'"
)));
}
}
Ok(Self {
full: format!("{scheme}://{tenant}/{namespace}/{topic}"),
})
}
pub fn persistent(tenant: &str, namespace: &str, topic: &str) -> Self {
Self::of("persistent", tenant, namespace, topic).expect("invalid pulsar topic component")
}
pub fn non_persistent(tenant: &str, namespace: &str, topic: &str) -> Self {
Self::of("non-persistent", tenant, namespace, topic)
.expect("invalid pulsar topic component")
}
pub fn parse(name: &str) -> Result<Self, PulsarError> {
let (scheme, rest) = name.strip_prefix("non-persistent://").map_or_else(
|| {
name.strip_prefix("persistent://")
.map_or(("persistent", name), |rest| ("persistent", rest))
},
|rest| ("non-persistent", rest),
);
let parts: Vec<&str> = rest.split('/').collect();
match parts.as_slice() {
[topic] => Self::of(scheme, "public", "default", topic),
[tenant, namespace, topic] => Self::of(scheme, tenant, namespace, topic),
_ => Err(PulsarError::Invalid(format!(
"topic '{name}' must be 'topic', 'tenant/namespace/topic', or fully qualified"
))),
}
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.full
}
}
impl std::fmt::Display for PulsarTopic {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.full)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn constructors_qualify_fully() {
assert_eq!(
PulsarTopic::persistent("acme", "orders", "created").as_str(),
"persistent://acme/orders/created"
);
assert_eq!(
PulsarTopic::non_persistent("acme", "telemetry", "ticks").as_str(),
"non-persistent://acme/telemetry/ticks"
);
}
#[test]
fn parse_defaults_bare_names_to_public_default() {
assert_eq!(
PulsarTopic::parse("orders").expect("parses").as_str(),
"persistent://public/default/orders"
);
}
#[test]
fn parse_rejects_malformed_shapes() {
assert!(PulsarTopic::parse("a/b").is_err());
assert!(PulsarTopic::parse("persistent://a//c").is_err());
assert!(PulsarTopic::parse("bad name").is_err());
}
}