client.rs 9.43 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
6
7
8
9
10
11
use std::sync::Arc;
use std::{collections::HashMap, time::Duration};

use anyhow::Result;
use arc_swap::ArcSwap;
use futures::StreamExt;
use tokio::net::unix::pipe::Receiver;

12
use crate::discovery::{DiscoveryEvent, DiscoveryInstance};
13
use crate::{
14
15
    component::{Endpoint, Instance},
    pipeline::async_trait,
16
17
18
19
20
    pipeline::{
        AddressedPushRouter, AddressedRequest, AsyncEngine, Data, ManyOut, PushRouter, RouterMode,
        SingleIn,
    },
    storage::key_value_store::{KeyValueStoreManager, WatchEvent},
21
22
    traits::DistributedRuntimeProvider,
    transports::etcd::Client as EtcdClient,
Ryan Olson's avatar
Ryan Olson committed
23
24
};

25
26
27
28
#[derive(Clone, Debug)]
pub struct Client {
    // This is me
    pub endpoint: Endpoint,
29
30
    // These are the remotes I know about from watching key-value store
    pub instance_source: Arc<tokio::sync::watch::Receiver<Vec<Instance>>>,
31
    // These are the instance source ids less those reported as down from sending rpc
32
    instance_avail: Arc<ArcSwap<Vec<u64>>>,
33
    // These are the instance source ids less those reported as busy (above threshold)
34
    instance_free: Arc<ArcSwap<Vec<u64>>>,
35
36
37
38
    // Watch sender for available instance IDs (for sending updates)
    instance_avail_tx: Arc<tokio::sync::watch::Sender<Vec<u64>>>,
    // Watch receiver for available instance IDs (for cloning to external subscribers)
    instance_avail_rx: tokio::sync::watch::Receiver<Vec<u64>>,
39
40
}

41
impl Client {
42
43
    // Client with auto-discover instances using key-value store
    pub(crate) async fn new(endpoint: Endpoint) -> Result<Self> {
44
        tracing::trace!(
45
46
47
            "Client::new_dynamic: Creating dynamic client for endpoint: {}",
            endpoint.path()
        );
48
        let instance_source = Self::get_or_create_dynamic_instance_source(&endpoint).await?;
49

50
        let (avail_tx, avail_rx) = tokio::sync::watch::channel(vec![]);
51
        let client = Client {
52
            endpoint: endpoint.clone(),
53
            instance_source: instance_source.clone(),
54
            instance_avail: Arc::new(ArcSwap::from(Arc::new(vec![]))),
55
            instance_free: Arc::new(ArcSwap::from(Arc::new(vec![]))),
56
57
            instance_avail_tx: Arc::new(avail_tx),
            instance_avail_rx: avail_rx,
58
        };
59
        client.monitor_instance_source();
60
        Ok(client)
61
62
63
64
65
66
67
68
69
70
71
    }

    pub fn path(&self) -> String {
        self.endpoint.path()
    }

    /// The root etcd path we watch in etcd to discover new instances to route to.
    pub fn etcd_root(&self) -> String {
        self.endpoint.etcd_root()
    }

72
    /// Instances available from watching key-value store
73
    pub fn instances(&self) -> Vec<Instance> {
74
        self.instance_source.borrow().clone()
75
76
    }

77
    pub fn instance_ids(&self) -> Vec<u64> {
78
79
80
        self.instances().into_iter().map(|ep| ep.id()).collect()
    }

81
    pub fn instance_ids_avail(&self) -> arc_swap::Guard<Arc<Vec<u64>>> {
82
83
84
        self.instance_avail.load()
    }

85
    pub fn instance_ids_free(&self) -> arc_swap::Guard<Arc<Vec<u64>>> {
86
87
88
        self.instance_free.load()
    }

89
90
91
92
93
    /// Get a watcher for available instance IDs
    pub fn instance_avail_watcher(&self) -> tokio::sync::watch::Receiver<Vec<u64>> {
        self.instance_avail_rx.clone()
    }

94
95
    /// Wait for at least one Instance to be available for this Endpoint
    pub async fn wait_for_instances(&self) -> Result<Vec<Instance>> {
96
        tracing::trace!(
97
98
99
            "wait_for_instances: Starting wait for endpoint: {}",
            self.endpoint.path()
        );
100
101
102
103
104
105
106
107
108
109
        let mut rx = self.instance_source.as_ref().clone();
        // wait for there to be 1 or more endpoints
        let mut instances: Vec<Instance>;
        loop {
            instances = rx.borrow_and_update().to_vec();
            if instances.is_empty() {
                rx.changed().await?;
            } else {
                tracing::info!(
                    "wait_for_instances: Found {} instance(s) for endpoint: {}",
110
111
112
                    instances.len(),
                    self.endpoint.path()
                );
113
                break;
114
115
116
117
118
            }
        }
        Ok(instances)
    }

119
    /// Mark an instance as down/unavailable
120
    pub fn report_instance_down(&self, instance_id: u64) {
121
122
123
124
125
        let filtered = self
            .instance_ids_avail()
            .iter()
            .filter_map(|&id| if id == instance_id { None } else { Some(id) })
            .collect::<Vec<_>>();
126
127
128
129
        self.instance_avail.store(Arc::new(filtered.clone()));

        // Notify watch channel subscribers about the change
        let _ = self.instance_avail_tx.send(filtered);
130
131
132
133

        tracing::debug!("inhibiting instance {instance_id}");
    }

134
    /// Update the set of free instances based on busy instance IDs
135
    pub fn update_free_instances(&self, busy_instance_ids: &[u64]) {
136
        let all_instance_ids = self.instance_ids();
137
        let free_ids: Vec<u64> = all_instance_ids
138
139
140
141
142
143
            .into_iter()
            .filter(|id| !busy_instance_ids.contains(id))
            .collect();
        self.instance_free.store(Arc::new(free_ids));
    }

144
    /// Monitor the key-value instance source and update instance_avail.
145
146
147
    fn monitor_instance_source(&self) {
        let cancel_token = self.endpoint.drt().primary_token();
        let client = self.clone();
148
        let endpoint_path = self.endpoint.path();
149
        tokio::task::spawn(async move {
150
            let mut rx = client.instance_source.as_ref().clone();
151
            while !cancel_token.is_cancelled() {
152
                let instance_ids: Vec<u64> = rx
153
154
155
156
                    .borrow_and_update()
                    .iter()
                    .map(|instance| instance.id())
                    .collect();
157
158
159

                // TODO: this resets both tracked available and free instances
                client.instance_avail.store(Arc::new(instance_ids.clone()));
160
                client.instance_free.store(Arc::new(instance_ids.clone()));
161

162
163
164
                // Send update to watch channel subscribers
                let _ = client.instance_avail_tx.send(instance_ids);

165
                if let Err(err) = rx.changed().await {
166
167
168
169
170
                    tracing::error!(
                        "monitor_instance_source: The Sender is dropped: {}, endpoint={}",
                        err,
                        endpoint_path
                    );
171
172
173
174
                    cancel_token.cancel();
                }
            }
        });
175
176
177
178
    }

    async fn get_or_create_dynamic_instance_source(
        endpoint: &Endpoint,
179
    ) -> Result<Arc<tokio::sync::watch::Receiver<Vec<Instance>>>> {
180
181
182
183
184
185
186
187
188
189
190
191
        let drt = endpoint.drt();
        let instance_sources = drt.instance_sources();
        let mut instance_sources = instance_sources.lock().await;

        if let Some(instance_source) = instance_sources.get(endpoint) {
            if let Some(instance_source) = instance_source.upgrade() {
                return Ok(instance_source);
            } else {
                instance_sources.remove(endpoint);
            }
        }

192
193
194
195
196
197
198
199
200
201
        let discovery = drt.discovery();
        let discovery_query = crate::discovery::DiscoveryQuery::Endpoint {
            namespace: endpoint.component.namespace.name.clone(),
            component: endpoint.component.name.clone(),
            endpoint: endpoint.name.clone(),
        };

        let mut discovery_stream = discovery
            .list_and_watch(discovery_query.clone(), None)
            .await?;
Ryan Olson's avatar
Ryan Olson committed
202
203
        let (watch_tx, watch_rx) = tokio::sync::watch::channel(vec![]);

204
        let secondary = endpoint.component.drt.runtime().secondary().clone();
Ryan Olson's avatar
Ryan Olson committed
205
206

        secondary.spawn(async move {
207
            tracing::trace!("endpoint_watcher: Starting for discovery query: {:?}", discovery_query);
208
            let mut map: HashMap<u64, Instance> = HashMap::new();
Ryan Olson's avatar
Ryan Olson committed
209
210

            loop {
211
                let discovery_event = tokio::select! {
Ryan Olson's avatar
Ryan Olson committed
212
213
214
                    _ = watch_tx.closed() => {
                        break;
                    }
215
216
217
218
219
220
221
222
223
                    discovery_event = discovery_stream.next() => {
                        match discovery_event {
                            Some(Ok(event)) => {
                                event
                            },
                            Some(Err(e)) => {
                                tracing::error!("endpoint_watcher: discovery stream error: {}; shutting down for discovery query: {:?}", e, discovery_query);
                                break;
                            }
Ryan Olson's avatar
Ryan Olson committed
224
225
226
227
228
229
230
                            None => {
                                break;
                            }
                        }
                    }
                };

231
                match discovery_event {
232
233
234
                    DiscoveryEvent::Added(discovery_instance) => {
                        if let DiscoveryInstance::Endpoint(instance) = discovery_instance {

235
                                map.insert(instance.instance_id, instance);
Ryan Olson's avatar
Ryan Olson committed
236
                        }
237
                    }
238
                    DiscoveryEvent::Removed(instance_id) => {
239
                        map.remove(&instance_id);
Ryan Olson's avatar
Ryan Olson committed
240
241
242
                    }
                }

243
244
                let instances: Vec<Instance> = map.values().cloned().collect();
                if watch_tx.send(instances).is_err() {
Ryan Olson's avatar
Ryan Olson committed
245
246
247
248
249
250
                    break;
                }
            }
            let _ = watch_tx.send(vec![]);
        });

251
        let instance_source = Arc::new(watch_rx);
252
253
        instance_sources.insert(endpoint.clone(), Arc::downgrade(&instance_source));
        Ok(instance_source)
254
    }
Ryan Olson's avatar
Ryan Olson committed
255
}