camel-core 0.6.0

Core engine for rust-camel
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
use std::sync::Arc;

use async_trait::async_trait;
use tokio::sync::OnceCell;

use camel_api::{
    CamelError, RuntimeCommand, RuntimeCommandBus, RuntimeCommandResult, RuntimeQuery,
    RuntimeQueryBus, RuntimeQueryResult,
};

use crate::lifecycle::application::commands::{
    CommandDeps, execute_command, handle_register_internal,
};
use crate::lifecycle::application::queries::{QueryDeps, execute_query};
use crate::lifecycle::application::route_definition::RouteDefinition;
use crate::lifecycle::ports::RouteRegistrationPort;
use crate::lifecycle::ports::{
    CommandDedupPort, EventPublisherPort, ProjectionStorePort, RouteRepositoryPort,
    RuntimeExecutionPort, RuntimeUnitOfWorkPort,
};

pub struct RuntimeBus {
    repo: Arc<dyn RouteRepositoryPort>,
    projections: Arc<dyn ProjectionStorePort>,
    events: Arc<dyn EventPublisherPort>,
    dedup: Arc<dyn CommandDedupPort>,
    uow: Option<Arc<dyn RuntimeUnitOfWorkPort>>,
    execution: Option<Arc<dyn RuntimeExecutionPort>>,
    journal_recovered_once: OnceCell<()>,
}

impl RuntimeBus {
    pub fn new(
        repo: Arc<dyn RouteRepositoryPort>,
        projections: Arc<dyn ProjectionStorePort>,
        events: Arc<dyn EventPublisherPort>,
        dedup: Arc<dyn CommandDedupPort>,
    ) -> Self {
        Self {
            repo,
            projections,
            events,
            dedup,
            uow: None,
            execution: None,
            journal_recovered_once: OnceCell::new(),
        }
    }

    pub fn with_uow(mut self, uow: Arc<dyn RuntimeUnitOfWorkPort>) -> Self {
        self.uow = Some(uow);
        self
    }

    pub fn with_execution(mut self, execution: Arc<dyn RuntimeExecutionPort>) -> Self {
        self.execution = Some(execution);
        self
    }

    pub fn repo(&self) -> &Arc<dyn RouteRepositoryPort> {
        &self.repo
    }

    fn deps(&self) -> CommandDeps {
        CommandDeps {
            repo: Arc::clone(&self.repo),
            projections: Arc::clone(&self.projections),
            events: Arc::clone(&self.events),
            uow: self.uow.clone(),
            execution: self.execution.clone(),
        }
    }

    fn query_deps(&self) -> QueryDeps {
        QueryDeps {
            projections: Arc::clone(&self.projections),
        }
    }

    async fn ensure_journal_recovered(&self) -> Result<(), CamelError> {
        let Some(uow) = &self.uow else {
            return Ok(());
        };

        self.journal_recovered_once
            .get_or_try_init(|| async {
                uow.recover_from_journal().await?;
                Ok::<(), CamelError>(())
            })
            .await?;
        Ok(())
    }
}

#[async_trait]
impl RuntimeCommandBus for RuntimeBus {
    async fn execute(&self, cmd: RuntimeCommand) -> Result<RuntimeCommandResult, CamelError> {
        self.ensure_journal_recovered().await?;
        let command_id = cmd.command_id().to_string();
        if !self.dedup.first_seen(&command_id).await? {
            return Ok(RuntimeCommandResult::Duplicate { command_id });
        }
        let deps = self.deps();
        match execute_command(&deps, cmd).await {
            Ok(result) => Ok(result),
            Err(err) => {
                let _ = self.dedup.forget_seen(&command_id).await;
                Err(err)
            }
        }
    }
}

#[async_trait]
impl RuntimeQueryBus for RuntimeBus {
    async fn ask(&self, query: RuntimeQuery) -> Result<RuntimeQueryResult, CamelError> {
        self.ensure_journal_recovered().await?;

        match query {
            RuntimeQuery::InFlightCount { route_id } => {
                if let Some(execution) = &self.execution {
                    execution
                        .in_flight_count(&route_id)
                        .await
                        .map_err(Into::into)
                } else {
                    Ok(RuntimeQueryResult::RouteNotFound { route_id })
                }
            }
            other => {
                let deps = self.query_deps();
                execute_query(&deps, other).await
            }
        }
    }
}

#[async_trait]
impl RouteRegistrationPort for RuntimeBus {
    async fn register_route(&self, def: RouteDefinition) -> Result<(), CamelError> {
        self.ensure_journal_recovered().await?;
        let deps = self.deps();
        handle_register_internal(&deps, def).await.map(|_| ())
    }
}

#[cfg(test)]
mod tests {
    use crate::lifecycle::domain::DomainError;

    use super::*;
    use std::collections::{HashMap, HashSet};
    use std::sync::Mutex;

    use crate::lifecycle::application::route_definition::RouteDefinition;
    use crate::lifecycle::domain::{RouteRuntimeAggregate, RuntimeEvent};
    use crate::lifecycle::ports::RouteRegistrationPort as InternalRuntimeCommandBus;
    use crate::lifecycle::ports::RouteStatusProjection;

    #[derive(Clone, Default)]
    struct InMemoryTestRepo {
        routes: Arc<Mutex<HashMap<String, RouteRuntimeAggregate>>>,
    }

    #[async_trait]
    impl RouteRepositoryPort for InMemoryTestRepo {
        async fn load(&self, route_id: &str) -> Result<Option<RouteRuntimeAggregate>, DomainError> {
            Ok(self
                .routes
                .lock()
                .expect("lock test routes")
                .get(route_id)
                .cloned())
        }

        async fn save(&self, aggregate: RouteRuntimeAggregate) -> Result<(), DomainError> {
            self.routes
                .lock()
                .expect("lock test routes")
                .insert(aggregate.route_id().to_string(), aggregate);
            Ok(())
        }

        async fn save_if_version(
            &self,
            aggregate: RouteRuntimeAggregate,
            expected_version: u64,
        ) -> Result<(), DomainError> {
            let route_id = aggregate.route_id().to_string();
            let mut routes = self.routes.lock().expect("lock test routes");
            let current = routes.get(&route_id).ok_or_else(|| {
                DomainError::InvalidState(format!(
                    "optimistic lock conflict for route '{route_id}': route not found"
                ))
            })?;

            if current.version() != expected_version {
                return Err(DomainError::InvalidState(format!(
                    "optimistic lock conflict for route '{route_id}': expected version {expected_version}, actual {}",
                    current.version()
                )));
            }

            routes.insert(route_id, aggregate);
            Ok(())
        }

        async fn delete(&self, route_id: &str) -> Result<(), DomainError> {
            self.routes
                .lock()
                .expect("lock test routes")
                .remove(route_id);
            Ok(())
        }
    }

    #[derive(Clone, Default)]
    struct InMemoryTestProjectionStore {
        statuses: Arc<Mutex<HashMap<String, RouteStatusProjection>>>,
    }

    #[async_trait]
    impl ProjectionStorePort for InMemoryTestProjectionStore {
        async fn upsert_status(&self, status: RouteStatusProjection) -> Result<(), DomainError> {
            self.statuses
                .lock()
                .expect("lock test statuses")
                .insert(status.route_id.clone(), status);
            Ok(())
        }

        async fn get_status(
            &self,
            route_id: &str,
        ) -> Result<Option<RouteStatusProjection>, DomainError> {
            Ok(self
                .statuses
                .lock()
                .expect("lock test statuses")
                .get(route_id)
                .cloned())
        }

        async fn list_statuses(&self) -> Result<Vec<RouteStatusProjection>, DomainError> {
            Ok(self
                .statuses
                .lock()
                .expect("lock test statuses")
                .values()
                .cloned()
                .collect())
        }

        async fn remove_status(&self, route_id: &str) -> Result<(), DomainError> {
            self.statuses
                .lock()
                .expect("lock test statuses")
                .remove(route_id);
            Ok(())
        }
    }

    #[derive(Clone, Default)]
    struct InMemoryTestEventPublisher;

    #[async_trait]
    impl EventPublisherPort for InMemoryTestEventPublisher {
        async fn publish(&self, _events: &[RuntimeEvent]) -> Result<(), DomainError> {
            Ok(())
        }
    }

    #[derive(Clone, Default)]
    struct InMemoryTestDedup {
        seen: Arc<Mutex<HashSet<String>>>,
    }

    #[derive(Clone, Default)]
    struct InspectableDedup {
        seen: Arc<Mutex<HashSet<String>>>,
        forget_calls: Arc<Mutex<u32>>,
    }

    #[async_trait]
    impl CommandDedupPort for InMemoryTestDedup {
        async fn first_seen(&self, command_id: &str) -> Result<bool, DomainError> {
            let mut seen = self.seen.lock().expect("lock dedup set");
            Ok(seen.insert(command_id.to_string()))
        }

        async fn forget_seen(&self, command_id: &str) -> Result<(), DomainError> {
            self.seen.lock().expect("lock dedup set").remove(command_id);
            Ok(())
        }
    }

    #[async_trait]
    impl CommandDedupPort for InspectableDedup {
        async fn first_seen(&self, command_id: &str) -> Result<bool, DomainError> {
            let mut seen = self.seen.lock().expect("lock dedup set");
            Ok(seen.insert(command_id.to_string()))
        }

        async fn forget_seen(&self, command_id: &str) -> Result<(), DomainError> {
            self.seen.lock().expect("lock dedup set").remove(command_id);
            let mut calls = self.forget_calls.lock().expect("forget calls");
            *calls += 1;
            Ok(())
        }
    }

    fn build_test_runtime_bus() -> RuntimeBus {
        let repo: Arc<dyn RouteRepositoryPort> = Arc::new(InMemoryTestRepo::default());
        let projections: Arc<dyn ProjectionStorePort> =
            Arc::new(InMemoryTestProjectionStore::default());
        let events: Arc<dyn EventPublisherPort> = Arc::new(InMemoryTestEventPublisher);
        let dedup: Arc<dyn CommandDedupPort> = Arc::new(InMemoryTestDedup::default());
        RuntimeBus::new(repo, projections, events, dedup)
    }

    #[derive(Default)]
    struct CountingUow {
        recover_calls: Arc<Mutex<u32>>,
    }

    #[derive(Default)]
    struct FailingRecoverUow;

    #[async_trait]
    impl RuntimeUnitOfWorkPort for CountingUow {
        async fn persist_upsert(
            &self,
            _aggregate: RouteRuntimeAggregate,
            _expected_version: Option<u64>,
            _projection: RouteStatusProjection,
            _events: &[RuntimeEvent],
        ) -> Result<(), DomainError> {
            Ok(())
        }

        async fn persist_delete(
            &self,
            _route_id: &str,
            _events: &[RuntimeEvent],
        ) -> Result<(), DomainError> {
            Ok(())
        }

        async fn recover_from_journal(&self) -> Result<(), DomainError> {
            let mut calls = self.recover_calls.lock().expect("recover_calls");
            *calls += 1;
            Ok(())
        }
    }

    #[async_trait]
    impl RuntimeUnitOfWorkPort for FailingRecoverUow {
        async fn persist_upsert(
            &self,
            _aggregate: RouteRuntimeAggregate,
            _expected_version: Option<u64>,
            _projection: RouteStatusProjection,
            _events: &[RuntimeEvent],
        ) -> Result<(), DomainError> {
            Ok(())
        }

        async fn persist_delete(
            &self,
            _route_id: &str,
            _events: &[RuntimeEvent],
        ) -> Result<(), DomainError> {
            Ok(())
        }

        async fn recover_from_journal(&self) -> Result<(), DomainError> {
            Err(DomainError::InvalidState("recover failed".into()))
        }
    }

    #[derive(Default)]
    struct InFlightExecutionPort;

    #[async_trait]
    impl RuntimeExecutionPort for InFlightExecutionPort {
        async fn register_route(&self, _definition: RouteDefinition) -> Result<(), DomainError> {
            Ok(())
        }
        async fn start_route(&self, _route_id: &str) -> Result<(), DomainError> {
            Ok(())
        }
        async fn stop_route(&self, _route_id: &str) -> Result<(), DomainError> {
            Ok(())
        }
        async fn suspend_route(&self, _route_id: &str) -> Result<(), DomainError> {
            Ok(())
        }
        async fn resume_route(&self, _route_id: &str) -> Result<(), DomainError> {
            Ok(())
        }
        async fn reload_route(&self, _route_id: &str) -> Result<(), DomainError> {
            Ok(())
        }
        async fn remove_route(&self, _route_id: &str) -> Result<(), DomainError> {
            Ok(())
        }
        async fn in_flight_count(&self, route_id: &str) -> Result<RuntimeQueryResult, DomainError> {
            if route_id == "known" {
                Ok(RuntimeQueryResult::InFlightCount {
                    route_id: route_id.to_string(),
                    count: 3,
                })
            } else {
                Ok(RuntimeQueryResult::RouteNotFound {
                    route_id: route_id.to_string(),
                })
            }
        }
    }

    #[tokio::test]
    async fn runtime_bus_implements_internal_command_bus() {
        let bus = build_test_runtime_bus();
        let def = RouteDefinition::new("timer:test", vec![]).with_route_id("internal-route");
        let result = InternalRuntimeCommandBus::register_route(&bus, def).await;
        assert!(
            result.is_ok(),
            "internal bus registration failed: {:?}",
            result
        );

        let status = bus
            .ask(RuntimeQuery::GetRouteStatus {
                route_id: "internal-route".to_string(),
            })
            .await
            .unwrap();
        match status {
            RuntimeQueryResult::RouteStatus { status, .. } => {
                assert_eq!(status, "Registered");
            }
            _ => panic!("unexpected query result"),
        }
    }

    #[tokio::test]
    async fn execute_returns_duplicate_for_replayed_command_id() {
        use camel_api::runtime::{CanonicalRouteSpec, CanonicalStepSpec, RuntimeCommand};

        let bus = build_test_runtime_bus();

        let mut spec = CanonicalRouteSpec::new("dup-route", "timer:tick");
        spec.steps = vec![CanonicalStepSpec::Stop];

        let cmd = RuntimeCommand::RegisterRoute {
            spec: spec.clone(),
            command_id: "dup-cmd".into(),
            causation_id: None,
        };
        let first = bus.execute(cmd).await.unwrap();
        assert!(matches!(
            first,
            RuntimeCommandResult::RouteRegistered { route_id } if route_id == "dup-route"
        ));

        let second = bus
            .execute(RuntimeCommand::RegisterRoute {
                spec,
                command_id: "dup-cmd".into(),
                causation_id: None,
            })
            .await
            .unwrap();
        assert!(matches!(
            second,
            RuntimeCommandResult::Duplicate { command_id } if command_id == "dup-cmd"
        ));
    }

    #[tokio::test]
    async fn ask_in_flight_count_without_execution_returns_route_not_found() {
        let bus = build_test_runtime_bus();
        let res = bus
            .ask(RuntimeQuery::InFlightCount {
                route_id: "missing".into(),
            })
            .await
            .unwrap();
        assert!(matches!(
            res,
            RuntimeQueryResult::RouteNotFound { route_id } if route_id == "missing"
        ));
    }

    #[tokio::test]
    async fn ask_in_flight_count_with_execution_delegates_to_adapter() {
        let repo: Arc<dyn RouteRepositoryPort> = Arc::new(InMemoryTestRepo::default());
        let projections: Arc<dyn ProjectionStorePort> =
            Arc::new(InMemoryTestProjectionStore::default());
        let events: Arc<dyn EventPublisherPort> = Arc::new(InMemoryTestEventPublisher);
        let dedup: Arc<dyn CommandDedupPort> = Arc::new(InMemoryTestDedup::default());
        let execution: Arc<dyn RuntimeExecutionPort> = Arc::new(InFlightExecutionPort);
        let bus = RuntimeBus::new(repo, projections, events, dedup).with_execution(execution);

        let known = bus
            .ask(RuntimeQuery::InFlightCount {
                route_id: "known".into(),
            })
            .await
            .unwrap();
        assert!(matches!(
            known,
            RuntimeQueryResult::InFlightCount { route_id, count }
            if route_id == "known" && count == 3
        ));
    }

    #[tokio::test]
    async fn journal_recovery_runs_once_even_with_multiple_commands() {
        use camel_api::runtime::{CanonicalRouteSpec, CanonicalStepSpec, RuntimeCommand};

        let repo: Arc<dyn RouteRepositoryPort> = Arc::new(InMemoryTestRepo::default());
        let projections: Arc<dyn ProjectionStorePort> =
            Arc::new(InMemoryTestProjectionStore::default());
        let events: Arc<dyn EventPublisherPort> = Arc::new(InMemoryTestEventPublisher);
        let dedup: Arc<dyn CommandDedupPort> = Arc::new(InMemoryTestDedup::default());
        let uow = Arc::new(CountingUow::default());
        let bus = RuntimeBus::new(repo, projections, events, dedup).with_uow(uow.clone());

        let mut spec_a = CanonicalRouteSpec::new("a", "timer:a");
        spec_a.steps = vec![CanonicalStepSpec::Stop];
        let mut spec_b = CanonicalRouteSpec::new("b", "timer:b");
        spec_b.steps = vec![CanonicalStepSpec::Stop];

        bus.execute(RuntimeCommand::RegisterRoute {
            spec: spec_a,
            command_id: "c-a".into(),
            causation_id: None,
        })
        .await
        .unwrap();

        bus.execute(RuntimeCommand::RegisterRoute {
            spec: spec_b,
            command_id: "c-b".into(),
            causation_id: None,
        })
        .await
        .unwrap();

        let calls = *uow.recover_calls.lock().expect("recover calls");
        assert_eq!(calls, 1, "journal recovery should run once");
    }

    #[tokio::test]
    async fn execute_on_command_error_forgets_dedup_marker() {
        use camel_api::runtime::{CanonicalRouteSpec, RuntimeCommand};

        let repo: Arc<dyn RouteRepositoryPort> = Arc::new(InMemoryTestRepo::default());
        let projections: Arc<dyn ProjectionStorePort> =
            Arc::new(InMemoryTestProjectionStore::default());
        let events: Arc<dyn EventPublisherPort> = Arc::new(InMemoryTestEventPublisher);
        let dedup = Arc::new(InspectableDedup::default());
        let dedup_port: Arc<dyn CommandDedupPort> = dedup.clone();

        let bus = RuntimeBus::new(repo, projections, events, dedup_port);

        // Invalid canonical contract: empty route_id -> execute_command should fail.
        let cmd = RuntimeCommand::RegisterRoute {
            spec: CanonicalRouteSpec::new("", "timer:tick"),
            command_id: "err-cmd".into(),
            causation_id: None,
        };

        let err = bus.execute(cmd).await.expect_err("must fail");
        assert!(err.to_string().contains("route_id cannot be empty"));

        assert_eq!(*dedup.forget_calls.lock().expect("forget calls"), 1);
        assert!(!dedup.seen.lock().expect("seen").contains("err-cmd"));
    }

    #[tokio::test]
    async fn execute_propagates_recover_error_from_uow() {
        use camel_api::runtime::{CanonicalRouteSpec, CanonicalStepSpec, RuntimeCommand};

        let repo: Arc<dyn RouteRepositoryPort> = Arc::new(InMemoryTestRepo::default());
        let projections: Arc<dyn ProjectionStorePort> =
            Arc::new(InMemoryTestProjectionStore::default());
        let events: Arc<dyn EventPublisherPort> = Arc::new(InMemoryTestEventPublisher);
        let dedup: Arc<dyn CommandDedupPort> = Arc::new(InMemoryTestDedup::default());
        let uow: Arc<dyn RuntimeUnitOfWorkPort> = Arc::new(FailingRecoverUow);

        let bus = RuntimeBus::new(repo, projections, events, dedup).with_uow(uow);

        let mut spec = CanonicalRouteSpec::new("x", "timer:x");
        spec.steps = vec![CanonicalStepSpec::Stop];
        let err = bus
            .execute(RuntimeCommand::RegisterRoute {
                spec,
                command_id: "recover-err".into(),
                causation_id: None,
            })
            .await
            .expect_err("recover should fail");

        assert!(err.to_string().contains("recover failed"));
    }

    #[tokio::test]
    async fn ask_in_flight_count_with_execution_handles_unknown_route() {
        let repo: Arc<dyn RouteRepositoryPort> = Arc::new(InMemoryTestRepo::default());
        let projections: Arc<dyn ProjectionStorePort> =
            Arc::new(InMemoryTestProjectionStore::default());
        let events: Arc<dyn EventPublisherPort> = Arc::new(InMemoryTestEventPublisher);
        let dedup: Arc<dyn CommandDedupPort> = Arc::new(InMemoryTestDedup::default());
        let execution: Arc<dyn RuntimeExecutionPort> = Arc::new(InFlightExecutionPort);
        let bus = RuntimeBus::new(repo, projections, events, dedup).with_execution(execution);

        let unknown = bus
            .ask(RuntimeQuery::InFlightCount {
                route_id: "unknown".into(),
            })
            .await
            .unwrap();
        assert!(matches!(
            unknown,
            RuntimeQueryResult::RouteNotFound { route_id } if route_id == "unknown"
        ));
    }
}