use super::server::SsoChannel;
use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
use futures::StreamExt;
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
pub struct RedisPubSubSsoChannel {
client: redis::Client,
connection_manager: redis::aio::ConnectionManager,
}
impl RedisPubSubSsoChannel {
pub fn new(connection_manager: redis::aio::ConnectionManager, client: redis::Client) -> Self {
Self {
client,
connection_manager,
}
}
}
#[async_trait]
impl SsoChannel for RedisPubSubSsoChannel {
async fn push(&self, topic: &str, message: &str) -> GarrisonResult<()> {
let mut conn = self.connection_manager.clone();
redis::cmd("PUBLISH")
.arg(topic)
.arg(message)
.query_async::<i64>(&mut conn)
.await
.map_err(|e| GarrisonError::Internal(format!("sso-redis-publish::{}", e)))?;
Ok(())
}
async fn subscribe(
&self,
topic: &str,
handler: Box<dyn Fn(String) + Send + Sync>,
) -> GarrisonResult<()> {
let topic = topic.to_string();
let client = self.client.clone();
let handler = Arc::new(handler);
tokio::spawn(async move {
let mut pubsub = match client.get_async_pubsub().await {
Ok(p) => p,
Err(e) => {
tracing::error!(
"Redis SUBSCRIBE connection failed: topic={}, err={}",
topic,
e
);
return;
},
};
if let Err(e) = pubsub.subscribe(&topic).await {
tracing::error!(
"Redis SUBSCRIBE subscribe failed: topic={}, err={}",
topic,
e
);
return;
}
let mut msg_stream = pubsub.on_message();
while let Some(msg) = msg_stream.next().await {
let payload: Result<String, _> = msg.get_payload();
match payload {
Ok(payload_str) => {
let handler_clone = handler.clone();
let result = std::panic::catch_unwind(AssertUnwindSafe(move || {
handler_clone(payload_str);
}));
if result.is_err() {
tracing::warn!(
"SSO channel handler panic: topic={}, continue subscribing",
topic
);
}
},
Err(e) => {
tracing::warn!(
"Redis message payload parse failed: topic={}, err={}",
topic,
e
);
},
}
}
tracing::info!("Redis SUBSCRIBE stream ended: topic={}", topic);
});
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn redis_pubsub_sso_channel_implements_sso_channel() {
fn assert_sso_channel<T: SsoChannel>() {}
assert_sso_channel::<RedisPubSubSsoChannel>();
}
#[test]
fn redis_pubsub_sso_channel_is_send_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<RedisPubSubSsoChannel>();
}
#[tokio::test]
#[ignore = "需要真实 Redis 连接(REDIS_URL 环境变量)"]
async fn new_creates_instance_with_redis() {
let redis_url =
std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string());
let client = redis::Client::open(redis_url.as_str()).unwrap();
let connection_manager = client
.get_connection_manager()
.await
.expect("连接 Redis 失败");
let channel = RedisPubSubSsoChannel::new(connection_manager, client);
let _ = &channel.client;
let _ = &channel.connection_manager;
}
#[tokio::test]
#[ignore = "需要真实 Redis 连接(REDIS_URL 环境变量)"]
async fn push_executes_publish_command() {
let redis_url =
std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string());
let client = redis::Client::open(redis_url.as_str()).unwrap();
let connection_manager = client
.get_connection_manager()
.await
.expect("连接 Redis 失败");
let channel = RedisPubSubSsoChannel::new(connection_manager, client);
let result = channel.push("test-topic", "hello").await;
assert!(result.is_ok(), "PUBLISH 应返回 Ok: {:?}", result);
}
#[tokio::test]
#[ignore = "需要真实 Redis 连接(REDIS_URL 环境变量)"]
async fn subscribe_receives_published_message() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
let redis_url =
std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string());
let client = redis::Client::open(redis_url.as_str()).unwrap();
let connection_manager = client
.get_connection_manager()
.await
.expect("连接 Redis 失败");
let channel = Arc::new(RedisPubSubSsoChannel::new(connection_manager, client));
let counter = Arc::new(AtomicUsize::new(0));
let counter_clone = counter.clone();
let topic = "test-sso-channel-subscribe";
channel
.subscribe(
topic,
Box::new(move |msg: String| {
if msg == "test-payload" {
counter_clone.fetch_add(1, Ordering::SeqCst);
}
}),
)
.await
.expect("subscribe 失败");
tokio::time::sleep(Duration::from_millis(100)).await;
channel.push(topic, "test-payload").await.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(counter.load(Ordering::SeqCst), 1, "应收到 1 条消息");
}
#[tokio::test]
#[ignore = "需要真实 Redis 连接(REDIS_URL 环境变量)"]
async fn subscribe_handler_panic_does_not_interrupt() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
let redis_url =
std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string());
let client = redis::Client::open(redis_url.as_str()).unwrap();
let connection_manager = client
.get_connection_manager()
.await
.expect("连接 Redis 失败");
let channel = Arc::new(RedisPubSubSsoChannel::new(connection_manager, client));
let counter = Arc::new(AtomicUsize::new(0));
let counter_clone = counter.clone();
let topic = "test-sso-channel-panic";
channel
.subscribe(
topic,
Box::new(move |msg: String| {
let count = counter_clone.fetch_add(1, Ordering::SeqCst);
if count == 0 && msg == "panic-trigger" {
panic!("handler 首次调用 panic");
}
}),
)
.await
.expect("subscribe 失败");
tokio::time::sleep(Duration::from_millis(100)).await;
channel.push(topic, "panic-trigger").await.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
channel.push(topic, "normal").await.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(
counter.load(Ordering::SeqCst),
2,
"handler 应被调用两次(panic 不中断)"
);
}
}