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
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};

use async_trait::async_trait;
use camel_api::{
    CamelError, CanonicalRouteSpec, RuntimeCommand, RuntimeCommandBus, RuntimeQuery,
    RuntimeQueryResult, SupervisionConfig,
};
use camel_component_api::{Component, ConcurrencyModel, Consumer, ConsumerContext, Endpoint};
use camel_component_timer::TimerComponent;
use camel_core::{CamelContext, RouteDefinition};
use camel_core::{
    InMemoryCommandDedup, InMemoryEventPublisher, InMemoryProjectionStore, InMemoryRouteRepository,
    RuntimeBus,
};

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_start_commands_preserve_single_winner_semantics() {
    let runtime = Arc::new(RuntimeBus::new(
        Arc::new(InMemoryRouteRepository::default()),
        Arc::new(InMemoryProjectionStore::default()),
        Arc::new(InMemoryEventPublisher::default()),
        Arc::new(InMemoryCommandDedup::default()),
    ));

    runtime
        .execute(RuntimeCommand::RegisterRoute {
            spec: CanonicalRouteSpec::new("concurrent-r1", "timer:tick"),
            command_id: "cmd-register".into(),
            causation_id: None,
        })
        .await
        .unwrap();

    let mut handles = Vec::new();
    for i in 0..12 {
        let rt = Arc::clone(&runtime);
        handles.push(tokio::spawn(async move {
            rt.execute(RuntimeCommand::StartRoute {
                route_id: "concurrent-r1".into(),
                command_id: format!("cmd-start-{i}"),
                causation_id: Some("cmd-register".into()),
            })
            .await
        }));
    }

    let mut ok = 0usize;
    let mut conflicts = 0usize;
    for handle in handles {
        let result = handle.await.expect("task join failed");
        match result {
            Ok(_) => ok += 1,
            Err(err) => {
                let text = err.to_string();
                assert!(
                    text.contains("optimistic lock conflict")
                        || text.contains("invalid transition"),
                    "unexpected concurrent error: {text}"
                );
                conflicts += 1;
            }
        }
    }

    assert_eq!(ok, 1, "exactly one start should succeed");
    assert_eq!(ok + conflicts, 12);

    let aggregate = runtime.repo().load("concurrent-r1").await.unwrap().unwrap();
    assert!(matches!(
        aggregate.state(),
        camel_core::RouteRuntimeState::Started
    ));
}

#[tokio::test]
async fn connected_runtime_query_reads_projection_source_of_truth() {
    let mut ctx = CamelContext::builder().build().await.unwrap();
    ctx.register_component(TimerComponent::new());
    let runtime = ctx.runtime();

    runtime
        .execute(RuntimeCommand::RegisterRoute {
            spec: CanonicalRouteSpec::new("rq-projection", "timer:tick"),
            command_id: "c1".into(),
            causation_id: None,
        })
        .await
        .unwrap();

    let out = runtime
        .ask(RuntimeQuery::GetRouteStatus {
            route_id: "rq-projection".into(),
        })
        .await
        .unwrap();

    match out {
        RuntimeQueryResult::RouteStatus { status, .. } => {
            assert_eq!(status, "Registered");
        }
        other => panic!("unexpected query result: {other:?}"),
    }
}

struct CrashingConsumer;

#[async_trait]
impl Consumer for CrashingConsumer {
    async fn start(&mut self, _ctx: ConsumerContext) -> Result<(), CamelError> {
        tokio::time::sleep(Duration::from_millis(50)).await;
        Err(CamelError::RouteError("boom".into()))
    }

    async fn stop(&mut self) -> Result<(), CamelError> {
        Ok(())
    }

    fn concurrency_model(&self) -> ConcurrencyModel {
        ConcurrencyModel::Sequential
    }
}

struct CrashingEndpoint;

impl Endpoint for CrashingEndpoint {
    fn uri(&self) -> &str {
        "crash:test"
    }

    fn create_consumer(&self) -> Result<Box<dyn Consumer>, CamelError> {
        Ok(Box::new(CrashingConsumer))
    }

    fn create_producer(
        &self,
        _ctx: &camel_api::ProducerContext,
    ) -> Result<camel_api::BoxProcessor, CamelError> {
        Err(CamelError::RouteError("no producer".into()))
    }
}

struct CrashingComponent;

impl Component for CrashingComponent {
    fn scheme(&self) -> &str {
        "crash"
    }

    fn create_endpoint(
        &self,
        _uri: &str,
        _ctx: &dyn camel_component_api::ComponentContext,
    ) -> Result<Box<dyn Endpoint>, CamelError> {
        Ok(Box::new(CrashingEndpoint))
    }
}

struct CrashOnceThenHoldConsumer {
    starts: Arc<AtomicU32>,
}

#[async_trait]
impl Consumer for CrashOnceThenHoldConsumer {
    async fn start(&mut self, ctx: ConsumerContext) -> Result<(), CamelError> {
        if self.starts.fetch_add(1, Ordering::SeqCst) == 0 {
            tokio::time::sleep(Duration::from_millis(50)).await;
            return Err(CamelError::RouteError("first run crash".into()));
        }
        ctx.cancelled().await;
        Ok(())
    }

    async fn stop(&mut self) -> Result<(), CamelError> {
        Ok(())
    }

    fn concurrency_model(&self) -> ConcurrencyModel {
        ConcurrencyModel::Sequential
    }
}

struct CrashOnceThenHoldEndpoint {
    starts: Arc<AtomicU32>,
}

impl Endpoint for CrashOnceThenHoldEndpoint {
    fn uri(&self) -> &str {
        "crash-once-hold:test"
    }

    fn create_consumer(&self) -> Result<Box<dyn Consumer>, CamelError> {
        Ok(Box::new(CrashOnceThenHoldConsumer {
            starts: Arc::clone(&self.starts),
        }))
    }

    fn create_producer(
        &self,
        _ctx: &camel_api::ProducerContext,
    ) -> Result<camel_api::BoxProcessor, CamelError> {
        Err(CamelError::RouteError("no producer".into()))
    }
}

struct CrashOnceThenHoldComponent {
    starts: Arc<AtomicU32>,
}

impl Component for CrashOnceThenHoldComponent {
    fn scheme(&self) -> &str {
        "crash-once-hold"
    }

    fn create_endpoint(
        &self,
        _uri: &str,
        _ctx: &dyn camel_component_api::ComponentContext,
    ) -> Result<Box<dyn Endpoint>, CamelError> {
        Ok(Box::new(CrashOnceThenHoldEndpoint {
            starts: Arc::clone(&self.starts),
        }))
    }
}

#[tokio::test]
async fn consumer_crash_updates_runtime_projection_to_failed() {
    let mut ctx = CamelContext::builder().build().await.unwrap();
    ctx.register_component(CrashingComponent);
    let runtime = ctx.runtime();

    runtime
        .execute(RuntimeCommand::RegisterRoute {
            spec: CanonicalRouteSpec::new("crash-sync-r1", "crash:test"),
            command_id: "c-register".into(),
            causation_id: None,
        })
        .await
        .unwrap();

    runtime
        .execute(RuntimeCommand::StartRoute {
            route_id: "crash-sync-r1".into(),
            command_id: "c-start".into(),
            causation_id: Some("c-register".into()),
        })
        .await
        .unwrap();

    tokio::time::sleep(std::time::Duration::from_millis(200)).await;

    let out = runtime
        .ask(RuntimeQuery::GetRouteStatus {
            route_id: "crash-sync-r1".into(),
        })
        .await
        .unwrap();

    match out {
        RuntimeQueryResult::RouteStatus { status, .. } => {
            assert_eq!(status, "Failed");
        }
        other => panic!("unexpected query result: {other:?}"),
    }
}

#[tokio::test]
async fn supervision_restart_reflects_crash_recovery_progress_in_runtime_projection() {
    let starts = Arc::new(AtomicU32::new(0));
    let mut ctx = CamelContext::builder()
        .supervision(SupervisionConfig {
            max_attempts: Some(5),
            initial_delay: Duration::from_millis(30),
            backoff_multiplier: 1.0,
            max_delay: Duration::from_secs(1),
        })
        .build()
        .await
        .unwrap();
    ctx.register_component(CrashOnceThenHoldComponent {
        starts: Arc::clone(&starts),
    });
    ctx.add_route_definition(
        RouteDefinition::new("crash-once-hold:test", vec![]).with_route_id("supervised-r1"),
    )
    .await
    .unwrap();
    ctx.start().await.unwrap();

    let deadline = Instant::now() + Duration::from_secs(2);
    loop {
        let status = match ctx
            .runtime()
            .ask(RuntimeQuery::GetRouteStatus {
                route_id: "supervised-r1".into(),
            })
            .await
            .unwrap()
        {
            RuntimeQueryResult::RouteStatus { status, .. } => status,
            other => panic!("unexpected query result: {other:?}"),
        };

        if starts.load(Ordering::SeqCst) >= 2 {
            assert!(
                status == "Started" || status == "Failed",
                "unexpected runtime projection status after supervised restart attempt: {status}"
            );
            break;
        }

        assert!(
            Instant::now() <= deadline,
            "expected supervised route to perform a restart attempt; last status={status}, starts={}",
            starts.load(Ordering::SeqCst)
        );

        tokio::time::sleep(Duration::from_millis(25)).await;
    }

    ctx.stop().await.unwrap();
}

#[tokio::test]
async fn supervision_respects_runtime_stopped_state_and_skips_restart() {
    let starts = Arc::new(AtomicU32::new(0));
    let mut ctx = CamelContext::builder()
        .supervision(SupervisionConfig {
            max_attempts: Some(5),
            initial_delay: Duration::from_millis(200),
            backoff_multiplier: 1.0,
            max_delay: Duration::from_secs(1),
        })
        .build()
        .await
        .unwrap();
    ctx.register_component(CrashOnceThenHoldComponent {
        starts: Arc::clone(&starts),
    });
    ctx.add_route_definition(
        RouteDefinition::new("crash-once-hold:test", vec![]).with_route_id("supervised-stop-r1"),
    )
    .await
    .unwrap();
    ctx.start().await.unwrap();

    let fail_deadline = Instant::now() + Duration::from_secs(2);
    loop {
        let status = match ctx
            .runtime()
            .ask(RuntimeQuery::GetRouteStatus {
                route_id: "supervised-stop-r1".into(),
            })
            .await
            .unwrap()
        {
            RuntimeQueryResult::RouteStatus { status, .. } => status,
            other => panic!("unexpected query result: {other:?}"),
        };

        if status == "Failed" {
            break;
        }

        assert!(
            Instant::now() <= fail_deadline,
            "expected route to crash into Failed state before manual stop; last status={status}"
        );
        tokio::time::sleep(Duration::from_millis(20)).await;
    }

    ctx.runtime()
        .execute(RuntimeCommand::StopRoute {
            route_id: "supervised-stop-r1".into(),
            command_id: "manual-stop-after-crash".into(),
            causation_id: None,
        })
        .await
        .unwrap();

    tokio::time::sleep(Duration::from_millis(350)).await;

    let status = match ctx
        .runtime()
        .ask(RuntimeQuery::GetRouteStatus {
            route_id: "supervised-stop-r1".into(),
        })
        .await
        .unwrap()
    {
        RuntimeQueryResult::RouteStatus { status, .. } => status,
        other => panic!("unexpected query result: {other:?}"),
    };
    assert_eq!(status, "Stopped");

    let starts_after_stop = starts.load(Ordering::SeqCst);
    tokio::time::sleep(Duration::from_millis(300)).await;
    assert_eq!(
        starts.load(Ordering::SeqCst),
        starts_after_stop,
        "supervision must stop issuing restart attempts once runtime state is Stopped"
    );

    ctx.stop().await.unwrap();
}