des-sim 0.1.0

Classical Event-Driven Simple Simulator Crate for Discrete Event System.
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
//! The `agent` module provides structures for defining and managing autonomous agents
//! within a discrete event simulation.
//!
//! It introduces `AgentStep` for individual actions and `AgentContinuation` for
//! chaining these actions into complex workflows, enabling agents to dynamically
//! interact with the simulation environment.

use crate::context::{EventContext, UserContext};
use crate::modeling::event::EventPriority;
use crate::modeling::model::Model;
use crate::primitive::time::Duration;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::fmt;
use std::rc::Rc;

/// Represents a single step in an agent's workflow.
///
/// This structure holds the logic and scheduling parameters for a specific
/// action within the simulation.
pub struct AgentStep<E, M: Model<E>> {
    /// A descriptive tag for the step, used for logging and debugging purposes.
    pub tag: &'static str,
    /// The time delay before this step is executed.
    pub delay: Duration,
    /// The event priority, determining the order of execution within the same simulation time.
    pub priority: EventPriority,
    /// The logic to be executed for this step.
    ///
    /// The closure is provided with the current event context, the model instance,
    /// and a mutable reference to the queue of subsequent steps, allowing for
    /// dynamic modification of the remaining workflow.
    #[allow(clippy::type_complexity)]
    pub logic: Box<dyn FnOnce(&mut EventContext<E, M>, &mut M, &mut VecDeque<AgentStep<E, M>>)>,
}

impl<E, M: Model<E>> fmt::Debug for AgentStep<E, M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AgentStep")
            .field("tag", &self.tag)
            .field("delay", &self.delay)
            .field("priority", &self.priority)
            // Since trait objects are opaque, output the type name and the function pointer address.
            .field("logic", &format_args!("Box<dyn FnOnce>({:p})", self.logic))
            .finish()
    }
}

pub struct AgentContinuation<E, M: Model<E>> {
    future_steps: VecDeque<AgentStep<E, M>>,
    to_event_payload: Rc<dyn Fn(AgentContinuation<E, M>) -> E>,
}

impl<E, M: Model<E>> fmt::Debug for AgentContinuation<E, M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AgentContinuation")
            .field("future_steps", &self.future_steps)
            // Output the internal Rc pointer address for identification.
            .field(
                "to_event_payload",
                &format_args!("Rc<dyn Fn>({:p})", Rc::as_ptr(&self.to_event_payload)),
            )
            .finish()
    }
}

impl<E: 'static, M: Model<E> + 'static> AgentContinuation<E, M> {
    /// Creates a new `AgentContinuation` instance.
    ///
    /// # Arguments
    ///
    /// * `to_event_payload` - A closure that defines how to transform the continuation
    ///   into an event payload for scheduling the next step.
    pub fn new<F>(to_event_payload: F) -> Self
    where
        F: Fn(AgentContinuation<E, M>) -> E + 'static,
    {
        Self {
            future_steps: VecDeque::new(),
            to_event_payload: Rc::new(to_event_payload),
        }
    }

    /// Appends a new step to be executed after the specified delay.
    ///
    /// # Arguments
    ///
    /// * `tag` - A descriptive label for the step, useful for debugging and tracking.
    /// * `delay` - The time duration to wait before executing this step.
    /// * `priority` - The priority of the event within the event scheduler.
    /// * `logic` - The closure containing the logic to be executed for this step.
    pub fn then_after<F>(
        mut self,
        tag: &'static str,
        delay: Duration,
        priority: EventPriority,
        logic: F,
    ) -> Self
    where
        F: FnOnce(&mut EventContext<E, M>, &mut M, &mut VecDeque<AgentStep<E, M>>) + 'static,
    {
        self.future_steps.push_back(AgentStep {
            tag,
            delay,
            priority,
            logic: Box::new(logic),
        });

        self
    }
}

impl<E, M: Model<E>> AgentContinuation<E, M> {
    /// Returns a reference to the next step scheduled to be executed,
    /// without consuming it.
    pub fn peek_next_step(&self) -> Option<&AgentStep<E, M>> {
        self.future_steps.front()
    }

    /// Returns the tag of the next scheduled step, if available.
    pub fn peek_next_step_tag(&self) -> Option<&'static str> {
        self.peek_next_step().map(|step| step.tag)
    }

    /// Returns the total number of steps remaining in the continuation.
    pub fn get_remain_step_count(&self) -> usize {
        self.future_steps.len()
    }

    /// Consumes and executes the current step, then schedules the next step if one exists.
    /// If no further steps remain, the continuation concludes gracefully.
    pub fn execute_and_schedule(mut self, context: &mut EventContext<E, M>, model: &mut M) {
        // Extract the current step.
        if let Some(current_step) = self.future_steps.pop_front() {
            // Process the event logic.
            // Note: Steps may be added/modified by the logic itself.
            (current_step.logic)(context, model, &mut self.future_steps);

            // Check if there is a subsequent step and schedule it for the future.
            let next_info = self.future_steps.front().map(|s| (s.delay, s.priority));
            if let Some((next_delay, next_priority)) = next_info {
                // Clone the reference to the event builder and schedule the remainder.
                let to_event_payload = Rc::clone(&self.to_event_payload);
                let next_payload = to_event_payload(self);

                context.schedule_event(next_delay, next_priority, next_payload);
            }
        }
    }
}

pub struct AgentActionTicket<E, M: Model<E>> {
    action: RefCell<Option<AgentContinuation<E, M>>>,
}

impl<E, M: Model<E>> fmt::Debug for AgentActionTicket<E, M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.action.borrow().as_ref() {
            Some(continuation) => fmt::Debug::fmt(continuation, f),
            None => write!(f, "ExecutedAction"),
        }
    }
}

impl<E, M: Model<E>> AgentActionTicket<E, M> {
    pub fn issue(continuation: AgentContinuation<E, M>) -> Self {
        Self {
            action: RefCell::new(Some(continuation)),
        }
    }

    pub fn execute(&self) -> Option<AgentContinuation<E, M>> {
        self.action.borrow_mut().take()
    }

    pub fn inspect<R, F>(&self, f: F) -> Option<R>
    where
        F: FnOnce(&AgentContinuation<E, M>) -> R,
    {
        self.action.borrow().as_ref().map(f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context::EventContext;
    use crate::event_scheduler::EventScheduler;
    use crate::modeling::event::{Event, EventPriority};
    use crate::modeling::hook::instance::HookDelegate;
    use crate::modeling::model::Model;
    use crate::primitive::time::{Duration, MicroStepStatus, SimTime, TickStatus};
    use crate::source_handler::SourceHandler;
    use std::assert_matches;
    use std::cell::RefCell;
    use std::rc::Rc;

    // Dummy Event for testing
    #[derive(Debug)]
    enum TestEvent {
        AgentContinuationEvent(AgentActionTicket<TestEvent, TestModel>),
        SimpleEvent(u32),
    }

    // Dummy Model for testing
    #[derive(Debug, Default)]
    struct TestModel {
        pub counter: Rc<RefCell<u32>>,
    }

    impl Model<TestEvent> for TestModel {
        fn handle_event(
            &mut self,
            context: &mut EventContext<TestEvent, Self>,
            event: &Event<TestEvent>,
        ) {
            match &event.payload {
                TestEvent::AgentContinuationEvent(ticket) => {
                    if let Some(continuation) = ticket.execute() {
                        continuation.execute_and_schedule(context, self);
                    }
                }
                TestEvent::SimpleEvent(val) => {
                    *self.counter.borrow_mut() += val;
                }
            }
        }
    }

    fn create_mock_event_context() -> EventContext<TestEvent, TestModel> {
        EventContext {
            current_tick_status: TickStatus::initialize(),
            current_micro_step_status: MicroStepStatus::initialize(),
            hook_delegate: HookDelegate::new(),
            source_handler: SourceHandler::new(),
            event_scheduler: EventScheduler::new(),
        }
    }

    #[test]
    fn test_agent_step_creation() {
        let step = AgentStep {
            tag: "test_step",
            delay: Duration::ticks(1),
            priority: EventPriority::new(5),
            logic: Box::new(|_, _: &mut TestModel, _| {}),
        };

        assert_eq!(step.tag, "test_step");
        assert_eq!(step.delay, Duration::ticks(1));
        assert_eq!(step.priority, EventPriority::new(5));
    }

    #[test]
    fn test_agent_continuation_new() {
        let continuation: AgentContinuation<TestEvent, TestModel> =
            AgentContinuation::new(|_| TestEvent::SimpleEvent(0));
        assert_eq!(continuation.get_remain_step_count(), 0);
        assert!(continuation.future_steps.is_empty());
    }

    #[test]
    fn test_agent_continuation_then_after() {
        let continuation: AgentContinuation<TestEvent, TestModel> =
            AgentContinuation::new(|_| TestEvent::SimpleEvent(0))
                .then_after(
                    "step1",
                    Duration::ticks(1),
                    EventPriority::new(5),
                    |_, _, _| {},
                )
                .then_after(
                    "step2",
                    Duration::ticks(2),
                    EventPriority::new(10),
                    |_, _, _| {},
                );

        assert_eq!(continuation.get_remain_step_count(), 2);

        let step1 = continuation.future_steps.front().unwrap();
        assert_eq!(step1.tag, "step1");
        assert_eq!(step1.delay, Duration::ticks(1));
        assert_eq!(step1.priority, EventPriority::new(5));

        let step2 = continuation.future_steps.get(1).unwrap();
        assert_eq!(step2.tag, "step2");
        assert_eq!(step2.delay, Duration::ticks(2));
        assert_eq!(step2.priority, EventPriority::new(10));
    }

    #[test]
    fn test_agent_continuation_peek_next_step() {
        let continuation: AgentContinuation<TestEvent, TestModel> =
            AgentContinuation::new(|_| TestEvent::SimpleEvent(0))
                .then_after(
                    "first",
                    Duration::ticks(1),
                    EventPriority::new(5),
                    |_, _, _| {},
                )
                .then_after(
                    "second",
                    Duration::ticks(2),
                    EventPriority::new(10),
                    |_, _, _| {},
                );

        assert_eq!(continuation.peek_next_step_tag(), Some("first"));
        assert_eq!(
            continuation.peek_next_step().unwrap().delay,
            Duration::ticks(1)
        );
    }

    #[test]
    fn test_agent_continuation_get_remain_step_count() {
        let continuation: AgentContinuation<TestEvent, TestModel> =
            AgentContinuation::new(|_| TestEvent::SimpleEvent(0))
                .then_after(
                    "s1",
                    Duration::ticks(1),
                    EventPriority::new(5),
                    |_, _, _| {},
                )
                .then_after(
                    "s2",
                    Duration::ticks(2),
                    EventPriority::new(10),
                    |_, _, _| {},
                )
                .then_after(
                    "s3",
                    Duration::ticks(3),
                    EventPriority::new(0),
                    |_, _, _| {},
                );

        assert_eq!(continuation.get_remain_step_count(), 3);
    }

    #[test]
    fn test_agent_continuation_execute_and_schedule_single_step() {
        let counter = Rc::new(RefCell::new(0));
        let mut context = create_mock_event_context();
        let mut model = TestModel {
            counter: Rc::clone(&counter),
        };

        let continuation: AgentContinuation<TestEvent, TestModel> =
            AgentContinuation::new(|_| TestEvent::SimpleEvent(0)).then_after(
                "single_step",
                Duration::ticks(1),
                EventPriority::new(5),
                |_, model: &mut TestModel, _| {
                    *model.counter.borrow_mut() += 10;
                },
            );

        continuation.execute_and_schedule(&mut context, &mut model);

        assert_eq!(*counter.borrow(), 10);
    }

    #[test]
    fn test_agent_continuation_execute_and_schedule_multiple_steps() {
        let counter = Rc::new(RefCell::new(0));
        let mut context = create_mock_event_context();
        let mut model = TestModel {
            counter: Rc::clone(&counter),
        };

        let continuation: AgentContinuation<TestEvent, TestModel> = AgentContinuation::new(|c| {
            TestEvent::AgentContinuationEvent(AgentActionTicket::issue(c))
        })
        .then_after(
            "step1",
            Duration::ticks(1),
            EventPriority::new(5),
            |_, model, _| {
                *model.counter.borrow_mut() += 1;
            },
        )
        .then_after(
            "step2",
            Duration::ticks(2),
            EventPriority::new(10),
            |_, model, _| {
                *model.counter.borrow_mut() += 10;
            },
        );

        context.schedule_event(
            Duration::one(),
            EventPriority::minimum(),
            TestEvent::AgentContinuationEvent(AgentActionTicket::issue(continuation)),
        );
        context.event_scheduler.flush_pending();
        let events = context.event_scheduler.drain_ready(SimTime::from_ticks(1));
        for event in events {
            model.handle_event(&mut context, &event);
        }

        assert_eq!(*counter.borrow(), 1); // Only step1 logic should have run

        context.event_scheduler.flush_pending();
        let mut scheduled_events = context.event_scheduler.drain_ready(SimTime::from_ticks(2));

        assert_eq!(scheduled_events.len(), 1);
        let event = scheduled_events.pop_front().unwrap();
        assert_eq!(event.priority, EventPriority::new(10));
        assert_matches!(event.payload, TestEvent::AgentContinuationEvent(_));

        if let TestEvent::AgentContinuationEvent(ticket) = event.payload {
            assert_eq!(
                ticket.inspect(|c| c.peek_next_step_tag()).unwrap(),
                Some("step2")
            );
        } else {
            panic!("Expected AgentContinuationEvent payload");
        }
    }

    #[test]
    fn test_agent_continuation_execute_and_schedule_no_steps() {
        let counter = Rc::new(RefCell::new(0));
        let mut context = create_mock_event_context();
        let mut model = TestModel {
            counter: Rc::clone(&counter),
        };

        let continuation: AgentContinuation<TestEvent, TestModel> =
            AgentContinuation::new(|_| TestEvent::SimpleEvent(0));

        continuation.execute_and_schedule(&mut context, &mut model);
        context.event_scheduler.flush_pending();

        assert_eq!(*counter.borrow(), 0);
        assert_eq!(context.event_scheduler.ready_queue_len(), 0);
    }

    #[test]
    fn test_agent_action_ticket_issue_and_execute() {
        let continuation: AgentContinuation<TestEvent, TestModel> =
            AgentContinuation::new(|_| TestEvent::SimpleEvent(0));
        let ticket = AgentActionTicket::issue(continuation);

        let executed_continuation = ticket.execute().unwrap();
        assert_eq!(executed_continuation.get_remain_step_count(), 0);

        assert!(ticket.execute().is_none()); // Should be None after first execution
    }

    #[test]
    fn test_agent_action_ticket_inspect() {
        let continuation: AgentContinuation<TestEvent, TestModel> =
            AgentContinuation::new(|_| TestEvent::SimpleEvent(0)).then_after(
                "inspect_step",
                Duration::ticks(1),
                EventPriority::new(5),
                |_, _, _| {},
            );
        let ticket = AgentActionTicket::issue(continuation);

        let tag = ticket.inspect(|c| c.peek_next_step_tag().unwrap()).unwrap();
        assert_eq!(tag, "inspect_step");

        let _ = ticket.execute(); // Consume the continuation
        assert!(ticket.inspect(|c| c.peek_next_step_tag()).is_none()); // Should be None after execution
    }
}