component.rs 22.7 KB
Newer Older
1
2
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
Ryan Olson's avatar
Ryan Olson committed
3
4
5

//! The [Component] module defines the top-level API for building distributed applications.
//!
Graham King's avatar
Graham King committed
6
7
8
//! A distributed application consists of a set of [Component] that can host one
//! or more [Endpoint]. Each [Endpoint] is a network-accessible service
//! that can be accessed by other [Component] in the distributed application.
Ryan Olson's avatar
Ryan Olson committed
9
10
11
12
//!
//! A [Component] is made discoverable by registering it with the distributed runtime under
//! a [`Namespace`].
//!
Graham King's avatar
Graham King committed
13
//! A [`Namespace`] is a logical grouping of [Component] that are grouped together.
Ryan Olson's avatar
Ryan Olson committed
14
15
16
17
18
19
20
21
22
23
24
25
//!
//! We might extend namespace to include grouping behavior, which would define groups of
//! components that are tightly coupled.
//!
//! A [Component] is the core building block of a distributed application. It is a logical
//! unit of work such as a `Preprocessor` or `SmartRouter` that has a well-defined role in the
//! distributed application.
//!
//! A [Component] can present to the distributed application one or more configuration files
//! which define how that component was constructed/configured and what capabilities it can
//! provide.
//!
Graham King's avatar
Graham King committed
26
//! Other [Component] can write to watching locations within a [Component] etcd
Ryan Olson's avatar
Ryan Olson committed
27
28
29
30
31
//! path. This allows the [Component] to take dynamic actions depending on the watch
//! triggers.
//!
//! TODO: Top-level Overview of Endpoints/Functions

32
use crate::{
33
34
35
36
    config::HealthStatus,
    discovery::Lease,
    metrics::{prometheus_names, MetricsRegistry},
    service::ServiceSet,
37
    transports::etcd::EtcdPath,
38
};
Ryan Olson's avatar
Ryan Olson committed
39

Ryan Olson's avatar
Ryan Olson committed
40
use super::{
41
42
43
44
45
46
    error,
    traits::*,
    transports::etcd::{COMPONENT_KEYWORD, ENDPOINT_KEYWORD},
    transports::nats::Slug,
    utils::Duration,
    DistributedRuntime, Result, Runtime,
Ryan Olson's avatar
Ryan Olson committed
47
};
Ryan Olson's avatar
Ryan Olson committed
48
49

use crate::pipeline::network::{ingress::push_endpoint::PushEndpoint, PushWorkHandler};
50
use crate::protocols::Endpoint as EndpointId;
51
use crate::service::ComponentNatsPrometheusMetrics;
Ryan Olson's avatar
Ryan Olson committed
52
53
54
55
56
57
58
59
use async_nats::{
    rustls::quic,
    service::{Service, ServiceExt},
};
use derive_builder::Builder;
use derive_getters::Getters;
use educe::Educe;
use serde::{Deserialize, Serialize};
60
use service::EndpointStatsHandler;
61
use std::{collections::HashMap, hash::Hash, sync::Arc};
Ryan Olson's avatar
Ryan Olson committed
62
63
64
use validator::{Validate, ValidationError};

mod client;
65
66
#[allow(clippy::module_inception)]
mod component;
Ryan Olson's avatar
Ryan Olson committed
67
mod endpoint;
Ryan Olson's avatar
Ryan Olson committed
68
mod namespace;
Ryan Olson's avatar
Ryan Olson committed
69
mod registry;
70
pub mod service;
Ryan Olson's avatar
Ryan Olson committed
71

72
73
74
75
76
77
pub use client::{Client, InstanceSource};

/// The root etcd path where each instance registers itself in etcd.
/// An instance is namespace+component+endpoint+lease_id and must be unique.
pub const INSTANCE_ROOT_PATH: &str = "instances";

78
79
80
/// The root etcd path where each namespace is registered in etcd.
pub const ETCD_ROOT_PATH: &str = "dynamo://";

Ryan Olson's avatar
Ryan Olson committed
81
82
83
84
85
86
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum TransportType {
    NatsTcp(String),
}

87
88
89
90
91
92
#[derive(Default)]
pub struct RegistryInner {
    services: HashMap<String, Service>,
    stats_handlers: HashMap<String, Arc<std::sync::Mutex<HashMap<String, EndpointStatsHandler>>>>,
}

Ryan Olson's avatar
Ryan Olson committed
93
94
#[derive(Clone)]
pub struct Registry {
95
    inner: Arc<tokio::sync::Mutex<RegistryInner>>,
Ryan Olson's avatar
Ryan Olson committed
96
97
98
}

#[derive(Debug, Clone, Serialize, Deserialize)]
99
pub struct Instance {
Ryan Olson's avatar
Ryan Olson committed
100
101
102
    pub component: String,
    pub endpoint: String,
    pub namespace: String,
103
    pub instance_id: i64,
Ryan Olson's avatar
Ryan Olson committed
104
105
106
    pub transport: TransportType,
}

107
impl Instance {
108
    pub fn id(&self) -> i64 {
109
        self.instance_id
110
111
112
    }
}

Ryan Olson's avatar
Ryan Olson committed
113
/// A [Component] a discoverable entity in the distributed runtime.
Graham King's avatar
Graham King committed
114
115
/// You can host [Endpoint] on a [Component] by first creating
/// a [Service] then adding one or more [Endpoint] to the [Service].
Ryan Olson's avatar
Ryan Olson committed
116
117
///
/// You can also issue a request to a [Component]'s [Endpoint] by creating a [Client].
118
#[derive(Educe, Builder, Clone, Validate)]
Ryan Olson's avatar
Ryan Olson committed
119
120
121
122
123
#[educe(Debug)]
#[builder(pattern = "owned")]
pub struct Component {
    #[builder(private)]
    #[educe(Debug(ignore))]
124
    drt: Arc<DistributedRuntime>,
Ryan Olson's avatar
Ryan Olson committed
125
126
127
128

    // todo - restrict the namespace to a-z0-9-_A-Z
    /// Name of the component
    #[builder(setter(into))]
129
    #[validate(custom(function = "validate_allowed_chars"))]
Ryan Olson's avatar
Ryan Olson committed
130
131
    name: String,

132
133
134
135
    /// Additional labels for metrics
    #[builder(default = "Vec::new()")]
    labels: Vec<(String, String)>,

Ryan Olson's avatar
Ryan Olson committed
136
137
138
    // todo - restrict the namespace to a-z0-9-_A-Z
    /// Namespace
    #[builder(setter(into))]
139
    namespace: Namespace,
140
141
142
143

    // A static component's endpoints cannot be discovered via etcd, they are
    // fixed at startup time.
    is_static: bool,
Ryan Olson's avatar
Ryan Olson committed
144
145
}

146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
impl Hash for Component {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.namespace.name().hash(state);
        self.name.hash(state);
        self.is_static.hash(state);
    }
}

impl PartialEq for Component {
    fn eq(&self, other: &Self) -> bool {
        self.namespace.name() == other.namespace.name()
            && self.name == other.name
            && self.is_static == other.is_static
    }
}

impl Eq for Component {}

164
165
impl std::fmt::Display for Component {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166
        write!(f, "{}.{}", self.namespace.name(), self.name)
167
168
169
    }
}

170
171
172
173
174
175
176
177
178
179
180
181
impl DistributedRuntimeProvider for Component {
    fn drt(&self) -> &DistributedRuntime {
        &self.drt
    }
}

impl RuntimeProvider for Component {
    fn rt(&self) -> &Runtime {
        self.drt.rt()
    }
}

182
183
184
185
186
187
188
189
190
191
192
193
194
195
impl MetricsRegistry for Component {
    fn basename(&self) -> String {
        self.name.clone()
    }

    fn parent_hierarchy(&self) -> Vec<String> {
        [
            self.namespace.parent_hierarchy(),
            vec![self.namespace.basename()],
        ]
        .concat()
    }
}

Ryan Olson's avatar
Ryan Olson committed
196
impl Component {
197
198
199
200
201
    /// The component part of an instance path in etcd.
    pub fn etcd_root(&self) -> String {
        let ns = self.namespace.name();
        let cp = &self.name;
        format!("{INSTANCE_ROOT_PATH}/{ns}/{cp}")
Ryan Olson's avatar
Ryan Olson committed
202
203
    }

204
    pub fn service_name(&self) -> String {
205
        let service_name = format!("{}_{}", self.namespace.name(), self.name);
206
        Slug::slugify(&service_name).to_string()
Ryan Olson's avatar
Ryan Olson committed
207
208
    }

209
    pub fn path(&self) -> String {
210
        format!("{}/{}", self.namespace.name(), self.name)
211
212
    }

213
214
215
216
217
    pub fn etcd_path(&self) -> EtcdPath {
        EtcdPath::new_component(&self.namespace.name(), &self.name)
            .expect("Component name and namespace should be valid")
    }

218
    pub fn namespace(&self) -> &Namespace {
219
220
221
        &self.namespace
    }

222
223
224
225
    pub fn name(&self) -> String {
        self.name.clone()
    }

Ryan Olson's avatar
Ryan Olson committed
226
227
228
229
    pub fn endpoint(&self, endpoint: impl Into<String>) -> Endpoint {
        Endpoint {
            component: self.clone(),
            name: endpoint.into(),
230
            is_static: self.is_static,
231
            labels: Vec::new(),
Ryan Olson's avatar
Ryan Olson committed
232
233
234
        }
    }

235
    pub async fn list_instances(&self) -> anyhow::Result<Vec<Instance>> {
236
237
238
239
240
241
        let Some(etcd_client) = self.drt.etcd_client() else {
            return Ok(vec![]);
        };
        let mut out = vec![];
        // The extra slash is important to only list exact component matches, not substrings.
        for kv in etcd_client
242
            .kv_get_prefix(format!("{}/", self.etcd_root()))
243
244
            .await?
        {
245
            let val = match serde_json::from_slice::<Instance>(kv.value()) {
246
247
248
                Ok(val) => val,
                Err(err) => {
                    anyhow::bail!(
249
                        "Error converting etcd response to Instance: {err}. {}",
250
251
252
253
254
255
256
                        kv.value_str()?
                    );
                }
            };
            out.push(val);
        }
        Ok(out)
Ryan Olson's avatar
Ryan Olson committed
257
258
    }

259
260
    /// Scrape ServiceSet, which contains NATS stats as well as user defined stats
    /// embedded in data field of ServiceInfo.
261
    pub async fn scrape_stats(&self, timeout: Duration) -> Result<ServiceSet> {
Ryan Olson's avatar
Ryan Olson committed
262
263
264
        let service_name = self.service_name();
        let service_client = self.drt().service_client();
        service_client
265
            .collect_services(&service_name, timeout)
Ryan Olson's avatar
Ryan Olson committed
266
267
268
            .await
    }

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
    /// Add Prometheus metrics for this component's service stats.
    ///
    /// Uses a channel to synchronize with the spawned async task, ensuring
    /// metrics are updated before the callback returns.
    pub fn add_metrics_callback(&self) -> Result<()> {
        let component_metrics = ComponentNatsPrometheusMetrics::new(self)?;

        let component_clone = self.clone();
        let mut hierarchies = self.parent_hierarchy();
        hierarchies.push(self.hierarchy());
        debug_assert_eq!(
            hierarchies.last().cloned().unwrap_or_default(),
            self.service_name()
        ); // it happens that in component, hierarchy and service name are the same

        // Register a metrics callback that scrapes component statistics
        let metrics_callback = Arc::new(move || {
            // Timeout for scraping metrics from components (in milliseconds)
            // This value is also used by KV Router metrics aggregator (300ms) and other components
            const METRICS_SCRAPE_TIMEOUT_MS: u64 = 300;

            // Get the current Tokio runtime handle
            let handle = tokio::runtime::Handle::try_current()
                .map_err(|err| anyhow::anyhow!("No Tokio runtime handle available: {}", err))?;

            let m = component_metrics.clone();
            let c = component_clone.clone();

            // Create a channel to synchronize with the spawned task
            let (tx, rx) = std::sync::mpsc::channel::<anyhow::Result<()>>();

            let timeout = std::time::Duration::from_millis(METRICS_SCRAPE_TIMEOUT_MS);
            handle.spawn(async move {
                let result = match c.scrape_stats(timeout).await {
                    Ok(service_set) => {
                        m.update_from_service_set(&service_set);
                        Ok(())
                    }
                    Err(err) => {
                        // Reset metrics on failure
                        m.reset_to_zeros();
                        Err(anyhow::anyhow!("Failed to scrape stats: {}", err))
                    }
                };

                // Send the result back to the waiting thread
                // If send fails, the receiver has already given up waiting
                let _ = tx.send(result);
            });

            // Wait for the spawned task to complete (with a timeout to prevent hanging)
            // Add 100ms buffer to the scrape timeout to account for processing overhead
            let recv_timeout = std::time::Duration::from_millis(METRICS_SCRAPE_TIMEOUT_MS + 100);
            match rx.recv_timeout(recv_timeout) {
                Ok(result) => result, // Return the actual result from scraping
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                    component_metrics.reset_to_zeros();
                    Err(anyhow::anyhow!("Metrics collection timed out"))
                }
                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                    component_metrics.reset_to_zeros();
                    Err(anyhow::anyhow!("Metrics collection task failed"))
                }
            }
        });

        self.drt()
            .register_metrics_callback(hierarchies, metrics_callback);

        Ok(())
    }

Graham King's avatar
Graham King committed
341
342
    /// TODO
    ///
Ryan Olson's avatar
Ryan Olson committed
343
    /// This method will scrape the stats for all available services
Graham King's avatar
Graham King committed
344
    /// Returns a stream of `ServiceInfo` objects.
Ryan Olson's avatar
Ryan Olson committed
345
346
347
348
349
350
351
352
353
354
355
356
    /// This should be consumed by a `[tokio::time::timeout_at`] because each services
    /// will only respond once, but there is no way to know when all services have responded.
    pub async fn stats_stream(&self) -> Result<()> {
        unimplemented!("collect_stats")
    }

    pub fn service_builder(&self) -> service::ServiceConfigBuilder {
        service::ServiceConfigBuilder::from_component(self.clone())
    }
}

impl ComponentBuilder {
357
    pub fn from_runtime(drt: Arc<DistributedRuntime>) -> Self {
Ryan Olson's avatar
Ryan Olson committed
358
359
360
361
362
363
364
365
366
367
368
        Self::default().drt(drt)
    }
}

#[derive(Debug, Clone)]
pub struct Endpoint {
    component: Component,

    // todo - restrict alphabet
    /// Endpoint name
    name: String,
369
370

    is_static: bool,
371
372
373

    /// Additional labels for metrics
    labels: Vec<(String, String)>,
Ryan Olson's avatar
Ryan Olson committed
374
375
}

376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
impl Hash for Endpoint {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.component.hash(state);
        self.name.hash(state);
        self.is_static.hash(state);
    }
}

impl PartialEq for Endpoint {
    fn eq(&self, other: &Self) -> bool {
        self.component == other.component
            && self.name == other.name
            && self.is_static == other.is_static
    }
}

impl Eq for Endpoint {}

394
395
396
397
398
399
400
401
402
403
404
405
impl DistributedRuntimeProvider for Endpoint {
    fn drt(&self) -> &DistributedRuntime {
        self.component.drt()
    }
}

impl RuntimeProvider for Endpoint {
    fn rt(&self) -> &Runtime {
        self.component.rt()
    }
}

406
407
408
409
410
411
412
413
414
415
416
417
418
419
impl MetricsRegistry for Endpoint {
    fn basename(&self) -> String {
        self.name.clone()
    }

    fn parent_hierarchy(&self) -> Vec<String> {
        [
            self.component.parent_hierarchy(),
            vec![self.component.basename()],
        ]
        .concat()
    }
}

Ryan Olson's avatar
Ryan Olson committed
420
impl Endpoint {
421
422
423
424
425
426
427
428
    pub fn id(&self) -> EndpointId {
        EndpointId {
            namespace: self.component.namespace().name().to_string(),
            component: self.component.name().to_string(),
            name: self.name().to_string(),
        }
    }

Ryan Olson's avatar
Ryan Olson committed
429
430
431
432
    pub fn name(&self) -> &str {
        &self.name
    }

433
434
435
436
    pub fn component(&self) -> &Component {
        &self.component
    }

437
    // todo(ryan): deprecate this as we move to Discovery traits and Component Identifiers
438
    pub fn path(&self) -> String {
439
440
441
442
443
444
        format!(
            "{}/{}/{}",
            self.component.path(),
            ENDPOINT_KEYWORD,
            self.name
        )
445
446
    }

447
448
449
450
451
    /// The endpoint part of an instance path in etcd
    pub fn etcd_root(&self) -> String {
        let component_path = self.component.etcd_root();
        let endpoint_name = &self.name;
        format!("{component_path}/{endpoint_name}")
Ryan Olson's avatar
Ryan Olson committed
452
453
    }

454
455
456
457
458
459
460
461
462
463
    /// The endpoint as an EtcdPath object
    pub fn etcd_path(&self) -> EtcdPath {
        EtcdPath::new_endpoint(
            &self.component.namespace().name(),
            &self.component.name(),
            &self.name,
        )
        .expect("Endpoint name and component name should be valid")
    }

464
    /// The fully path of an instance in etcd
465
    pub fn etcd_path_with_lease_id(&self, lease_id: i64) -> String {
466
        let endpoint_root = self.etcd_root();
467
        if self.is_static {
468
            endpoint_root
469
        } else {
470
            format!("{endpoint_root}:{lease_id:x}")
471
        }
Ryan Olson's avatar
Ryan Olson committed
472
473
    }

474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
    /// The endpoint as an EtcdPath object with lease ID
    pub fn etcd_path_object_with_lease_id(&self, lease_id: i64) -> EtcdPath {
        if self.is_static {
            self.etcd_path()
        } else {
            EtcdPath::new_endpoint_with_lease(
                &self.component.namespace().name(),
                &self.component.name(),
                &self.name,
                lease_id,
            )
            .expect("Endpoint name and component name should be valid")
        }
    }

Ryan Olson's avatar
Ryan Olson committed
489
    pub fn name_with_id(&self, lease_id: i64) -> String {
490
491
492
493
494
        if self.is_static {
            self.name.clone()
        } else {
            format!("{}-{:x}", self.name, lease_id)
        }
Ryan Olson's avatar
Ryan Olson committed
495
496
    }

Ryan Olson's avatar
Ryan Olson committed
497
498
499
500
501
502
503
504
505
506
507
    pub fn subject(&self) -> String {
        format!("{}.{}", self.component.service_name(), self.name)
    }

    /// Subject to an instance of the [Endpoint] with a specific lease id
    pub fn subject_to(&self, lease_id: i64) -> String {
        format!(
            "{}.{}",
            self.component.service_name(),
            self.name_with_id(lease_id)
        )
Ryan Olson's avatar
Ryan Olson committed
508
509
    }

510
    pub async fn client(&self) -> Result<client::Client> {
511
512
513
514
515
        if self.is_static {
            client::Client::new_static(self.clone()).await
        } else {
            client::Client::new_dynamic(self.clone()).await
        }
Ryan Olson's avatar
Ryan Olson committed
516
517
518
519
520
521
522
    }

    pub fn endpoint_builder(&self) -> endpoint::EndpointConfigBuilder {
        endpoint::EndpointConfigBuilder::from_endpoint(self.clone())
    }
}

523
#[derive(Builder, Clone, Validate)]
Ryan Olson's avatar
Ryan Olson committed
524
525
526
#[builder(pattern = "owned")]
pub struct Namespace {
    #[builder(private)]
527
    runtime: Arc<DistributedRuntime>,
Ryan Olson's avatar
Ryan Olson committed
528

529
    #[validate(custom(function = "validate_allowed_chars"))]
Ryan Olson's avatar
Ryan Olson committed
530
    name: String,
531
532

    is_static: bool,
533
534
535

    #[builder(default = "None")]
    parent: Option<Arc<Namespace>>,
536
537
538
539

    /// Additional labels for metrics
    #[builder(default = "Vec::new()")]
    labels: Vec<(String, String)>,
Ryan Olson's avatar
Ryan Olson committed
540
541
}

542
543
544
545
546
547
impl DistributedRuntimeProvider for Namespace {
    fn drt(&self) -> &DistributedRuntime {
        &self.runtime
    }
}

548
549
550
551
552
553
554
555
556
557
impl std::fmt::Debug for Namespace {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Namespace {{ name: {}; is_static: {}; parent: {:?} }}",
            self.name, self.is_static, self.parent
        )
    }
}

558
559
560
561
562
563
impl RuntimeProvider for Namespace {
    fn rt(&self) -> &Runtime {
        self.runtime.rt()
    }
}

564
565
566
567
568
569
impl std::fmt::Display for Namespace {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name)
    }
}

Ryan Olson's avatar
Ryan Olson committed
570
impl Namespace {
571
    pub(crate) fn new(runtime: DistributedRuntime, name: String, is_static: bool) -> Result<Self> {
Ryan Olson's avatar
Ryan Olson committed
572
        Ok(NamespaceBuilder::default()
573
            .runtime(Arc::new(runtime))
Ryan Olson's avatar
Ryan Olson committed
574
            .name(name)
575
            .is_static(is_static)
Ryan Olson's avatar
Ryan Olson committed
576
577
578
            .build()?)
    }

579
    /// Create a [`Component`] in the namespace who's endpoints can be discovered with etcd
Ryan Olson's avatar
Ryan Olson committed
580
    pub fn component(&self, name: impl Into<String>) -> Result<Component> {
581
        let component = ComponentBuilder::from_runtime(self.runtime.clone())
Ryan Olson's avatar
Ryan Olson committed
582
            .name(name)
583
            .namespace(self.clone())
584
            .is_static(self.is_static)
585
586
587
588
589
590
591
592
593
594
595
596
597
598
            .build()?;

        // Register the metrics callback for this component.
        // If registration fails, log a warning but do not propagate the error,
        // as metrics are not mission critical and should not block component creation.
        if let Err(err) = component.add_metrics_callback() {
            tracing::warn!(
                "Failed to add metrics callback for component '{}': {}",
                component.service_name(),
                err
            );
        }

        Ok(component)
Ryan Olson's avatar
Ryan Olson committed
599
    }
Ryan Olson's avatar
Ryan Olson committed
600

601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
    /// Create a [`Namespace`] in the parent namespace
    pub fn namespace(&self, name: impl Into<String>) -> Result<Namespace> {
        Ok(NamespaceBuilder::default()
            .runtime(self.runtime.clone())
            .name(name.into())
            .is_static(self.is_static)
            .parent(Some(Arc::new(self.clone())))
            .build()?)
    }

    pub fn etcd_path(&self) -> String {
        format!("{}{}", ETCD_ROOT_PATH, self.name())
    }

    pub fn name(&self) -> String {
        match &self.parent {
            Some(parent) => format!("{}.{}", parent.name(), self.name),
            None => self.name.clone(),
        }
Ryan Olson's avatar
Ryan Olson committed
620
    }
Ryan Olson's avatar
Ryan Olson committed
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
}

// Custom validator function
fn validate_allowed_chars(input: &str) -> Result<(), ValidationError> {
    // Define the allowed character set using a regex
    let regex = regex::Regex::new(r"^[a-z0-9-_]+$").unwrap();

    if regex.is_match(input) {
        Ok(())
    } else {
        Err(ValidationError::new("invalid_characters"))
    }
}

// TODO - enable restrictions to the character sets allowed for namespaces,
// components, and endpoints.
//
// Put Validate traits on the struct and use the `validate_allowed_chars` method
// to validate the fields.

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

//     #[test]
//     fn test_valid_names() {
//         // Valid strings
//         let valid_inputs = vec![
//             "abc",        // Lowercase letters
//             "abc123",     // Letters and numbers
//             "a-b-c",      // Letters with hyphens
//             "a_b_c",      // Letters with underscores
//             "a-b_c-123",  // Mixed valid characters
//             "a",          // Single character
//             "a_b",        // Short valid pattern
//             "123456",     // Only numbers
//             "a---b_c123", // Repeated hyphens/underscores
//         ];

//         for input in valid_inputs {
//             let result = validate_allowed_chars(input);
//             assert!(result.is_ok(), "Expected '{}' to be valid", input);
//         }
//     }

//     #[test]
//     fn test_invalid_names() {
//         // Invalid strings
//         let invalid_inputs = vec![
//             "abc!",     // Invalid character `!`
//             "abc@",     // Invalid character `@`
//             "123$",     // Invalid character `$`
//             "foo.bar",  // Invalid character `.`
//             "foo/bar",  // Invalid character `/`
//             "foo\\bar", // Invalid character `\`
//             "abc#",     // Invalid character `#`
//             "abc def",  // Spaces are not allowed
//             "foo,",     // Invalid character `,`
//             "",         // Empty string
//         ];

//         for input in invalid_inputs {
//             let result = validate_allowed_chars(input);
//             assert!(result.is_err(), "Expected '{}' to be invalid", input);
//         }
//     }

//     // #[test]
//     // fn test_struct_validation_valid() {
//     //     // Struct with valid data
//     //     let valid_data = InputData {
//     //         name: "valid-name_123".to_string(),
//     //     };
//     //     assert!(valid_data.validate().is_ok());
//     // }

//     // #[test]
//     // fn test_struct_validation_invalid() {
//     //     // Struct with invalid data
//     //     let invalid_data = InputData {
//     //         name: "invalid!name".to_string(),
//     //     };
//     //     let result = invalid_data.validate();
//     //     assert!(result.is_err());

//     //     if let Err(errors) = result {
//     //         let error_map = errors.field_errors();
//     //         assert!(error_map.contains_key("name"));
//     //         let name_errors = &error_map["name"];
//     //         assert_eq!(name_errors[0].code, "invalid_characters");
//     //     }
//     // }

//     #[test]
//     fn test_edge_cases() {
//         // Edge cases
//         let edge_inputs = vec![
//             ("-", true),   // Single hyphen
//             ("_", true),   // Single underscore
//             ("a-", true),  // Letter with hyphen
//             ("-", false),  // Repeated hyphens
//             ("-a", false), // Hyphen at the beginning
//             ("a-", false), // Hyphen at the end
//         ];

//         for (input, expected_validity) in edge_inputs {
//             let result = validate_allowed_chars(input);
//             if expected_validity {
//                 assert!(result.is_ok(), "Expected '{}' to be valid", input);
//             } else {
//                 assert!(result.is_err(), "Expected '{}' to be invalid", input);
//             }
//         }
//     }
// }