a3s-lane 0.5.0

Lane-based priority command queue for async task scheduling with reliability, scalability, and observability features
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
//! Queue monitor for tracking queue metrics and health

use crate::queue::CommandQueue;
use crate::QueueStats;
use std::sync::Arc;
use std::time::Duration;
use tracing::{debug, warn};

/// Queue monitor configuration
#[derive(Debug, Clone)]
pub struct MonitorConfig {
    /// Monitoring interval
    pub interval: Duration,
    /// Warning threshold for pending commands
    pub pending_warning_threshold: usize,
    /// Warning threshold for active commands
    pub active_warning_threshold: usize,
}

impl Default for MonitorConfig {
    fn default() -> Self {
        Self {
            interval: Duration::from_secs(10),
            pending_warning_threshold: 100,
            active_warning_threshold: 50,
        }
    }
}

/// Queue monitor
pub struct QueueMonitor {
    queue: Arc<CommandQueue>,
    config: MonitorConfig,
}

impl QueueMonitor {
    /// Create a new queue monitor
    pub fn new(queue: Arc<CommandQueue>) -> Self {
        Self::with_config(queue, MonitorConfig::default())
    }

    /// Create a new queue monitor with custom configuration
    pub fn with_config(queue: Arc<CommandQueue>, config: MonitorConfig) -> Self {
        Self { queue, config }
    }

    /// Start monitoring
    pub async fn start(self: Arc<Self>) {
        let mut ticker = tokio::time::interval(self.config.interval);

        tokio::spawn(async move {
            loop {
                ticker.tick().await;
                self.check_health().await;
            }
        });
    }

    /// Check queue health
    async fn check_health(&self) {
        let status = self.queue.status().await;

        let mut total_pending = 0;
        let mut total_active = 0;

        for (lane_id, lane_status) in status.iter() {
            total_pending += lane_status.pending;
            total_active += lane_status.active;

            debug!(
                "Lane {}: pending={}, active={}, max={}",
                lane_id, lane_status.pending, lane_status.active, lane_status.max
            );

            // Check if lane is at capacity
            if lane_status.active >= lane_status.max {
                warn!("Lane {} is at maximum capacity", lane_id);
            }
        }

        // Check global thresholds
        if total_pending > self.config.pending_warning_threshold {
            warn!(
                "High number of pending commands: {} (threshold: {})",
                total_pending, self.config.pending_warning_threshold
            );
        }

        if total_active > self.config.active_warning_threshold {
            warn!(
                "High number of active commands: {} (threshold: {})",
                total_active, self.config.active_warning_threshold
            );
        }
    }

    /// Get current statistics
    pub async fn stats(&self) -> QueueStats {
        let lane_status = self.queue.status().await;

        let mut total_pending = 0;
        let mut total_active = 0;

        for status in lane_status.values() {
            total_pending += status.pending;
            total_active += status.active;
        }

        let dead_letter_count = match self.queue.dlq() {
            Some(dlq) => dlq.len().await,
            None => 0,
        };

        QueueStats {
            total_pending,
            total_active,
            dead_letter_count,
            lanes: lane_status,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::LaneConfig;
    use crate::error::Result;
    use crate::event::EventEmitter;
    use crate::queue::{lane_ids, priorities, Command, Lane};
    use async_trait::async_trait;

    /// Helper: create a CommandQueue with default lanes registered
    async fn make_queue_with_lanes() -> Arc<CommandQueue> {
        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter));

        let lanes = [
            (lane_ids::SYSTEM, priorities::SYSTEM, 5),
            (lane_ids::CONTROL, priorities::CONTROL, 3),
            (lane_ids::QUERY, priorities::QUERY, 10),
            (lane_ids::PROMPT, priorities::PROMPT, 2),
        ];

        for (id, priority, max) in lanes {
            let config = LaneConfig::new(1, max);
            queue
                .register_lane(Arc::new(Lane::new(id, config, priority)))
                .await;
        }

        queue
    }

    struct TestCommand {
        result: serde_json::Value,
    }

    #[async_trait]
    impl Command for TestCommand {
        async fn execute(&self) -> Result<serde_json::Value> {
            Ok(self.result.clone())
        }
        fn command_type(&self) -> &str {
            "test"
        }
    }

    // ========================================================================
    // MonitorConfig Tests
    // ========================================================================

    #[test]
    fn test_monitor_config_default() {
        let config = MonitorConfig::default();
        assert_eq!(config.interval, Duration::from_secs(10));
        assert_eq!(config.pending_warning_threshold, 100);
        assert_eq!(config.active_warning_threshold, 50);
    }

    #[test]
    fn test_monitor_config_custom() {
        let config = MonitorConfig {
            interval: Duration::from_secs(5),
            pending_warning_threshold: 50,
            active_warning_threshold: 20,
        };
        assert_eq!(config.interval, Duration::from_secs(5));
        assert_eq!(config.pending_warning_threshold, 50);
        assert_eq!(config.active_warning_threshold, 20);
    }

    #[test]
    fn test_monitor_config_clone() {
        let config = MonitorConfig {
            interval: Duration::from_millis(500),
            pending_warning_threshold: 10,
            active_warning_threshold: 5,
        };
        let cloned = config.clone();
        assert_eq!(cloned.interval, Duration::from_millis(500));
        assert_eq!(cloned.pending_warning_threshold, 10);
        assert_eq!(cloned.active_warning_threshold, 5);
    }

    #[test]
    fn test_monitor_config_debug() {
        let config = MonitorConfig::default();
        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("MonitorConfig"));
        assert!(debug_str.contains("interval"));
        assert!(debug_str.contains("pending_warning_threshold"));
        assert!(debug_str.contains("active_warning_threshold"));
    }

    // ========================================================================
    // QueueMonitor Construction Tests
    // ========================================================================

    #[tokio::test]
    async fn test_monitor_new_default_config() {
        let queue = make_queue_with_lanes().await;
        let monitor = QueueMonitor::new(Arc::clone(&queue));
        assert_eq!(monitor.config.interval, Duration::from_secs(10));
        assert_eq!(monitor.config.pending_warning_threshold, 100);
        assert_eq!(monitor.config.active_warning_threshold, 50);
    }

    #[tokio::test]
    async fn test_monitor_with_config() {
        let queue = make_queue_with_lanes().await;
        let config = MonitorConfig {
            interval: Duration::from_secs(1),
            pending_warning_threshold: 10,
            active_warning_threshold: 5,
        };
        let monitor = QueueMonitor::with_config(Arc::clone(&queue), config);
        assert_eq!(monitor.config.interval, Duration::from_secs(1));
        assert_eq!(monitor.config.pending_warning_threshold, 10);
        assert_eq!(monitor.config.active_warning_threshold, 5);
    }

    // ========================================================================
    // stats() Tests
    // ========================================================================

    #[tokio::test]
    async fn test_monitor_stats_empty_queue() {
        let queue = make_queue_with_lanes().await;
        let monitor = QueueMonitor::new(queue);

        let stats = monitor.stats().await;
        assert_eq!(stats.total_pending, 0);
        assert_eq!(stats.total_active, 0);
        assert_eq!(stats.lanes.len(), 4);
    }

    #[tokio::test]
    async fn test_monitor_stats_with_pending_commands() {
        let queue = make_queue_with_lanes().await;

        // Enqueue commands (without starting scheduler, they stay pending)
        for _ in 0..3 {
            let cmd = Box::new(TestCommand {
                result: serde_json::json!({}),
            });
            let _ = queue.submit(lane_ids::QUERY, cmd).await;
        }
        for _ in 0..2 {
            let cmd = Box::new(TestCommand {
                result: serde_json::json!({}),
            });
            let _ = queue.submit(lane_ids::PROMPT, cmd).await;
        }

        let monitor = QueueMonitor::new(queue);
        let stats = monitor.stats().await;

        assert_eq!(stats.total_pending, 5);
        assert_eq!(stats.total_active, 0);
        assert_eq!(stats.lanes[lane_ids::QUERY].pending, 3);
        assert_eq!(stats.lanes[lane_ids::PROMPT].pending, 2);
        assert_eq!(stats.lanes[lane_ids::SYSTEM].pending, 0);
        assert_eq!(stats.lanes[lane_ids::CONTROL].pending, 0);
    }

    #[tokio::test]
    async fn test_monitor_stats_lane_concurrency() {
        let queue = make_queue_with_lanes().await;
        let monitor = QueueMonitor::new(queue);

        let stats = monitor.stats().await;
        assert_eq!(stats.lanes[lane_ids::SYSTEM].max, 5);
        assert_eq!(stats.lanes[lane_ids::CONTROL].max, 3);
        assert_eq!(stats.lanes[lane_ids::QUERY].max, 10);
        assert_eq!(stats.lanes[lane_ids::PROMPT].max, 2);
    }

    #[tokio::test]
    async fn test_monitor_stats_no_lanes() {
        let emitter = EventEmitter::new(100);
        let queue = Arc::new(CommandQueue::new(emitter));
        let monitor = QueueMonitor::new(queue);

        let stats = monitor.stats().await;
        assert_eq!(stats.total_pending, 0);
        assert_eq!(stats.total_active, 0);
        assert!(stats.lanes.is_empty());
    }

    // ========================================================================
    // check_health() Tests
    // ========================================================================

    #[tokio::test]
    async fn test_check_health_no_warnings() {
        let queue = make_queue_with_lanes().await;
        let monitor = QueueMonitor::new(queue);

        // Should not panic or error with empty queue
        monitor.check_health().await;
    }

    #[tokio::test]
    async fn test_check_health_with_pending_below_threshold() {
        let queue = make_queue_with_lanes().await;

        // Add a few commands (below default threshold of 100)
        for _ in 0..5 {
            let cmd = Box::new(TestCommand {
                result: serde_json::json!({}),
            });
            let _ = queue.submit(lane_ids::QUERY, cmd).await;
        }

        let monitor = QueueMonitor::new(queue);

        // Should complete without errors
        monitor.check_health().await;
    }

    #[tokio::test]
    async fn test_check_health_with_pending_above_threshold() {
        let queue = make_queue_with_lanes().await;

        // Set a low threshold and add commands above it
        let config = MonitorConfig {
            interval: Duration::from_secs(10),
            pending_warning_threshold: 3,
            active_warning_threshold: 50,
        };

        // Add 5 commands (above threshold of 3)
        for _ in 0..5 {
            let cmd = Box::new(TestCommand {
                result: serde_json::json!({}),
            });
            let _ = queue.submit(lane_ids::QUERY, cmd).await;
        }

        let monitor = QueueMonitor::with_config(queue, config);

        // Should not panic, just emit warning log
        monitor.check_health().await;
    }

    #[tokio::test]
    async fn test_check_health_at_exact_threshold() {
        let queue = make_queue_with_lanes().await;

        let config = MonitorConfig {
            interval: Duration::from_secs(10),
            pending_warning_threshold: 3,
            active_warning_threshold: 50,
        };

        // Add exactly 3 commands (equal to threshold, should NOT trigger warning)
        for _ in 0..3 {
            let cmd = Box::new(TestCommand {
                result: serde_json::json!({}),
            });
            let _ = queue.submit(lane_ids::QUERY, cmd).await;
        }

        let monitor = QueueMonitor::with_config(queue, config);
        monitor.check_health().await;
    }

    // ========================================================================
    // start() Tests
    // ========================================================================

    #[tokio::test]
    async fn test_monitor_start_runs_periodically() {
        let queue = make_queue_with_lanes().await;
        let config = MonitorConfig {
            interval: Duration::from_millis(30),
            pending_warning_threshold: 100,
            active_warning_threshold: 50,
        };
        let monitor = Arc::new(QueueMonitor::with_config(queue, config));

        // Clone Arc before start() consumes it
        let monitor_ref = Arc::clone(&monitor);
        monitor.start().await;

        // Let monitor run a few cycles
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Verify the monitor is still functional via the cloned reference
        let stats = monitor_ref.stats().await;
        assert_eq!(stats.total_pending, 0);
        assert_eq!(stats.total_active, 0);
    }

    #[tokio::test]
    async fn test_monitor_start_with_commands() {
        let queue = make_queue_with_lanes().await;

        // Add some pending commands
        for _ in 0..3 {
            let cmd = Box::new(TestCommand {
                result: serde_json::json!({}),
            });
            let _ = queue.submit(lane_ids::QUERY, cmd).await;
        }

        let config = MonitorConfig {
            interval: Duration::from_millis(20),
            pending_warning_threshold: 2, // Below current pending, will trigger warning
            active_warning_threshold: 50,
        };
        let monitor = Arc::new(QueueMonitor::with_config(queue, config));

        // Clone Arc before start() consumes it
        let monitor_ref = Arc::clone(&monitor);
        monitor.start().await;

        // Let monitor run and check health (should not panic even with warnings)
        tokio::time::sleep(Duration::from_millis(80)).await;

        let stats = monitor_ref.stats().await;
        assert_eq!(stats.total_pending, 3);
    }

    // ========================================================================
    // QueueStats Tests
    // ========================================================================

    #[test]
    fn test_queue_stats_default() {
        let stats = QueueStats::default();
        assert_eq!(stats.total_pending, 0);
        assert_eq!(stats.total_active, 0);
        assert!(stats.lanes.is_empty());
    }

    #[test]
    fn test_queue_stats_serialization() {
        let mut lanes = std::collections::HashMap::new();
        lanes.insert(
            "query".to_string(),
            crate::queue::LaneStatus {
                pending: 5,
                active: 2,
                min: 1,
                max: 10,
            },
        );

        let stats = QueueStats {
            total_pending: 5,
            total_active: 2,
            dead_letter_count: 0,
            lanes,
        };

        let json = serde_json::to_string(&stats).unwrap();
        let parsed: QueueStats = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.total_pending, 5);
        assert_eq!(parsed.total_active, 2);
        assert_eq!(parsed.lanes["query"].pending, 5);
        assert_eq!(parsed.lanes["query"].max, 10);
    }

    #[test]
    fn test_queue_stats_clone() {
        let stats = QueueStats {
            total_pending: 10,
            total_active: 3,
            dead_letter_count: 0,
            lanes: std::collections::HashMap::new(),
        };
        let cloned = stats.clone();
        assert_eq!(cloned.total_pending, 10);
        assert_eq!(cloned.total_active, 3);
    }
}