mod activation;
mod execution;
mod limits;
mod plan;
mod publisher;
mod shutdown;
pub use limits::{PartitionExecutorCfg, PartitionExecutorScope, PartitionLimits};
pub use plan::{PartitionRecord, RecordIdentity};
pub use publisher::PublisherSnapshot;
pub use runtime::{ExecutionDomainSnapshot, PartitionSnapshot};
pub use shutdown::PartitionShutdownReport;
pub mod command;
pub(crate) mod disposition;
pub mod fencing;
pub(crate) mod retryop;
pub mod runtime;
use std::collections::HashMap;
use std::sync::Arc;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use crate::client::RedisClient;
use crate::config::{CompatibilityProfile, PartitionCfg, MAX_REDIS_NAME_BYTES};
use crate::error::{NasaRedisError, Result};
use crate::lock::DistributedLock;
pub fn compat_string_hash(s: &str) -> i32 {
s.encode_utf16()
.fold(0i32, |h, u| h.wrapping_mul(31).wrapping_add(u as i32))
}
pub fn compat_long_hash(v: i64) -> i32 {
(v ^ ((v as u64) >> 32) as i64) as i32
}
pub fn route_str(key: &str, count: u32) -> u32 {
((compat_string_hash(key) & 0x7FFF_FFFF) as u32) % count
}
pub fn route_i64(key: i64, count: u32) -> u32 {
((compat_long_hash(key) & 0x7FFF_FFFF) as u32) % count
}
fn command_timeout_millis(timeout: std::time::Duration) -> Result<u64> {
if timeout > std::time::Duration::from_millis(crate::config::MAX_REDIS_RUNTIME_DURATION_MS) {
return Err(NasaRedisError::Config(format!(
"partition command timeout 超过运行时上限 {}ms",
crate::config::MAX_REDIS_RUNTIME_DURATION_MS
)));
}
u64::try_from(timeout.as_millis())
.map_err(|_| NasaRedisError::Config("partition command timeout 毫秒值溢出".into()))
}
pub fn compat_double_to_string(v: f64) -> String {
if v.is_nan() {
return "NaN".to_string();
}
if v.is_infinite() {
return if v > 0.0 {
"Infinity"
} else {
"-Infinity"
}
.to_string();
}
if v == 0.0 {
return if v.is_sign_negative() {
"-0.0"
} else {
"0.0"
}
.to_string();
}
let neg = v < 0.0;
let s = format!("{:e}", v.abs());
let (mant, exp_str) = s.split_once('e').expect("{:e} 必含 e");
let exp: i32 = exp_str.parse().expect("指数可解析");
let digits: String = mant.chars().filter(|c| *c != '.').collect(); let body = if (-3..=6).contains(&exp) {
let point = exp + 1;
let n = digits.len() as i32;
if point <= 0 {
format!("0.{}{}", "0".repeat((-point) as usize), digits)
} else if point >= n {
format!("{}{}.0", digits, "0".repeat((point - n) as usize))
} else {
format!(
"{}.{}",
&digits[..point as usize],
&digits[point as usize..]
)
}
} else {
let frac = if digits.len() > 1 {
&digits[1..]
} else {
"0"
};
format!("{}.{}E{}", &digits[..1], frac, exp)
};
if neg {
format!("-{body}")
} else {
body
}
}
#[derive(Debug, Clone)]
pub struct KeyLayout {
pub prefix: String,
pub profile: CompatibilityProfile,
}
impl KeyLayout {
pub fn stream(&self, p: u32) -> String {
format!("{}:{}", self.prefix, p)
}
pub fn lock_business_key(&self, p: u32) -> String {
format!("{}:lock:{}", self.prefix, p)
}
pub fn nodes(&self) -> String {
match self.profile {
CompatibilityProfile::RustV2 => format!("{}:nodes:v2", self.prefix),
_ => format!("{}:nodes", self.prefix),
}
}
pub fn wake(&self) -> String {
format!("{}:wake", self.prefix)
}
pub fn group(&self) -> &str {
&self.prefix
}
}
fn assert_same_slot_cluster(layout: &KeyLayout, lock_prefix: &str, count: u32) -> Result<()> {
use crate::keytag::redis_slot;
if layout.group().is_empty() {
return Err(NasaRedisError::Config(
"cluster 同槽自检:default_group 为空,`{}` 空 hash-tag 会使各 key 落不同 slot → 多键 Lua CROSSSLOT".into(),
));
}
for p in 0..count {
let stream = layout.stream(p);
let want = redis_slot(stream.as_bytes());
let keys = vec![
stream.clone(),
format!("{lock_prefix}{}", layout.lock_business_key(p)),
crate::partition::fencing::fence_key(layout),
crate::partition::disposition::marker_key(layout, p),
crate::partition::disposition::quarantine_key(layout, "self-check"),
crate::partition::disposition::parked_index_key(layout, p),
crate::partition::disposition::dlq_stream_key(layout),
crate::partition::retryop::marker_key(layout, p, "self-check"),
crate::partition::command::cmd_stream_key(layout, p),
crate::partition::command::result_key(layout, p, "self-check"),
layout.nodes(),
layout.wake(),
];
for k in &keys {
let got = redis_slot(k.as_bytes());
if got != want {
return Err(NasaRedisError::Config(format!(
"cluster 同槽自检失败:分区 {p} 的 key \"{k}\"(slot {got})与 stream \"{stream}\"(slot {want})不同槽——\
KeyLayout 命名可能破坏了 `{{group}}` hash-tag 不变量,多键 Lua 会 CROSSSLOT"
)));
}
}
}
tracing::info!(group = %layout.group(), count, "cluster 同槽自检通过(所有分区 Lua key 同 slot)");
Ok(())
}
async fn build_group_layout(
client: &Arc<RedisClient>,
base: &str,
count: u32,
) -> Result<KeyLayout> {
if count == 0 {
return Err(NasaRedisError::Config(format!(
"partition 组 \"{base}\" count 必须 > 0"
)));
}
let prefix = if client.is_cluster() {
format!("{{{base}}}")
} else {
base.to_string()
};
let layout = KeyLayout {
prefix,
profile: client.profile(),
};
{
let v2 = format!("{}:nodes:v2", layout.prefix);
let v1 = format!("{}:nodes", layout.prefix);
let n2 = client.z_card(&v2).await.unwrap_or(0);
let n1 = client.z_card(&v1).await.unwrap_or(0);
if n2 > 0 && n1 > 0 {
tracing::warn!(group = %layout.prefix, v2_nodes = n2, v1_nodes = n1,
"同 group 检测到 RustV2 与墙钟两 profile 共存——nodes 已物理隔离,但 fair-share 会倾斜");
}
}
if client.is_cluster() {
assert_same_slot_cluster(&layout, &client.config().lock.prefix, count)?;
}
for p in 0..count {
let stream = layout.stream(p);
let r: std::result::Result<String, redis::RedisError> = redis::cmd("XGROUP")
.arg("CREATE")
.arg(&stream)
.arg(layout.group())
.arg("0-0")
.arg("MKSTREAM")
.query_async(&mut client.conn())
.await;
match r {
Ok(reply) if reply == "OK" => {}
Err(e) if e.code() == Some("BUSYGROUP") => {}
Ok(_) => {
return Err(NasaRedisError::Parsing(
"invalid partition group creation response".into(),
));
}
Err(e) => return Err(e.into()),
}
}
Ok(layout)
}
fn de_null_as_default<'de, D, T>(deserializer: D) -> std::result::Result<T, D::Error>
where
D: serde::Deserializer<'de>,
T: serde::Deserialize<'de> + Default,
{
Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Envelope {
#[serde(default, deserialize_with = "de_null_as_default")]
pub topic: String,
#[serde(default, deserialize_with = "de_null_as_default")]
pub event: String,
#[serde(default)]
pub data: serde_json::Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub passthrough: Option<serde_json::Map<String, serde_json::Value>>,
}
pub const DATA_FIELD: &str = "data";
pub type ErasedHandler = Arc<
dyn Fn(Vec<(String, serde_json::Value)>) -> futures::future::BoxFuture<'static, Vec<String>>
+ Send
+ Sync,
>;
pub type HandlerMap = HashMap<(String, String), ErasedHandler>;
pub const DEFAULT_GROUP_ID: &str = "";
struct PreparedGroup {
id: String,
layout: KeyLayout,
count: u32,
plans: plan::PlanMap,
cfg: PartitionCfg,
stream_cfg: crate::config::StreamCfg,
}
pub struct PreparedPartition {
client: Arc<RedisClient>,
lock: Arc<DistributedLock>,
node_id: String,
groups: Vec<PreparedGroup>,
topic_to_group: HashMap<String, usize>,
registration_error: Option<NasaRedisError>,
next_plan_id: u32,
}
pub struct RunningPartition {
stop: Arc<shutdown::ShutdownOperation>,
start_gate: tokio_util::sync::CancellationToken,
inner: Arc<runtime::GroupRuntime>,
groups: HashMap<String, Arc<runtime::GroupRuntime>>,
topic_to_group: HashMap<String, String>,
}
impl PreparedPartition {
pub async fn prepare(client: Arc<RedisClient>, lock: Arc<DistributedLock>) -> Result<Self> {
let cfg = client.config().partition.clone();
if !cfg.enabled {
return Err(NasaRedisError::Config(
"partition.enabled=false:分区设施未启用。需启用请显式设 \
cfg.partition.enabled=true(对齐 Legacy 总开关语义)"
.into(),
));
}
if cfg.count == 0 {
return Err(NasaRedisError::Config("partition.count 必须 > 0".into()));
}
if cfg.default_group.trim().is_empty()
|| cfg.default_group != cfg.default_group.trim()
|| cfg.default_group.len() > MAX_REDIS_NAME_BYTES
|| cfg.default_group.contains(['{', '}', ':'])
{
return Err(NasaRedisError::Config(format!(
"partition.default_group 非法:必须无首尾空白、非空、不超过 {MAX_REDIS_NAME_BYTES} 字节且不得含 `{{`/`}}`/`:`(cluster 下作 hash-tag)"
)));
}
let mut groups: Vec<PreparedGroup> = Vec::with_capacity(1 + cfg.groups.len());
let mut topic_to_group: HashMap<String, usize> = HashMap::new();
let global_stream = client.config().stream.clone();
let def_layout = build_group_layout(&client, &cfg.default_group, cfg.count).await?;
let mut def_cfg = cfg.clone();
def_cfg.groups = HashMap::new();
groups.push(PreparedGroup {
id: DEFAULT_GROUP_ID.to_string(),
layout: def_layout,
count: cfg.count,
plans: HashMap::new(),
cfg: def_cfg,
stream_cfg: global_stream.clone(),
});
for (logical, gcfg) in &cfg.groups {
if logical.trim().is_empty()
|| logical != logical.trim()
|| logical.len() > MAX_REDIS_NAME_BYTES
|| logical.contains(['{', '}', ':'])
{
return Err(NasaRedisError::Config(format!(
"partition.groups 含非法逻辑名:必须无首尾空白、非空、不超过 {MAX_REDIS_NAME_BYTES} 字节且不得含 `{{`/`}}`/`:`"
)));
}
let gcount = if gcfg.count > 0 {
gcfg.count
} else {
cfg.count
};
let base = format!("{}:{}", cfg.default_group, logical); let layout = build_group_layout(&client, &base, gcount).await?;
let idx = groups.len();
let topics: Vec<String> = if gcfg.topics.is_empty() {
vec![logical.clone()]
} else {
gcfg.topics.clone()
};
for t in topics {
if t.trim().is_empty() || t != t.trim() || t.len() > MAX_REDIS_NAME_BYTES {
return Err(NasaRedisError::Config(format!(
"partition.groups 含非法 topic:必须无首尾空白、非空且不超过 {MAX_REDIS_NAME_BYTES} 字节"
)));
}
if let Some(&prev) = topic_to_group.get(&t) {
return Err(NasaRedisError::Config(format!(
"topic \"{t}\" 被多个隔离组路由(组 \"{}\" 与 \"{}\");一个 topic 只能属一个组",
groups[prev].id, logical
)));
}
topic_to_group.insert(t, idx);
}
groups.push(PreparedGroup {
id: logical.clone(),
layout,
count: gcount,
plans: HashMap::new(),
cfg: gcfg.resolved_partition(&cfg, gcount),
stream_cfg: gcfg.resolved_stream(&global_stream),
});
}
if !cfg.groups.is_empty() {
tracing::info!(default = %cfg.default_group, isolation_groups = cfg.groups.len(),
"partition 多组就绪:1 默认 + {} 隔离组(高频/低频隔离消费)", cfg.groups.len());
}
Ok(Self {
client,
lock,
node_id: format!("n-{}", uuid::Uuid::new_v4().simple()),
groups,
topic_to_group,
registration_error: None,
next_plan_id: 1,
})
}
pub fn register<T, F, Fut>(&mut self, topic: &str, event: &str, f: F) -> &mut Self
where
T: DeserializeOwned + Send + 'static,
F: Fn(Vec<T>) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = std::result::Result<(), String>> + Send + 'static,
{
if let Err(error) = self.try_register_legacy(topic, event, f) {
if self.registration_error.is_none() {
self.registration_error = Some(error);
}
}
self
}
pub fn try_register_legacy<T, F, Fut>(
&mut self,
topic: &str,
event: &str,
f: F,
) -> Result<&mut Self>
where
T: DeserializeOwned + Send + 'static,
F: Fn(Vec<T>) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = std::result::Result<(), String>> + Send + 'static,
{
activation::validate_route(topic, event)?;
let idx = self.topic_to_group.get(topic).copied().unwrap_or(0);
let key = (topic.to_string(), event.to_string());
if self.groups[idx].plans.contains_key(&key) {
return Err(NasaRedisError::Config(format!(
"partition route already registered: ({topic}, {event})"
)));
}
let id = self.reserve_plan_id()?;
self.groups[idx]
.plans
.insert(key, plan::ConsumerPlan::legacy::<T, _, _>(id, f));
Ok(self)
}
fn reserve_plan_id(&mut self) -> Result<u32> {
let id = self.next_plan_id;
if id >= u32::MAX / 2 {
return Err(NasaRedisError::Config(
"consumer plan identity exhausted".into(),
));
}
self.next_plan_id += 1;
Ok(id)
}
pub fn register_partitioned<T, K, I, S, KF, H, Fut>(
&mut self,
topics: I,
event: impl Into<String>,
key_fn: KF,
handler: H,
) -> Result<&mut Self>
where
T: DeserializeOwned + Send + 'static,
K: std::hash::Hash,
I: IntoIterator<Item = S>,
S: Into<String>,
KF: Fn(&T) -> Option<K> + Send + Sync + 'static,
H: Fn(PartitionRecord<T>) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = std::result::Result<(), String>> + Send + 'static,
{
self.register_partitioned_with_weight(topics, event, key_fn, |_| 0, handler)
}
pub fn register_partitioned_with_weight<T, K, I, S, KF, WF, H, Fut>(
&mut self,
topics: I,
event: impl Into<String>,
key_fn: KF,
weight: WF,
handler: H,
) -> Result<&mut Self>
where
T: DeserializeOwned + Send + 'static,
K: std::hash::Hash,
I: IntoIterator<Item = S>,
S: Into<String>,
KF: Fn(&T) -> Option<K> + Send + Sync + 'static,
WF: Fn(&T) -> usize + Send + Sync + 'static,
H: Fn(PartitionRecord<T>) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = std::result::Result<(), String>> + Send + 'static,
{
let event = event.into();
let topics: Vec<String> = topics.into_iter().map(Into::into).collect();
let mut seen = std::collections::HashSet::new();
if topics.is_empty() {
return Err(NasaRedisError::Config(
"consumer plan topics cannot be empty".into(),
));
}
for topic in &topics {
activation::validate_route(topic, &event)?;
let idx = self.topic_to_group.get(topic).copied().unwrap_or(0);
if !seen.insert(topic)
|| self.groups[idx]
.plans
.contains_key(&(topic.clone(), event.clone()))
{
return Err(NasaRedisError::Config(format!(
"partition route already registered: ({topic}, {event})"
)));
}
}
let id = self.reserve_plan_id()?;
let plan = plan::ConsumerPlan::typed(id, key_fn, weight, handler);
for topic in topics {
let idx = self.topic_to_group.get(&topic).copied().unwrap_or(0);
self.groups[idx]
.plans
.insert((topic, event.clone()), plan.clone());
}
Ok(self)
}
pub async fn start(self) -> Result<RunningPartition> {
self.start_inner(true).await
}
pub async fn start_suspended(self) -> Result<RunningPartition> {
self.start_inner(false).await
}
async fn start_inner(self, activate: bool) -> Result<RunningPartition> {
let PreparedPartition {
client,
lock,
node_id,
groups,
topic_to_group,
registration_error,
next_plan_id,
} = self;
if let Some(error) = registration_error {
return Err(error);
}
activation::validate_routes(&groups)?;
let mut activation = activation::PlanActivation::new();
let config = client.config().partition.clone();
for group in &groups {
config.limits.validate(group.stream_cfg.batch_size)?;
}
let execution_plan = execution::ExecutionPlan::build(
&groups,
&config.executor,
&config.limits,
(next_plan_id - 1) as usize,
)?;
let core =
runtime::engine::RedisPartitionRuntime::new(config.limits.clone(), execution_plan)?;
activation.track_core(core.clone());
if let Err(error) = core.start(activation.start_gate()).await {
return Err(activation.rollback(error).await);
}
let publisher = publisher::PublisherCoordinator::new(config.limits.clone());
let ids: Vec<String> = groups.iter().map(|g| g.id.clone()).collect();
let mut runtimes: HashMap<String, Arc<runtime::GroupRuntime>> = HashMap::new();
let mut inner: Option<Arc<runtime::GroupRuntime>> = None;
for (i, g) in groups.into_iter().enumerate() {
let rt = match runtime::GroupRuntime::start(
Arc::clone(&client),
Arc::clone(&lock),
g.layout,
g.count,
g.plans,
core.clone(),
publisher.clone(),
node_id.clone(),
g.cfg,
g.stream_cfg,
activation.start_gate(),
)
.await
{
Ok(rt) => rt,
Err(e) => {
return Err(activation.rollback(e).await);
}
};
if i == 0 {
inner = Some(Arc::clone(&rt)); }
activation.track(Arc::clone(&rt));
runtimes.insert(g.id, rt);
}
let topic_to_group: HashMap<String, String> = topic_to_group
.into_iter()
.map(|(t, idx)| (t, ids[idx].clone()))
.collect();
for runtime in runtimes.values() {
if let Err(error) = runtime.ensure_stream_contract().await {
return Err(activation.rollback(error).await);
}
}
if core
.executions
.domains
.iter()
.any(|domain| domain.runner.health() != napart::RunnerHealth::Healthy)
{
return Err(activation
.rollback(NasaRedisError::Config(
"partition runner is not healthy at activation".into(),
))
.await);
}
let running = RunningPartition {
start_gate: activation.start_gate(),
stop: shutdown::ShutdownOperation::new(
core,
publisher,
runtimes.values().cloned().collect(),
),
inner: inner.expect("默认组恒存在(groups[0])"),
groups: runtimes,
topic_to_group,
};
activation.commit(activate);
Ok(running)
}
}
impl RunningPartition {
pub fn shutdown_report(&self) -> PartitionShutdownReport {
self.stop.report()
}
pub fn activate(&self) {
if !self
.stop
.core
.roots_closed
.load(std::sync::atomic::Ordering::Acquire)
{
self.start_gate.cancel();
}
}
pub fn begin_shutdown(&self) {
self.stop.begin();
}
pub fn retain_shutdown_dependency<T: Send + 'static>(
&self,
guard: T,
) -> std::result::Result<(), T> {
self.stop.retain_dependency(guard)
}
fn rt_for_topic(&self, topic: &str) -> &Arc<runtime::GroupRuntime> {
self.topic_to_group
.get(topic)
.and_then(|g| self.groups.get(g))
.unwrap_or(&self.inner)
}
fn rt_by_group(&self, group: &str) -> Result<&Arc<runtime::GroupRuntime>> {
self.groups.get(group).ok_or_else(|| {
NasaRedisError::Config(format!(
"分区组 \"{group}\" 不存在(默认组用 \"\"=DEFAULT_GROUP_ID,隔离组用其逻辑名)"
))
})
}
pub fn async_delete_pending(&self) -> usize {
self.groups.values().fold(0usize, |total, runtime| {
total.saturating_add(runtime.async_delete_pending())
})
}
pub async fn publish<T: Serialize>(
&self,
topic: &str,
event: &str,
key: &str,
data: &T,
) -> Result<String> {
let rt = self.rt_for_topic(topic);
rt.publish(topic, event, route_str(key, rt.count), data, None)
.await
}
pub async fn publish_round_robin<T: Serialize>(
&self,
topic: &str,
event: &str,
data: &T,
) -> Result<String> {
self.rt_for_topic(topic)
.publish_round_robin(topic, event, data)
.await
}
pub async fn publish_i64<T: Serialize>(
&self,
topic: &str,
event: &str,
key: i64,
data: &T,
) -> Result<String> {
let rt = self.rt_for_topic(topic);
rt.publish(topic, event, route_i64(key, rt.count), data, None)
.await
}
pub async fn publish_if_valid<T: Serialize>(
&self,
topic: &str,
event: &str,
key: &str,
data: &T,
) -> Result<Option<String>> {
if topic.is_empty() || event.is_empty() {
tracing::warn!(topic, event, "publish_if_valid: 入参无效,未发布");
return Ok(None);
}
Ok(Some(self.publish(topic, event, key, data).await?))
}
pub async fn claimed_partitions(&self) -> Vec<u32> {
self.inner.claimed_partitions().await
}
pub async fn parked(&self, p: u32) -> Result<Option<String>> {
self.inner.parked_id(p).await
}
pub async fn resume_parked(&self, p: u32) -> Result<Vec<String>> {
self.inner.resume_parked(p).await
}
pub async fn drop_parked(&self, p: u32) -> Result<()> {
self.inner.drop_parked(p).await
}
pub async fn dlq_parked(&self, p: u32) -> Result<Vec<String>> {
self.inner.dlq_parked(p).await
}
pub async fn force_republish(&self, p: u32) -> Result<Vec<String>> {
self.inner.force_republish(p).await
}
pub async fn force_takeover(&self, p: u32) -> Result<Vec<String>> {
self.inner.force_takeover(p).await
}
pub async fn submit_command(
&self,
p: u32,
operation_id: &str,
action: command::CmdAction,
timeout: std::time::Duration,
) -> Result<command::CmdResult> {
if p >= self.inner.count {
return Err(NasaRedisError::Config(
"partition command target is outside the default group".into(),
));
}
let timeout_ms = command_timeout_millis(timeout)?;
command::submit(
&self.inner.client,
&self.inner.layout,
p,
operation_id,
action,
timeout_ms,
)
.await
}
pub async fn command_result(
&self,
p: u32,
operation_id: &str,
) -> Result<Option<command::CmdResult>> {
command::query(&self.inner.client, &self.inner.layout, p, operation_id).await
}
pub async fn claimed_partitions_by_group(&self) -> HashMap<String, Vec<u32>> {
let mut out = HashMap::new();
for (id, rt) in &self.groups {
out.insert(id.clone(), rt.claimed_partitions().await);
}
out
}
pub async fn claimed_partitions_display(&self) -> HashMap<String, Vec<u32>> {
self.claimed_partitions_by_group()
.await
.into_iter()
.map(|(id, v)| {
let k = if id == DEFAULT_GROUP_ID {
"<default>".to_string()
} else if id == "<default>" {
format!("group:{id}")
} else {
id
};
(k, v)
})
.collect()
}
pub async fn parked_in(&self, group: &str, p: u32) -> Result<Option<String>> {
self.rt_by_group(group)?.parked_id(p).await
}
pub async fn resume_parked_in(&self, group: &str, p: u32) -> Result<Vec<String>> {
self.rt_by_group(group)?.resume_parked(p).await
}
pub async fn drop_parked_in(&self, group: &str, p: u32) -> Result<()> {
self.rt_by_group(group)?.drop_parked(p).await
}
pub async fn dlq_parked_in(&self, group: &str, p: u32) -> Result<Vec<String>> {
self.rt_by_group(group)?.dlq_parked(p).await
}
pub async fn force_republish_in(&self, group: &str, p: u32) -> Result<Vec<String>> {
self.rt_by_group(group)?.force_republish(p).await
}
pub async fn force_takeover_in(&self, group: &str, p: u32) -> Result<Vec<String>> {
self.rt_by_group(group)?.force_takeover(p).await
}
pub async fn submit_command_in(
&self,
group: &str,
p: u32,
operation_id: &str,
action: command::CmdAction,
timeout: std::time::Duration,
) -> Result<command::CmdResult> {
let rt = self.rt_by_group(group)?;
if p >= rt.count {
return Err(NasaRedisError::Config(
"partition command target is outside the selected group".into(),
));
}
let timeout_ms = command_timeout_millis(timeout)?;
command::submit(&rt.client, &rt.layout, p, operation_id, action, timeout_ms).await
}
pub async fn command_result_in(
&self,
group: &str,
p: u32,
operation_id: &str,
) -> Result<Option<command::CmdResult>> {
let rt = self.rt_by_group(group)?;
command::query(&rt.client, &rt.layout, p, operation_id).await
}
pub async fn parked_for_topic(&self, topic: &str, p: u32) -> Result<Option<String>> {
self.rt_for_topic(topic).parked_id(p).await
}
pub async fn shutdown(&self) -> PartitionShutdownReport {
let timeout = std::time::Duration::from_millis(self.inner.cfg.drain_timeout_ms);
self.shutdown_until(std::time::Instant::now() + timeout)
.await
}
pub async fn shutdown_until(&self, deadline: std::time::Instant) -> PartitionShutdownReport {
self.stop.wait(deadline).await
}
pub async fn force_shutdown_until(
&self,
deadline: std::time::Instant,
) -> PartitionShutdownReport {
self.stop.force(deadline).await
}
pub fn snapshot(&self) -> PartitionSnapshot {
self.stop.core.snapshot()
}
pub fn publisher_snapshot(&self) -> PublisherSnapshot {
self.stop.publisher.snapshot()
}
}
impl Drop for RunningPartition {
fn drop(&mut self) {
if tokio::runtime::Handle::try_current().is_ok() {
self.stop.begin();
} else {
self.stop.core.revoke_all();
for group in self.groups.values() {
group.cancel_best_effort();
}
}
}
}