mabi-core 1.6.2

Mabinogion - Core abstractions and utilities for industrial protocol simulator
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
//! Configuration file watcher for hot reload support.
//!
//! This module provides infrastructure for watching configuration files
//! and notifying subscribers when changes occur. The actual file watching
//! implementation is provided by external crates (e.g., notify) at the
//! application level, while this module defines the interfaces and event types.
//!
//! # Architecture
//!
//! ```text
//! ┌─────────────────┐     ┌──────────────────┐     ┌─────────────────┐
//! │  Config File    │────▶│  ConfigWatcher   │────▶│  Subscribers    │
//! │  (YAML/JSON)    │     │  (notify events) │     │  (engine, etc.) │
//! └─────────────────┘     └──────────────────┘     └─────────────────┘
//! ```
//!
//! # Example
//!
//! ```rust,ignore
//! use mabi_core::config::{ConfigEvent, ConfigEventHandler, ConfigSource};
//!
//! struct MyHandler;
//!
//! impl ConfigEventHandler for MyHandler {
//!     fn on_config_change(&self, event: ConfigEvent) {
//!         match event {
//!             ConfigEvent::Modified { source, .. } => {
//!                 println!("Config modified: {:?}", source);
//!             }
//!             _ => {}
//!         }
//!     }
//! }
//! ```

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;

use parking_lot::RwLock;
use tokio::sync::broadcast;

/// Configuration source identifier.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ConfigSource {
    /// Main simulator configuration file.
    Main(PathBuf),
    /// Device configuration file.
    Device(PathBuf),
    /// Scenario configuration file.
    Scenario(PathBuf),
    /// Protocol-specific configuration.
    Protocol { protocol: String, path: PathBuf },
    /// Custom configuration source.
    Custom { name: String, path: PathBuf },
}

impl ConfigSource {
    /// Get the path of this configuration source.
    pub fn path(&self) -> &PathBuf {
        match self {
            Self::Main(p) => p,
            Self::Device(p) => p,
            Self::Scenario(p) => p,
            Self::Protocol { path, .. } => path,
            Self::Custom { path, .. } => path,
        }
    }

    /// Get a descriptive name for this source.
    pub fn name(&self) -> String {
        match self {
            Self::Main(_) => "main".to_string(),
            Self::Device(_) => "device".to_string(),
            Self::Scenario(_) => "scenario".to_string(),
            Self::Protocol { protocol, .. } => format!("protocol:{}", protocol),
            Self::Custom { name, .. } => format!("custom:{}", name),
        }
    }
}

/// Configuration change event.
#[derive(Debug, Clone)]
pub enum ConfigEvent {
    /// Configuration file was created.
    Created {
        source: ConfigSource,
        timestamp: Instant,
    },
    /// Configuration file was modified.
    Modified {
        source: ConfigSource,
        timestamp: Instant,
    },
    /// Configuration file was deleted.
    Deleted {
        source: ConfigSource,
        timestamp: Instant,
    },
    /// Configuration file was renamed.
    Renamed {
        source: ConfigSource,
        old_path: PathBuf,
        new_path: PathBuf,
        timestamp: Instant,
    },
    /// Error occurred while watching.
    Error {
        source: Option<ConfigSource>,
        message: String,
        timestamp: Instant,
    },
    /// Configuration was reloaded successfully.
    Reloaded {
        source: ConfigSource,
        timestamp: Instant,
    },
}

impl ConfigEvent {
    /// Get the timestamp of this event.
    pub fn timestamp(&self) -> Instant {
        match self {
            Self::Created { timestamp, .. } => *timestamp,
            Self::Modified { timestamp, .. } => *timestamp,
            Self::Deleted { timestamp, .. } => *timestamp,
            Self::Renamed { timestamp, .. } => *timestamp,
            Self::Error { timestamp, .. } => *timestamp,
            Self::Reloaded { timestamp, .. } => *timestamp,
        }
    }

    /// Get the source of this event, if available.
    pub fn source(&self) -> Option<&ConfigSource> {
        match self {
            Self::Created { source, .. } => Some(source),
            Self::Modified { source, .. } => Some(source),
            Self::Deleted { source, .. } => Some(source),
            Self::Renamed { source, .. } => Some(source),
            Self::Error { source, .. } => source.as_ref(),
            Self::Reloaded { source, .. } => Some(source),
        }
    }

    /// Check if this is an error event.
    pub fn is_error(&self) -> bool {
        matches!(self, Self::Error { .. })
    }
}

/// Trait for handling configuration events.
///
/// Implement this trait to receive notifications when configuration changes.
pub trait ConfigEventHandler: Send + Sync {
    /// Called when a configuration event occurs.
    fn on_config_change(&self, event: ConfigEvent);

    /// Called before configuration reload.
    /// Return false to cancel the reload.
    fn before_reload(&self, _source: &ConfigSource) -> bool {
        true
    }

    /// Called after successful configuration reload.
    fn after_reload(&self, _source: &ConfigSource) {}
}

/// Configuration watcher state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WatcherState {
    /// Watcher is stopped.
    Stopped,
    /// Watcher is running.
    Running,
    /// Watcher is paused (events are queued but not processed).
    Paused,
}

/// Configuration watcher for hot reload support.
///
/// This struct manages configuration file watching and event distribution.
/// The actual file system watching should be implemented at the application level
/// using this struct to distribute events.
pub struct ConfigWatcher {
    /// Current state.
    state: RwLock<WatcherState>,

    /// Registered sources.
    sources: RwLock<Vec<ConfigSource>>,

    /// Event broadcaster.
    event_tx: broadcast::Sender<ConfigEvent>,

    /// Debounce duration in milliseconds.
    debounce_ms: u64,

    /// Last event time per source (for debouncing).
    last_events: RwLock<std::collections::HashMap<String, Instant>>,
}

impl ConfigWatcher {
    /// Create a new configuration watcher.
    pub fn new() -> Self {
        let (event_tx, _) = broadcast::channel(256);

        Self {
            state: RwLock::new(WatcherState::Stopped),
            sources: RwLock::new(Vec::new()),
            event_tx,
            debounce_ms: 100,
            last_events: RwLock::new(std::collections::HashMap::new()),
        }
    }

    /// Create a new configuration watcher with custom debounce duration.
    pub fn with_debounce(debounce_ms: u64) -> Self {
        let mut watcher = Self::new();
        watcher.debounce_ms = debounce_ms;
        watcher
    }

    /// Get the current state.
    pub fn state(&self) -> WatcherState {
        *self.state.read()
    }

    /// Start the watcher.
    pub fn start(&self) {
        *self.state.write() = WatcherState::Running;
    }

    /// Stop the watcher.
    pub fn stop(&self) {
        *self.state.write() = WatcherState::Stopped;
    }

    /// Pause the watcher (events are still received but not processed).
    pub fn pause(&self) {
        *self.state.write() = WatcherState::Paused;
    }

    /// Resume the watcher.
    pub fn resume(&self) {
        *self.state.write() = WatcherState::Running;
    }

    /// Register a configuration source to watch.
    pub fn register(&self, source: ConfigSource) {
        let mut sources = self.sources.write();
        if !sources.iter().any(|s| s.path() == source.path()) {
            sources.push(source);
        }
    }

    /// Unregister a configuration source.
    pub fn unregister(&self, path: &PathBuf) {
        self.sources.write().retain(|s| s.path() != path);
    }

    /// Get all registered sources.
    pub fn sources(&self) -> Vec<ConfigSource> {
        self.sources.read().clone()
    }

    /// Subscribe to configuration events.
    pub fn subscribe(&self) -> broadcast::Receiver<ConfigEvent> {
        self.event_tx.subscribe()
    }

    /// Emit a configuration event.
    ///
    /// This method should be called by the file system watcher implementation.
    /// Events are debounced based on the configured duration.
    pub fn emit(&self, event: ConfigEvent) {
        // Check if watcher is running
        if *self.state.read() != WatcherState::Running {
            return;
        }

        // Debounce check
        if let Some(source) = event.source() {
            let source_key = source.name();
            let now = Instant::now();

            let mut last_events = self.last_events.write();
            if let Some(last_time) = last_events.get(&source_key) {
                if now.duration_since(*last_time).as_millis() < self.debounce_ms as u128 {
                    return; // Skip debounced event
                }
            }
            last_events.insert(source_key, now);
        }

        // Broadcast event
        let _ = self.event_tx.send(event);
    }

    /// Emit a modification event for a source.
    pub fn emit_modified(&self, source: ConfigSource) {
        self.emit(ConfigEvent::Modified {
            source,
            timestamp: Instant::now(),
        });
    }

    /// Emit a reload success event.
    pub fn emit_reloaded(&self, source: ConfigSource) {
        self.emit(ConfigEvent::Reloaded {
            source,
            timestamp: Instant::now(),
        });
    }

    /// Emit an error event.
    pub fn emit_error(&self, source: Option<ConfigSource>, message: impl Into<String>) {
        self.emit(ConfigEvent::Error {
            source,
            message: message.into(),
            timestamp: Instant::now(),
        });
    }
}

impl Default for ConfigWatcher {
    fn default() -> Self {
        Self::new()
    }
}

/// Arc-wrapped ConfigWatcher for shared access.
pub type SharedConfigWatcher = Arc<ConfigWatcher>;

/// Create a shared config watcher.
pub fn create_config_watcher() -> SharedConfigWatcher {
    Arc::new(ConfigWatcher::new())
}

/// Callback-based event handler adapter.
pub struct CallbackHandler<F>
where
    F: Fn(ConfigEvent) + Send + Sync,
{
    callback: F,
}

impl<F> CallbackHandler<F>
where
    F: Fn(ConfigEvent) + Send + Sync,
{
    /// Create a new callback handler.
    pub fn new(callback: F) -> Self {
        Self { callback }
    }
}

impl<F> ConfigEventHandler for CallbackHandler<F>
where
    F: Fn(ConfigEvent) + Send + Sync,
{
    fn on_config_change(&self, event: ConfigEvent) {
        (self.callback)(event);
    }
}

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

    #[test]
    fn test_config_source() {
        let source = ConfigSource::Main(PathBuf::from("/etc/config.yaml"));
        assert_eq!(source.name(), "main");
        assert_eq!(source.path(), &PathBuf::from("/etc/config.yaml"));

        let protocol_source = ConfigSource::Protocol {
            protocol: "modbus".to_string(),
            path: PathBuf::from("/etc/modbus.yaml"),
        };
        assert_eq!(protocol_source.name(), "protocol:modbus");
    }

    #[test]
    fn test_config_watcher_lifecycle() {
        let watcher = ConfigWatcher::new();

        assert_eq!(watcher.state(), WatcherState::Stopped);

        watcher.start();
        assert_eq!(watcher.state(), WatcherState::Running);

        watcher.pause();
        assert_eq!(watcher.state(), WatcherState::Paused);

        watcher.resume();
        assert_eq!(watcher.state(), WatcherState::Running);

        watcher.stop();
        assert_eq!(watcher.state(), WatcherState::Stopped);
    }

    #[test]
    fn test_config_watcher_sources() {
        let watcher = ConfigWatcher::new();

        let source1 = ConfigSource::Main(PathBuf::from("/etc/config1.yaml"));
        let source2 = ConfigSource::Device(PathBuf::from("/etc/config2.yaml"));

        watcher.register(source1.clone());
        watcher.register(source2.clone());

        let sources = watcher.sources();
        assert_eq!(sources.len(), 2);

        watcher.unregister(&PathBuf::from("/etc/config1.yaml"));
        let sources = watcher.sources();
        assert_eq!(sources.len(), 1);
    }

    #[tokio::test]
    async fn test_config_watcher_events() {
        let watcher = ConfigWatcher::new();
        watcher.start();

        let mut rx = watcher.subscribe();

        let source = ConfigSource::Main(PathBuf::from("/etc/config.yaml"));
        watcher.emit_modified(source.clone());

        let event = tokio::time::timeout(std::time::Duration::from_millis(100), rx.recv())
            .await
            .expect("Timeout")
            .expect("Channel closed");

        assert!(matches!(event, ConfigEvent::Modified { .. }));
    }

    #[test]
    fn test_config_event_methods() {
        let source = ConfigSource::Main(PathBuf::from("/etc/config.yaml"));
        let event = ConfigEvent::Modified {
            source: source.clone(),
            timestamp: Instant::now(),
        };

        assert!(!event.is_error());
        assert_eq!(event.source().unwrap().name(), "main");

        let error_event = ConfigEvent::Error {
            source: None,
            message: "Test error".to_string(),
            timestamp: Instant::now(),
        };
        assert!(error_event.is_error());
    }
}