camel-api 0.28.0

Core traits and interfaces 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
//! Component metadata schema types.
//!
//! Defines the core metadata structures used by component registries and
//! schema generation: option definitions, capability declarations, and the
//! top-level component descriptor.

use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// OptionKind — closed enum of supported option value types
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema, ts_rs::TS))]
#[cfg_attr(feature = "schema", ts(rename_all = "snake_case"))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum OptionKind {
    String,
    Int,
    Bool,
    Float,
    Duration,
    Enum(Vec<String>),
    List(Box<OptionKind>),
}

// ---------------------------------------------------------------------------
// UriOptionMatch — pattern matching for open-namespace URI options
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema, ts_rs::TS))]
#[cfg_attr(feature = "schema", ts(rename_all = "snake_case"))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum UriOptionMatch {
    #[serde(rename_all = "snake_case")]
    Prefix {
        #[cfg_attr(feature = "schema", schemars(default))]
        separator: String,
    },
}

// ---------------------------------------------------------------------------
// UriOption — a single URI-parameter definition with builder
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema, ts_rs::TS))]
#[cfg_attr(feature = "schema", ts(rename_all = "snake_case"))]
pub struct UriOption {
    pub name: String,
    pub description: String,
    pub kind: OptionKind,
    #[cfg_attr(feature = "schema", schemars(default))]
    #[serde(default)]
    pub required: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_value: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub aliases: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deprecated: Option<String>,
    #[cfg_attr(feature = "schema", schemars(default))]
    #[serde(default)]
    pub secret: bool,
    #[cfg_attr(feature = "schema", schemars(default))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pattern: Option<UriOptionMatch>,
}

impl UriOption {
    pub fn new(name: &str, description: &str, kind: OptionKind) -> Self {
        Self {
            name: name.to_string(),
            description: description.to_string(),
            kind,
            required: false,
            default_value: None,
            aliases: Vec::new(),
            deprecated: None,
            secret: false,
            pattern: None,
        }
    }

    #[must_use]
    pub fn required(mut self) -> Self {
        self.required = true;
        self
    }

    #[must_use]
    pub fn with_default(mut self, value: &str) -> Self {
        self.default_value = Some(value.to_string());
        self
    }

    #[must_use]
    pub fn with_alias(mut self, alias: &str) -> Self {
        self.aliases.push(alias.to_string());
        self
    }

    #[must_use]
    pub fn deprecated(mut self, reason: &str) -> Self {
        self.deprecated = Some(reason.to_string());
        self
    }

    #[must_use]
    pub fn secret(mut self) -> Self {
        self.secret = true;
        self
    }

    #[must_use]
    pub fn pattern_prefix(mut self, separator: &str) -> Self {
        self.pattern = Some(UriOptionMatch::Prefix {
            separator: separator.to_string(),
        });
        self
    }
}

// ---------------------------------------------------------------------------
// ComponentCapabilities — named boolean flags + query matching
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema, ts_rs::TS))]
pub struct ComponentCapabilities {
    pub supports_consumer: bool,
    pub supports_producer: bool,
    pub supports_polling_consumer: bool,
    pub supports_streaming: bool,
}

impl ComponentCapabilities {
    /// Returns `true` when every field present in `query` matches this
    /// capability set.  Fields set to `None` in the query are ignored
    /// (no constraint).
    pub fn matches_query(&self, query: &CapabilityQuery) -> bool {
        query
            .supports_consumer
            .is_none_or(|v| self.supports_consumer == v)
            && query
                .supports_producer
                .is_none_or(|v| self.supports_producer == v)
            && query
                .supports_polling_consumer
                .is_none_or(|v| self.supports_polling_consumer == v)
            && query
                .supports_streaming
                .is_none_or(|v| self.supports_streaming == v)
    }
}

// ---------------------------------------------------------------------------
// CapabilityQuery — tri-state query for filtering components
// ---------------------------------------------------------------------------

/// Tri-state query struct.  Each field, when `Some(v)`, constrains the
/// corresponding [`ComponentCapabilities`] field to equal `v`.  `None`
/// means "don't care".
#[derive(Debug, Clone, Default)]
pub struct CapabilityQuery {
    pub supports_consumer: Option<bool>,
    pub supports_producer: Option<bool>,
    pub supports_polling_consumer: Option<bool>,
    pub supports_streaming: Option<bool>,
}

// ---------------------------------------------------------------------------
// ComponentMetadata — top-level component descriptor
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema, ts_rs::TS))]
pub struct ComponentMetadata {
    pub scheme: String,
    pub schema_version: String,
    pub version: String,
    pub description: String,
    pub uri_syntax: String,
    pub capabilities: ComponentCapabilities,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub uri_options: Vec<UriOption>,
}

impl ComponentMetadata {
    /// Current schema version string.
    pub const SCHEMA_VERSION: &'static str = "1";

    /// Build a minimal metadata entry for `scheme`.
    ///
    /// Sets `schema_version` to [`Self::SCHEMA_VERSION`].  The `version` field is
    /// left empty — components that override `Component::metadata` should
    /// supply their own `env!("CARGO_PKG_VERSION")`.
    pub fn minimal(scheme: &str) -> Self {
        Self {
            scheme: scheme.to_string(),
            schema_version: Self::SCHEMA_VERSION.to_string(),
            version: String::new(),
            description: String::new(),
            uri_syntax: String::new(),
            capabilities: ComponentCapabilities::default(),
            uri_options: Vec::new(),
        }
    }

    /// Set the human-readable `description` field.
    #[must_use]
    pub fn with_description(mut self, description: &str) -> Self {
        self.description = description.to_string();
        self
    }

    /// Replace the `capabilities` block.
    #[must_use]
    pub fn with_capabilities(mut self, caps: ComponentCapabilities) -> Self {
        self.capabilities = caps;
        self
    }

    /// Append to the `uri_options` list.
    #[must_use]
    pub fn with_uri_options(mut self, opts: Vec<UriOption>) -> Self {
        self.uri_options.extend(opts);
        self
    }

    /// Validate that this metadata's `scheme` matches the given
    /// `component_scheme`.  Returns `Err` with a descriptive message on
    /// mismatch.
    pub fn validate_scheme(&self, component_scheme: &str) -> Result<(), String> {
        if self.scheme == component_scheme {
            Ok(())
        } else {
            Err(format!(
                "Scheme mismatch: component metadata scheme is '{}' but component scheme is '{}'",
                self.scheme, component_scheme
            ))
        }
    }
}

// ---------------------------------------------------------------------------
// ComponentMetadataCatalog — runtime query interface
// ---------------------------------------------------------------------------

/// Query interface for component metadata at runtime.
///
/// Implementations store [`ComponentMetadata`] entries keyed by URI scheme
/// and provide lookup and capability-filtering operations.
pub trait ComponentMetadataCatalog: Send + Sync {
    /// Look up metadata for a component by its URI scheme.
    fn get_metadata(&self, scheme: &str) -> Option<ComponentMetadata>;

    /// Return all schemes that have registered metadata.
    fn schemes(&self) -> Vec<String>;

    /// Return metadata for all registered components.
    fn all_metadata(&self) -> Vec<ComponentMetadata>;

    /// Filter components by capability query. Returns all metadata
    /// entries whose capabilities match every field in the query.
    fn query_capabilities(&self, query: &CapabilityQuery) -> Vec<ComponentMetadata> {
        self.all_metadata()
            .into_iter()
            .filter(|m| m.capabilities.matches_query(query))
            .collect()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // -----------------------------------------------------------------------
    // UriOptionMatch tests — TDD: written before implementation
    // -----------------------------------------------------------------------

    #[test]
    fn pattern_prefix_sets_prefix_variant() {
        let opt = UriOption::new("param", "desc", OptionKind::String).pattern_prefix("param.");

        assert_eq!(
            opt.pattern,
            Some(UriOptionMatch::Prefix {
                separator: "param.".to_string()
            })
        );
        // All original fields unchanged
        assert_eq!(opt.name, "param");
        assert_eq!(opt.description, "desc");
        assert_eq!(opt.kind, OptionKind::String);
        assert!(!opt.secret);
        assert!(!opt.required);
        assert_eq!(opt.default_value, None);
        assert!(opt.aliases.is_empty());
        assert_eq!(opt.deprecated, None);
    }

    #[test]
    fn pattern_defaults_to_none() {
        let opt = UriOption::new("foo", "desc", OptionKind::String);
        assert_eq!(opt.pattern, None);
    }

    #[test]
    fn serialize_pattern_none_omits_field() {
        let opt = UriOption::new("foo", "desc", OptionKind::String);
        // Fixture: serialize the pre-change struct shape (no pattern field).
        let fixture = serde_json::to_string(&opt).unwrap();
        // After adding pattern: None with skip_serializing_if, bytes must be identical.
        assert!(
            !fixture.contains("\"pattern\""),
            "serialized JSON should not contain \"pattern\" when pattern is None, got: {fixture}"
        );
        // Roundtrip: the fixture must deserialize back to the same shape.
        let roundtripped: UriOption = serde_json::from_str(&fixture).unwrap();
        assert_eq!(opt, roundtripped);
    }

    #[test]
    fn serialize_pattern_some_emits_externally_tagged_snake_case() {
        let opt = UriOption::new("param", "desc", OptionKind::String).pattern_prefix("param.");
        let json = serde_json::to_string(&opt).unwrap();
        assert!(
            json.contains("\"pattern\":{\"prefix\":{\"separator\":\"param.\"}}"),
            "expected externally-tagged snake_case serialization, got: {json}"
        );
    }

    #[test]
    fn deserialize_pattern_some_roundtrips() {
        let opt = UriOption::new("param", "desc", OptionKind::String).pattern_prefix("param.");
        let json = serde_json::to_string(&opt).unwrap();
        let deser: UriOption = serde_json::from_str(&json).unwrap();
        assert_eq!(
            deser.pattern,
            Some(UriOptionMatch::Prefix {
                separator: "param.".to_string()
            })
        );
    }

    // -----------------------------------------------------------------------
    // Pre-existing tests
    // -----------------------------------------------------------------------

    #[test]
    fn uri_option_builder_chain() {
        let opt = UriOption::new("my_param", "A test parameter", OptionKind::String)
            .required()
            .with_default("default_val")
            .with_alias("mp")
            .with_alias("my-param")
            .deprecated("Use new_param instead")
            .secret();

        assert_eq!(opt.name, "my_param");
        assert_eq!(opt.description, "A test parameter");
        assert_eq!(opt.kind, OptionKind::String);
        assert!(opt.required);
        assert_eq!(opt.default_value, Some("default_val".to_string()));
        assert_eq!(opt.aliases, vec!["mp".to_string(), "my-param".to_string()]);
        assert_eq!(opt.deprecated, Some("Use new_param instead".to_string()));
        assert!(opt.secret);
    }

    #[test]
    fn enum_kind_holds_variants() {
        let kind = OptionKind::Enum(vec!["a".to_string(), "b".to_string()]);
        match &kind {
            OptionKind::Enum(variants) => {
                assert_eq!(variants.len(), 2);
                assert_eq!(variants[0], "a");
                assert_eq!(variants[1], "b");
            }
            other => panic!("Expected Enum variant, got {other:?}"),
        }
    }

    #[test]
    fn component_capabilities_default_all_false() {
        let caps = ComponentCapabilities::default();
        assert!(!caps.supports_consumer);
        assert!(!caps.supports_producer);
        assert!(!caps.supports_polling_consumer);
        assert!(!caps.supports_streaming);
    }

    #[test]
    fn minimal_metadata_has_scheme_and_empty_fields() {
        let meta = ComponentMetadata::minimal("timer");
        assert_eq!(meta.scheme, "timer");
        assert_eq!(meta.schema_version, "1");
        assert!(meta.description.is_empty());
        assert!(meta.uri_syntax.is_empty());
        assert!(meta.uri_options.is_empty());
        assert!(meta.version.is_empty());
    }

    #[test]
    fn with_description_sets() {
        let meta = ComponentMetadata::minimal("sql").with_description("test");
        assert_eq!(meta.description, "test");
    }

    #[test]
    fn with_capabilities_sets_flags() {
        let meta = ComponentMetadata::minimal("x").with_capabilities(ComponentCapabilities {
            supports_producer: true,
            ..Default::default()
        });
        assert!(meta.capabilities.supports_producer);
        assert!(!meta.capabilities.supports_consumer);
    }

    #[test]
    fn with_uri_options_appends() {
        let meta = ComponentMetadata::minimal("x").with_uri_options(vec![UriOption::new(
            "p",
            "d",
            OptionKind::String,
        )]);
        assert_eq!(meta.uri_options.len(), 1);
        assert_eq!(meta.uri_options[0].name, "p");
    }

    #[test]
    fn validate_scheme_mismatch_returns_err() {
        let meta = ComponentMetadata::minimal("timer");
        let result = meta.validate_scheme("log");
        assert!(result.is_err());
        let err_msg = result.unwrap_err();
        assert!(err_msg.contains("timer"));
        assert!(err_msg.contains("log"));
    }

    #[test]
    fn capability_query_tri_state_matching() {
        let caps = ComponentCapabilities {
            supports_consumer: true,
            ..Default::default()
        };

        // supports_consumer = true matches query asking for Some(true)
        assert!(caps.matches_query(&CapabilityQuery {
            supports_consumer: Some(true),
            ..Default::default()
        }));

        // supports_producer = false does NOT match query asking for
        // Some(true)
        assert!(!caps.matches_query(&CapabilityQuery {
            supports_producer: Some(true),
            ..Default::default()
        }));

        // supports_producer = false DOES match query asking for
        // Some(false)
        assert!(caps.matches_query(&CapabilityQuery {
            supports_producer: Some(false),
            ..Default::default()
        }));
    }

    // -----------------------------------------------------------------------
    // Mock catalog for testing
    // -----------------------------------------------------------------------

    struct MockCatalog {
        entries: std::collections::HashMap<String, ComponentMetadata>,
    }

    impl ComponentMetadataCatalog for MockCatalog {
        fn get_metadata(&self, scheme: &str) -> Option<ComponentMetadata> {
            self.entries.get(scheme).cloned()
        }

        fn schemes(&self) -> Vec<String> {
            self.entries.keys().cloned().collect()
        }

        fn all_metadata(&self) -> Vec<ComponentMetadata> {
            self.entries.values().cloned().collect()
        }
    }

    #[test]
    fn catalog_trait_object_safety() {
        let mut entries = std::collections::HashMap::new();
        entries.insert("timer".to_string(), ComponentMetadata::minimal("timer"));
        let catalog = MockCatalog { entries };
        let dyn_catalog: &dyn ComponentMetadataCatalog = &catalog;
        assert_eq!(dyn_catalog.schemes(), vec!["timer".to_string()]);
    }

    #[test]
    fn catalog_query_capabilities_default_impl() {
        let consumer = ComponentMetadata {
            scheme: "timer".to_string(),
            capabilities: ComponentCapabilities {
                supports_consumer: true,
                ..Default::default()
            },
            ..ComponentMetadata::minimal("timer")
        };
        let producer = ComponentMetadata {
            scheme: "log".to_string(),
            capabilities: ComponentCapabilities {
                supports_producer: true,
                ..Default::default()
            },
            ..ComponentMetadata::minimal("log")
        };
        let mut entries = std::collections::HashMap::new();
        entries.insert("timer".to_string(), consumer);
        entries.insert("log".to_string(), producer);
        let catalog = MockCatalog { entries };

        let query_consumer = CapabilityQuery {
            supports_consumer: Some(true),
            ..Default::default()
        };
        let results = catalog.query_capabilities(&query_consumer);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].scheme, "timer");

        let query_producer = CapabilityQuery {
            supports_producer: Some(true),
            ..Default::default()
        };
        let results = catalog.query_capabilities(&query_producer);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].scheme, "log");

        // Query with no constraints returns all
        let query_none = CapabilityQuery::default();
        let results = catalog.query_capabilities(&query_none);
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn catalog_schemes_and_all_metadata() {
        let mut entries = std::collections::HashMap::new();
        entries.insert("timer".to_string(), ComponentMetadata::minimal("timer"));
        entries.insert("log".to_string(), ComponentMetadata::minimal("log"));
        let catalog = MockCatalog { entries };

        let mut schemes = catalog.schemes();
        schemes.sort();
        assert_eq!(schemes, vec!["log".to_string(), "timer".to_string()]);

        let all = catalog.all_metadata();
        assert_eq!(all.len(), 2);
        let schemes_from_meta: std::collections::BTreeSet<&str> =
            all.iter().map(|m| m.scheme.as_str()).collect();
        assert!(schemes_from_meta.contains("timer"));
        assert!(schemes_from_meta.contains("log"));
    }
}