1use async_trait::async_trait;
2use serde::{Deserialize, Serialize};
3
4use crate::CamelError;
5use crate::declarative::LanguageExpressionDef;
6use crate::splitter::StreamSplitConfig;
7
8pub const CANONICAL_CONTRACT_NAME: &str = "canonical-v1";
9pub const CANONICAL_CONTRACT_VERSION: u32 = 2;
10pub const CANONICAL_CONTRACT_SUPPORTED_STEPS: &[&str] = &[
11 "to",
12 "log",
13 "wire_tap",
14 "script",
15 "filter",
16 "choice",
17 "split",
18 "aggregate",
19 "stop",
20 "delay",
21 "cache",
22 "cache_invalidate",
23 "cache_peek_stale",
24];
25pub const CANONICAL_CONTRACT_DECLARATIVE_ONLY_STEPS: &[&str] =
26 &["script", "filter", "choice", "split"];
27pub const CANONICAL_CONTRACT_EXCLUDED_DECLARATIVE_STEPS: &[&str] = &[
28 "set_header",
29 "set_property",
30 "set_body",
31 "multicast",
32 "convert_body_to",
33 "bean",
34 "marshal",
35 "unmarshal",
36];
37pub const CANONICAL_CONTRACT_RUST_ONLY_STEPS: &[&str] = &[
38 "processor",
39 "process",
40 "process_fn",
41 "map_body",
42 "set_body_fn",
43 "set_header_fn",
44];
45
46pub fn canonical_contract_supports_step(step: &str) -> bool {
47 CANONICAL_CONTRACT_SUPPORTED_STEPS.contains(&step)
48}
49
50pub fn canonical_contract_rejection_reason(step: &str) -> Option<&'static str> {
51 if CANONICAL_CONTRACT_EXCLUDED_DECLARATIVE_STEPS.contains(&step) {
52 return Some(
53 "declared out-of-scope for canonical v2; use declarative route compilation path outside CQRS canonical commands",
54 );
55 }
56
57 if CANONICAL_CONTRACT_RUST_ONLY_STEPS.contains(&step) {
58 return Some("rust-only programmable step; not representable in canonical v2 contract");
59 }
60
61 if canonical_contract_supports_step(step)
62 && CANONICAL_CONTRACT_DECLARATIVE_ONLY_STEPS.contains(&step)
63 {
64 return Some(
65 "supported only as declarative/serializable expression form; closure/processor variants are outside canonical v2",
66 );
67 }
68
69 None
70}
71
72#[derive(
73 Debug,
74 Clone,
75 PartialEq,
76 Eq,
77 serde::Serialize,
78 serde::Deserialize,
79 schemars::JsonSchema,
80 ts_rs::TS,
81)]
82#[serde(rename_all = "snake_case")]
83#[ts(rename_all = "snake_case")]
84pub struct CanonicalRouteSpec {
85 pub route_id: String,
95 pub from: String,
96 pub steps: Vec<CanonicalStepSpec>,
97 pub circuit_breaker: Option<CanonicalCircuitBreakerSpec>,
98 pub auto_startup: Option<bool>,
99 pub startup_order: Option<i32>,
100 pub concurrency: Option<CanonicalConcurrencySpec>,
101 pub version: u32,
102}
103
104#[derive(
105 Debug,
106 Clone,
107 PartialEq,
108 Eq,
109 serde::Serialize,
110 serde::Deserialize,
111 schemars::JsonSchema,
112 ts_rs::TS,
113)]
114#[serde(tag = "step", content = "config", rename_all = "snake_case")]
115#[ts(rename_all = "snake_case")]
116#[non_exhaustive]
117pub enum CanonicalStepSpec {
118 To {
119 uri: String,
120 },
121 Log {
122 message: String,
123 },
124 WireTap {
125 uri: String,
126 },
127 Script {
128 expression: LanguageExpressionDef,
129 },
130 Filter {
131 predicate: LanguageExpressionDef,
132 steps: Vec<CanonicalStepSpec>,
133 },
134 Choice {
135 whens: Vec<CanonicalWhenSpec>,
136 otherwise: Option<Vec<CanonicalStepSpec>>,
137 },
138 Split {
139 expression: CanonicalSplitExpressionSpec,
140 aggregation: CanonicalSplitAggregationSpec,
141 parallel: bool,
142 parallel_limit: Option<usize>,
143 stop_on_exception: bool,
144 steps: Vec<CanonicalStepSpec>,
145 },
146 Aggregate(CanonicalAggregateSpec),
147 Stop,
148 Delay {
149 #[ts(type = "number")]
150 delay_ms: u64,
151 dynamic_header: Option<String>,
152 },
153 Cache {
154 repository: Option<String>,
155 key: String,
156 ttl: Option<String>,
157 max_entry_bytes: Option<usize>,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
161 coalesce_misses: Option<bool>,
162 on_miss: Vec<CanonicalStepSpec>,
163 },
164 CacheInvalidate {
165 repository: Option<String>,
166 #[serde(default, skip_serializing_if = "Option::is_none")]
168 key: Option<String>,
169 #[serde(default, skip_serializing_if = "Option::is_none")]
171 key_prefix: Option<String>,
172 },
173 CacheClear {
174 repository: Option<String>,
175 },
176 CacheStats {
177 repository: Option<String>,
178 },
179 CachePeekStale {
180 repository: Option<String>,
181 key: String,
182 #[serde(default, skip_serializing_if = "Option::is_none")]
184 on_miss: Option<String>,
185 },
186}
187
188#[derive(
189 Debug,
190 Clone,
191 PartialEq,
192 Eq,
193 serde::Serialize,
194 serde::Deserialize,
195 schemars::JsonSchema,
196 ts_rs::TS,
197)]
198#[serde(rename_all = "snake_case")]
199#[ts(rename_all = "snake_case")]
200pub struct CanonicalWhenSpec {
201 pub predicate: LanguageExpressionDef,
202 pub steps: Vec<CanonicalStepSpec>,
203}
204
205#[derive(
206 Debug,
207 Clone,
208 PartialEq,
209 Eq,
210 serde::Serialize,
211 serde::Deserialize,
212 schemars::JsonSchema,
213 ts_rs::TS,
214)]
215#[serde(rename_all = "snake_case")]
216#[ts(rename_all = "snake_case")]
217#[non_exhaustive]
218pub enum CanonicalSplitExpressionSpec {
219 BodyLines,
220 BodyJsonArray,
221 Language(LanguageExpressionDef),
222 Stream(StreamSplitConfig),
223}
224
225#[derive(
226 Debug,
227 Clone,
228 PartialEq,
229 Eq,
230 serde::Serialize,
231 serde::Deserialize,
232 schemars::JsonSchema,
233 ts_rs::TS,
234)]
235#[serde(rename_all = "snake_case")]
236#[ts(rename_all = "snake_case")]
237#[non_exhaustive]
238pub enum CanonicalSplitAggregationSpec {
239 LastWins,
240 CollectAll,
241 Original,
242}
243
244#[derive(
245 Debug,
246 Clone,
247 PartialEq,
248 Eq,
249 serde::Serialize,
250 serde::Deserialize,
251 schemars::JsonSchema,
252 ts_rs::TS,
253)]
254#[serde(rename_all = "snake_case")]
255#[ts(rename_all = "snake_case")]
256#[non_exhaustive]
257pub enum CanonicalAggregateStrategySpec {
258 CollectAll,
259}
260
261#[derive(
262 Debug,
263 Clone,
264 PartialEq,
265 Eq,
266 serde::Serialize,
267 serde::Deserialize,
268 schemars::JsonSchema,
269 ts_rs::TS,
270)]
271#[serde(rename_all = "snake_case")]
272#[ts(rename_all = "snake_case")]
273pub struct CanonicalAggregateSpec {
274 pub header: String,
275 pub completion_size: Option<usize>,
276 #[ts(type = "number")]
277 pub completion_timeout_ms: Option<u64>,
278 pub correlation_key: Option<String>,
279 pub force_completion_on_stop: Option<bool>,
280 pub discard_on_timeout: Option<bool>,
281 pub strategy: CanonicalAggregateStrategySpec,
282 pub max_buckets: Option<usize>,
283 #[serde(default)]
286 pub max_bucket_size: Option<usize>,
287 #[ts(type = "number")]
288 pub bucket_ttl_ms: Option<u64>,
289 #[serde(default)]
293 pub completion_predicate: Option<LanguageExpressionDef>,
294}
295
296#[derive(
297 Debug,
298 Clone,
299 PartialEq,
300 Eq,
301 serde::Serialize,
302 serde::Deserialize,
303 schemars::JsonSchema,
304 ts_rs::TS,
305)]
306#[serde(rename_all = "snake_case")]
307#[ts(rename_all = "snake_case")]
308pub struct CanonicalCircuitBreakerSpec {
309 pub failure_threshold: u32,
310 #[ts(type = "number")]
311 pub open_duration_ms: u64,
312 #[serde(default, skip_serializing_if = "Vec::is_empty")]
313 pub fallback: Vec<CanonicalStepSpec>,
314}
315
316#[derive(
317 Debug,
318 Clone,
319 PartialEq,
320 Eq,
321 serde::Serialize,
322 serde::Deserialize,
323 schemars::JsonSchema,
324 ts_rs::TS,
325)]
326#[serde(tag = "mode", rename_all = "snake_case")]
327#[non_exhaustive]
328pub enum CanonicalConcurrencySpec {
329 Sequential,
330 Concurrent { max: usize },
331}
332
333impl CanonicalRouteSpec {
334 pub fn new(route_id: impl Into<String>, from: impl Into<String>) -> Self {
335 Self {
336 route_id: route_id.into(),
337 from: from.into(),
338 steps: Vec::new(),
339 circuit_breaker: None,
340 auto_startup: None,
341 startup_order: None,
342 concurrency: None,
343 version: CANONICAL_CONTRACT_VERSION,
344 }
345 }
346
347 pub fn with_auto_startup(mut self, auto: bool) -> Self {
348 self.auto_startup = Some(auto);
349 self
350 }
351
352 pub fn with_startup_order(mut self, order: i32) -> Self {
353 self.startup_order = Some(order);
354 self
355 }
356
357 pub fn with_concurrency(mut self, concurrency: CanonicalConcurrencySpec) -> Self {
358 self.concurrency = Some(concurrency);
359 self
360 }
361
362 pub fn validate_contract(&self) -> Result<(), CamelError> {
363 if self.route_id.trim().is_empty() {
364 return Err(CamelError::RouteError(
365 "canonical contract violation: route_id cannot be empty".to_string(),
366 ));
367 }
368 if self.from.trim().is_empty() {
369 return Err(CamelError::RouteError(
370 "canonical contract violation: from cannot be empty".to_string(),
371 ));
372 }
373 if self.version == 0 || self.version > CANONICAL_CONTRACT_VERSION {
374 return Err(CamelError::RouteError(format!(
375 "canonical contract violation: expected version {}, got {}",
376 CANONICAL_CONTRACT_VERSION, self.version
377 )));
378 }
379 validate_steps(&self.steps)?;
380 if let Some(cb) = &self.circuit_breaker {
381 if cb.failure_threshold == 0 {
382 return Err(CamelError::RouteError(
383 "canonical contract violation: circuit_breaker.failure_threshold must be > 0"
384 .to_string(),
385 ));
386 }
387 if cb.open_duration_ms == 0 {
388 return Err(CamelError::RouteError(
389 "canonical contract violation: circuit_breaker.open_duration_ms must be > 0"
390 .to_string(),
391 ));
392 }
393 validate_steps(&cb.fallback)?;
394 }
395 if let Some(CanonicalConcurrencySpec::Concurrent { max: 0 }) = &self.concurrency {
396 return Err(CamelError::RouteError(
397 "canonical contract violation: concurrency max must be > 0".to_string(),
398 ));
399 }
400 Ok(())
401 }
402}
403
404#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
405pub struct CanonicalFieldLoss {
406 pub field: &'static str,
407 pub reason: String,
408 pub target_version: u32,
409}
410
411#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize)]
412pub struct CanonicalLossReport {
413 pub dropped_fields: Vec<CanonicalFieldLoss>,
414}
415
416impl CanonicalLossReport {
417 pub fn from_field(field: &'static str, reason: &str, target_version: u32) -> Self {
418 Self {
419 dropped_fields: vec![CanonicalFieldLoss {
420 field,
421 reason: reason.to_string(),
422 target_version,
423 }],
424 }
425 }
426
427 pub fn is_empty(&self) -> bool {
428 self.dropped_fields.is_empty()
429 }
430}
431
432fn validate_steps(steps: &[CanonicalStepSpec]) -> Result<(), CamelError> {
433 for step in steps {
434 match step {
435 CanonicalStepSpec::To { uri } | CanonicalStepSpec::WireTap { uri } => {
436 if uri.trim().is_empty() {
437 return Err(CamelError::RouteError(
438 "canonical contract violation: endpoint uri cannot be empty".to_string(),
439 ));
440 }
441 }
442 CanonicalStepSpec::Filter { steps, .. } => validate_steps(steps)?,
443 CanonicalStepSpec::Choice { whens, otherwise } => {
444 for when in whens {
445 validate_steps(&when.steps)?;
446 }
447 if let Some(otherwise) = otherwise {
448 validate_steps(otherwise)?;
449 }
450 }
451 CanonicalStepSpec::Split {
452 parallel_limit,
453 steps,
454 ..
455 } => {
456 if let Some(limit) = parallel_limit
457 && *limit == 0
458 {
459 return Err(CamelError::RouteError(
460 "canonical contract violation: split.parallel_limit must be > 0"
461 .to_string(),
462 ));
463 }
464 validate_steps(steps)?;
465 }
466 CanonicalStepSpec::Aggregate(config) => {
467 if config.header.trim().is_empty() {
468 return Err(CamelError::RouteError(
469 "canonical contract violation: aggregate.header cannot be empty"
470 .to_string(),
471 ));
472 }
473 if let Some(size) = config.completion_size
474 && size == 0
475 {
476 return Err(CamelError::RouteError(
477 "canonical contract violation: aggregate.completion_size must be > 0"
478 .to_string(),
479 ));
480 }
481 }
482 CanonicalStepSpec::Cache { on_miss, .. } => {
483 validate_steps(on_miss)?;
484 }
485 CanonicalStepSpec::Log { .. }
486 | CanonicalStepSpec::Script { .. }
487 | CanonicalStepSpec::Stop
488 | CanonicalStepSpec::Delay { .. }
489 | CanonicalStepSpec::CacheInvalidate { .. }
490 | CanonicalStepSpec::CacheClear { .. }
491 | CanonicalStepSpec::CacheStats { .. }
492 | CanonicalStepSpec::CachePeekStale { .. } => {}
493 }
494 }
495 Ok(())
496}
497
498#[derive(Debug, Clone, PartialEq, Eq)]
499#[non_exhaustive]
500pub enum RuntimeCommand {
501 RegisterRoute {
502 spec: CanonicalRouteSpec,
503 command_id: String,
504 causation_id: Option<String>,
505 },
506 StartRoute {
507 route_id: String,
508 command_id: String,
509 causation_id: Option<String>,
510 },
511 StopRoute {
512 route_id: String,
513 command_id: String,
514 causation_id: Option<String>,
515 },
516 SuspendRoute {
517 route_id: String,
518 command_id: String,
519 causation_id: Option<String>,
520 },
521 ResumeRoute {
522 route_id: String,
523 command_id: String,
524 causation_id: Option<String>,
525 },
526 ReloadRoute {
527 route_id: String,
528 command_id: String,
529 causation_id: Option<String>,
530 },
531 FailRoute {
535 route_id: String,
536 error: String,
537 command_id: String,
538 causation_id: Option<String>,
539 },
540 RemoveRoute {
541 route_id: String,
542 command_id: String,
543 causation_id: Option<String>,
544 },
545 ReloadTlsCerts {
546 scheme: String,
547 host: String,
548 port: u16,
549 command_id: String,
550 causation_id: Option<String>,
551 },
552 ReloadTemplates {
559 route_id: String,
560 command_id: String,
561 causation_id: Option<String>,
562 },
563}
564
565impl RuntimeCommand {
566 pub fn command_id(&self) -> &str {
567 match self {
568 RuntimeCommand::RegisterRoute { command_id, .. }
569 | RuntimeCommand::StartRoute { command_id, .. }
570 | RuntimeCommand::StopRoute { command_id, .. }
571 | RuntimeCommand::SuspendRoute { command_id, .. }
572 | RuntimeCommand::ResumeRoute { command_id, .. }
573 | RuntimeCommand::ReloadRoute { command_id, .. }
574 | RuntimeCommand::FailRoute { command_id, .. }
575 | RuntimeCommand::RemoveRoute { command_id, .. }
576 | RuntimeCommand::ReloadTlsCerts { command_id, .. }
577 | RuntimeCommand::ReloadTemplates { command_id, .. } => command_id,
578 }
579 }
580
581 pub fn causation_id(&self) -> Option<&str> {
582 match self {
583 RuntimeCommand::RegisterRoute { causation_id, .. }
584 | RuntimeCommand::StartRoute { causation_id, .. }
585 | RuntimeCommand::StopRoute { causation_id, .. }
586 | RuntimeCommand::SuspendRoute { causation_id, .. }
587 | RuntimeCommand::ResumeRoute { causation_id, .. }
588 | RuntimeCommand::ReloadRoute { causation_id, .. }
589 | RuntimeCommand::FailRoute { causation_id, .. }
590 | RuntimeCommand::RemoveRoute { causation_id, .. }
591 | RuntimeCommand::ReloadTlsCerts { causation_id, .. }
592 | RuntimeCommand::ReloadTemplates { causation_id, .. } => causation_id.as_deref(),
593 }
594 }
595}
596
597#[derive(Debug, Clone, PartialEq, Eq)]
598#[non_exhaustive]
599pub enum RuntimeCommandResult {
600 Accepted,
601 Duplicate {
602 command_id: String,
603 },
604 RouteRegistered {
605 route_id: String,
606 },
607 RouteStateChanged {
608 route_id: String,
609 status: String,
610 },
611 TlsCertsReloaded {
612 scheme: String,
613 host: String,
614 port: u16,
615 },
616 TemplatesReloaded {
617 route_id: String,
618 },
619}
620
621#[derive(Debug, Clone, PartialEq, Eq)]
622#[non_exhaustive]
623pub enum RuntimeQuery {
624 GetRouteStatus {
625 route_id: String,
626 },
627 InFlightCount {
631 route_id: String,
632 },
633 ListRoutes,
634}
635
636#[derive(Debug, Clone, PartialEq, Eq)]
637#[non_exhaustive]
638pub enum RuntimeQueryResult {
639 InFlightCount { route_id: String, count: u64 },
640 RouteNotFound { route_id: String },
641 RouteStatus { route_id: String, status: String },
642 Routes { route_ids: Vec<String> },
643}
644
645#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
646#[non_exhaustive]
647pub enum RuntimeEvent {
648 RouteRegistered { route_id: String },
649 RouteStartRequested { route_id: String },
650 RouteStarted { route_id: String },
651 RouteFailed { route_id: String, error: String },
652 RouteStopped { route_id: String },
653 RouteSuspended { route_id: String },
654 RouteResumed { route_id: String },
655 RouteReloaded { route_id: String },
656 RouteRemoved { route_id: String },
657}
658
659#[async_trait]
660pub trait RuntimeCommandBus: Send + Sync {
661 async fn execute(&self, cmd: RuntimeCommand) -> Result<RuntimeCommandResult, CamelError>;
662}
663
664#[async_trait]
665pub trait RuntimeQueryBus: Send + Sync {
666 async fn ask(&self, query: RuntimeQuery) -> Result<RuntimeQueryResult, CamelError>;
667}
668
669pub trait RuntimeHandle: RuntimeCommandBus + RuntimeQueryBus {}
670
671impl<T> RuntimeHandle for T where T: RuntimeCommandBus + RuntimeQueryBus {}
672
673#[cfg(test)]
674mod tests {
675 use super::*;
676 use async_trait::async_trait;
677 use futures::executor::block_on;
678
679 struct NoopRuntime;
680
681 #[async_trait]
682 impl RuntimeCommandBus for NoopRuntime {
683 async fn execute(&self, cmd: RuntimeCommand) -> Result<RuntimeCommandResult, CamelError> {
684 Ok(match cmd {
685 RuntimeCommand::RegisterRoute { spec, .. } => {
686 RuntimeCommandResult::RouteRegistered {
687 route_id: spec.route_id,
688 }
689 }
690 RuntimeCommand::StartRoute { route_id, .. }
691 | RuntimeCommand::StopRoute { route_id, .. }
692 | RuntimeCommand::SuspendRoute { route_id, .. }
693 | RuntimeCommand::ResumeRoute { route_id, .. }
694 | RuntimeCommand::ReloadRoute { route_id, .. }
695 | RuntimeCommand::FailRoute { route_id, .. }
696 | RuntimeCommand::RemoveRoute { route_id, .. } => {
697 RuntimeCommandResult::RouteStateChanged {
698 route_id,
699 status: "ok".to_string(),
700 }
701 }
702 RuntimeCommand::ReloadTlsCerts {
703 scheme, host, port, ..
704 } => RuntimeCommandResult::TlsCertsReloaded { scheme, host, port },
705 RuntimeCommand::ReloadTemplates { route_id, .. } => {
706 RuntimeCommandResult::TemplatesReloaded { route_id }
707 }
708 })
709 }
710 }
711
712 #[async_trait]
713 impl RuntimeQueryBus for NoopRuntime {
714 async fn ask(&self, query: RuntimeQuery) -> Result<RuntimeQueryResult, CamelError> {
715 Ok(match query {
716 RuntimeQuery::GetRouteStatus { route_id } => RuntimeQueryResult::RouteStatus {
717 route_id,
718 status: "Started".to_string(),
719 },
720 RuntimeQuery::InFlightCount { route_id } => {
721 RuntimeQueryResult::InFlightCount { route_id, count: 0 }
722 }
723 RuntimeQuery::ListRoutes => RuntimeQueryResult::Routes {
724 route_ids: vec!["r1".to_string()],
725 },
726 })
727 }
728 }
729
730 #[test]
731 fn command_and_query_ids_are_exposed() {
732 let cmd = RuntimeCommand::StartRoute {
733 route_id: "r1".into(),
734 command_id: "c1".into(),
735 causation_id: None,
736 };
737 assert_eq!(cmd.command_id(), "c1");
738 }
739
740 #[test]
741 fn canonical_spec_requires_route_id_and_from() {
742 let spec = CanonicalRouteSpec::new("r1", "timer:tick");
743 assert_eq!(spec.route_id, "r1");
744 assert_eq!(spec.from, "timer:tick");
745 assert_eq!(spec.version, CANONICAL_CONTRACT_VERSION);
746 assert!(spec.steps.is_empty());
747 assert!(spec.circuit_breaker.is_none());
748 }
749
750 #[test]
751 fn canonical_contract_rejects_invalid_version() {
752 let mut spec = CanonicalRouteSpec::new("r1", "timer:tick");
753 spec.version = 3;
754 let err = spec.validate_contract().unwrap_err().to_string();
755 assert!(err.contains("expected version"));
756 }
757
758 #[test]
759 fn canonical_contract_declares_subset_scope() {
760 assert!(canonical_contract_supports_step("to"));
761 assert!(canonical_contract_supports_step("split"));
762 assert!(!canonical_contract_supports_step("set_header"));
763 assert!(!canonical_contract_supports_step("set_property"));
764
765 assert!(CANONICAL_CONTRACT_DECLARATIVE_ONLY_STEPS.contains(&"split"));
766 assert!(CANONICAL_CONTRACT_EXCLUDED_DECLARATIVE_STEPS.contains(&"set_header"));
767 assert!(CANONICAL_CONTRACT_EXCLUDED_DECLARATIVE_STEPS.contains(&"set_property"));
768 assert!(CANONICAL_CONTRACT_RUST_ONLY_STEPS.contains(&"processor"));
769 }
770
771 #[test]
772 fn canonical_contract_rejection_reason_is_explicit() {
773 let set_header_reason = canonical_contract_rejection_reason("set_header")
774 .expect("set_header should have explicit reason");
775 assert!(set_header_reason.contains("out-of-scope"));
776
777 let set_property_reason = canonical_contract_rejection_reason("set_property")
778 .expect("set_property should have explicit reason");
779 assert!(set_property_reason.contains("out-of-scope"));
780
781 let processor_reason = canonical_contract_rejection_reason("processor")
782 .expect("processor should be rust-only");
783 assert!(processor_reason.contains("rust-only"));
784
785 let split_reason = canonical_contract_rejection_reason("split")
786 .expect("split should require declarative form");
787 assert!(split_reason.contains("declarative"));
788 }
789
790 #[test]
791 fn command_causation_id_is_exposed() {
792 let cmd = RuntimeCommand::StopRoute {
793 route_id: "r1".into(),
794 command_id: "c2".into(),
795 causation_id: Some("c1".into()),
796 };
797 assert_eq!(cmd.command_id(), "c2");
798 assert_eq!(cmd.causation_id(), Some("c1"));
799 }
800
801 #[test]
802 fn canonical_contract_rejects_empty_route_id_and_from() {
803 let spec = CanonicalRouteSpec::new(" ", "timer:tick");
804 let err = spec.validate_contract().unwrap_err().to_string();
805 assert!(err.contains("route_id cannot be empty"));
806
807 let spec = CanonicalRouteSpec::new("r1", " ");
808 let err = spec.validate_contract().unwrap_err().to_string();
809 assert!(err.contains("from cannot be empty"));
810 }
811
812 #[test]
813 fn canonical_contract_rejects_invalid_nested_steps() {
814 let mut spec = CanonicalRouteSpec::new("r1", "timer:tick");
815 spec.steps = vec![CanonicalStepSpec::Split {
816 expression: CanonicalSplitExpressionSpec::BodyLines,
817 aggregation: CanonicalSplitAggregationSpec::CollectAll,
818 parallel: true,
819 parallel_limit: Some(0),
820 stop_on_exception: false,
821 steps: vec![CanonicalStepSpec::To {
822 uri: "log:ok".to_string(),
823 }],
824 }];
825 let err = spec.validate_contract().unwrap_err().to_string();
826 assert!(err.contains("split.parallel_limit must be > 0"));
827
828 spec.steps = vec![CanonicalStepSpec::To {
829 uri: " ".to_string(),
830 }];
831 let err = spec.validate_contract().unwrap_err().to_string();
832 assert!(err.contains("endpoint uri cannot be empty"));
833 }
834
835 #[test]
836 fn canonical_contract_rejects_invalid_aggregate_and_circuit_breaker() {
837 let mut spec = CanonicalRouteSpec::new("r1", "timer:tick");
838 spec.steps = vec![CanonicalStepSpec::Aggregate(CanonicalAggregateSpec {
839 header: " ".to_string(),
840 completion_size: Some(1),
841 completion_timeout_ms: None,
842 correlation_key: None,
843 force_completion_on_stop: None,
844 discard_on_timeout: None,
845 strategy: CanonicalAggregateStrategySpec::CollectAll,
846 max_buckets: None,
847 max_bucket_size: None,
848 bucket_ttl_ms: None,
849 completion_predicate: None,
850 })];
851 let err = spec.validate_contract().unwrap_err().to_string();
852 assert!(err.contains("aggregate.header cannot be empty"));
853
854 spec.steps = vec![CanonicalStepSpec::Aggregate(CanonicalAggregateSpec {
855 header: "k".to_string(),
856 completion_size: Some(0),
857 completion_timeout_ms: None,
858 correlation_key: None,
859 force_completion_on_stop: None,
860 discard_on_timeout: None,
861 strategy: CanonicalAggregateStrategySpec::CollectAll,
862 max_buckets: None,
863 max_bucket_size: None,
864 bucket_ttl_ms: None,
865 completion_predicate: None,
866 })];
867 let err = spec.validate_contract().unwrap_err().to_string();
868 assert!(err.contains("aggregate.completion_size must be > 0"));
869
870 spec.steps = vec![];
871 spec.circuit_breaker = Some(CanonicalCircuitBreakerSpec {
872 failure_threshold: 0,
873 open_duration_ms: 10,
874 fallback: vec![],
875 });
876 let err = spec.validate_contract().unwrap_err().to_string();
877 assert!(err.contains("failure_threshold must be > 0"));
878
879 spec.circuit_breaker = Some(CanonicalCircuitBreakerSpec {
880 failure_threshold: 1,
881 open_duration_ms: 0,
882 fallback: vec![],
883 });
884 let err = spec.validate_contract().unwrap_err().to_string();
885 assert!(err.contains("open_duration_ms must be > 0"));
886 }
887
888 #[test]
889 fn canonical_contract_rejects_invalid_fallback_step() {
890 let mut spec = CanonicalRouteSpec::new("r1", "timer:tick");
891 spec.circuit_breaker = Some(CanonicalCircuitBreakerSpec {
892 failure_threshold: 1,
893 open_duration_ms: 10,
894 fallback: vec![CanonicalStepSpec::To {
895 uri: " ".to_string(),
896 }],
897 });
898 let err = spec.validate_contract().unwrap_err().to_string();
899 assert!(err.contains("endpoint uri cannot be empty"));
900 }
901
902 #[test]
903 fn canonical_contract_rejection_reason_none_for_regular_steps() {
904 assert!(canonical_contract_rejection_reason("to").is_none());
905 assert!(canonical_contract_rejection_reason("unknown-step").is_none());
906 }
907
908 #[test]
909 fn command_helpers_cover_all_variants() {
910 let spec = CanonicalRouteSpec::new("r1", "timer:tick");
911 let cmds = [
912 RuntimeCommand::RegisterRoute {
913 spec,
914 command_id: "c1".into(),
915 causation_id: Some("root".into()),
916 },
917 RuntimeCommand::StartRoute {
918 route_id: "r1".into(),
919 command_id: "c2".into(),
920 causation_id: None,
921 },
922 RuntimeCommand::StopRoute {
923 route_id: "r1".into(),
924 command_id: "c3".into(),
925 causation_id: None,
926 },
927 RuntimeCommand::SuspendRoute {
928 route_id: "r1".into(),
929 command_id: "c4".into(),
930 causation_id: None,
931 },
932 RuntimeCommand::ResumeRoute {
933 route_id: "r1".into(),
934 command_id: "c5".into(),
935 causation_id: None,
936 },
937 RuntimeCommand::ReloadRoute {
938 route_id: "r1".into(),
939 command_id: "c6".into(),
940 causation_id: None,
941 },
942 RuntimeCommand::FailRoute {
943 route_id: "r1".into(),
944 error: "boom".into(),
945 command_id: "c7".into(),
946 causation_id: None,
947 },
948 RuntimeCommand::RemoveRoute {
949 route_id: "r1".into(),
950 command_id: "c8".into(),
951 causation_id: None,
952 },
953 RuntimeCommand::ReloadTlsCerts {
954 scheme: "https".into(),
955 host: "example.com".into(),
956 port: 8443,
957 command_id: "c9".into(),
958 causation_id: None,
959 },
960 ];
961
962 let ids: Vec<&str> = cmds.iter().map(RuntimeCommand::command_id).collect();
963 assert_eq!(
964 ids,
965 vec!["c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9"]
966 );
967 assert_eq!(cmds[0].causation_id(), Some("root"));
968 assert_eq!(cmds[1].causation_id(), None);
969 }
970
971 #[test]
972 fn canonical_route_spec_serde_roundtrip() {
973 let mut spec = CanonicalRouteSpec::new("test-route", "timer:tick?period=1000");
974 spec.steps.push(CanonicalStepSpec::Log {
975 message: "Hello".into(),
976 });
977 spec.steps.push(CanonicalStepSpec::To {
978 uri: "log:info".into(),
979 });
980 spec.steps.push(CanonicalStepSpec::Stop);
981
982 let json = serde_json::to_string(&spec).unwrap();
983 let deserialized: CanonicalRouteSpec = serde_json::from_str(&json).unwrap();
984 assert_eq!(spec, deserialized);
985 }
986
987 #[test]
988 fn canonical_step_spec_serde_variants() {
989 let steps = vec![
990 CanonicalStepSpec::To {
991 uri: "direct:a".into(),
992 },
993 CanonicalStepSpec::Log {
994 message: "msg".into(),
995 },
996 CanonicalStepSpec::WireTap {
997 uri: "direct:audit".into(),
998 },
999 CanonicalStepSpec::Stop,
1000 CanonicalStepSpec::Delay {
1001 delay_ms: 100,
1002 dynamic_header: None,
1003 },
1004 ];
1005 let json = serde_json::to_string_pretty(&steps).unwrap();
1006 let back: Vec<CanonicalStepSpec> = serde_json::from_str(&json).unwrap();
1007 assert_eq!(steps, back);
1008 }
1009
1010 #[test]
1011 fn canonical_cache_peek_stale_on_miss_round_trip() {
1012 let some = CanonicalStepSpec::CachePeekStale {
1013 repository: None,
1014 key: "k".into(),
1015 on_miss: Some("continue".into()),
1016 };
1017 let json = serde_json::to_string(&some).unwrap();
1018 assert!(json.contains("continue"));
1019 let back: CanonicalStepSpec = serde_json::from_str(&json).unwrap();
1020 assert_eq!(some, back);
1021
1022 let none = CanonicalStepSpec::CachePeekStale {
1023 repository: None,
1024 key: "k".into(),
1025 on_miss: None,
1026 };
1027 let json = serde_json::to_string(&none).unwrap();
1028 assert!(
1029 !json.contains("on_miss"),
1030 "on_miss: None must omit the key from JSON, got: {json}"
1031 );
1032 let back: CanonicalStepSpec = serde_json::from_str(&json).unwrap();
1033 assert_eq!(none, back);
1034 }
1035
1036 #[test]
1037 fn canonical_cache_invalidate_prefix_round_trip() {
1038 let prefixed = CanonicalStepSpec::CacheInvalidate {
1039 repository: Some("persistent".into()),
1040 key: None,
1041 key_prefix: Some("ns:".into()),
1042 };
1043 let json = serde_json::to_string(&prefixed).unwrap();
1044 assert!(json.contains("key_prefix"), "must emit key_prefix: {json}");
1045 let back: CanonicalStepSpec = serde_json::from_str(&json).unwrap();
1046 assert_eq!(prefixed, back);
1047
1048 let legacy = r#"{"step":"cache_invalidate","config":{"repository":null,"key":"k"}}"#;
1051 let parsed: CanonicalStepSpec = serde_json::from_str(legacy).unwrap();
1052 assert_eq!(
1053 parsed,
1054 CanonicalStepSpec::CacheInvalidate {
1055 repository: None,
1056 key: Some("k".into()),
1057 key_prefix: None,
1058 }
1059 );
1060 }
1061
1062 #[test]
1063 fn canonical_cache_clear_stats_round_trip() {
1064 let clear = CanonicalStepSpec::CacheClear {
1065 repository: Some("persistent".into()),
1066 };
1067 let json = serde_json::to_string(&clear).unwrap();
1068 assert!(json.contains("cache_clear"));
1069 let back: CanonicalStepSpec = serde_json::from_str(&json).unwrap();
1070 assert_eq!(clear, back);
1071
1072 let stats = CanonicalStepSpec::CacheStats { repository: None };
1073 let json = serde_json::to_string(&stats).unwrap();
1074 assert!(json.contains("cache_stats"));
1075 let back: CanonicalStepSpec = serde_json::from_str(&json).unwrap();
1076 assert_eq!(stats, back);
1077 }
1078
1079 #[test]
1080 fn canonical_circuit_breaker_fallback_roundtrip() {
1081 let mut spec = CanonicalRouteSpec::new("cb-fallback", "direct:start");
1082 spec.circuit_breaker = Some(CanonicalCircuitBreakerSpec {
1083 failure_threshold: 1,
1084 open_duration_ms: 60000,
1085 fallback: vec![CanonicalStepSpec::CachePeekStale {
1086 repository: Some("persistent".into()),
1087 key: "tile-xyz".into(),
1088 on_miss: None,
1089 }],
1090 });
1091
1092 let json = serde_json::to_string(&spec).unwrap();
1093 let back: CanonicalRouteSpec = serde_json::from_str(&json).unwrap();
1094 assert_eq!(spec, back);
1095 assert_eq!(back.circuit_breaker.as_ref().unwrap().fallback.len(), 1);
1096
1097 let without = CanonicalCircuitBreakerSpec {
1099 failure_threshold: 1,
1100 open_duration_ms: 60000,
1101 fallback: vec![],
1102 };
1103 let json = serde_json::to_string(&without).unwrap();
1104 assert!(
1105 !json.contains("fallback"),
1106 "empty fallback must omit the key from JSON, got: {json}"
1107 );
1108 let back: CanonicalCircuitBreakerSpec = serde_json::from_str(&json).unwrap();
1109 assert!(back.fallback.is_empty());
1110 }
1111
1112 #[test]
1113 fn canonical_route_spec_json_schema_generates() {
1114 let schema = schemars::schema_for!(CanonicalRouteSpec);
1115 let json = serde_json::to_string(&schema).unwrap();
1116 assert!(json.contains("CanonicalRouteSpec"));
1117 assert!(json.contains("route_id"));
1118 }
1119
1120 #[test]
1121 fn canonical_json_schema_has_no_function_step() {
1122 let schema = schemars::schema_for!(CanonicalRouteSpec);
1123 let json = serde_json::to_string(&schema).unwrap();
1124 assert!(
1125 !json.contains("\"function\""),
1126 "canonical JSON schema must not contain 'function' step"
1127 );
1128 }
1129
1130 #[test]
1131 fn canonical_contract_does_not_support_function() {
1132 assert!(
1133 !canonical_contract_supports_step("function"),
1134 "function must not be in CANONICAL_CONTRACT_SUPPORTED_STEPS"
1135 );
1136 }
1137
1138 #[test]
1139 fn runtime_command_result_all_variants_are_distinct() {
1140 let accepted = RuntimeCommandResult::Accepted;
1141 let dup = RuntimeCommandResult::Duplicate {
1142 command_id: "c1".into(),
1143 };
1144 let registered = RuntimeCommandResult::RouteRegistered {
1145 route_id: "r1".into(),
1146 };
1147 let changed = RuntimeCommandResult::RouteStateChanged {
1148 route_id: "r1".into(),
1149 status: "Started".into(),
1150 };
1151
1152 assert_ne!(accepted, dup);
1153 assert_ne!(dup, registered);
1154 assert_ne!(registered, changed);
1155
1156 let dup2 = RuntimeCommandResult::Duplicate {
1157 command_id: "c1".into(),
1158 };
1159 assert_eq!(dup, dup2);
1160 }
1161
1162 #[test]
1163 fn runtime_event_serialization_round_trip() {
1164 let event = RuntimeEvent::RouteFailed {
1165 route_id: "route-a".to_string(),
1166 error: "boom".to_string(),
1167 };
1168 let json = serde_json::to_string(&event).unwrap();
1169 let back: RuntimeEvent = serde_json::from_str(&json).unwrap();
1170 assert_eq!(event, back);
1171 }
1172
1173 #[test]
1174 fn noop_runtime_execute_and_ask_return_expected_shapes() {
1175 let rt = NoopRuntime;
1176 let cmd = RuntimeCommand::RegisterRoute {
1177 spec: CanonicalRouteSpec::new("r2", "timer:tick"),
1178 command_id: "c1".into(),
1179 causation_id: None,
1180 };
1181 let cmd_result = block_on(rt.execute(cmd)).unwrap();
1182 assert_eq!(
1183 cmd_result,
1184 RuntimeCommandResult::RouteRegistered {
1185 route_id: "r2".into()
1186 }
1187 );
1188
1189 let query_result = block_on(rt.ask(RuntimeQuery::GetRouteStatus {
1190 route_id: "r2".into(),
1191 }))
1192 .unwrap();
1193 assert_eq!(
1194 query_result,
1195 RuntimeQueryResult::RouteStatus {
1196 route_id: "r2".into(),
1197 status: "Started".into()
1198 }
1199 );
1200 }
1201
1202 #[test]
1203 fn canonical_contract_name_and_version_constants_match() {
1204 assert_eq!(CANONICAL_CONTRACT_NAME, "canonical-v1");
1205 assert_eq!(CANONICAL_CONTRACT_VERSION, 2);
1206 }
1207
1208 #[test]
1209 fn canonical_concurrency_spec_rejects_zero_max() {
1210 let spec = CanonicalRouteSpec::new("r1", "timer:tick")
1211 .with_concurrency(CanonicalConcurrencySpec::Concurrent { max: 0 });
1212 let err = spec.validate_contract().unwrap_err().to_string();
1213 assert!(err.contains("concurrency max must be > 0"), "{err}");
1214 }
1215
1216 #[test]
1217 fn canonical_v2_round_trip() {
1218 let spec = CanonicalRouteSpec::new("r1", "timer:tick")
1219 .with_auto_startup(false)
1220 .with_startup_order(42)
1221 .with_concurrency(CanonicalConcurrencySpec::Concurrent { max: 8 });
1222 spec.validate_contract().unwrap();
1223 }
1224
1225 #[test]
1226 fn canonical_v2_version_is_2() {
1227 assert_eq!(CANONICAL_CONTRACT_VERSION, 2);
1228 }
1229
1230 #[test]
1231 fn canonical_loss_report_builder() {
1232 let report =
1233 CanonicalLossReport::from_field("error_handler", "not supported by canonical path", 2);
1234 assert_eq!(report.dropped_fields.len(), 1);
1235 assert_eq!(report.dropped_fields[0].field, "error_handler");
1236 }
1237
1238 #[test]
1239 fn canonical_v1_json_deserializes_in_v2() {
1240 let json = r#"{"route_id":"r1","from":"timer:tick","steps":[],"version":1}"#;
1241 let spec: CanonicalRouteSpec = serde_json::from_str(json).unwrap();
1242 assert_eq!(spec.route_id, "r1");
1243 assert!(spec.auto_startup.is_none());
1244 assert!(spec.startup_order.is_none());
1245 assert!(spec.concurrency.is_none());
1246 spec.validate_contract().unwrap();
1248 }
1249}