"pcdet/models/vscode:/vscode.git/clone" did not exist on "adbb322f1a2a42f8dcb9e6644c402f97861b23fe"
service.rs 3.76 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Ryan Olson's avatar
Ryan Olson committed
15
16

use derive_getters::Dissolve;
17
18
use std::collections::HashMap;
use std::sync::Mutex;
Ryan Olson's avatar
Ryan Olson committed
19
20
21
22
23
24
25
26

use super::*;

use async_nats::service::{endpoint, Service};

pub type StatsHandler =
    Box<dyn FnMut(String, endpoint::Stats) -> serde_json::Value + Send + Sync + 'static>;

27
28
29
pub type EndpointStatsHandler =
    Box<dyn FnMut(endpoint::Stats) -> serde_json::Value + Send + Sync + 'static>;

Neelay Shah's avatar
Neelay Shah committed
30
pub const PROJECT_NAME: &str = "Dynamo";
31

Ryan Olson's avatar
Ryan Olson committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#[derive(Educe, Builder, Dissolve)]
#[educe(Debug)]
#[builder(pattern = "owned", build_fn(private, name = "build_internal"))]
pub struct ServiceConfig {
    #[builder(private)]
    component: Component,

    /// Description
    #[builder(default)]
    description: Option<String>,
}

impl ServiceConfigBuilder {
    /// Create the [`Component`]'s service and store it in the registry.
    pub async fn create(self) -> Result<Component> {
47
        let (component, description) = self.build_internal()?.dissolve();
Ryan Olson's avatar
Ryan Olson committed
48

49
        let version = "0.0.1".to_string();
Ryan Olson's avatar
Ryan Olson committed
50

Ryan Olson's avatar
Ryan Olson committed
51
        let service_name = component.service_name();
52
53
        log::debug!("component: {component}; creating, service_name: {service_name}");

Ryan Olson's avatar
Ryan Olson committed
54
        let description = description.unwrap_or(format!(
55
            "{PROJECT_NAME} component {} in namespace {}",
Ryan Olson's avatar
Ryan Olson committed
56
57
58
            component.name, component.namespace
        ));

59
60
61
62
        let stats_handler_registry: Arc<Mutex<HashMap<String, EndpointStatsHandler>>> =
            Arc::new(Mutex::new(HashMap::new()));

        let stats_handler_registry_clone = stats_handler_registry.clone();
Ryan Olson's avatar
Ryan Olson committed
63

64
65
66
        let mut guard = component.drt.component_registry.inner.lock().await;

        if guard.services.contains_key(&service_name) {
Ryan Olson's avatar
Ryan Olson committed
67
68
69
70
71
            return Err(anyhow::anyhow!("Service already exists"));
        }

        // create service on the secondary runtime
        let builder = component.drt.nats_client.client().service_builder();
72
73
74
75
76
77
78
79
80
81
82

        tracing::debug!("Starting service: {}", service_name);
        let service = builder
            .description(description)
            .stats_handler(move |name, stats| {
                log::trace!("stats_handler: {name}, {stats:?}");
                let mut guard = stats_handler_registry.lock().unwrap();
                match guard.get_mut(&name) {
                    Some(handler) => handler(stats),
                    None => serde_json::Value::Null,
                }
Ryan Olson's avatar
Ryan Olson committed
83
            })
84
85
            .start(service_name.clone(), version)
            .await
Ryan Olson's avatar
Ryan Olson committed
86
87
            .map_err(|e| anyhow::anyhow!("Failed to start service: {e}"))?;

88
89
90
91
92
93
94
95
96
97
98
99
        // new copy of service_name as the previous one is moved into the task above
        let service_name = component.service_name();

        // insert the service into the registry
        guard.services.insert(service_name.clone(), service);

        // insert the stats handler into the registry
        guard
            .stats_handlers
            .insert(service_name, stats_handler_registry_clone);

        // drop the guard to unlock the mutex
Ryan Olson's avatar
Ryan Olson committed
100
101
102
103
104
105
106
107
108
109
110
        drop(guard);

        Ok(component)
    }
}

impl ServiceConfigBuilder {
    pub(crate) fn from_component(component: Component) -> Self {
        Self::default().component(component)
    }
}