use tokio_util::sync::CancellationToken;
use crate::ids::{CorrelationId, MessageId};
#[derive(Debug, Clone)]
pub struct HandlerContext {
pub message_id: MessageId,
pub correlation_id: CorrelationId,
pub cancellation: CancellationToken,
pub span: tracing::Span,
}
impl HandlerContext {
#[must_use]
pub fn new(message_id: MessageId, correlation_id: CorrelationId) -> Self {
Self {
message_id,
correlation_id,
cancellation: CancellationToken::new(),
span: tracing::Span::current(),
}
}
#[must_use]
pub fn with_span(mut self, span: tracing::Span) -> Self {
self.span = span;
self
}
#[must_use]
pub fn with_cancellation(mut self, token: CancellationToken) -> Self {
self.cancellation = token;
self
}
#[must_use]
pub fn is_cancelled(&self) -> bool {
self.cancellation.is_cancelled()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_context_is_not_cancelled() {
let ctx = HandlerContext::new(MessageId::new(), CorrelationId::new());
assert!(!ctx.is_cancelled());
}
#[test]
fn cancellation_propagates_from_parent() {
let parent = CancellationToken::new();
let child = parent.child_token();
let ctx =
HandlerContext::new(MessageId::new(), CorrelationId::new()).with_cancellation(child);
assert!(!ctx.is_cancelled());
parent.cancel();
assert!(ctx.is_cancelled());
}
#[test]
fn context_is_clone() {
let ctx = HandlerContext::new(MessageId::new(), CorrelationId::new());
let cloned = ctx.clone();
assert_eq!(ctx.message_id, cloned.message_id);
assert_eq!(ctx.correlation_id, cloned.correlation_id);
}
}