client.rs 9.13 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
            "Client::new_dynamic: Creating dynamic client for endpoint: {}",
46
            endpoint.id()
47
        );
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
    /// Instances available from watching key-value store
64
    pub fn instances(&self) -> Vec<Instance> {
65
        self.instance_source.borrow().clone()
66
67
    }

68
    pub fn instance_ids(&self) -> Vec<u64> {
69
70
71
        self.instances().into_iter().map(|ep| ep.id()).collect()
    }

72
    pub fn instance_ids_avail(&self) -> arc_swap::Guard<Arc<Vec<u64>>> {
73
74
75
        self.instance_avail.load()
    }

76
    pub fn instance_ids_free(&self) -> arc_swap::Guard<Arc<Vec<u64>>> {
77
78
79
        self.instance_free.load()
    }

80
81
82
83
84
    /// Get a watcher for available instance IDs
    pub fn instance_avail_watcher(&self) -> tokio::sync::watch::Receiver<Vec<u64>> {
        self.instance_avail_rx.clone()
    }

85
86
    /// Wait for at least one Instance to be available for this Endpoint
    pub async fn wait_for_instances(&self) -> Result<Vec<Instance>> {
87
        tracing::trace!(
88
            "wait_for_instances: Starting wait for endpoint: {}",
89
            self.endpoint.id()
90
        );
91
92
93
94
95
96
97
98
99
100
        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: {}",
101
                    instances.len(),
102
                    self.endpoint.id()
103
                );
104
                break;
105
106
107
108
109
            }
        }
        Ok(instances)
    }

110
    /// Mark an instance as down/unavailable
111
    pub fn report_instance_down(&self, instance_id: u64) {
112
113
114
115
116
        let filtered = self
            .instance_ids_avail()
            .iter()
            .filter_map(|&id| if id == instance_id { None } else { Some(id) })
            .collect::<Vec<_>>();
117
118
119
120
        self.instance_avail.store(Arc::new(filtered.clone()));

        // Notify watch channel subscribers about the change
        let _ = self.instance_avail_tx.send(filtered);
121
122
123
124

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

125
    /// Update the set of free instances based on busy instance IDs
126
    pub fn update_free_instances(&self, busy_instance_ids: &[u64]) {
127
        let all_instance_ids = self.instance_ids();
128
        let free_ids: Vec<u64> = all_instance_ids
129
130
131
132
133
134
            .into_iter()
            .filter(|id| !busy_instance_ids.contains(id))
            .collect();
        self.instance_free.store(Arc::new(free_ids));
    }

135
    /// Monitor the key-value instance source and update instance_avail.
136
137
138
    fn monitor_instance_source(&self) {
        let cancel_token = self.endpoint.drt().primary_token();
        let client = self.clone();
139
        let endpoint_id = self.endpoint.id();
140
        tokio::task::spawn(async move {
141
            let mut rx = client.instance_source.as_ref().clone();
142
            while !cancel_token.is_cancelled() {
143
                let instance_ids: Vec<u64> = rx
144
145
146
147
                    .borrow_and_update()
                    .iter()
                    .map(|instance| instance.id())
                    .collect();
148
149
150

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

153
154
155
                // Send update to watch channel subscribers
                let _ = client.instance_avail_tx.send(instance_ids);

156
                if let Err(err) = rx.changed().await {
157
                    tracing::error!(
158
                        "monitor_instance_source: The Sender is dropped: {err}, endpoint={endpoint_id}",
159
                    );
160
161
162
163
                    cancel_token.cancel();
                }
            }
        });
164
165
166
167
    }

    async fn get_or_create_dynamic_instance_source(
        endpoint: &Endpoint,
168
    ) -> Result<Arc<tokio::sync::watch::Receiver<Vec<Instance>>>> {
169
170
171
172
173
174
175
176
177
178
179
180
        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);
            }
        }

181
182
183
184
185
186
187
188
189
190
        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
191
192
        let (watch_tx, watch_rx) = tokio::sync::watch::channel(vec![]);

193
        let secondary = endpoint.component.drt.runtime().secondary().clone();
Ryan Olson's avatar
Ryan Olson committed
194
195

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

            loop {
200
                let discovery_event = tokio::select! {
Ryan Olson's avatar
Ryan Olson committed
201
202
203
                    _ = watch_tx.closed() => {
                        break;
                    }
204
205
206
207
208
209
210
211
212
                    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
213
214
215
216
217
218
219
                            None => {
                                break;
                            }
                        }
                    }
                };

220
                match discovery_event {
221
222
223
                    DiscoveryEvent::Added(discovery_instance) => {
                        if let DiscoveryInstance::Endpoint(instance) = discovery_instance {

224
                                map.insert(instance.instance_id, instance);
Ryan Olson's avatar
Ryan Olson committed
225
                        }
226
                    }
227
                    DiscoveryEvent::Removed(instance_id) => {
228
                        map.remove(&instance_id);
Ryan Olson's avatar
Ryan Olson committed
229
230
231
                    }
                }

232
233
                let instances: Vec<Instance> = map.values().cloned().collect();
                if watch_tx.send(instances).is_err() {
Ryan Olson's avatar
Ryan Olson committed
234
235
236
237
238
239
                    break;
                }
            }
            let _ = watch_tx.send(vec![]);
        });

240
        let instance_source = Arc::new(watch_rx);
241
242
        instance_sources.insert(endpoint.clone(), Arc::downgrade(&instance_source));
        Ok(instance_source)
243
    }
Ryan Olson's avatar
Ryan Olson committed
244
}