use super::server::SsoChannel;
use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
use std::sync::Arc;
pub struct RedisPubSubSsoChannel {
pubsub: oxcache::pubsub::RedisPubSub,
}
impl RedisPubSubSsoChannel {
pub async fn new(url: &str) -> GarrisonResult<Self> {
let pubsub = oxcache::pubsub::RedisPubSub::new(url)
.await
.map_err(|e| GarrisonError::Internal(format!("sso-redis-init::{e}")))?;
Ok(Self { pubsub })
}
#[must_use]
pub fn with_reconnect_attempts(mut self, attempts: usize) -> Self {
self.pubsub = self.pubsub.with_reconnect_attempts(attempts);
self
}
pub fn shutdown(&self) -> usize {
self.pubsub.shutdown()
}
}
#[async_trait]
impl SsoChannel for RedisPubSubSsoChannel {
async fn push(&self, topic: &str, message: &str) -> GarrisonResult<()> {
self.pubsub
.publish(topic, message)
.await
.map(|_| ())
.map_err(|e| GarrisonError::Internal(format!("sso-redis-publish::{e}")))
}
async fn subscribe(
&self,
topic: &str,
handler: Box<dyn Fn(String) + Send + Sync>,
) -> GarrisonResult<()> {
self.pubsub
.subscribe(topic, Arc::new(handler))
.await
.map_err(|e| GarrisonError::Internal(format!("sso-redis-subscribe::{e}")))
}
}
#[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]
async fn new_with_unreachable_port_returns_err() {
let result = RedisPubSubSsoChannel::new("redis://127.0.0.1:1").await;
match result {
Err(GarrisonError::Internal(msg)) => assert!(
msg.contains("sso-redis-init::"),
"错误应带 sso-redis-init:: 前缀,实际: {msg}"
),
Ok(_) => panic!("构造指向不可达端口应返回 Err,实际 Ok"),
Err(other) => panic!("期望 Internal 错误,实际: {other:?}"),
}
}
#[tokio::test]
async fn new_rejects_malformed_url() {
let result = RedisPubSubSsoChannel::new("not-a-redis-url").await;
assert!(result.is_err(), "非法 URL 应构造失败");
}
async fn redis_reachable() -> bool {
tokio::net::TcpStream::connect("127.0.0.1:6379")
.await
.is_ok()
}
fn skip_if_unreachable(guard: bool, scenario: &str) {
if !guard {
eprintln!(
"[SKIP] Redis 不可达(127.0.0.1:6379 未监听),跳过 {scenario}(CI 将注入 \
Redis service 真实执行)"
);
}
}
async fn make_local_channel() -> RedisPubSubSsoChannel {
RedisPubSubSsoChannel::new("redis://127.0.0.1:6379")
.await
.expect("连接 Redis 失败")
}
#[tokio::test]
async fn new_creates_instance_with_redis() {
let reachable = redis_reachable().await;
skip_if_unreachable(reachable, "new_creates_instance_with_redis");
if !reachable {
return;
}
let channel = make_local_channel().await;
assert_eq!(channel.shutdown(), 0);
}
#[tokio::test]
async fn push_executes_publish_command() {
let reachable = redis_reachable().await;
skip_if_unreachable(reachable, "push_executes_publish_command");
if !reachable {
return;
}
let channel = make_local_channel().await;
let result = channel.push("garrison-channel-test-push", "hello").await;
assert!(result.is_ok(), "push 应成功,实际: {result:?}");
}
#[tokio::test]
async fn subscribe_receives_published_message() {
let reachable = redis_reachable().await;
skip_if_unreachable(reachable, "subscribe_receives_published_message");
if !reachable {
return;
}
let channel = make_local_channel().await;
let (tx, rx) = std::sync::mpsc::channel::<String>();
let topic = "garrison-channel-test-e2e";
channel
.subscribe(
topic,
Box::new(move |msg| {
let _ = tx.send(msg);
}),
)
.await
.expect("subscribe 应成功");
let mut received: Option<String> = None;
for _ in 0..3 {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
channel.push(topic, "test-payload").await.unwrap();
if let Ok(msg) = rx.recv_timeout(std::time::Duration::from_secs(3)) {
received = Some(msg);
break;
}
}
assert_eq!(
received.as_deref(),
Some("test-payload"),
"应收到发布的消息"
);
channel.shutdown();
}
}