brainwires-relay 0.2.0

MCP server framework, relay client, and agent communication backbone for Brainwires
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
//! Priority Command Queue
//!
//! Implements a priority queue for remote commands with deadline tracking
//! and retry logic.

use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::time::{Duration, Instant};
use tracing::debug;

use super::protocol::{BackendCommand, CommandPriority, PrioritizedCommand};

const DEFAULT_QUEUE_MAX_DEPTH: usize = 1000;

/// Entry in the priority queue
#[derive(Debug)]
pub struct QueueEntry {
    /// The prioritized command
    pub command: PrioritizedCommand,
    /// When the command was enqueued
    pub enqueued_at: Instant,
    /// Deadline instant (if set)
    pub deadline: Option<Instant>,
    /// Current retry attempt (0-based)
    pub retry_attempt: u32,
    /// Sequence number for FIFO within same priority
    pub sequence: u64,
}

impl QueueEntry {
    /// Create a new queue entry
    pub fn new(command: PrioritizedCommand, sequence: u64) -> Self {
        let now = Instant::now();
        let deadline = command
            .deadline_ms
            .map(|ms| now + Duration::from_millis(ms));

        Self {
            command,
            enqueued_at: now,
            deadline,
            retry_attempt: 0,
            sequence,
        }
    }

    /// Check if the command has expired
    pub fn is_expired(&self) -> bool {
        self.deadline.map(|d| Instant::now() > d).unwrap_or(false)
    }

    /// Get time until deadline (if set)
    pub fn time_until_deadline(&self) -> Option<Duration> {
        self.deadline.and_then(|d| {
            let now = Instant::now();
            if now < d { Some(d - now) } else { None }
        })
    }

    /// Calculate next retry delay
    pub fn next_retry_delay(&self) -> Option<Duration> {
        self.command.retry_policy.as_ref().and_then(|policy| {
            if self.retry_attempt >= policy.max_attempts {
                None
            } else {
                let delay_ms = policy.initial_delay_ms as f32
                    * policy.backoff_multiplier.powi(self.retry_attempt as i32);
                Some(Duration::from_millis(delay_ms as u64))
            }
        })
    }

    /// Increment retry attempt
    pub fn increment_retry(&mut self) {
        self.retry_attempt += 1;
    }

    /// Check if should retry
    pub fn should_retry(&self) -> bool {
        self.command
            .retry_policy
            .as_ref()
            .map(|p| self.retry_attempt < p.max_attempts)
            .unwrap_or(false)
    }
}

// Implement ordering for BinaryHeap (max-heap, so we reverse for min priority)
impl PartialEq for QueueEntry {
    fn eq(&self, other: &Self) -> bool {
        self.command.priority == other.command.priority && self.sequence == other.sequence
    }
}

impl Eq for QueueEntry {}

impl PartialOrd for QueueEntry {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for QueueEntry {
    fn cmp(&self, other: &Self) -> Ordering {
        // Lower priority value = higher priority (Critical=0 is highest)
        // Reverse ordering because BinaryHeap is a max-heap
        match other.command.priority.cmp(&self.command.priority) {
            Ordering::Equal => {
                // Within same priority, use sequence (FIFO)
                // Lower sequence = earlier = should be processed first
                other.sequence.cmp(&self.sequence)
            }
            ord => ord,
        }
    }
}

/// Priority command queue
pub struct CommandQueue {
    /// The priority queue
    queue: BinaryHeap<QueueEntry>,
    /// Sequence counter for FIFO ordering within priority
    sequence: u64,
    /// Maximum queue depth
    max_depth: usize,
}

impl CommandQueue {
    /// Create a new command queue
    pub fn new(max_depth: usize) -> Self {
        Self {
            queue: BinaryHeap::new(),
            sequence: 0,
            max_depth,
        }
    }

    /// Enqueue a command with priority
    pub fn enqueue(&mut self, command: PrioritizedCommand) -> Result<(), QueueError> {
        // Check queue depth
        if self.queue.len() >= self.max_depth {
            // For critical commands, we allow exceeding the limit
            if command.priority != CommandPriority::Critical {
                return Err(QueueError::QueueFull);
            }
        }

        let entry = QueueEntry::new(command, self.sequence);
        self.sequence = self.sequence.wrapping_add(1);
        self.queue.push(entry);
        Ok(())
    }

    /// Enqueue a simple command (no priority metadata)
    pub fn enqueue_simple(&mut self, command: BackendCommand) -> Result<(), QueueError> {
        self.enqueue(PrioritizedCommand {
            command,
            priority: CommandPriority::Normal,
            deadline_ms: None,
            retry_policy: None,
        })
    }

    /// Dequeue the highest priority command
    pub fn dequeue(&mut self) -> Option<QueueEntry> {
        // Remove expired entries
        self.remove_expired();

        self.queue.pop()
    }

    /// Peek at the highest priority command without removing it
    pub fn peek(&self) -> Option<&QueueEntry> {
        self.queue.peek()
    }

    /// Get current queue depth
    pub fn len(&self) -> usize {
        self.queue.len()
    }

    /// Check if queue is empty
    pub fn is_empty(&self) -> bool {
        self.queue.is_empty()
    }

    /// Remove expired entries
    fn remove_expired(&mut self) {
        let mut temp = BinaryHeap::new();
        while let Some(entry) = self.queue.pop() {
            if !entry.is_expired() {
                temp.push(entry);
            } else {
                debug!(
                    "Removed expired command: {:?}",
                    std::mem::discriminant(&entry.command.command)
                );
            }
        }
        self.queue = temp;
    }

    /// Re-enqueue a command for retry
    pub fn requeue_for_retry(&mut self, mut entry: QueueEntry) -> Result<(), QueueError> {
        if !entry.should_retry() {
            return Err(QueueError::MaxRetriesExceeded);
        }

        entry.increment_retry();
        // Update sequence to maintain fairness
        entry.sequence = self.sequence;
        self.sequence = self.sequence.wrapping_add(1);
        self.queue.push(entry);
        Ok(())
    }

    /// Get queue statistics
    pub fn stats(&self) -> QueueStats {
        let mut critical = 0;
        let mut high = 0;
        let mut normal = 0;
        let mut low = 0;

        for entry in self.queue.iter() {
            match entry.command.priority {
                CommandPriority::Critical => critical += 1,
                CommandPriority::High => high += 1,
                CommandPriority::Normal => normal += 1,
                CommandPriority::Low => low += 1,
            }
        }

        QueueStats {
            total: self.queue.len(),
            critical,
            high,
            normal,
            low,
        }
    }
}

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

/// Queue statistics
#[derive(Debug, Clone, Default)]
pub struct QueueStats {
    /// Total number of commands in the queue.
    pub total: usize,
    /// Number of critical priority commands.
    pub critical: usize,
    /// Number of high priority commands.
    pub high: usize,
    /// Number of normal priority commands.
    pub normal: usize,
    /// Number of low priority commands.
    pub low: usize,
}

/// Queue errors
#[derive(Debug, thiserror::Error)]
pub enum QueueError {
    /// The queue has reached its maximum depth.
    #[error("Queue is full")]
    QueueFull,
    /// The command has exceeded its maximum retry attempts.
    #[error("Maximum retries exceeded")]
    MaxRetriesExceeded,
}

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

    fn make_command(priority: CommandPriority) -> PrioritizedCommand {
        PrioritizedCommand {
            command: BackendCommand::Ping { timestamp: 0 },
            priority,
            deadline_ms: None,
            retry_policy: None,
        }
    }

    #[test]
    fn test_priority_ordering() {
        let mut queue = CommandQueue::new(100);

        queue.enqueue(make_command(CommandPriority::Low)).unwrap();
        queue.enqueue(make_command(CommandPriority::High)).unwrap();
        queue
            .enqueue(make_command(CommandPriority::Normal))
            .unwrap();
        queue
            .enqueue(make_command(CommandPriority::Critical))
            .unwrap();

        assert_eq!(
            queue.dequeue().unwrap().command.priority,
            CommandPriority::Critical
        );
        assert_eq!(
            queue.dequeue().unwrap().command.priority,
            CommandPriority::High
        );
        assert_eq!(
            queue.dequeue().unwrap().command.priority,
            CommandPriority::Normal
        );
        assert_eq!(
            queue.dequeue().unwrap().command.priority,
            CommandPriority::Low
        );
    }

    #[test]
    fn test_fifo_within_priority() {
        let mut queue = CommandQueue::new(100);

        // Enqueue multiple normal priority commands
        for i in 0..5 {
            queue
                .enqueue(PrioritizedCommand {
                    command: BackendCommand::Ping { timestamp: i },
                    priority: CommandPriority::Normal,
                    deadline_ms: None,
                    retry_policy: None,
                })
                .unwrap();
        }

        // Should come out in FIFO order
        for i in 0..5 {
            let entry = queue.dequeue().unwrap();
            if let BackendCommand::Ping { timestamp } = entry.command.command {
                assert_eq!(timestamp, i);
            } else {
                panic!("Expected Ping command");
            }
        }
    }

    #[test]
    fn test_queue_full() {
        let mut queue = CommandQueue::new(2);

        queue
            .enqueue(make_command(CommandPriority::Normal))
            .unwrap();
        queue
            .enqueue(make_command(CommandPriority::Normal))
            .unwrap();

        // Third normal should fail
        assert!(matches!(
            queue.enqueue(make_command(CommandPriority::Normal)),
            Err(QueueError::QueueFull)
        ));

        // But critical should succeed even when full
        assert!(
            queue
                .enqueue(make_command(CommandPriority::Critical))
                .is_ok()
        );
    }

    #[test]
    fn test_retry_logic() {
        let mut queue = CommandQueue::new(100);

        let cmd = PrioritizedCommand {
            command: BackendCommand::Ping { timestamp: 42 },
            priority: CommandPriority::Normal,
            deadline_ms: None,
            retry_policy: Some(RetryPolicy {
                max_attempts: 3,
                backoff_multiplier: 2.0,
                initial_delay_ms: 100,
            }),
        };

        queue.enqueue(cmd).unwrap();
        let mut entry = queue.dequeue().unwrap();

        // Should be able to retry 3 times
        assert!(entry.should_retry());
        queue.requeue_for_retry(entry).unwrap();

        entry = queue.dequeue().unwrap();
        assert_eq!(entry.retry_attempt, 1);
        assert!(entry.should_retry());
        queue.requeue_for_retry(entry).unwrap();

        entry = queue.dequeue().unwrap();
        assert_eq!(entry.retry_attempt, 2);
        assert!(entry.should_retry());
        queue.requeue_for_retry(entry).unwrap();

        entry = queue.dequeue().unwrap();
        assert_eq!(entry.retry_attempt, 3);
        assert!(!entry.should_retry()); // No more retries

        // Should fail to requeue
        assert!(matches!(
            queue.requeue_for_retry(entry),
            Err(QueueError::MaxRetriesExceeded)
        ));
    }
}