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