client.rs 10.9 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
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

use crate::pipeline::{
    network::egress::push::{AddressedPushRouter, AddressedRequest, PushRouter},
    AsyncEngine, Data, ManyOut, SingleIn,
};
use rand::Rng;
use std::collections::HashMap;
use std::sync::{
    atomic::{AtomicU64, Ordering},
    Arc,
};
use tokio::{net::unix::pipe::Receiver, sync::Mutex};

use crate::{pipeline::async_trait, transports::etcd::WatchEvent, Error};

use super::*;

/// Each state will be have a nonce associated with it
/// The state will be emitted in a watch channel, so we can observe the
/// critical state transitions.
enum MapState {
    /// The map is empty; value = nonce
    Empty(u64),

    /// The map is not-empty; values are (nonce, count)
    NonEmpty(u64, u64),

    /// The watcher has finished, no more events will be emitted
    Finished,
}

enum EndpointEvent {
    Put(String, i64),
    Delete(String),
}

51
52
53
54
55
56
57
58
59
60
61
62
#[derive(Default, Debug, Clone, Copy)]
pub enum RouterMode {
    #[default]
    Random,
    RoundRobin,
    //KV,
    //
    // Always and only go to the given endpoint ID.
    // TODO: Is this useful?
    Direct(i64),
}

Ryan Olson's avatar
Ryan Olson committed
63
64
65
66
67
#[derive(Clone)]
pub struct Client<T: Data, U: Data> {
    endpoint: Endpoint,
    router: PushRouter<T, U>,
    counter: Arc<AtomicU64>,
68
    endpoints: EndpointSource,
69
    router_mode: RouterMode,
70
71
72
73
74
75
}

#[derive(Clone, Debug)]
enum EndpointSource {
    Static,
    Dynamic(tokio::sync::watch::Receiver<Vec<i64>>),
Ryan Olson's avatar
Ryan Olson committed
76
77
78
79
80
81
82
}

impl<T, U> Client<T, U>
where
    T: Data + Serialize,
    U: Data + for<'de> Deserialize<'de>,
{
83
84
85
86
87
88
89
    // Client will only talk to a single static endpoint
    pub(crate) async fn new_static(endpoint: Endpoint) -> Result<Self> {
        Ok(Client {
            router: router(&endpoint).await?,
            endpoint,
            counter: Arc::new(AtomicU64::new(0)),
            endpoints: EndpointSource::Static,
90
            router_mode: Default::default(),
91
92
        })
    }
Ryan Olson's avatar
Ryan Olson committed
93

94
95
    // Client with auto-discover endpoints using etcd
    pub(crate) async fn new_dynamic(endpoint: Endpoint) -> Result<Self> {
Ryan Olson's avatar
Ryan Olson committed
96
        // create live endpoint watcher
97
98
99
100
        let Some(etcd_client) = &endpoint.component.drt.etcd_client else {
            anyhow::bail!("Attempt to create a dynamic client on a static endpoint");
        };
        let prefix_watcher = etcd_client
Ryan Olson's avatar
Ryan Olson committed
101
102
103
104
105
106
107
108
109
110
111
112
113
            .kv_get_and_watch_prefix(endpoint.etcd_path())
            .await?;

        let (prefix, _watcher, mut kv_event_rx) = prefix_watcher.dissolve();

        let (watch_tx, watch_rx) = tokio::sync::watch::channel(vec![]);

        let secondary = endpoint.component.drt.runtime.secondary().clone();

        // this task should be included in the registry
        // currently this is created once per client, but this object/task should only be instantiated
        // once per worker/instance
        secondary.spawn(async move {
114
            tracing::debug!("Starting endpoint watcher for prefix: {}", prefix);
Ryan Olson's avatar
Ryan Olson committed
115
116
117
118
119
            let mut map = HashMap::new();

            loop {
                let kv_event = tokio::select! {
                    _ = watch_tx.closed() => {
120
                        tracing::debug!("all watchers have closed; shutting down endpoint watcher for prefix: {}", prefix);
Ryan Olson's avatar
Ryan Olson committed
121
122
123
124
125
126
                        break;
                    }
                    kv_event = kv_event_rx.recv() => {
                        match kv_event {
                            Some(kv_event) => kv_event,
                            None => {
127
                                tracing::debug!("watch stream has closed; shutting down endpoint watcher for prefix: {}", prefix);
Ryan Olson's avatar
Ryan Olson committed
128
129
130
131
132
133
134
135
136
137
138
139
140
                                break;
                            }
                        }
                    }
                };

                match kv_event {
                    WatchEvent::Put(kv) => {
                        let key = String::from_utf8(kv.key().to_vec());
                        let val = serde_json::from_slice::<ComponentEndpointInfo>(kv.value());
                        if let (Ok(key), Ok(val)) = (key, val) {
                            map.insert(key.clone(), val.lease_id);
                        } else {
141
                            tracing::error!("Unable to parse put endpoint event; shutting down endpoint watcher for prefix: {}", prefix);
Ryan Olson's avatar
Ryan Olson committed
142
143
144
145
146
147
148
                            break;
                        }
                    }
                    WatchEvent::Delete(kv) => {
                        match String::from_utf8(kv.key().to_vec()) {
                            Ok(key) => { map.remove(&key); }
                            Err(_) => {
149
                                tracing::error!("Unable to parse delete endpoint event; shutting down endpoint watcher for prefix: {}", prefix);
Ryan Olson's avatar
Ryan Olson committed
150
151
152
153
154
155
156
157
158
                                break;
                            }
                        }
                    }
                }

                let endpoint_ids: Vec<i64> = map.values().cloned().collect();

                if watch_tx.send(endpoint_ids).is_err() {
159
                    tracing::debug!("Unable to send watch updates; shutting down endpoint watcher for prefix: {}", prefix);
Ryan Olson's avatar
Ryan Olson committed
160
161
162
163
164
                    break;
                }

            }

165
            tracing::debug!("Completed endpoint watcher for prefix: {}", prefix);
Ryan Olson's avatar
Ryan Olson committed
166
167
168
169
            let _ = watch_tx.send(vec![]);
        });

        Ok(Client {
170
            router: router(&endpoint).await?,
Ryan Olson's avatar
Ryan Olson committed
171
172
            endpoint,
            counter: Arc::new(AtomicU64::new(0)),
173
            endpoints: EndpointSource::Dynamic(watch_rx),
174
            router_mode: Default::default(),
Ryan Olson's avatar
Ryan Olson committed
175
176
177
        })
    }

178
    /// String identifying `<namespace>/<component>/<endpoint>`
179
180
181
182
    pub fn path(&self) -> String {
        self.endpoint.path()
    }

183
    /// String identifying `<namespace>/component/<component>/<endpoint>`
184
185
186
187
    pub fn etcd_path(&self) -> String {
        self.endpoint.etcd_path()
    }

188
189
190
191
192
    pub fn endpoint_ids(&self) -> Vec<i64> {
        match &self.endpoints {
            EndpointSource::Static => vec![0],
            EndpointSource::Dynamic(watch_rx) => watch_rx.borrow().clone(),
        }
Ryan Olson's avatar
Ryan Olson committed
193
194
    }

195
196
197
198
    pub fn set_router_mode(&mut self, mode: RouterMode) {
        self.router_mode = mode
    }

Ryan Olson's avatar
Ryan Olson committed
199
200
    /// Wait for at least one [`Endpoint`] to be available
    pub async fn wait_for_endpoints(&self) -> Result<()> {
201
202
203
204
205
206
207
208
        if let EndpointSource::Dynamic(mut rx) = self.endpoints.clone() {
            // wait for there to be 1 or more endpoints
            loop {
                if rx.borrow_and_update().is_empty() {
                    rx.changed().await?;
                } else {
                    break;
                }
Ryan Olson's avatar
Ryan Olson committed
209
210
211
212
213
            }
        }
        Ok(())
    }

214
215
216
217
218
    /// Is this component know at startup and not discovered via etcd?
    pub fn is_static(&self) -> bool {
        matches!(self.endpoints, EndpointSource::Static)
    }

Ryan Olson's avatar
Ryan Olson committed
219
220
221
222
223
    /// Issue a request to the next available endpoint in a round-robin fashion
    pub async fn round_robin(&self, request: SingleIn<T>) -> Result<ManyOut<U>> {
        let counter = self.counter.fetch_add(1, Ordering::Relaxed);

        let endpoint_id = {
224
            let endpoints = self.endpoint_ids();
Ryan Olson's avatar
Ryan Olson committed
225
226
227
228
229
230
231
232
233
234
            let count = endpoints.len();
            if count == 0 {
                return Err(error!(
                    "no endpoints found for endpoint {:?}",
                    self.endpoint.etcd_path()
                ));
            }
            let offset = counter % count as u64;
            endpoints[offset as usize]
        };
235
        tracing::trace!("round robin router selected {endpoint_id}");
Ryan Olson's avatar
Ryan Olson committed
236

Ryan Olson's avatar
Ryan Olson committed
237
        let subject = self.endpoint.subject_to(endpoint_id);
Ryan Olson's avatar
Ryan Olson committed
238
239
240
241
242
243
244
245
        let request = request.map(|req| AddressedRequest::new(req, subject));

        self.router.generate(request).await
    }

    /// Issue a request to a random endpoint
    pub async fn random(&self, request: SingleIn<T>) -> Result<ManyOut<U>> {
        let endpoint_id = {
246
            let endpoints = self.endpoint_ids();
Ryan Olson's avatar
Ryan Olson committed
247
248
249
250
251
252
253
            let count = endpoints.len();
            if count == 0 {
                return Err(error!(
                    "no endpoints found for endpoint {:?}",
                    self.endpoint.etcd_path()
                ));
            }
254
            let counter = rand::rng().random::<u64>();
Ryan Olson's avatar
Ryan Olson committed
255
256
257
            let offset = counter % count as u64;
            endpoints[offset as usize]
        };
258
        tracing::trace!("random router selected {endpoint_id}");
Ryan Olson's avatar
Ryan Olson committed
259

Ryan Olson's avatar
Ryan Olson committed
260
        let subject = self.endpoint.subject_to(endpoint_id);
Ryan Olson's avatar
Ryan Olson committed
261
262
263
264
265
266
267
268
        let request = request.map(|req| AddressedRequest::new(req, subject));

        self.router.generate(request).await
    }

    /// Issue a request to a specific endpoint
    pub async fn direct(&self, request: SingleIn<T>, endpoint_id: i64) -> Result<ManyOut<U>> {
        let found = {
269
            let endpoints = self.endpoint_ids();
Ryan Olson's avatar
Ryan Olson committed
270
271
272
273
274
275
276
277
278
279
280
            endpoints.contains(&endpoint_id)
        };

        if !found {
            return Err(error!(
                "endpoint_id={} not found for endpoint {:?}",
                endpoint_id,
                self.endpoint.etcd_path()
            ));
        }

Ryan Olson's avatar
Ryan Olson committed
281
        let subject = self.endpoint.subject_to(endpoint_id);
Ryan Olson's avatar
Ryan Olson committed
282
283
284
285
        let request = request.map(|req| AddressedRequest::new(req, subject));

        self.router.generate(request).await
    }
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300

    pub async fn r#static(&self, request: SingleIn<T>) -> Result<ManyOut<U>> {
        let subject = self.endpoint.subject();
        tracing::debug!("static got subject: {subject}");
        let request = request.map(|req| AddressedRequest::new(req, subject));
        tracing::debug!("router generate");
        self.router.generate(request).await
    }
}

async fn router(endpoint: &Endpoint) -> Result<Arc<AddressedPushRouter>> {
    AddressedPushRouter::new(
        endpoint.component.drt.nats_client.client().clone(),
        endpoint.component.drt.tcp_server().await?,
    )
Ryan Olson's avatar
Ryan Olson committed
301
302
303
304
305
306
307
308
309
}

#[async_trait]
impl<T, U> AsyncEngine<SingleIn<T>, ManyOut<U>, Error> for Client<T, U>
where
    T: Data + Serialize,
    U: Data + for<'de> Deserialize<'de>,
{
    async fn generate(&self, request: SingleIn<T>) -> Result<ManyOut<U>, Error> {
310
311
        match &self.endpoints {
            EndpointSource::Static => self.r#static(request).await,
312
313
314
315
316
            EndpointSource::Dynamic(_) => match self.router_mode {
                RouterMode::Random => self.random(request).await,
                RouterMode::RoundRobin => self.round_robin(request).await,
                RouterMode::Direct(endpoint_id) => self.direct(request, endpoint_id).await,
            },
317
        }
Ryan Olson's avatar
Ryan Olson committed
318
319
    }
}