"docs/vscode:/vscode.git/clone" did not exist on "0a2a820bcacda705d927c6fdfcf37ec076e4e3fd"
client.rs 15.8 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
// 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, DiscoveryInstanceId};
13
use crate::{
14
15
    component::{Endpoint, Instance},
    pipeline::async_trait,
16
17
18
19
    pipeline::{
        AddressedPushRouter, AddressedRequest, AsyncEngine, Data, ManyOut, PushRouter, RouterMode,
        SingleIn,
    },
20
21
    traits::DistributedRuntimeProvider,
    transports::etcd::Client as EtcdClient,
Ryan Olson's avatar
Ryan Olson committed
22
23
};

24
25
26
/// Default interval for periodic reconciliation of instance_avail with instance_source
const DEFAULT_RECONCILE_INTERVAL: Duration = Duration::from_secs(5);

27
28
29
30
#[derive(Clone, Debug)]
pub struct Client {
    // This is me
    pub endpoint: Endpoint,
31
32
    // These are the remotes I know about from watching key-value store
    pub instance_source: Arc<tokio::sync::watch::Receiver<Vec<Instance>>>,
33
    // These are the instance source ids less those reported as down from sending rpc
34
    instance_avail: Arc<ArcSwap<Vec<u64>>>,
35
    // These are the instance source ids less those reported as busy (above threshold)
36
    instance_free: Arc<ArcSwap<Vec<u64>>>,
37
38
39
40
    // 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>>,
41
42
43
    /// Interval for periodic reconciliation of instance_avail with instance_source.
    /// This ensures instances removed via `report_instance_down` are eventually restored.
    reconcile_interval: Duration,
44
45
}

46
impl Client {
47
48
    // Client with auto-discover instances using key-value store
    pub(crate) async fn new(endpoint: Endpoint) -> Result<Self> {
49
50
51
52
53
54
55
56
57
58
        Self::with_reconcile_interval(endpoint, DEFAULT_RECONCILE_INTERVAL).await
    }

    /// Create a client with a custom reconcile interval.
    /// The reconcile interval controls how often `instance_avail` is reset to match
    /// `instance_source`, restoring any instances removed via `report_instance_down`.
    pub(crate) async fn with_reconcile_interval(
        endpoint: Endpoint,
        reconcile_interval: Duration,
    ) -> Result<Self> {
59
        tracing::trace!(
60
            "Client::new_dynamic: Creating dynamic client for endpoint: {}",
61
            endpoint.id()
62
        );
63
        let instance_source = Self::get_or_create_dynamic_instance_source(&endpoint).await?;
64

65
66
67
68
69
70
71
72
73
74
        // Seed instance_avail from the current instance_source snapshot so that
        // callers who proceed immediately after wait_for_instances (which reads
        // instance_source directly) will also find instances in instance_avail
        // (which is read by the routing methods like random/round_robin).
        let initial_ids: Vec<u64> = instance_source
            .borrow()
            .iter()
            .map(|instance| instance.id())
            .collect();
        let (avail_tx, avail_rx) = tokio::sync::watch::channel(initial_ids.clone());
75
        let client = Client {
76
            endpoint: endpoint.clone(),
77
            instance_source: instance_source.clone(),
78
79
            instance_avail: Arc::new(ArcSwap::from(Arc::new(initial_ids.clone()))),
            instance_free: Arc::new(ArcSwap::from(Arc::new(initial_ids))),
80
81
            instance_avail_tx: Arc::new(avail_tx),
            instance_avail_rx: avail_rx,
82
            reconcile_interval,
83
        };
84
        client.monitor_instance_source();
85
        Ok(client)
86
87
    }

88
    /// Instances available from watching key-value store
89
    pub fn instances(&self) -> Vec<Instance> {
90
        self.instance_source.borrow().clone()
91
92
    }

93
    pub fn instance_ids(&self) -> Vec<u64> {
94
95
96
        self.instances().into_iter().map(|ep| ep.id()).collect()
    }

97
    pub fn instance_ids_avail(&self) -> arc_swap::Guard<Arc<Vec<u64>>> {
98
99
100
        self.instance_avail.load()
    }

101
    pub fn instance_ids_free(&self) -> arc_swap::Guard<Arc<Vec<u64>>> {
102
103
104
        self.instance_free.load()
    }

105
106
107
108
109
    /// Get a watcher for available instance IDs
    pub fn instance_avail_watcher(&self) -> tokio::sync::watch::Receiver<Vec<u64>> {
        self.instance_avail_rx.clone()
    }

110
111
    /// Wait for at least one Instance to be available for this Endpoint
    pub async fn wait_for_instances(&self) -> Result<Vec<Instance>> {
112
        tracing::trace!(
113
            "wait_for_instances: Starting wait for endpoint: {}",
114
            self.endpoint.id()
115
        );
116
117
118
119
120
121
122
123
124
125
        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: {}",
126
                    instances.len(),
127
                    self.endpoint.id()
128
                );
129
                break;
130
131
132
133
134
            }
        }
        Ok(instances)
    }

135
    /// Mark an instance as down/unavailable
136
    pub fn report_instance_down(&self, instance_id: u64) {
137
138
139
140
141
        let filtered = self
            .instance_ids_avail()
            .iter()
            .filter_map(|&id| if id == instance_id { None } else { Some(id) })
            .collect::<Vec<_>>();
142
143
144
145
        self.instance_avail.store(Arc::new(filtered.clone()));

        // Notify watch channel subscribers about the change
        let _ = self.instance_avail_tx.send(filtered);
146
147
148
149

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

150
    /// Update the set of free instances based on busy instance IDs
151
    pub fn update_free_instances(&self, busy_instance_ids: &[u64]) {
152
        let all_instance_ids = self.instance_ids();
153
        let free_ids: Vec<u64> = all_instance_ids
154
155
156
157
158
159
            .into_iter()
            .filter(|id| !busy_instance_ids.contains(id))
            .collect();
        self.instance_free.store(Arc::new(free_ids));
    }

160
    /// Monitor the key-value instance source and update instance_avail.
161
162
163
164
165
    ///
    /// This function also performs periodic reconciliation: if `instance_source` hasn't
    /// changed for `reconcile_interval`, we reset `instance_avail` to match
    /// `instance_source`. This ensures instances removed via `report_instance_down`
    /// are eventually restored even if the discovery source doesn't emit updates.
166
    fn monitor_instance_source(&self) {
167
        let reconcile_interval = self.reconcile_interval;
168
169
        let cancel_token = self.endpoint.drt().primary_token();
        let client = self.clone();
170
        let endpoint_id = self.endpoint.id();
171
        tokio::task::spawn(async move {
172
            let mut rx = client.instance_source.as_ref().clone();
173
            while !cancel_token.is_cancelled() {
174
                let instance_ids: Vec<u64> = rx
175
176
177
178
                    .borrow_and_update()
                    .iter()
                    .map(|instance| instance.id())
                    .collect();
179
180
181

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

184
185
186
                // Send update to watch channel subscribers
                let _ = client.instance_avail_tx.send(instance_ids);

187
188
189
190
191
192
193
194
195
196
197
198
199
200
                tokio::select! {
                    result = rx.changed() => {
                        if let Err(err) = result {
                            tracing::error!(
                                "monitor_instance_source: The Sender is dropped: {err}, endpoint={endpoint_id}",
                            );
                            cancel_token.cancel();
                        }
                    }
                    _ = tokio::time::sleep(reconcile_interval) => {
                        tracing::trace!(
                            "monitor_instance_source: periodic reconciliation for endpoint={endpoint_id}",
                        );
                    }
201
202
203
                }
            }
        });
204
205
206
207
    }

    async fn get_or_create_dynamic_instance_source(
        endpoint: &Endpoint,
208
    ) -> Result<Arc<tokio::sync::watch::Receiver<Vec<Instance>>>> {
209
210
211
212
213
214
215
216
217
218
219
220
        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);
            }
        }

221
222
223
224
225
226
227
228
229
230
        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
231
232
        let (watch_tx, watch_rx) = tokio::sync::watch::channel(vec![]);

233
        let secondary = endpoint.component.drt.runtime().secondary().clone();
Ryan Olson's avatar
Ryan Olson committed
234
235

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

            loop {
240
                let discovery_event = tokio::select! {
Ryan Olson's avatar
Ryan Olson committed
241
242
243
                    _ = watch_tx.closed() => {
                        break;
                    }
244
245
246
247
248
249
250
251
252
                    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
253
254
255
256
257
258
259
                            None => {
                                break;
                            }
                        }
                    }
                };

260
                match discovery_event {
261
262
263
                    DiscoveryEvent::Added(discovery_instance) => {
                        if let DiscoveryInstance::Endpoint(instance) = discovery_instance {

264
                                map.insert(instance.instance_id, instance);
Ryan Olson's avatar
Ryan Olson committed
265
                        }
266
                    }
267
268
                    DiscoveryEvent::Removed(id) => {
                        map.remove(&id.instance_id());
Ryan Olson's avatar
Ryan Olson committed
269
270
271
                    }
                }

272
273
                let instances: Vec<Instance> = map.values().cloned().collect();
                if watch_tx.send(instances).is_err() {
Ryan Olson's avatar
Ryan Olson committed
274
275
276
277
278
279
                    break;
                }
            }
            let _ = watch_tx.send(vec![]);
        });

280
        let instance_source = Arc::new(watch_rx);
281
282
        instance_sources.insert(endpoint.clone(), Arc::downgrade(&instance_source));
        Ok(instance_source)
283
    }
Ryan Olson's avatar
Ryan Olson committed
284
}
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{DistributedRuntime, Runtime, distributed::DistributedConfig};

    /// Test that instances removed via report_instance_down are restored after
    /// the reconciliation interval elapses.
    #[tokio::test]
    async fn test_instance_reconciliation() {
        const TEST_RECONCILE_INTERVAL: Duration = Duration::from_millis(100);

        let rt = Runtime::from_current().unwrap();
        // Use process_local config to avoid needing etcd/nats
        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
            .await
            .unwrap();
        let ns = drt.namespace("test_reconciliation".to_string()).unwrap();
        let component = ns.component("test_component".to_string()).unwrap();
        let endpoint = component.endpoint("test_endpoint".to_string());

        // Use a short reconcile interval for faster tests
        let client = Client::with_reconcile_interval(endpoint, TEST_RECONCILE_INTERVAL)
            .await
            .unwrap();

        // Initially, instance_avail should be empty (no registered instances)
        assert!(client.instance_ids_avail().is_empty());

        // For this test, we'll directly manipulate instance_avail and verify reconciliation
        // Store some test IDs
        client.instance_avail.store(Arc::new(vec![1, 2, 3]));

        assert_eq!(**client.instance_ids_avail(), vec![1u64, 2, 3]);

        // Simulate report_instance_down removing instance 2
        client.report_instance_down(2);
        assert_eq!(**client.instance_ids_avail(), vec![1u64, 3]);

        // Wait for reconciliation interval + buffer
        // The monitor_instance_source will reset instance_avail to match instance_source
        // Since instance_source is empty, after reconciliation instance_avail should be empty
        tokio::time::sleep(TEST_RECONCILE_INTERVAL + Duration::from_millis(50)).await;

        // After reconciliation, instance_avail should match instance_source (which is empty)
        assert!(
            client.instance_ids_avail().is_empty(),
            "After reconciliation, instance_avail should match instance_source"
        );

        rt.shutdown();
    }

    /// Test that report_instance_down correctly removes an instance from instance_avail.
    #[tokio::test]
    async fn test_report_instance_down() {
        let rt = Runtime::from_current().unwrap();
        // Use process_local config to avoid needing etcd/nats
        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
            .await
            .unwrap();
        let ns = drt.namespace("test_report_down".to_string()).unwrap();
        let component = ns.component("test_component".to_string()).unwrap();
        let endpoint = component.endpoint("test_endpoint".to_string());

        let client = endpoint.client().await.unwrap();

        // Manually set up instance_avail with test instances
        client.instance_avail.store(Arc::new(vec![1, 2, 3]));
        assert_eq!(**client.instance_ids_avail(), vec![1u64, 2, 3]);

        // Report instance 2 as down
        client.report_instance_down(2);

        // Verify instance 2 is removed
        let avail = client.instance_ids_avail();
        assert!(avail.contains(&1), "Instance 1 should still be available");
        assert!(
            !avail.contains(&2),
            "Instance 2 should be removed after report_instance_down"
        );
        assert!(avail.contains(&3), "Instance 3 should still be available");

        rt.shutdown();
    }

    /// Test that instance_avail_watcher receives updates when instances change.
    #[tokio::test]
    async fn test_instance_avail_watcher() {
        let rt = Runtime::from_current().unwrap();
        // Use process_local config to avoid needing etcd/nats
        let drt = DistributedRuntime::new(rt.clone(), DistributedConfig::process_local())
            .await
            .unwrap();
        let ns = drt.namespace("test_watcher".to_string()).unwrap();
        let component = ns.component("test_component".to_string()).unwrap();
        let endpoint = component.endpoint("test_endpoint".to_string());

        let client = endpoint.client().await.unwrap();
        let watcher = client.instance_avail_watcher();

        // Set initial instances
        client.instance_avail.store(Arc::new(vec![1, 2, 3]));

        // Report instance down - this should notify the watcher
        client.report_instance_down(2);

        // The watcher should receive the update
        // Note: We need to check if changed() was signaled
        let current = watcher.borrow().clone();
        assert_eq!(current, vec![1, 3]);

        rt.shutdown();
    }
}