netrun-sim 0.2.0

A flow-based development (FBD) simulation engine.
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
//! Integration tests for the NetSim public API.

mod common;

use netrun_sim::graph::{Edge, PortRef, PortType};
use netrun_sim::net::{
    Epoch, NetAction, NetActionError, NetActionResponse, NetActionResponseData, NetEvent, NetSim,
    PacketLocation, Salvo,
};

// ========== Helper Functions ==========

fn get_packet_id(response: &NetActionResponse) -> netrun_sim::net::PacketID {
    match response {
        NetActionResponse::Success(NetActionResponseData::Packet(id), _) => id.clone(),
        _ => panic!("Expected Packet response, got: {:?}", response),
    }
}

fn get_created_epoch(response: &NetActionResponse) -> Epoch {
    match response {
        NetActionResponse::Success(NetActionResponseData::CreatedEpoch(epoch), _) => epoch.clone(),
        _ => panic!("Expected CreatedEpoch response, got: {:?}", response),
    }
}

fn get_started_epoch(response: &NetActionResponse) -> Epoch {
    match response {
        NetActionResponse::Success(NetActionResponseData::StartedEpoch(epoch), _) => epoch.clone(),
        _ => panic!("Expected StartedEpoch response, got: {:?}", response),
    }
}

fn get_events(response: &NetActionResponse) -> Vec<NetEvent> {
    match response {
        NetActionResponse::Success(_, events) => events.clone(),
        _ => panic!("Expected Success response, got: {:?}", response),
    }
}

// ========== NetSim Construction Tests ==========

#[test]
fn test_net_new_with_valid_graph() {
    let graph = common::linear_graph_3();
    let net = NetSim::new(graph);

    // NetSim should be created successfully
    assert!(net.graph.nodes().contains_key("A"));
    assert!(net.graph.nodes().contains_key("B"));
    assert!(net.graph.nodes().contains_key("C"));
}

#[test]
fn test_net_new_with_empty_graph() {
    use netrun_sim::graph::Graph;
    let graph = Graph::new(vec![], vec![]);
    let _net = NetSim::new(graph);
    // Should not panic
}

// ========== Packet Creation Tests ==========

#[test]
fn test_create_packet_outside_net() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let response = net.do_action(&NetAction::CreatePacket(None));

    assert!(matches!(
        response,
        NetActionResponse::Success(NetActionResponseData::Packet(_), _)
    ));

    // Check events
    let events = get_events(&response);
    assert_eq!(events.len(), 1);
    assert!(matches!(events[0], NetEvent::PacketCreated(_, _)));
}

#[test]
fn test_create_packet_location_is_outside_net() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let packet_id = get_packet_id(&net.do_action(&NetAction::CreatePacket(None)));

    // Verify packet is at OutsideNet
    let packet = net.get_packet(&packet_id).unwrap();
    assert_eq!(packet.location, PacketLocation::OutsideNet);
}

// ========== Packet Consumption Tests ==========

#[test]
fn test_consume_packet() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let packet_id = get_packet_id(&net.do_action(&NetAction::CreatePacket(None)));

    let response = net.do_action(&NetAction::ConsumePacket(packet_id));

    assert!(matches!(
        response,
        NetActionResponse::Success(NetActionResponseData::None, _)
    ));
}

#[test]
fn test_consume_nonexistent_packet() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let fake_id = ulid::Ulid::new();
    let response = net.do_action(&NetAction::ConsumePacket(fake_id));

    assert!(matches!(
        response,
        NetActionResponse::Error(NetActionError::PacketNotFound { .. })
    ));
}

#[test]
fn test_packet_not_found_error_contains_id() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let fake_id = ulid::Ulid::new();
    let response = net.do_action(&NetAction::ConsumePacket(fake_id));

    match response {
        NetActionResponse::Error(NetActionError::PacketNotFound { packet_id }) => {
            assert_eq!(packet_id, fake_id);
        }
        _ => panic!("Expected PacketNotFound error"),
    }
}

// ========== Epoch Tests ==========

#[test]
fn test_start_nonexistent_epoch() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let fake_id = ulid::Ulid::new();
    let response = net.do_action(&NetAction::StartEpoch(fake_id));

    assert!(matches!(
        response,
        NetActionResponse::Error(NetActionError::EpochNotFound { .. })
    ));
}

#[test]
fn test_finish_nonexistent_epoch() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let fake_id = ulid::Ulid::new();
    let response = net.do_action(&NetAction::FinishEpoch(fake_id));

    assert!(matches!(
        response,
        NetActionResponse::Error(NetActionError::EpochNotFound { .. })
    ));
}

#[test]
fn test_cancel_nonexistent_epoch() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let fake_id = ulid::Ulid::new();
    let response = net.do_action(&NetAction::CancelEpoch(fake_id));

    assert!(matches!(
        response,
        NetActionResponse::Error(NetActionError::EpochNotFound { .. })
    ));
}

// ========== Create Epoch Tests ==========

#[test]
fn test_create_epoch_with_invalid_node() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let salvo = Salvo {
        salvo_condition: "manual".to_string(),
        packets: vec![],
    };

    let response = net.do_action(&NetAction::CreateEpoch("NonExistent".to_string(), salvo));

    assert!(matches!(
        response,
        NetActionResponse::Error(NetActionError::NodeNotFound { .. })
    ));
}

#[test]
fn test_create_epoch_node_not_found_error_contains_name() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let salvo = Salvo {
        salvo_condition: "manual".to_string(),
        packets: vec![],
    };

    let response = net.do_action(&NetAction::CreateEpoch("MissingNode".to_string(), salvo));

    match response {
        NetActionResponse::Error(NetActionError::NodeNotFound { node_name }) => {
            assert_eq!(node_name, "MissingNode");
        }
        _ => panic!("Expected NodeNotFound error"),
    }
}

// ========== Run Until Blocked Tests ==========

#[test]
fn test_run_until_blocked_on_empty_net() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let events = net.run_until_blocked();

    // Should return empty events (nothing to do)
    assert!(events.is_empty());
}

// ========== Error Display Tests ==========

#[test]
fn test_net_action_error_display() {
    let error = NetActionError::PacketNotFound {
        packet_id: ulid::Ulid::new(),
    };

    // Test that Display is implemented (from thiserror)
    let msg = format!("{}", error);
    assert!(msg.contains("packet not found"));
}

#[test]
fn test_epoch_not_found_error_display() {
    let epoch_id = ulid::Ulid::new();
    let error = NetActionError::EpochNotFound { epoch_id };

    let msg = format!("{}", error);
    assert!(msg.contains("epoch not found"));
    assert!(msg.contains(&epoch_id.to_string()));
}

// ========== NetEvent Tests ==========

#[test]
fn test_packet_created_event_structure() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let response = net.do_action(&NetAction::CreatePacket(None));
    let events = get_events(&response);

    assert_eq!(events.len(), 1);
    match &events[0] {
        NetEvent::PacketCreated(timestamp, packet_id) => {
            assert!(*timestamp > 0);
            assert!(!packet_id.is_nil());
        }
        _ => panic!("Expected PacketCreated event"),
    }
}

#[test]
fn test_packet_consumed_event_structure() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let packet_id = get_packet_id(&net.do_action(&NetAction::CreatePacket(None)));
    let response = net.do_action(&NetAction::ConsumePacket(packet_id.clone()));
    let events = get_events(&response);

    assert_eq!(events.len(), 1);
    match &events[0] {
        NetEvent::PacketConsumed(timestamp, consumed_id, location) => {
            assert!(*timestamp > 0);
            assert_eq!(*consumed_id, packet_id);
            assert!(matches!(location, PacketLocation::OutsideNet));
        }
        _ => panic!("Expected PacketConsumed event"),
    }
}

// ========== NetActionResponse Pattern Matching Tests ==========

#[test]
fn test_response_pattern_matching_success() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let response = net.do_action(&NetAction::CreatePacket(None));

    // Test that we can pattern match on responses
    let packet_id = match response {
        NetActionResponse::Success(NetActionResponseData::Packet(id), events) => {
            assert!(!events.is_empty());
            id
        }
        NetActionResponse::Success(_, _) => panic!("Wrong response data type"),
        NetActionResponse::Error(e) => panic!("Unexpected error: {}", e),
    };

    assert!(!packet_id.is_nil());
}

#[test]
fn test_response_pattern_matching_error() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let response = net.do_action(&NetAction::ConsumePacket(ulid::Ulid::new()));

    match response {
        NetActionResponse::Error(NetActionError::PacketNotFound { packet_id }) => {
            // Successfully matched the specific error variant with data
            assert!(!packet_id.is_nil());
        }
        NetActionResponse::Error(e) => panic!("Wrong error type: {}", e),
        NetActionResponse::Success(_, _) => panic!("Expected error"),
    }
}

// ========== Public Accessor Tests ==========

#[test]
fn test_get_packet() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let packet_id = get_packet_id(&net.do_action(&NetAction::CreatePacket(None)));

    // Should find the packet
    let packet = net.get_packet(&packet_id);
    assert!(packet.is_some());
    assert_eq!(packet.unwrap().id, packet_id);

    // Should not find non-existent packet
    let fake_id = ulid::Ulid::new();
    assert!(net.get_packet(&fake_id).is_none());
}

#[test]
fn test_get_epoch() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    // Create packet and transport to input port
    let packet_id = get_packet_id(&net.do_action(&NetAction::CreatePacket(None)));
    let input_port_loc = PacketLocation::InputPort("B".to_string(), "in".to_string());
    net.do_action(&NetAction::TransportPacketToLocation(
        packet_id.clone(),
        input_port_loc,
    ));

    // Create and start epoch
    let salvo = Salvo {
        salvo_condition: "manual".to_string(),
        packets: vec![("in".to_string(), packet_id)],
    };
    let epoch = get_created_epoch(&net.do_action(&NetAction::CreateEpoch("B".to_string(), salvo)));
    let epoch = get_started_epoch(&net.do_action(&NetAction::StartEpoch(epoch.id)));

    // Should find the epoch
    let found_epoch = net.get_epoch(&epoch.id);
    assert!(found_epoch.is_some());
    assert_eq!(found_epoch.unwrap().node_name, "B");

    // Should not find non-existent epoch
    let fake_id = ulid::Ulid::new();
    assert!(net.get_epoch(&fake_id).is_none());
}

#[test]
fn test_get_startable_epochs() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    // Initially no startable epochs
    assert!(net.get_startable_epochs().is_empty());

    // Create packet and transport to edge
    let packet_id = get_packet_id(&net.do_action(&NetAction::CreatePacket(None)));
    let edge_loc = PacketLocation::Edge(Edge {
        source: PortRef {
            node_name: "A".to_string(),
            port_type: PortType::Output,
            port_name: "out".to_string(),
        },
        target: PortRef {
            node_name: "B".to_string(),
            port_type: PortType::Input,
            port_name: "in".to_string(),
        },
    });
    net.do_action(&NetAction::TransportPacketToLocation(
        packet_id.clone(),
        edge_loc,
    ));

    // Run until blocked
    net.run_until_blocked();

    // Should now have a startable epoch
    let startable = net.get_startable_epochs();
    assert_eq!(startable.len(), 1);
}

#[test]
fn test_packet_count_at() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    // Create some packets
    let _p1 = get_packet_id(&net.do_action(&NetAction::CreatePacket(None)));
    let _p2 = get_packet_id(&net.do_action(&NetAction::CreatePacket(None)));

    // Should be 2 packets at OutsideNet
    assert_eq!(net.packet_count_at(&PacketLocation::OutsideNet), 2);

    // Should be 0 at input port
    let input_port = PacketLocation::InputPort("B".to_string(), "in".to_string());
    assert_eq!(net.packet_count_at(&input_port), 0);
}

#[test]
fn test_get_packets_at_location() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let p1 = get_packet_id(&net.do_action(&NetAction::CreatePacket(None)));
    let p2 = get_packet_id(&net.do_action(&NetAction::CreatePacket(None)));

    let packets = net.get_packets_at_location(&PacketLocation::OutsideNet);
    assert_eq!(packets.len(), 2);
    assert!(packets.contains(&p1));
    assert!(packets.contains(&p2));
}

#[test]
fn test_transport_packet_to_location() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let packet_id = get_packet_id(&net.do_action(&NetAction::CreatePacket(None)));

    // Transport to input port
    let input_port = PacketLocation::InputPort("B".to_string(), "in".to_string());
    let result = net.do_action(&NetAction::TransportPacketToLocation(
        packet_id.clone(),
        input_port.clone(),
    ));
    assert!(matches!(result, NetActionResponse::Success(_, _)));

    // Verify packet is at new location
    let packet = net.get_packet(&packet_id).unwrap();
    assert_eq!(packet.location, input_port);
    assert_eq!(net.packet_count_at(&input_port), 1);
    assert_eq!(net.packet_count_at(&PacketLocation::OutsideNet), 0);
}

#[test]
fn test_transport_packet_to_location_fails_for_nonexistent_packet() {
    let graph = common::linear_graph_3();
    let mut net = NetSim::new(graph);

    let fake_id = ulid::Ulid::new();
    let input_port = PacketLocation::InputPort("B".to_string(), "in".to_string());

    let result = net.do_action(&NetAction::TransportPacketToLocation(fake_id, input_port));
    assert!(matches!(
        result,
        NetActionResponse::Error(NetActionError::PacketNotFound { .. })
    ));
}