endpoint.rs 5.64 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
17
18
19

use derive_getters::Dissolve;

use super::*;

20
21
pub use async_nats::service::endpoint::Stats as EndpointStats;

Ryan Olson's avatar
Ryan Olson committed
22
23
24
25
26
27
28
#[derive(Educe, Builder, Dissolve)]
#[educe(Debug)]
#[builder(pattern = "owned", build_fn(private, name = "build_internal"))]
pub struct EndpointConfig {
    #[builder(private)]
    endpoint: Endpoint,

29
    // todo: move lease to component/service
Ryan Olson's avatar
Ryan Olson committed
30
31
32
33
34
35
36
37
    /// Lease
    #[educe(Debug(ignore))]
    #[builder(default)]
    lease: Option<Lease>,

    /// Endpoint handler
    #[educe(Debug(ignore))]
    handler: Arc<dyn PushWorkHandler>,
38
39
40
41
42

    /// Stats handler
    #[educe(Debug(ignore))]
    #[builder(default, private)]
    _stats_handler: Option<EndpointStatsHandler>,
43

44
45
46
47
    /// Additional labels for metrics
    #[builder(default, setter(into))]
    metrics_labels: Option<Vec<(String, String)>>,

48
49
50
    /// Whether to wait for inflight requests to complete during shutdown
    #[builder(default = "true")]
    graceful_shutdown: bool,
Ryan Olson's avatar
Ryan Olson committed
51
52
53
54
55
56
57
}

impl EndpointConfigBuilder {
    pub(crate) fn from_endpoint(endpoint: Endpoint) -> Self {
        Self::default().endpoint(endpoint)
    }

58
59
    pub fn stats_handler<F>(self, handler: F) -> Self
    where
60
        F: FnMut(EndpointStats) -> serde_json::Value + Send + Sync + 'static,
61
62
63
64
    {
        self._stats_handler(Some(Box::new(handler)))
    }

Ryan Olson's avatar
Ryan Olson committed
65
    pub async fn start(self) -> Result<()> {
66
        let (endpoint, lease, handler, stats_handler, metrics_labels, graceful_shutdown) =
67
            self.build_internal()?.dissolve();
68
69
        let lease = lease.or(endpoint.drt().primary_lease());
        let lease_id = lease.as_ref().map(|l| l.id()).unwrap_or(0);
Ryan Olson's avatar
Ryan Olson committed
70

71
72
73
74
        tracing::debug!(
            "Starting endpoint: {}",
            endpoint.etcd_path_with_lease_id(lease_id)
        );
Ryan Olson's avatar
Ryan Olson committed
75

76
77
78
79
80
        let service_name = endpoint.component.service_name();

        // acquire the registry lock
        let registry = endpoint.drt().component_registry.inner.lock().await;

81
82
83
        let metrics_labels: Option<Vec<(&str, &str)>> = metrics_labels
            .as_ref()
            .map(|v| v.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect());
84
        // Add metrics to the handler. The endpoint provides additional information to the handler.
85
        handler.add_metrics(&endpoint, metrics_labels.as_deref())?;
86

87
88
        // get the group
        let group = registry
Ryan Olson's avatar
Ryan Olson committed
89
            .services
90
            .get(&service_name)
Ryan Olson's avatar
Ryan Olson committed
91
            .map(|service| service.group(endpoint.component.service_name()))
Ryan Olson's avatar
Ryan Olson committed
92
93
            .ok_or(error!("Service not found"))?;

94
95
96
97
98
99
100
101
102
103
104
105
106
107
        // get the stats handler map
        let handler_map = registry
            .stats_handlers
            .get(&service_name)
            .cloned()
            .expect("no stats handler registry; this is unexpected");

        drop(registry);

        // insert the stats handler
        if let Some(stats_handler) = stats_handler {
            handler_map
                .lock()
                .unwrap()
108
                .insert(endpoint.subject_to(lease_id), stats_handler);
109
        }
Ryan Olson's avatar
Ryan Olson committed
110
111
112

        // creates an endpoint for the service
        let service_endpoint = group
113
            .endpoint(&endpoint.name_with_id(lease_id))
Ryan Olson's avatar
Ryan Olson committed
114
115
116
            .await
            .map_err(|e| anyhow::anyhow!("Failed to start endpoint: {e}"))?;

117
118
119
        let cancel_token = lease
            .map(|l| l.child_token())
            .unwrap_or_else(|| endpoint.drt().child_token());
Ryan Olson's avatar
Ryan Olson committed
120
121
122
123

        let push_endpoint = PushEndpoint::builder()
            .service_handler(handler)
            .cancellation_token(cancel_token.clone())
124
            .graceful_shutdown(graceful_shutdown)
Ryan Olson's avatar
Ryan Olson committed
125
126
127
128
            .build()
            .map_err(|e| anyhow::anyhow!("Failed to build push endpoint: {e}"))?;

        // launch in primary runtime
129
130
        let task = tokio::spawn(push_endpoint.start(
            service_endpoint,
131
132
            endpoint.component.namespace.name.clone(),
            endpoint.component.name.clone(),
133
            endpoint.name.clone(),
134
            lease_id,
135
136
            endpoint.drt().system_health.clone(),
        ));
Ryan Olson's avatar
Ryan Olson committed
137
138
139
140

        // make the components service endpoint discovery in etcd

        // client.register_service()
141
        let info = Instance {
Ryan Olson's avatar
Ryan Olson committed
142
143
            component: endpoint.component.name.clone(),
            endpoint: endpoint.name.clone(),
144
            namespace: endpoint.component.namespace.name.clone(),
145
            instance_id: lease_id,
146
            transport: TransportType::NatsTcp(endpoint.subject_to(lease_id)),
Ryan Olson's avatar
Ryan Olson committed
147
148
149
150
        };

        let info = serde_json::to_vec_pretty(&info)?;

151
152
        if let Some(etcd_client) = &endpoint.component.drt.etcd_client {
            if let Err(e) = etcd_client
153
                .kv_create(
154
                    &endpoint.etcd_path_with_lease_id(lease_id),
155
156
157
                    info,
                    Some(lease_id),
                )
158
159
160
161
162
163
                .await
            {
                tracing::error!("Failed to register discoverable service: {:?}", e);
                cancel_token.cancel();
                return Err(error!("Failed to register discoverable service"));
            }
Ryan Olson's avatar
Ryan Olson committed
164
165
166
167
168
169
        }
        task.await??;

        Ok(())
    }
}