#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum TransactionId {
#[default]
NoTransaction,
Id(String),
}
impl TransactionId {
pub fn as_header_value(&self) -> &str {
match self {
Self::NoTransaction => "NONE",
Self::Id(id) => id,
}
}
pub fn from_header_value(s: &str) -> Self {
match s {
"NONE" => Self::NoTransaction,
other => Self::Id(other.to_string()),
}
}
pub fn is_active(&self) -> bool {
matches!(self, Self::Id(_))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn uuid_is_retained_as_transaction_id() {
let uuid = "17cbc429-462a-4da3-9a06-02b6507d0d01";
assert_eq!(
TransactionId::from_header_value(uuid),
TransactionId::Id(uuid.to_string())
);
}
#[test]
fn none_sentinel_maps_to_no_transaction() {
assert_eq!(
TransactionId::from_header_value("NONE"),
TransactionId::NoTransaction
);
}
#[test]
fn header_value_round_trips() {
let uuid = "17cbc429-462a-4da3-9a06-02b6507d0d01";
let id = TransactionId::from_header_value(uuid);
assert_eq!(id.as_header_value(), uuid);
assert_eq!(TransactionId::from_header_value(id.as_header_value()), id);
}
#[test]
fn default_is_no_transaction_and_serialises_to_none() {
let id = TransactionId::default();
assert_eq!(id, TransactionId::NoTransaction);
assert_eq!(id.as_header_value(), "NONE");
assert!(!id.is_active());
}
#[test]
fn only_id_is_active() {
assert!(TransactionId::Id("abc".to_string()).is_active());
assert!(!TransactionId::NoTransaction.is_active());
}
}