descartes-core 0.1.1

Core DES framework
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
//! Event scheduling and management
//!
//! This module provides the core event system for discrete event simulation,
//! including event definitions and a priority-based event scheduler.

use crate::error::EventError;
use crate::time::SimTime;
use crate::types::EventId;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::collections::BinaryHeap;

/// Event payload that can be attached to events
///
/// This is a flexible container for event-specific data. Users can extend
/// this enum with their own event types.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EventPayload {
    /// Generic event with no specific payload
    Generic,
    /// Custom event with arbitrary data
    Custom(Vec<u8>),
    /// Process wakeup event
    ProcessWakeup { process_id: u64 },
    /// Timeout event
    Timeout { context: String },
}

/// An event in the simulation
///
/// Events are the fundamental unit of simulation activity. Each event has:
/// - A unique ID for tracking
/// - A scheduled time when it should occur
/// - A sequence number for deterministic ordering of events at the same time
/// - An optional payload with event-specific data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Event {
    /// Unique identifier for this event
    id: EventId,
    /// Simulation time when this event should occur
    time: SimTime,
    /// Sequence number for deterministic ordering
    sequence: u64,
    /// Event-specific data
    payload: EventPayload,
}

impl Event {
    /// Create a new event
    pub fn new(id: EventId, time: SimTime, sequence: u64) -> Self {
        Self {
            id,
            time,
            sequence,
            payload: EventPayload::Generic,
        }
    }

    /// Create a new event with a payload
    pub fn with_payload(
        id: EventId,
        time: SimTime,
        sequence: u64,
        payload: EventPayload,
    ) -> Self {
        Self {
            id,
            time,
            sequence,
            payload,
        }
    }

    /// Get the event ID
    pub fn id(&self) -> EventId {
        self.id
    }

    /// Get the scheduled time
    pub fn time(&self) -> SimTime {
        self.time
    }



    /// Get the sequence number
    pub fn sequence(&self) -> u64 {
        self.sequence
    }

    /// Get a reference to the payload
    pub fn payload(&self) -> &EventPayload {
        &self.payload
    }

    /// Get a mutable reference to the payload
    pub fn payload_mut(&mut self) -> &mut EventPayload {
        &mut self.payload
    }

    /// Consume the event and return the payload
    pub fn into_payload(self) -> EventPayload {
        self.payload
    }
}

/// Wrapper for events in the scheduler's priority queue
///
/// This wrapper implements reverse ordering so that BinaryHeap (which is a max-heap)
/// behaves as a min-heap for our purposes.
#[derive(Debug, Clone)]
struct ScheduledEvent(Event);

impl PartialEq for ScheduledEvent {
    fn eq(&self, other: &Self) -> bool {
        self.0.time == other.0.time && self.0.sequence == other.0.sequence
    }
}

impl Eq for ScheduledEvent {}

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

impl Ord for ScheduledEvent {
    fn cmp(&self, other: &Self) -> Ordering {
        // Reverse ordering for min-heap behavior
        // First compare by time (earlier times have higher priority)
        other
            .0
            .time
            .cmp(&self.0.time)
            // Then by sequence number for deterministic ordering
            .then_with(|| other.0.sequence.cmp(&self.0.sequence))
    }
}

/// Event scheduler using a priority queue
///
/// The EventScheduler maintains a priority queue of events ordered by:
/// 1. Simulation time (earlier events first)
/// 2. Sequence number (lower sequence numbers first, for determinism)
///
/// This ensures deterministic event ordering even when multiple events
/// are scheduled for the same simulation time.
pub struct EventScheduler {
    /// Priority queue of scheduled events
    queue: BinaryHeap<ScheduledEvent>,
    /// Next event ID to assign
    next_id: u64,
    /// Next sequence number for deterministic ordering
    next_sequence: u64,
}

impl EventScheduler {
    /// Create a new empty event scheduler
    pub fn new() -> Self {
        Self {
            queue: BinaryHeap::new(),
            next_id: 0,
            next_sequence: 0,
        }
    }

    /// Schedule a new event
    ///
    /// Returns the ID of the scheduled event.
    ///
    /// # Arguments
    /// * `time` - The simulation time when the event should occur
    /// * `payload` - The event payload
    ///
    /// # Examples
    /// ```
    /// # use des_core::event::{EventScheduler, EventPayload};
    /// # use des_core::SimTime;
    /// let mut scheduler = EventScheduler::new();
    /// let event_id = scheduler.schedule(
    ///     SimTime::from_millis(100),
    ///     EventPayload::Generic,
    /// );
    /// ```
    pub fn schedule(&mut self, time: SimTime, payload: EventPayload) -> EventId {
        let id = EventId(self.next_id);
        self.next_id += 1;

        let sequence = self.next_sequence;
        self.next_sequence += 1;

        let event = Event::with_payload(id, time, sequence, payload);
        self.queue.push(ScheduledEvent(event));

        id
    }

    /// Peek at the next event without removing it
    ///
    /// Returns `None` if the queue is empty.
    pub fn peek_next(&self) -> Option<&Event> {
        self.queue.peek().map(|scheduled| &scheduled.0)
    }

    /// Remove and return the next event
    ///
    /// Returns an error if the queue is empty.
    pub fn pop_next(&mut self) -> Result<Event, EventError> {
        self.queue
            .pop()
            .map(|scheduled| scheduled.0)
            .ok_or(EventError::EmptyQueue)
    }

    /// Check if the scheduler has any pending events
    pub fn is_empty(&self) -> bool {
        self.queue.is_empty()
    }

    /// Get the number of pending events
    pub fn len(&self) -> usize {
        self.queue.len()
    }

    /// Clear all pending events
    pub fn clear(&mut self) {
        self.queue.clear();
    }
}

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

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

    #[test]
    fn test_event_creation() {
        let event = Event::new(
            EventId(1),
            SimTime::from_millis(100),
            0,
        );

        assert_eq!(event.id(), EventId(1));
        assert_eq!(event.time(), SimTime::from_millis(100));
        assert_eq!(event.sequence(), 0);
    }

    #[test]
    fn test_event_with_payload() {
        let payload = EventPayload::Timeout {
            context: "test".to_string(),
        };
        let event = Event::with_payload(
            EventId(1),
            SimTime::from_millis(100),
            0,
            payload,
        );

        match event.payload() {
            EventPayload::Timeout { context } => assert_eq!(context, "test"),
            _ => panic!("Wrong payload type"),
        }
    }

    #[test]
    fn test_scheduler_basic() {
        let mut scheduler = EventScheduler::new();

        assert!(scheduler.is_empty());
        assert_eq!(scheduler.len(), 0);

        let id = scheduler.schedule(
            SimTime::from_millis(100),
            EventPayload::Generic,
        );

        assert!(!scheduler.is_empty());
        assert_eq!(scheduler.len(), 1);
        assert_eq!(id, EventId(0));
    }

    #[test]
    fn test_scheduler_ordering_by_time() {
        let mut scheduler = EventScheduler::new();

        // Schedule events in reverse time order
        scheduler.schedule(
            SimTime::from_millis(300),
            EventPayload::Generic,
        );
        scheduler.schedule(
            SimTime::from_millis(100),
            EventPayload::Generic,
        );
        scheduler.schedule(
            SimTime::from_millis(200),
            EventPayload::Generic,
        );

        // Should come out in time order
        let e1 = scheduler.pop_next().unwrap();
        assert_eq!(e1.time(), SimTime::from_millis(100));

        let e2 = scheduler.pop_next().unwrap();
        assert_eq!(e2.time(), SimTime::from_millis(200));

        let e3 = scheduler.pop_next().unwrap();
        assert_eq!(e3.time(), SimTime::from_millis(300));
    }

    #[test]
    fn test_scheduler_ordering_by_sequence() {
        let mut scheduler = EventScheduler::new();

        // Schedule events at same time - should come out in sequence order
        let time = SimTime::from_millis(100);
        let id1 = scheduler.schedule(time, EventPayload::Generic);
        let id2 = scheduler.schedule(time, EventPayload::Generic);
        let id3 = scheduler.schedule(time, EventPayload::Generic);

        // Should come out in scheduling order (sequence order)
        let e1 = scheduler.pop_next().unwrap();
        assert_eq!(e1.id(), id1);

        let e2 = scheduler.pop_next().unwrap();
        assert_eq!(e2.id(), id2);

        let e3 = scheduler.pop_next().unwrap();
        assert_eq!(e3.id(), id3);
    }

    #[test]
    fn test_scheduler_deterministic_ordering() {
        let mut scheduler = EventScheduler::new();

        // Schedule multiple events at same time
        let time = SimTime::from_millis(100);

        let id1 = scheduler.schedule(time, EventPayload::Generic);
        let id2 = scheduler.schedule(time, EventPayload::Generic);
        let id3 = scheduler.schedule(time, EventPayload::Generic);

        // Should come out in scheduling order (deterministic via sequence numbers)
        let e1 = scheduler.pop_next().unwrap();
        assert_eq!(e1.id(), id1);

        let e2 = scheduler.pop_next().unwrap();
        assert_eq!(e2.id(), id2);

        let e3 = scheduler.pop_next().unwrap();
        assert_eq!(e3.id(), id3);
    }

    #[test]
    fn test_scheduler_peek() {
        let mut scheduler = EventScheduler::new();

        scheduler.schedule(
            SimTime::from_millis(100),
            EventPayload::Generic,
        );

        // Peek should not remove the event
        let peeked = scheduler.peek_next().unwrap();
        assert_eq!(peeked.time(), SimTime::from_millis(100));
        assert_eq!(scheduler.len(), 1);

        // Pop should remove it
        let popped = scheduler.pop_next().unwrap();
        assert_eq!(popped.time(), SimTime::from_millis(100));
        assert_eq!(scheduler.len(), 0);
    }

    #[test]
    fn test_scheduler_empty_queue() {
        let mut scheduler = EventScheduler::new();

        assert!(scheduler.peek_next().is_none());
        assert!(scheduler.pop_next().is_err());

        match scheduler.pop_next() {
            Err(EventError::EmptyQueue) => (),
            _ => panic!("Expected EmptyQueue error"),
        }
    }

    #[test]
    fn test_scheduler_clear() {
        let mut scheduler = EventScheduler::new();

        scheduler.schedule(
            SimTime::from_millis(100),
            EventPayload::Generic,
        );
        scheduler.schedule(
            SimTime::from_millis(200),
            EventPayload::Generic,
        );

        assert_eq!(scheduler.len(), 2);

        scheduler.clear();

        assert_eq!(scheduler.len(), 0);
        assert!(scheduler.is_empty());
    }

    #[test]
    fn test_complex_ordering() {
        let mut scheduler = EventScheduler::new();

        // Mix of times and sequences
        let id1 = scheduler.schedule(SimTime::from_millis(100), EventPayload::Generic);
        let id2 = scheduler.schedule(SimTime::from_millis(100), EventPayload::Generic);
        let id3 = scheduler.schedule(SimTime::from_millis(50), EventPayload::Generic);
        let id4 = scheduler.schedule(SimTime::from_millis(100), EventPayload::Generic);
        let id5 = scheduler.schedule(SimTime::from_millis(50), EventPayload::Generic);

        // Expected order:
        // 1. time=50, sequence=2 (earliest time, first scheduled at that time)
        // 2. time=50, sequence=4 (earliest time, second scheduled at that time)
        // 3. time=100, sequence=0 (later time, first scheduled at that time)
        // 4. time=100, sequence=1 (later time, second scheduled at that time)
        // 5. time=100, sequence=3 (later time, third scheduled at that time)

        let e1 = scheduler.pop_next().unwrap();
        assert_eq!(e1.time(), SimTime::from_millis(50));
        assert_eq!(e1.id(), id3);

        let e2 = scheduler.pop_next().unwrap();
        assert_eq!(e2.time(), SimTime::from_millis(50));
        assert_eq!(e2.id(), id5);

        let e3 = scheduler.pop_next().unwrap();
        assert_eq!(e3.time(), SimTime::from_millis(100));
        assert_eq!(e3.id(), id1);

        let e4 = scheduler.pop_next().unwrap();
        assert_eq!(e4.time(), SimTime::from_millis(100));
        assert_eq!(e4.id(), id2);

        let e5 = scheduler.pop_next().unwrap();
        assert_eq!(e5.time(), SimTime::from_millis(100));
        assert_eq!(e5.id(), id4);
    }
}