polaris_graph 0.4.4

Graph execution primitives for Polaris (Layer 2).
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! Shared test utilities for `polaris_graph` integration tests.
//!
//! This module provides common helpers, systems, and resources used across
//! multiple test files. Import via `mod test_utils;` in test files.

#![allow(
    dead_code,
    missing_docs,
    reason = "shared test utilities — not all items used in every test binary"
)]

use polaris_graph::dev::{DevToolsPlugin, SystemInfo};
use polaris_graph::graph::Graph;
use polaris_graph::hooks::HooksAPI;
use polaris_graph::node::NodeId;
use polaris_graph::{CaughtError, ErrorKind};
use polaris_system::param::{ParamError, SystemContext};
use polaris_system::plugin::Plugin;
use polaris_system::resource::LocalResource;
use polaris_system::server::Server;
use polaris_system::system::{BoxFuture, System, SystemError};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex};

// ═══════════════════════════════════════════════════════════════════════════════
// TEST SERVER SETUP
// ═══════════════════════════════════════════════════════════════════════════════

/// Creates a test server with `DevToolsPlugin` enabled.
pub fn create_test_server() -> Server {
    let mut server = Server::new();
    DevToolsPlugin::default().build(&mut server);
    server
}

/// Returns the `HooksAPI` from a server, if available.
pub fn get_hooks(server: &Server) -> Option<&HooksAPI> {
    server.api::<HooksAPI>()
}

// ═══════════════════════════════════════════════════════════════════════════════
// GRAPH BUILDER HELPERS
// ═══════════════════════════════════════════════════════════════════════════════

/// Wraps a closure in a Box for use in parallel/switch branches.
///
/// # Example
///
/// ```
/// # use polaris_graph::Graph;
/// # use polaris_graph_test_utils::branch;
/// # async fn system_a() -> i32 { 1 }
/// # async fn system_b() -> i32 { 2 }
/// # let mut graph = Graph::new();
/// graph.add_parallel("par", [
///     branch(|g| g.add_system(system_a)),
///     branch(|g| g.add_system(system_b)),
/// ]);
/// ```
pub fn branch<F>(f: F) -> Box<dyn FnOnce(&mut Graph)>
where
    F: FnOnce(&mut Graph) + 'static,
{
    Box::new(f)
}

// ═══════════════════════════════════════════════════════════════════════════════
// COMMON RESOURCES
// ═══════════════════════════════════════════════════════════════════════════════

/// Tracks whether a handler was invoked during execution.
#[derive(Clone, Default)]
pub struct HandlerLog {
    invoked: Arc<Mutex<bool>>,
}

impl LocalResource for HandlerLog {}

impl HandlerLog {
    /// Returns whether the handler was invoked.
    pub fn was_invoked(&self) -> bool {
        *self.invoked.lock().unwrap()
    }

    /// Marks the handler as invoked.
    pub fn mark_invoked(&self) {
        *self.invoked.lock().unwrap() = true;
    }
}

/// Execution log that records which `NodeId`s were executed in order.
///
/// Uses `Res<SystemInfo>` injected by `DevToolsPlugin` to verify the *correct* nodes ran.
#[derive(Clone, Default)]
pub struct ExecutionLog {
    executed: Arc<Mutex<Vec<NodeId>>>,
}

impl LocalResource for ExecutionLog {}

impl ExecutionLog {
    /// Records that a node was executed.
    pub fn record(&self, node_id: &NodeId) {
        self.executed.lock().unwrap().push(node_id.clone());
    }

    /// Returns all executed node IDs in execution order.
    pub fn executed(&self) -> Vec<NodeId> {
        self.executed.lock().unwrap().clone()
    }

    /// Count occurrences of a specific node.
    pub fn count(&self, node_id: &NodeId) -> usize {
        self.executed
            .lock()
            .unwrap()
            .iter()
            .filter(|id| *id == node_id)
            .count()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// COMMON SYSTEMS
// ═══════════════════════════════════════════════════════════════════════════════

/// System that always succeeds immediately.
pub struct SuccessSystem;

impl System for SuccessSystem {
    type Output = ();

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async move { Ok(()) })
    }

    fn name(&self) -> &'static str {
        "success_system"
    }
}

/// System that always fails with an error.
pub struct FailingSystem;

impl System for FailingSystem {
    type Output = ();

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async move { Err(SystemError::ExecutionError("intentional failure".into())) })
    }

    fn name(&self) -> &'static str {
        "failing_system"
    }

    fn is_fallible(&self) -> bool {
        true
    }
}

/// System that sleeps for a specified duration.
pub struct SlowSystem {
    pub duration: std::time::Duration,
}

impl System for SlowSystem {
    type Output = ();

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        let duration = self.duration;
        Box::pin(async move {
            tokio::time::sleep(duration).await;
            Ok(())
        })
    }

    fn name(&self) -> &'static str {
        "slow_system"
    }
}

/// System that marks a handler was invoked via `HandlerLog`.
pub struct HandlerSystem;

impl System for HandlerSystem {
    type Output = ();

    fn run<'a>(
        &'a self,
        ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async move {
            if let Ok(log) = ctx.get_resource::<HandlerLog>() {
                log.mark_invoked();
            }
            Ok(())
        })
    }

    fn name(&self) -> &'static str {
        "handler_system"
    }
}

/// System that sets a boolean flag when executed.
pub struct FlagSystem {
    pub flag: Arc<Mutex<bool>>,
}

impl System for FlagSystem {
    type Output = ();

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        let flag = Arc::clone(&self.flag);
        Box::pin(async move {
            *flag.lock().unwrap() = true;
            Ok(())
        })
    }

    fn name(&self) -> &'static str {
        "flag_system"
    }
}

/// System that logs its own `NodeId` when executed.
///
/// Uses `Res<SystemInfo>` injected by `DevToolsPlugin` and `Res<ExecutionLog>`.
pub struct LoggingSystem;

impl System for LoggingSystem {
    type Output = NodeId;

    fn run<'a>(
        &'a self,
        ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async move {
            let info = ctx
                .get_resource::<SystemInfo>()
                .expect("SystemInfo not injected by DevToolsPlugin");
            let node_id = info.node_id();
            let log = ctx
                .get_resource::<ExecutionLog>()
                .expect("ExecutionLog resource not found");
            log.record(&node_id);
            Ok(node_id)
        })
    }

    fn name(&self) -> &'static str {
        "logging_system"
    }

    fn access(&self) -> polaris_system::param::SystemAccess {
        polaris_system::param::SystemAccess::new()
            .with_read::<SystemInfo>()
            .with_read::<ExecutionLog>()
    }
}

/// Adds a logging system to the graph that records its node ID when executed.
///
/// Returns the node ID assigned to this system.
pub fn add_tracker(g: &mut Graph) -> NodeId {
    g.add_boxed_system(Box::new(LoggingSystem))
}

// ═══════════════════════════════════════════════════════════════════════════════
// OUTPUT/PREDICATE TEST SYSTEMS
// ═══════════════════════════════════════════════════════════════════════════════

/// Output from producer system for chaining tests.
#[derive(Debug, Clone)]
pub struct ProducerOutput {
    /// The produced value.
    pub value: i32,
}

/// System that produces an output value.
pub struct ProducerSystem {
    pub value: i32,
}

impl System for ProducerSystem {
    type Output = ProducerOutput;

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        let value = self.value;
        Box::pin(async move { Ok(ProducerOutput { value }) })
    }

    fn name(&self) -> &'static str {
        "producer_system"
    }
}

/// System that reads and stores the producer output value.
pub struct ConsumerSystem {
    pub received: Arc<Mutex<Option<i32>>>,
}

impl System for ConsumerSystem {
    type Output = ();

    fn run<'a>(
        &'a self,
        ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        let received = Arc::clone(&self.received);
        Box::pin(async move {
            let output = ctx
                .get_output::<ProducerOutput>()
                .expect("ProducerOutput should be available");
            *received.lock().unwrap() = Some(output.value);
            Ok(())
        })
    }

    fn name(&self) -> &'static str {
        "consumer_system"
    }
}

/// Marker type for decision predicate output.
#[derive(Debug)]
pub struct DecisionOutput {
    pub take_true: bool,
}

/// System that outputs a decision marker.
pub struct DecisionSystem {
    pub take_true: bool,
}

impl System for DecisionSystem {
    type Output = DecisionOutput;

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        let take_true = self.take_true;
        Box::pin(async move { Ok(DecisionOutput { take_true }) })
    }

    fn name(&self) -> &'static str {
        "decision_system"
    }
}

/// Output for switch discriminator tests.
#[derive(Debug)]
pub struct SwitchOutput {
    /// The switch key to select the branch.
    pub key: &'static str,
}

/// System that outputs a switch key.
pub struct SwitchKeySystem {
    /// The switch key to output.
    pub key: &'static str,
}

impl System for SwitchKeySystem {
    type Output = SwitchOutput;

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        let key = self.key;
        Box::pin(async move { Ok(SwitchOutput { key }) })
    }

    fn name(&self) -> &'static str {
        "switch_key_system"
    }
}

/// Loop state for termination predicate tests.
#[derive(Debug)]
pub struct LoopState {
    /// Current iteration count.
    pub iteration: usize,
}

/// System that tracks loop iteration count.
pub struct LoopIterationSystem {
    /// Shared counter for iterations.
    pub counter: Arc<Mutex<usize>>,
}

impl System for LoopIterationSystem {
    type Output = LoopState;

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        let counter = Arc::clone(&self.counter);
        Box::pin(async move {
            let mut count = counter.lock().unwrap();
            *count += 1;
            Ok(LoopState { iteration: *count })
        })
    }

    fn name(&self) -> &'static str {
        "loop_iteration_system"
    }
}

/// System that produces initial loop state (iteration 0).
pub struct InitialStateSystem;

impl System for InitialStateSystem {
    type Output = LoopState;

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async move { Ok(LoopState { iteration: 0 }) })
    }

    fn name(&self) -> &'static str {
        "initial_state_system"
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ERROR KIND CHECKING SYSTEMS
// ═══════════════════════════════════════════════════════════════════════════════

/// System that fails with a `ParamError` (parameter resolution failure).
pub struct ParamFailingSystem;

impl System for ParamFailingSystem {
    type Output = ();

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async move {
            Err(SystemError::ParamError(ParamError::ResourceNotFound(
                "MissingType",
            )))
        })
    }

    fn name(&self) -> &'static str {
        "param_failing_system"
    }
}

/// System that records the `ErrorKind` from `CaughtError` via `HandlerLog`.
pub struct KindCheckingHandler;

impl System for KindCheckingHandler {
    type Output = ();

    fn run<'a>(
        &'a self,
        ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async move {
            if let Ok(log) = ctx.get_resource::<HandlerLog>() {
                log.mark_invoked();
            }
            if let Ok(caught) = ctx.get_output::<CaughtError>()
                && let Ok(kind_log) = ctx.get_resource::<ErrorKindLog>()
            {
                kind_log.record(caught.kind);
            }
            Ok(())
        })
    }

    fn name(&self) -> &'static str {
        "kind_checking_handler"
    }
}

/// Resource that records the `ErrorKind` observed by an error handler.
#[derive(Clone, Default)]
pub struct ErrorKindLog {
    kind: Arc<Mutex<Option<ErrorKind>>>,
}

impl LocalResource for ErrorKindLog {}

impl ErrorKindLog {
    /// Returns the recorded error kind, if any.
    pub fn kind(&self) -> Option<ErrorKind> {
        *self.kind.lock().unwrap()
    }

    /// Records an error kind.
    pub fn record(&self, kind: ErrorKind) {
        *self.kind.lock().unwrap() = Some(kind);
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RETRY TEST SYSTEMS
// ═══════════════════════════════════════════════════════════════════════════════

/// A system that fails the first `fail_count` times, then succeeds.
///
/// Tracks attempt count via a shared `AtomicU32` so tests can verify
/// how many times the system was invoked.
pub struct EventuallySucceedsSystem {
    /// Number of times to fail before succeeding.
    pub fail_count: u32,
    /// Shared counter tracking total invocations.
    pub attempts: Arc<AtomicU32>,
}

impl System for EventuallySucceedsSystem {
    type Output = ();

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async move {
            let attempt = self.attempts.fetch_add(1, Ordering::SeqCst);
            if attempt < self.fail_count {
                Err(SystemError::ExecutionError(format!(
                    "transient failure (attempt {attempt})"
                )))
            } else {
                Ok(())
            }
        })
    }

    fn name(&self) -> &'static str {
        "eventually_succeeds_system"
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SCOPE TEST SYSTEMS
// ═══════════════════════════════════════════════════════════════════════════════

/// A clonable local resource for testing scope resource forwarding.
#[derive(Debug, Clone)]
pub struct TestConfig {
    pub value: i32,
}
impl LocalResource for TestConfig {}

/// System that reads `TestConfig` and captures its value.
pub struct ReadConfigCapture {
    pub captured: Arc<Mutex<Option<i32>>>,
}

impl System for ReadConfigCapture {
    type Output = ();

    fn run<'a>(
        &'a self,
        ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        let captured = Arc::clone(&self.captured);
        Box::pin(async move {
            let config = ctx
                .get_resource::<TestConfig>()
                .map_err(|err| SystemError::ExecutionError(err.to_string()))?;
            *captured.lock().unwrap() = Some(config.value);
            Ok(())
        })
    }

    fn name(&self) -> &'static str {
        "read_config_capture"
    }
}

/// System that declares `Res<TestConfig>` (read-only access, for validation tests).
pub struct ReadConfigSystem;

impl System for ReadConfigSystem {
    type Output = ();

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async { Ok(()) })
    }

    fn name(&self) -> &'static str {
        "read_config_system"
    }

    fn access(&self) -> polaris_system::param::SystemAccess {
        polaris_system::param::SystemAccess::new().with_read::<TestConfig>()
    }
}

/// System that declares `ResMut<TestConfig>` (write access, for validation tests).
pub struct WriteConfigSystem;

impl System for WriteConfigSystem {
    type Output = ();

    fn run<'a>(
        &'a self,
        _ctx: &'a SystemContext<'_>,
    ) -> BoxFuture<'a, Result<Self::Output, SystemError>> {
        Box::pin(async { Ok(()) })
    }

    fn name(&self) -> &'static str {
        "write_config_system"
    }

    fn access(&self) -> polaris_system::param::SystemAccess {
        polaris_system::param::SystemAccess::new().with_write::<TestConfig>()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TRACKER NODE COLLECTION
// ═══════════════════════════════════════════════════════════════════════════════

/// Collects tracker `NodeId`s during graph building.
#[derive(Clone, Default)]
pub struct TrackerNodes(Arc<Mutex<Vec<NodeId>>>);

impl TrackerNodes {
    /// Adds a node ID to the collection.
    pub fn add(&self, id: NodeId) {
        self.0.lock().unwrap().push(id);
    }

    /// Consumes self and returns the collected node IDs.
    pub fn into_vec(self) -> Vec<NodeId> {
        Arc::try_unwrap(self.0)
            .map(|m| m.into_inner().unwrap())
            .unwrap_or_else(|arc| arc.lock().unwrap().clone())
    }
}