component.rs 14.6 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

Ryan Olson's avatar
Ryan Olson committed
32
use crate::{discovery::Lease, service::ServiceSet};
Ryan Olson's avatar
Ryan Olson committed
33

Ryan Olson's avatar
Ryan Olson committed
34
35
36
use super::{
    error, traits::*, transports::nats::Slug, utils::Duration, DistributedRuntime, Result, Runtime,
};
Ryan Olson's avatar
Ryan Olson committed
37
38

use crate::pipeline::network::{ingress::push_endpoint::PushEndpoint, PushWorkHandler};
39
use crate::protocols::Endpoint as EndpointId;
Ryan Olson's avatar
Ryan Olson committed
40
41
42
43
44
45
46
47
use async_nats::{
    rustls::quic,
    service::{Service, ServiceExt},
};
use derive_builder::Builder;
use derive_getters::Getters;
use educe::Educe;
use serde::{Deserialize, Serialize};
48
use service::EndpointStatsHandler;
Ryan Olson's avatar
Ryan Olson committed
49
50
51
52
use std::{collections::HashMap, sync::Arc};
use validator::{Validate, ValidationError};

mod client;
53
54
#[allow(clippy::module_inception)]
mod component;
Ryan Olson's avatar
Ryan Olson committed
55
mod endpoint;
Ryan Olson's avatar
Ryan Olson committed
56
mod namespace;
Ryan Olson's avatar
Ryan Olson committed
57
mod registry;
58
pub mod service;
Ryan Olson's avatar
Ryan Olson committed
59

60
61
62
63
64
65
66
67
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";

/// The root etcd path for ModelEntry
pub const MODEL_ROOT_PATH: &str = "models";
Ryan Olson's avatar
Ryan Olson committed
68
69
70
71
72
73
74

#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum TransportType {
    NatsTcp(String),
}

75
76
77
78
79
80
#[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
81
82
#[derive(Clone)]
pub struct Registry {
83
    inner: Arc<tokio::sync::Mutex<RegistryInner>>,
Ryan Olson's avatar
Ryan Olson committed
84
85
86
}

#[derive(Debug, Clone, Serialize, Deserialize)]
87
pub struct Instance {
Ryan Olson's avatar
Ryan Olson committed
88
89
90
    pub component: String,
    pub endpoint: String,
    pub namespace: String,
91
    pub instance_id: i64,
Ryan Olson's avatar
Ryan Olson committed
92
93
94
    pub transport: TransportType,
}

95
impl Instance {
96
    pub fn id(&self) -> i64 {
97
        self.instance_id
98
99
100
    }
}

Ryan Olson's avatar
Ryan Olson committed
101
/// A [Component] a discoverable entity in the distributed runtime.
Graham King's avatar
Graham King committed
102
103
/// 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
///
/// You can also issue a request to a [Component]'s [Endpoint] by creating a [Client].
#[derive(Educe, Builder, Clone)]
#[educe(Debug)]
#[builder(pattern = "owned")]
pub struct Component {
    #[builder(private)]
    #[educe(Debug(ignore))]
    drt: DistributedRuntime,

    // todo - restrict the namespace to a-z0-9-_A-Z
    /// Name of the component
    #[builder(setter(into))]
    name: String,

    // todo - restrict the namespace to a-z0-9-_A-Z
    /// Namespace
    #[builder(setter(into))]
122
    namespace: Namespace,
123
124
125
126

    // 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
127
128
}

129
130
impl std::fmt::Display for Component {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131
        write!(f, "{}.{}", self.namespace.name(), self.name)
132
133
134
    }
}

135
136
137
138
139
140
141
142
143
144
145
146
impl DistributedRuntimeProvider for Component {
    fn drt(&self) -> &DistributedRuntime {
        &self.drt
    }
}

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

Ryan Olson's avatar
Ryan Olson committed
147
impl Component {
148
149
150
151
152
    /// 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
153
154
    }

155
    pub fn service_name(&self) -> String {
156
        let service_name = format!("{}_{}", self.namespace.name(), self.name);
157
        Slug::slugify(&service_name).to_string()
Ryan Olson's avatar
Ryan Olson committed
158
159
    }

160
    pub fn path(&self) -> String {
161
        format!("{}/{}", self.namespace.name(), self.name)
162
163
    }

164
    pub fn namespace(&self) -> &Namespace {
165
166
167
        &self.namespace
    }

168
169
170
171
    pub fn name(&self) -> String {
        self.name.clone()
    }

Ryan Olson's avatar
Ryan Olson committed
172
173
174
175
    pub fn endpoint(&self, endpoint: impl Into<String>) -> Endpoint {
        Endpoint {
            component: self.clone(),
            name: endpoint.into(),
176
            is_static: self.is_static,
Ryan Olson's avatar
Ryan Olson committed
177
178
179
        }
    }

180
    pub async fn list_instances(&self) -> anyhow::Result<Vec<Instance>> {
181
182
183
184
185
186
        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
187
            .kv_get_prefix(format!("{}/", self.etcd_root()))
188
189
            .await?
        {
190
            let val = match serde_json::from_slice::<Instance>(kv.value()) {
191
192
193
                Ok(val) => val,
                Err(err) => {
                    anyhow::bail!(
194
                        "Error converting etcd response to Instance: {err}. {}",
195
196
197
198
199
200
201
                        kv.value_str()?
                    );
                }
            };
            out.push(val);
        }
        Ok(out)
Ryan Olson's avatar
Ryan Olson committed
202
203
    }

204
    pub async fn scrape_stats(&self, timeout: Duration) -> Result<ServiceSet> {
Ryan Olson's avatar
Ryan Olson committed
205
206
207
        let service_name = self.service_name();
        let service_client = self.drt().service_client();
        service_client
208
            .collect_services(&service_name, timeout)
Ryan Olson's avatar
Ryan Olson committed
209
210
211
            .await
    }

Graham King's avatar
Graham King committed
212
213
    /// TODO
    ///
Ryan Olson's avatar
Ryan Olson committed
214
    /// This method will scrape the stats for all available services
Graham King's avatar
Graham King committed
215
    /// Returns a stream of `ServiceInfo` objects.
Ryan Olson's avatar
Ryan Olson committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
    /// 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 {
    pub fn from_runtime(drt: DistributedRuntime) -> Self {
        Self::default().drt(drt)
    }
}

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

    // todo - restrict alphabet
    /// Endpoint name
    name: String,
240
241

    is_static: bool,
Ryan Olson's avatar
Ryan Olson committed
242
243
}

244
245
246
247
248
249
250
251
252
253
254
255
impl DistributedRuntimeProvider for Endpoint {
    fn drt(&self) -> &DistributedRuntime {
        self.component.drt()
    }
}

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

Ryan Olson's avatar
Ryan Olson committed
256
impl Endpoint {
257
258
259
260
261
262
263
264
    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
265
266
267
268
    pub fn name(&self) -> &str {
        &self.name
    }

269
270
271
272
    pub fn component(&self) -> &Component {
        &self.component
    }

273
274
275
276
    pub fn path(&self) -> String {
        format!("{}/{}", self.component.path(), self.name)
    }

277
278
279
280
281
    /// 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
282
283
    }

284
285
286
    /// The fully path of an instance in etcd
    pub fn etcd_path(&self, lease_id: i64) -> String {
        let endpoint_root = self.etcd_root();
287
        if self.is_static {
288
            endpoint_root
289
        } else {
290
            format!("{endpoint_root}:{lease_id:x}")
291
        }
Ryan Olson's avatar
Ryan Olson committed
292
293
294
    }

    pub fn name_with_id(&self, lease_id: i64) -> String {
295
296
297
298
299
        if self.is_static {
            self.name.clone()
        } else {
            format!("{}-{:x}", self.name, lease_id)
        }
Ryan Olson's avatar
Ryan Olson committed
300
301
    }

Ryan Olson's avatar
Ryan Olson committed
302
303
304
305
306
307
308
309
310
311
312
    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
313
314
    }

315
    pub async fn client(&self) -> Result<client::Client> {
316
317
318
319
320
        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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
    }

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

#[derive(Educe, Builder, Clone, Validate)]
#[educe(Debug)]
#[builder(pattern = "owned")]
pub struct Namespace {
    #[builder(private)]
    #[educe(Debug(ignore))]
    runtime: DistributedRuntime,

    #[validate()]
    name: String,
338
339

    is_static: bool,
Ryan Olson's avatar
Ryan Olson committed
340
341
}

342
343
344
345
346
347
348
349
350
351
352
353
impl DistributedRuntimeProvider for Namespace {
    fn drt(&self) -> &DistributedRuntime {
        &self.runtime
    }
}

impl RuntimeProvider for Namespace {
    fn rt(&self) -> &Runtime {
        self.runtime.rt()
    }
}

354
355
356
357
358
359
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
360
impl Namespace {
361
    pub(crate) fn new(runtime: DistributedRuntime, name: String, is_static: bool) -> Result<Self> {
Ryan Olson's avatar
Ryan Olson committed
362
363
364
        Ok(NamespaceBuilder::default()
            .runtime(runtime)
            .name(name)
365
            .is_static(is_static)
Ryan Olson's avatar
Ryan Olson committed
366
367
368
            .build()?)
    }

369
    /// Create a [`Component`] in the namespace who's endpoints can be discovered with etcd
Ryan Olson's avatar
Ryan Olson committed
370
371
372
    pub fn component(&self, name: impl Into<String>) -> Result<Component> {
        Ok(ComponentBuilder::from_runtime(self.runtime.clone())
            .name(name)
373
            .namespace(self.clone())
374
            .is_static(self.is_static)
Ryan Olson's avatar
Ryan Olson committed
375
376
            .build()?)
    }
Ryan Olson's avatar
Ryan Olson committed
377
378
379
380

    pub fn name(&self) -> &str {
        &self.name
    }
Ryan Olson's avatar
Ryan Olson committed
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
}

// 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);
//             }
//         }
//     }
// }