peat-protocol 0.9.0-rc.1

Peat Coordination Protocol — hierarchical capability composition over CRDTs for heterogeneous mesh networks
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
//! Timeout management for hierarchical commands
//!
//! Handles command expiration (TTL) and acknowledgment timeout tracking.

use crate::error::Result;
use peat_schema::command::v1::HierarchicalCommand;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use tokio::sync::RwLock;

/// Acknowledgment timeout tracking
#[derive(Debug, Clone)]
pub struct AckTimeout {
    /// Command ID being tracked
    pub command_id: String,
    /// Node IDs expected to acknowledge
    pub expected_acks: Vec<String>,
    /// Node IDs that have acknowledged
    pub received_acks: Vec<String>,
    /// Time when timeout expires
    pub expires_at: SystemTime,
}

/// Timeout manager for commands and acknowledgments
///
/// Tracks command expiration (TTL) and acknowledgment timeouts.
/// Provides efficient lookup of expired commands via BTreeMap.
pub struct TimeoutManager {
    /// Commands indexed by expiration time
    /// Key: expiration time, Value: list of command IDs expiring at that time
    expiring_commands: Arc<RwLock<BTreeMap<SystemTime, Vec<String>>>>,

    /// Acknowledgment timeout tracking
    /// Key: command_id, Value: acknowledgment timeout info
    ack_timeouts: Arc<RwLock<HashMap<String, AckTimeout>>>,
}

impl TimeoutManager {
    /// Create a new timeout manager
    pub fn new() -> Self {
        Self {
            expiring_commands: Arc::new(RwLock::new(BTreeMap::new())),
            ack_timeouts: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Register a command for expiration tracking
    ///
    /// If the command has an `expires_at` field, it will be tracked
    /// for automatic expiration.
    pub async fn register_expiration(&self, command: &HierarchicalCommand) -> Result<()> {
        if let Some(expires_at) = command.expires_at.as_ref() {
            let expiry = SystemTime::UNIX_EPOCH + Duration::from_secs(expires_at.seconds);
            self.expiring_commands
                .write()
                .await
                .entry(expiry)
                .or_default()
                .push(command.command_id.clone());
        }
        Ok(())
    }

    /// Check and process expired commands
    ///
    /// Returns a list of command IDs that have expired.
    /// This should be called periodically by a background task.
    pub async fn process_expired(&self) -> Vec<String> {
        let now = SystemTime::now();
        let mut expired = Vec::new();

        let mut expiring = self.expiring_commands.write().await;

        // Collect all expired keys (expiration times <= now)
        let expired_keys: Vec<SystemTime> = expiring.range(..=now).map(|(k, _)| *k).collect();

        // Remove and collect all expired commands
        for key in expired_keys {
            if let Some(commands) = expiring.remove(&key) {
                expired.extend(commands);
            }
        }

        expired
    }

    /// Unregister a command from expiration tracking
    ///
    /// Called when a command completes before expiring.
    pub async fn unregister_expiration(&self, command_id: &str) -> Result<()> {
        let mut expiring = self.expiring_commands.write().await;

        // Remove command from all expiration time buckets
        for (_, cmd_list) in expiring.iter_mut() {
            cmd_list.retain(|id| id != command_id);
        }

        // Clean up empty time buckets
        expiring.retain(|_, cmd_list| !cmd_list.is_empty());

        Ok(())
    }

    /// Register an acknowledgment timeout
    ///
    /// Tracks expected acknowledgments for a command with a timeout.
    pub async fn register_ack_timeout(
        &self,
        command_id: String,
        expected_acks: Vec<String>,
        timeout: Duration,
    ) -> Result<()> {
        let ack_timeout = AckTimeout {
            command_id: command_id.clone(),
            expected_acks,
            received_acks: Vec::new(),
            expires_at: SystemTime::now() + timeout,
        };

        self.ack_timeouts
            .write()
            .await
            .insert(command_id, ack_timeout);

        Ok(())
    }

    /// Record a received acknowledgment
    ///
    /// Updates the tracking for a command's acknowledgments.
    /// Returns true if all expected acks have been received.
    pub async fn record_ack(&self, command_id: &str, node_id: &str) -> bool {
        let mut timeouts = self.ack_timeouts.write().await;

        if let Some(timeout) = timeouts.get_mut(command_id) {
            if !timeout.received_acks.contains(&node_id.to_string()) {
                timeout.received_acks.push(node_id.to_string());
            }

            // Check if all expected acks received
            timeout.received_acks.len() >= timeout.expected_acks.len()
        } else {
            false
        }
    }

    /// Check for acknowledgment timeouts
    ///
    /// Returns list of command IDs that have timed out waiting for acks.
    /// A command has timed out if:
    /// 1. The timeout period has elapsed
    /// 2. Not all expected acknowledgments have been received
    pub async fn check_ack_timeouts(&self) -> Vec<String> {
        let now = SystemTime::now();
        let timeouts = self.ack_timeouts.read().await;

        timeouts
            .iter()
            .filter(|(_, t)| t.expires_at <= now && t.received_acks.len() < t.expected_acks.len())
            .map(|(id, _)| id.clone())
            .collect()
    }

    /// Get acknowledgment status for a command
    ///
    /// Returns the acknowledgment tracking info if it exists.
    pub async fn get_ack_status(&self, command_id: &str) -> Option<AckTimeout> {
        self.ack_timeouts.read().await.get(command_id).cloned()
    }

    /// Remove acknowledgment timeout tracking
    ///
    /// Called when a command completes or is cancelled.
    pub async fn unregister_ack_timeout(&self, command_id: &str) -> Result<()> {
        self.ack_timeouts.write().await.remove(command_id);
        Ok(())
    }

    /// Get count of commands being tracked for expiration
    pub async fn expiration_count(&self) -> usize {
        self.expiring_commands
            .read()
            .await
            .values()
            .map(|v| v.len())
            .sum()
    }

    /// Get count of commands being tracked for ack timeout
    pub async fn ack_timeout_count(&self) -> usize {
        self.ack_timeouts.read().await.len()
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use peat_schema::command::v1::{command_target::Scope, CommandTarget};
    use peat_schema::common::v1::Timestamp;
    use tokio::time::sleep;

    fn create_test_command_with_ttl(
        command_id: &str,
        expires_at_seconds: u64,
    ) -> HierarchicalCommand {
        HierarchicalCommand {
            command_id: command_id.to_string(),
            originator_id: "test-node".to_string(),
            target: Some(CommandTarget {
                scope: Scope::Individual as i32,
                target_ids: vec!["target-1".to_string()],
            }),
            expires_at: Some(Timestamp {
                seconds: expires_at_seconds,
                nanos: 0,
            }),
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn test_register_and_process_expired() {
        let manager = TimeoutManager::new();

        // Create command that expires in the past
        let now_secs = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let expired_cmd = create_test_command_with_ttl("cmd-1", now_secs - 10);

        manager.register_expiration(&expired_cmd).await.unwrap();

        // Process expired commands
        let expired = manager.process_expired().await;

        assert_eq!(expired.len(), 1);
        assert_eq!(expired[0], "cmd-1");

        // Verify count updated
        assert_eq!(manager.expiration_count().await, 0);
    }

    #[tokio::test]
    async fn test_command_not_expired_yet() {
        let manager = TimeoutManager::new();

        // Create command that expires in the future
        let now_secs = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let future_cmd = create_test_command_with_ttl("cmd-1", now_secs + 3600);

        manager.register_expiration(&future_cmd).await.unwrap();

        // Process expired - should be empty
        let expired = manager.process_expired().await;

        assert_eq!(expired.len(), 0);
        assert_eq!(manager.expiration_count().await, 1);
    }

    #[tokio::test]
    async fn test_unregister_expiration() {
        let manager = TimeoutManager::new();

        let now_secs = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let cmd = create_test_command_with_ttl("cmd-1", now_secs + 3600);

        manager.register_expiration(&cmd).await.unwrap();
        assert_eq!(manager.expiration_count().await, 1);

        manager.unregister_expiration("cmd-1").await.unwrap();
        assert_eq!(manager.expiration_count().await, 0);
    }

    #[tokio::test]
    async fn test_ack_timeout_registration() {
        let manager = TimeoutManager::new();

        manager
            .register_ack_timeout(
                "cmd-1".to_string(),
                vec!["node-1".to_string(), "node-2".to_string()],
                Duration::from_secs(30),
            )
            .await
            .unwrap();

        let status = manager.get_ack_status("cmd-1").await.unwrap();
        assert_eq!(status.command_id, "cmd-1");
        assert_eq!(status.expected_acks.len(), 2);
        assert_eq!(status.received_acks.len(), 0);
    }

    #[tokio::test]
    async fn test_record_ack() {
        let manager = TimeoutManager::new();

        manager
            .register_ack_timeout(
                "cmd-1".to_string(),
                vec!["node-1".to_string(), "node-2".to_string()],
                Duration::from_secs(30),
            )
            .await
            .unwrap();

        // Record first ack
        let all_received = manager.record_ack("cmd-1", "node-1").await;
        assert!(!all_received);

        // Record second ack
        let all_received = manager.record_ack("cmd-1", "node-2").await;
        assert!(all_received);

        let status = manager.get_ack_status("cmd-1").await.unwrap();
        assert_eq!(status.received_acks.len(), 2);
    }

    #[tokio::test]
    async fn test_ack_timeout_detection() {
        let manager = TimeoutManager::new();

        // Register with very short timeout
        manager
            .register_ack_timeout(
                "cmd-1".to_string(),
                vec!["node-1".to_string(), "node-2".to_string()],
                Duration::from_millis(100),
            )
            .await
            .unwrap();

        // Only record one ack
        manager.record_ack("cmd-1", "node-1").await;

        // Wait for timeout
        sleep(Duration::from_millis(150)).await;

        // Check for timeouts
        let timed_out = manager.check_ack_timeouts().await;
        assert_eq!(timed_out.len(), 1);
        assert_eq!(timed_out[0], "cmd-1");
    }

    #[tokio::test]
    async fn test_ack_timeout_not_detected_if_all_received() {
        let manager = TimeoutManager::new();

        manager
            .register_ack_timeout(
                "cmd-1".to_string(),
                vec!["node-1".to_string(), "node-2".to_string()],
                Duration::from_millis(100),
            )
            .await
            .unwrap();

        // Record all acks
        manager.record_ack("cmd-1", "node-1").await;
        manager.record_ack("cmd-1", "node-2").await;

        // Wait for timeout
        sleep(Duration::from_millis(150)).await;

        // Check for timeouts - should be empty since all acks received
        let timed_out = manager.check_ack_timeouts().await;
        assert_eq!(timed_out.len(), 0);
    }

    #[tokio::test]
    async fn test_unregister_ack_timeout() {
        let manager = TimeoutManager::new();

        manager
            .register_ack_timeout(
                "cmd-1".to_string(),
                vec!["node-1".to_string()],
                Duration::from_secs(30),
            )
            .await
            .unwrap();

        assert_eq!(manager.ack_timeout_count().await, 1);

        manager.unregister_ack_timeout("cmd-1").await.unwrap();
        assert_eq!(manager.ack_timeout_count().await, 0);
    }

    #[tokio::test]
    async fn test_multiple_commands_same_expiration() {
        let manager = TimeoutManager::new();

        let now_secs = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Two commands with same expiration time
        let cmd1 = create_test_command_with_ttl("cmd-1", now_secs - 10);
        let cmd2 = create_test_command_with_ttl("cmd-2", now_secs - 10);

        manager.register_expiration(&cmd1).await.unwrap();
        manager.register_expiration(&cmd2).await.unwrap();

        let expired = manager.process_expired().await;

        assert_eq!(expired.len(), 2);
        assert!(expired.contains(&"cmd-1".to_string()));
        assert!(expired.contains(&"cmd-2".to_string()));
    }

    #[tokio::test]
    async fn test_duplicate_ack_not_counted_twice() {
        let manager = TimeoutManager::new();

        manager
            .register_ack_timeout(
                "cmd-1".to_string(),
                vec!["node-1".to_string(), "node-2".to_string()],
                Duration::from_secs(30),
            )
            .await
            .unwrap();

        // Record same ack twice
        manager.record_ack("cmd-1", "node-1").await;
        manager.record_ack("cmd-1", "node-1").await;

        let status = manager.get_ack_status("cmd-1").await.unwrap();
        assert_eq!(status.received_acks.len(), 1); // Should only count once
    }
}