use std::collections::HashSet;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
use super::{runtime::GroupRuntime, PreparedGroup};
use crate::config::MAX_REDIS_NAME_BYTES;
use crate::error::{NasaRedisError, Result};
pub(super) fn validate_route(topic: &str, event: &str) -> Result<()> {
for (field, value) in [("topic", topic), ("event", event)] {
if value.is_empty()
|| value.trim() != value
|| value.len() > MAX_REDIS_NAME_BYTES
|| value.chars().any(char::is_control)
{
return Err(NasaRedisError::Config(format!(
"partition {field} must be nonempty, trimmed, without control characters and at most {MAX_REDIS_NAME_BYTES} bytes"
)));
}
}
Ok(())
}
pub(super) fn validate_routes(groups: &[PreparedGroup]) -> Result<()> {
let mut routes = HashSet::new();
for group in groups {
for (topic, event) in group.plans.keys() {
validate_route(topic, event)?;
if !routes.insert((topic.as_str(), event.as_str())) {
return Err(NasaRedisError::Config(
"partition duplicate route at activation".into(),
));
}
}
}
if routes.is_empty() {
return Err(NasaRedisError::Config(
"partition requires at least one consumer plan".into(),
));
}
Ok(())
}
pub(super) struct PlanActivation {
gate: CancellationToken,
groups: Vec<Arc<GroupRuntime>>,
committed: bool,
core: Option<Arc<super::runtime::engine::RedisPartitionRuntime>>,
}
impl PlanActivation {
pub(super) fn new() -> Self {
Self {
gate: CancellationToken::new(),
groups: Vec::new(),
committed: false,
core: None,
}
}
pub(super) fn start_gate(&self) -> CancellationToken {
self.gate.clone()
}
pub(super) fn track(&mut self, group: Arc<GroupRuntime>) {
self.groups.push(group);
}
pub(super) fn commit(mut self, activate: bool) {
self.committed = true;
if activate {
self.gate.cancel();
}
}
pub(super) async fn rollback(&mut self, cause: NasaRedisError) -> NasaRedisError {
let Some(core) = self.core.take() else {
return cause;
};
let timeout_ms = self
.groups
.first()
.map_or(35_000, |group| group.cfg.drain_timeout_ms);
let publisher = super::publisher::PublisherCoordinator::new(core.limits.clone());
let cleanup = super::shutdown::ShutdownOperation::new(
core,
publisher,
std::mem::take(&mut self.groups),
);
let report = cleanup
.wait(std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms))
.await;
if report.converged {
cause
} else {
NasaRedisError::StartRollbackNotConverged {
cause: cause.to_string(),
remaining: Box::new(report),
}
}
}
pub(super) fn track_core(&mut self, core: Arc<super::runtime::engine::RedisPartitionRuntime>) {
self.core = Some(core);
}
}
impl Drop for PlanActivation {
fn drop(&mut self) {
if !self.committed {
if let Some(core) = self.core.take() {
core.close_roots();
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.spawn(async move {
core.stop().await;
});
}
}
for group in &self.groups {
group.shutdown_on_drop();
}
}
}
}