redis-watcher-temp 0.1.1

Redis watcher for Casbin-RS (Test Package)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
// Copyright 2025 The Casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use casbin::{EventData, Watcher};
use redis::{AsyncCommands, Client};
use serde::{Deserialize, Serialize};
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc, Mutex,
};
use std::thread::{self, JoinHandle};
use thiserror::Error;
use tokio::runtime::Runtime;
use tokio_stream::StreamExt;

// ========== Error Types ==========

#[derive(Error, Debug)]
pub enum WatcherError {
    #[error("Redis connection error: {0}")]
    RedisConnection(#[from] redis::RedisError),

    #[error("Serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    #[error("Callback not set")]
    CallbackNotSet,

    #[error("Watcher already closed")]
    AlreadyClosed,

    #[error("Configuration error: {0}")]
    Configuration(String),

    #[error("Runtime error: {0}")]
    Runtime(String),
}

pub type Result<T> = std::result::Result<T, WatcherError>;

// Type aliases to reduce complexity
type UpdateCallback = Box<dyn FnMut(String) + Send + Sync>;
type CallbackArc = Arc<Mutex<Option<UpdateCallback>>>;

// ========== Message Types ==========

/// Message types for communication between watcher instances
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub enum UpdateType {
    Update,
    UpdateForAddPolicy,
    UpdateForRemovePolicy,
    UpdateForRemoveFilteredPolicy,
    UpdateForSavePolicy,
    UpdateForAddPolicies,
    UpdateForRemovePolicies,
    UpdateForUpdatePolicy,
    UpdateForUpdatePolicies,
}

impl std::fmt::Display for UpdateType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            UpdateType::Update => write!(f, "Update"),
            UpdateType::UpdateForAddPolicy => write!(f, "UpdateForAddPolicy"),
            UpdateType::UpdateForRemovePolicy => write!(f, "UpdateForRemovePolicy"),
            UpdateType::UpdateForRemoveFilteredPolicy => write!(f, "UpdateForRemoveFilteredPolicy"),
            UpdateType::UpdateForSavePolicy => write!(f, "UpdateForSavePolicy"),
            UpdateType::UpdateForAddPolicies => write!(f, "UpdateForAddPolicies"),
            UpdateType::UpdateForRemovePolicies => write!(f, "UpdateForRemovePolicies"),
            UpdateType::UpdateForUpdatePolicy => write!(f, "UpdateForUpdatePolicy"),
            UpdateType::UpdateForUpdatePolicies => write!(f, "UpdateForUpdatePolicies"),
        }
    }
}

/// Message structure for Redis pub/sub communication
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Message {
    pub method: UpdateType,
    #[serde(rename = "ID")]
    pub id: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub sec: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub ptype: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub old_rule: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub old_rules: Vec<Vec<String>>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub new_rule: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub new_rules: Vec<Vec<String>>,
    #[serde(default)]
    pub field_index: i32,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub field_values: Vec<String>,
}

impl Message {
    pub fn new(method: UpdateType, id: String) -> Self {
        Self {
            method,
            id,
            sec: String::new(),
            ptype: String::new(),
            old_rule: Vec::new(),
            old_rules: Vec::new(),
            new_rule: Vec::new(),
            new_rules: Vec::new(),
            field_index: 0,
            field_values: Vec::new(),
        }
    }

    pub fn to_json(&self) -> Result<String> {
        Ok(serde_json::to_string(self)?)
    }

    pub fn from_json(json: &str) -> Result<Self> {
        Ok(serde_json::from_str(json)?)
    }
}

// ========== Helper Functions ==========

/// Convert EventData to Message for publishing
fn event_data_to_message(event_data: &EventData, local_id: &str) -> Message {
    match event_data {
        EventData::AddPolicy(sec, ptype, rule) => {
            let mut message = Message::new(UpdateType::UpdateForAddPolicy, local_id.to_string());
            message.sec = sec.clone();
            message.ptype = ptype.clone();
            message.new_rule = rule.clone();
            message
        }
        EventData::AddPolicies(sec, ptype, rules) => {
            let mut message = Message::new(UpdateType::UpdateForAddPolicies, local_id.to_string());
            message.sec = sec.clone();
            message.ptype = ptype.clone();
            message.new_rules = rules.clone();
            message
        }
        EventData::RemovePolicy(sec, ptype, rule) => {
            let mut message = Message::new(UpdateType::UpdateForRemovePolicy, local_id.to_string());
            message.sec = sec.clone();
            message.ptype = ptype.clone();
            message.old_rule = rule.clone();
            message
        }
        EventData::RemovePolicies(sec, ptype, rules) => {
            let mut message =
                Message::new(UpdateType::UpdateForRemovePolicies, local_id.to_string());
            message.sec = sec.clone();
            message.ptype = ptype.clone();
            message.old_rules = rules.clone();
            message
        }
        EventData::RemoveFilteredPolicy(sec, ptype, field_values) => {
            let mut message = Message::new(
                UpdateType::UpdateForRemoveFilteredPolicy,
                local_id.to_string(),
            );
            message.sec = sec.clone();
            message.ptype = ptype.clone();
            if !field_values.is_empty() {
                message.field_values = field_values[0].clone();
            }
            message
        }
        EventData::SavePolicy(_) => {
            Message::new(UpdateType::UpdateForSavePolicy, local_id.to_string())
        }
        EventData::ClearPolicy => Message::new(UpdateType::Update, local_id.to_string()),
        EventData::ClearCache => Message::new(UpdateType::Update, local_id.to_string()),
    }
}

// ========== Redis Client Wrapper ==========

/// Wrapper to support both standalone and cluster Redis
enum RedisClientWrapper {
    Standalone(Client),
    // For Cluster mode, we also keep a standalone client for pubsub
    // because Redis Cluster doesn't have native async pubsub support
    ClusterWithPubSub {
        cluster: Box<redis::cluster::ClusterClient>,
        pubsub_client: Client,
    },
}

impl RedisClientWrapper {
    async fn get_async_pubsub(&self) -> redis::RedisResult<redis::aio::PubSub> {
        match self {
            RedisClientWrapper::Standalone(client) => client.get_async_pubsub().await,
            RedisClientWrapper::ClusterWithPubSub { pubsub_client, .. } => {
                // Use the dedicated pubsub client for cluster mode
                pubsub_client.get_async_pubsub().await
            }
        }
    }

    async fn publish_message(&self, channel: &str, payload: String) -> redis::RedisResult<()> {
        match self {
            RedisClientWrapper::Standalone(client) => {
                let mut conn = client.get_multiplexed_async_connection().await?;
                let _: i32 = conn.publish(channel, payload).await?;
                Ok(())
            }
            RedisClientWrapper::ClusterWithPubSub { cluster, .. } => {
                // Use cluster connection for publishing
                let mut conn = cluster.get_async_connection().await?;
                let _: i32 = conn.publish(channel, payload).await?;
                Ok(())
            }
        }
    }
}

// ========== Redis Watcher Implementation ==========

pub struct RedisWatcher {
    runtime: Arc<Runtime>,
    client: Arc<RedisClientWrapper>,
    options: crate::WatcherOptions,
    callback: CallbackArc,
    subscription_handle: Arc<Mutex<Option<JoinHandle<()>>>>,
    is_closed: Arc<AtomicBool>,
}

impl RedisWatcher {
    /// Create a new Redis watcher for standalone Redis
    pub fn new(redis_url: &str, options: crate::WatcherOptions) -> Result<Self> {
        let runtime = Arc::new(
            tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .build()
                .map_err(|e| WatcherError::Runtime(e.to_string()))?,
        );

        let client = Arc::new(RedisClientWrapper::Standalone(Client::open(redis_url)?));

        // Test connection
        let client_clone = client.clone();
        runtime.block_on(async move {
            match &*client_clone {
                RedisClientWrapper::Standalone(c) => {
                    let mut conn = c.get_multiplexed_async_connection().await?;
                    let _: String = redis::cmd("PING").query_async(&mut conn).await?;
                }
                RedisClientWrapper::ClusterWithPubSub { .. } => unreachable!(),
            }
            Ok::<(), WatcherError>(())
        })?;

        Ok(Self {
            runtime,
            client,
            options,
            callback: Arc::new(Mutex::new(None)),
            subscription_handle: Arc::new(Mutex::new(None)),
            is_closed: Arc::new(AtomicBool::new(false)),
        })
    }

    /// Create a new Redis watcher for Redis Cluster
    ///
    /// # Arguments
    /// * `cluster_urls` - Comma-separated list of Redis cluster nodes (e.g., "127.0.0.1:7000,127.0.0.1:7001,127.0.0.1:7002")
    /// * `options` - Watcher configuration options
    ///
    /// # Example
    /// ```no_run
    /// use redis_watcher_temp::{RedisWatcher, WatcherOptions};
    ///
    /// let options = WatcherOptions::default();
    /// let watcher = RedisWatcher::new_cluster(
    ///     "redis://127.0.0.1:7000,redis://127.0.0.1:7001,redis://127.0.0.1:7002",
    ///     options
    /// ).unwrap();
    /// ```
    pub fn new_cluster(cluster_urls: &str, options: crate::WatcherOptions) -> Result<Self> {
        let runtime = Arc::new(
            tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .build()
                .map_err(|e| WatcherError::Runtime(e.to_string()))?,
        );

        // Parse cluster URLs
        let urls: Vec<&str> = cluster_urls.split(',').map(|s| s.trim()).collect();
        if urls.is_empty() {
            return Err(WatcherError::Configuration(
                "No cluster URLs provided".to_string(),
            ));
        }

        // Create cluster client
        let cluster_client = redis::cluster::ClusterClient::builder(urls.clone())
            .build()
            .map_err(|e| {
                WatcherError::Configuration(format!("Failed to build cluster client: {}", e))
            })?;

        // Create a standalone client for pubsub (connect to first node)
        // Redis Cluster pubsub requires connecting to a specific node
        let pubsub_client = Client::open(urls[0]).map_err(|e| {
            WatcherError::Configuration(format!("Failed to create pubsub client: {}", e))
        })?;

        let client = Arc::new(RedisClientWrapper::ClusterWithPubSub {
            cluster: Box::new(cluster_client),
            pubsub_client,
        });

        // Test connection
        let client_clone = client.clone();
        runtime.block_on(async move {
            match &*client_clone {
                RedisClientWrapper::Standalone(_) => unreachable!(),
                RedisClientWrapper::ClusterWithPubSub {
                    cluster,
                    pubsub_client,
                } => {
                    // Test cluster connection
                    let mut conn = cluster
                        .get_async_connection()
                        .await
                        .map_err(WatcherError::RedisConnection)?;
                    let _: String = redis::cmd("PING").query_async(&mut conn).await?;

                    // Test pubsub connection
                    let mut pubsub_conn = pubsub_client.get_multiplexed_async_connection().await?;
                    let _: String = redis::cmd("PING").query_async(&mut pubsub_conn).await?;
                }
            }
            Ok::<(), WatcherError>(())
        })?;

        Ok(Self {
            runtime,
            client,
            options,
            callback: Arc::new(Mutex::new(None)),
            subscription_handle: Arc::new(Mutex::new(None)),
            is_closed: Arc::new(AtomicBool::new(false)),
        })
    }

    /// Publish message to Redis channel
    fn publish_message(&self, message: &Message) -> Result<()> {
        if self.is_closed.load(Ordering::Relaxed) {
            return Err(WatcherError::AlreadyClosed);
        }

        let payload = message.to_json()?;
        let client = self.client.clone();
        let channel = self.options.channel.clone();

        self.runtime.block_on(async move {
            client.publish_message(&channel, payload).await?;
            Ok::<(), WatcherError>(())
        })?;

        Ok(())
    }

    /// Start subscription to Redis channel
    fn start_subscription(&self) -> Result<()> {
        if self.is_closed.load(Ordering::Relaxed) {
            return Err(WatcherError::AlreadyClosed);
        }

        let callback = self.callback.clone();
        let channel = self.options.channel.clone();
        let local_id = self.options.local_id.clone();
        let ignore_self = self.options.ignore_self;
        let is_closed = self.is_closed.clone();
        let client = self.client.clone();

        let handle = thread::spawn(move || {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap();

            rt.block_on(async move {
                // Use a timeout-aware subscription loop
                let result = async {
                    let mut pubsub = match client.get_async_pubsub().await {
                        Ok(p) => p,
                        Err(e) => {
                            log::error!("Failed to get async pubsub: {}", e);
                            return Err(e);
                        }
                    };

                    if let Err(e) = pubsub.subscribe(&channel).await {
                        log::error!("Failed to subscribe to channel {}: {}", channel, e);
                        return Err(e);
                    }

                    log::debug!("Successfully subscribed to channel: {}", channel);

                    let mut stream = pubsub.on_message();

                    loop {
                        // Check if closed before waiting for next message
                        if is_closed.load(Ordering::Relaxed) {
                            break;
                        }

                        // Use tokio::select! to check for shutdown while waiting
                        tokio::select! {
                            msg_opt = stream.next() => {
                                match msg_opt {
                                    Some(msg) => {
                                        let payload: String = msg.get_payload().unwrap_or_default();

                                        // Parse message and check if we should ignore it
                                        if ignore_self {
                                            if let Ok(parsed_msg) = Message::from_json(&payload) {
                                                if parsed_msg.id == local_id {
                                                    continue;
                                                }
                                            }
                                        }

                                        // Call callback
                                        if let Ok(mut cb_guard) = callback.lock() {
                                            if let Some(ref mut cb) = *cb_guard {
                                                cb(payload);
                                            }
                                        }
                                    }
                                    None => {
                                        // Stream ended
                                        log::debug!("Pubsub stream ended");
                                        break;
                                    }
                                }
                            }
                            _ = tokio::time::sleep(tokio::time::Duration::from_millis(100)) => {
                                // Periodic check for shutdown
                                if is_closed.load(Ordering::Relaxed) {
                                    break;
                                }
                            }
                        }
                    }

                    Ok::<(), redis::RedisError>(())
                };

                if let Err(e) = result.await {
                    log::error!("Subscription error: {}", e);
                }
            });
        });

        *self.subscription_handle.lock().unwrap() = Some(handle);
        Ok(())
    }
}

impl Watcher for RedisWatcher {
    fn set_update_callback(&mut self, cb: Box<dyn FnMut(String) + Send + Sync>) {
        *self.callback.lock().unwrap() = Some(cb);
        // Start subscription when callback is set
        let _ = self.start_subscription();
    }

    fn update(&mut self, d: EventData) {
        let message = event_data_to_message(&d, &self.options.local_id);
        let _ = self.publish_message(&message);
    }
}

impl Drop for RedisWatcher {
    fn drop(&mut self) {
        // Signal closure first
        self.is_closed.store(true, Ordering::Relaxed);

        // Wait for subscription thread to finish with a timeout
        if let Ok(mut handle_guard) = self.subscription_handle.lock() {
            if let Some(handle) = handle_guard.take() {
                // Give the thread a reasonable time to finish
                // The subscription loop checks is_closed every 100ms, so 500ms should be enough
                let _join_handle = std::thread::spawn(move || handle.join());

                // Don't block indefinitely - if thread doesn't finish in 1 second, continue anyway
                std::thread::sleep(std::time::Duration::from_millis(1000));
                // Thread will be cleaned up by OS if it's still running
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_message_serialization() {
        let message = Message::new(UpdateType::Update, "test-id".to_string());
        let json = message.to_json().unwrap();
        let parsed = Message::from_json(&json).unwrap();
        assert_eq!(message.method, parsed.method);
        assert_eq!(message.id, parsed.id);
    }

    #[test]
    fn test_event_data_conversion() {
        let event = EventData::AddPolicy(
            "p".to_string(),
            "p".to_string(),
            vec!["alice".to_string(), "data1".to_string(), "read".to_string()],
        );

        let message = event_data_to_message(&event, "test-id");
        assert_eq!(message.method, UpdateType::UpdateForAddPolicy);
        assert_eq!(message.sec, "p");
        assert_eq!(message.ptype, "p");
        assert_eq!(message.new_rule, vec!["alice", "data1", "read"]);
    }

    // Note: Integration tests that require Redis are in watcher_test.rs
}