pakem/core/echo/
manager.rs1use crate::core::echo::broadcaster::{ChannelAuthRequest, ChannelAuthResponse};
2use serde::{Deserialize, Serialize};
3use std::collections::{HashMap, HashSet};
4use std::sync::{Arc, RwLock};
5use tokio::sync::mpsc;
6use uuid::Uuid;
7
8#[derive(Debug, Serialize, Deserialize, Clone)]
9pub struct EchoMessage {
10 pub channel: String,
11 pub event: String,
12 pub data: serde_json::Value,
13}
14
15pub type AuthorizerFn = Arc<
16 dyn Fn(&str, Option<&str>) -> bool + Send + Sync + 'static,
17>;
18
19pub struct EchoManager {
20 channels: RwLock<HashMap<String, HashSet<Uuid>>>,
22 connections: RwLock<HashMap<Uuid, mpsc::UnboundedSender<EchoMessage>>>,
24 authorizers: RwLock<HashMap<String, AuthorizerFn>>,
26 #[cfg(feature = "redis")]
27 redis_client: Option<redis::Client>,
28}
29
30impl EchoManager {
31 pub fn new() -> Self {
32 Self {
33 channels: RwLock::new(HashMap::new()),
34 connections: RwLock::new(HashMap::new()),
35 authorizers: RwLock::new(HashMap::new()),
36 #[cfg(feature = "redis")]
37 redis_client: None,
38 }
39 }
40
41 #[cfg(feature = "redis")]
42 pub fn with_redis(redis_url: &str) -> Result<Self, String> {
43 let client = redis::Client::open(redis_url)
44 .map_err(|e| format!("Gagal inisialisasi Redis client untuk Echo: {}", e))?;
45 Ok(Self {
46 channels: RwLock::new(HashMap::new()),
47 connections: RwLock::new(HashMap::new()),
48 authorizers: RwLock::new(HashMap::new()),
49 redis_client: Some(client),
50 })
51 }
52
53 pub fn add_connection(&self, id: Uuid, tx: mpsc::UnboundedSender<EchoMessage>) {
55 let mut connections = self.connections.write().unwrap();
56 connections.insert(id, tx);
57 }
58
59 pub fn remove_connection(&self, id: &Uuid) {
61 let mut connections = self.connections.write().unwrap();
62 connections.remove(id);
63
64 let mut channels = self.channels.write().unwrap();
65 for subscribers in channels.values_mut() {
66 subscribers.remove(id);
67 }
68 }
69
70 pub fn subscribe(&self, id: Uuid, channel: &str) {
72 let mut channels = self.channels.write().unwrap();
73 channels
74 .entry(channel.to_string())
75 .or_insert_with(HashSet::new)
76 .insert(id);
77 }
78
79 pub fn unsubscribe(&self, id: &Uuid, channel: &str) {
81 let mut channels = self.channels.write().unwrap();
82 if let Some(subscribers) = channels.get_mut(channel) {
83 subscribers.remove(id);
84 }
85 }
86
87 pub fn broadcast_local(&self, channel: &str, event: &str, data: serde_json::Value) {
89 let subscribers = {
90 let channels = self.channels.read().unwrap();
91 channels.get(channel).cloned()
92 };
93
94 if let Some(ids) = subscribers {
95 let connections = self.connections.read().unwrap();
96 let message = EchoMessage {
97 channel: channel.to_string(),
98 event: event.to_string(),
99 data,
100 };
101
102 for id in ids {
103 if let Some(tx) = connections.get(&id) {
104 let _ = tx.send(message.clone());
105 }
106 }
107 }
108 }
109
110 pub fn broadcast(&self, channel: &str, event: &str, data: serde_json::Value) {
112 self.broadcast_local(channel, event, data.clone());
113
114 #[cfg(feature = "redis")]
115 if let Some(ref client) = self.redis_client {
116 let client = client.clone();
117 let msg = EchoMessage {
118 channel: channel.to_string(),
119 event: event.to_string(),
120 data,
121 };
122 tokio::spawn(async move {
123 if let Ok(mut conn) = client.get_multiplexed_async_connection().await {
124 if let Ok(serialized) = serde_json::to_string(&msg) {
125 let _: Result<(), redis::RedisError> = redis::cmd("PUBLISH")
126 .arg("lumina_echo_events")
127 .arg(serialized)
128 .query_async(&mut conn)
129 .await;
130 }
131 }
132 });
133 }
134 }
135
136 #[cfg(feature = "redis")]
138 pub fn start_redis_subscriber(self: &Arc<Self>, redis_url: &str) {
139 use futures::StreamExt;
140 let echo = self.clone();
141 let url = redis_url.to_string();
142
143 tokio::spawn(async move {
144 match redis::Client::open(url) {
145 Ok(client) => match client.get_async_pubsub().await {
146 Ok(mut pubsub) => {
147 if let Err(e) = pubsub.subscribe("lumina_echo_events").await {
148 eprintln!("⚠️ [Lumina Echo Redis] Gagal subscribe: {}", e);
149 return;
150 }
151 println!("📡 [Lumina Echo] Redis Pub/Sub cluster listener aktif.");
152
153 let mut msg_stream = pubsub.on_message();
154 while let Some(msg) = msg_stream.next().await {
155 if let Ok(payload_str) = msg.get_payload::<String>() {
156 if let Ok(echo_msg) = serde_json::from_str::<EchoMessage>(&payload_str) {
157 echo.broadcast_local(&echo_msg.channel, &echo_msg.event, echo_msg.data);
158 }
159 }
160 }
161 }
162 Err(e) => {
163 eprintln!("⚠️ [Lumina Echo Redis] Gagal inisialisasi pubsub: {}", e);
164 }
165 },
166 Err(e) => {
167 eprintln!("⚠️ [Lumina Echo Redis] URL Redis tidak valid: {}", e);
168 }
169 }
170 });
171 }
172
173 pub fn authorize_channel<F>(&self, channel_pattern: &str, authorizer: F)
175 where
176 F: Fn(&str, Option<&str>) -> bool + Send + Sync + 'static,
177 {
178 let mut authorizers = self.authorizers.write().unwrap();
179 authorizers.insert(channel_pattern.to_string(), Arc::new(authorizer));
180 }
181
182 pub fn is_authorized(&self, channel_name: &str, socket_id: Option<&str>) -> bool {
184 if !channel_name.starts_with("private-") && !channel_name.starts_with("presence-") {
186 return true;
187 }
188
189 let authorizers = self.authorizers.read().unwrap();
190
191 if let Some(auth) = authorizers.get(channel_name) {
193 return auth(channel_name, socket_id);
194 }
195
196 for (pattern, auth) in authorizers.iter() {
198 if pattern.ends_with('*') {
199 let prefix = &pattern[..pattern.len() - 1];
200 if channel_name.starts_with(prefix) {
201 return auth(channel_name, socket_id);
202 }
203 }
204 }
205
206 true
208 }
209
210 pub fn authenticate_channel(&self, req: &ChannelAuthRequest) -> ChannelAuthResponse {
212 let auth_param = req.token.as_deref().or(req.socket_id.as_deref());
213 let authorized = self.is_authorized(&req.channel_name, auth_param);
214 let token = if authorized {
215 format!("auth-ok:{}", req.channel_name)
216 } else {
217 "forbidden".to_string()
218 };
219
220 ChannelAuthResponse {
221 auth: token,
222 channel: req.channel_name.clone(),
223 authorized,
224 }
225 }
226}