mock.rs 8.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use super::{
    DiscoveryClient, DiscoveryEvent, DiscoveryInstance, DiscoveryKey, DiscoverySpec,
    DiscoveryStream,
};
use crate::Result;
use async_trait::async_trait;
use std::sync::{Arc, Mutex};

/// Shared in-memory registry for mock discovery
#[derive(Clone, Default)]
pub struct SharedMockRegistry {
    instances: Arc<Mutex<Vec<DiscoveryInstance>>>,
}

impl SharedMockRegistry {
    pub fn new() -> Self {
        Self::default()
    }
}

/// Mock implementation of DiscoveryClient for testing
/// We can potentially remove this once we have KeyValueDiscoveryClient implemented
pub struct MockDiscoveryClient {
    instance_id: u64,
    registry: SharedMockRegistry,
}

impl MockDiscoveryClient {
    pub fn new(instance_id: Option<u64>, registry: SharedMockRegistry) -> Self {
        let instance_id = instance_id.unwrap_or_else(|| {
            use std::sync::atomic::{AtomicU64, Ordering};
            static COUNTER: AtomicU64 = AtomicU64::new(1);
            COUNTER.fetch_add(1, Ordering::SeqCst)
        });

        Self {
            instance_id,
            registry,
        }
    }
}

/// Helper function to check if an instance matches a discovery key query
fn matches_key(instance: &DiscoveryInstance, key: &DiscoveryKey) -> bool {
    match (instance, key) {
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
        // Endpoint matching
        (DiscoveryInstance::Endpoint(_), DiscoveryKey::AllEndpoints) => true,
        (DiscoveryInstance::Endpoint(inst), DiscoveryKey::NamespacedEndpoints { namespace }) => {
            &inst.namespace == namespace
        }
        (
            DiscoveryInstance::Endpoint(inst),
            DiscoveryKey::ComponentEndpoints {
                namespace,
                component,
            },
        ) => &inst.namespace == namespace && &inst.component == component,
        (
            DiscoveryInstance::Endpoint(inst),
            DiscoveryKey::Endpoint {
                namespace,
                component,
                endpoint,
            },
        ) => {
            &inst.namespace == namespace
                && &inst.component == component
                && &inst.endpoint == endpoint
        }

        // ModelCard matching
        (DiscoveryInstance::ModelCard { .. }, DiscoveryKey::AllModelCards) => true,
76
        (
77
78
            DiscoveryInstance::ModelCard {
                namespace: inst_ns, ..
79
            },
80
81
            DiscoveryKey::NamespacedModelCards { namespace },
        ) => inst_ns == namespace,
82
        (
83
84
85
            DiscoveryInstance::ModelCard {
                namespace: inst_ns,
                component: inst_comp,
86
87
                ..
            },
88
            DiscoveryKey::ComponentModelCards {
89
90
91
                namespace,
                component,
            },
92
        ) => inst_ns == namespace && inst_comp == component,
93
        (
94
95
96
97
            DiscoveryInstance::ModelCard {
                namespace: inst_ns,
                component: inst_comp,
                endpoint: inst_ep,
98
99
                ..
            },
100
            DiscoveryKey::EndpointModelCards {
101
102
103
104
                namespace,
                component,
                endpoint,
            },
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
        ) => inst_ns == namespace && inst_comp == component && inst_ep == endpoint,

        // Cross-type matches return false
        (
            DiscoveryInstance::Endpoint(_),
            DiscoveryKey::AllModelCards
            | DiscoveryKey::NamespacedModelCards { .. }
            | DiscoveryKey::ComponentModelCards { .. }
            | DiscoveryKey::EndpointModelCards { .. },
        ) => false,
        (
            DiscoveryInstance::ModelCard { .. },
            DiscoveryKey::AllEndpoints
            | DiscoveryKey::NamespacedEndpoints { .. }
            | DiscoveryKey::ComponentEndpoints { .. }
            | DiscoveryKey::Endpoint { .. },
        ) => false,
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
    }
}

#[async_trait]
impl DiscoveryClient for MockDiscoveryClient {
    fn instance_id(&self) -> u64 {
        self.instance_id
    }

    async fn register(&self, spec: DiscoverySpec) -> Result<DiscoveryInstance> {
        let instance = spec.with_instance_id(self.instance_id);

        self.registry
            .instances
            .lock()
            .unwrap()
            .push(instance.clone());

        Ok(instance)
    }

143
144
145
146
147
148
149
150
151
    async fn list(&self, key: DiscoveryKey) -> Result<Vec<DiscoveryInstance>> {
        let instances = self.registry.instances.lock().unwrap();
        Ok(instances
            .iter()
            .filter(|instance| matches_key(instance, &key))
            .cloned()
            .collect())
    }

152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
    async fn list_and_watch(&self, key: DiscoveryKey) -> Result<DiscoveryStream> {
        use std::collections::HashSet;

        let registry = self.registry.clone();

        let stream = async_stream::stream! {
            let mut known_instances = HashSet::new();

            loop {
                let current: Vec<_> = {
                    let instances = registry.instances.lock().unwrap();
                    instances
                        .iter()
                        .filter(|instance| matches_key(instance, &key))
                        .cloned()
                        .collect()
                };

                let current_ids: HashSet<_> = current.iter().map(|i| {
                    match i {
172
173
                        DiscoveryInstance::Endpoint(inst) => inst.instance_id,
                        DiscoveryInstance::ModelCard { instance_id, .. } => *instance_id,
174
175
176
177
178
179
                    }
                }).collect();

                // Emit Added events for new instances
                for instance in current {
                    let id = match &instance {
180
181
                        DiscoveryInstance::Endpoint(inst) => inst.instance_id,
                        DiscoveryInstance::ModelCard { instance_id, .. } => *instance_id,
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
                    };
                    if known_instances.insert(id) {
                        yield Ok(DiscoveryEvent::Added(instance));
                    }
                }

                // Emit Removed events for instances that are gone
                for id in known_instances.difference(&current_ids).cloned().collect::<Vec<_>>() {
                    yield Ok(DiscoveryEvent::Removed(id));
                    known_instances.remove(&id);
                }

                tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
            }
        };

        Ok(Box::pin(stream))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::StreamExt;

    #[tokio::test]
    async fn test_mock_discovery_add_and_remove() {
        let registry = SharedMockRegistry::new();
        let client1 = MockDiscoveryClient::new(Some(1), registry.clone());
        let client2 = MockDiscoveryClient::new(Some(2), registry.clone());

        let spec = DiscoverySpec::Endpoint {
            namespace: "test-ns".to_string(),
            component: "test-comp".to_string(),
            endpoint: "test-ep".to_string(),
217
            transport: crate::component::TransportType::NatsTcp("test-subject".to_string()),
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
        };

        let key = DiscoveryKey::Endpoint {
            namespace: "test-ns".to_string(),
            component: "test-comp".to_string(),
            endpoint: "test-ep".to_string(),
        };

        // Start watching
        let mut stream = client1.list_and_watch(key.clone()).await.unwrap();

        // Add first instance
        client1.register(spec.clone()).await.unwrap();

        let event = stream.next().await.unwrap().unwrap();
        match event {
234
235
            DiscoveryEvent::Added(DiscoveryInstance::Endpoint(inst)) => {
                assert_eq!(inst.instance_id, 1);
236
237
238
239
240
241
242
243
244
            }
            _ => panic!("Expected Added event for instance-1"),
        }

        // Add second instance
        client2.register(spec.clone()).await.unwrap();

        let event = stream.next().await.unwrap().unwrap();
        match event {
245
246
            DiscoveryEvent::Added(DiscoveryInstance::Endpoint(inst)) => {
                assert_eq!(inst.instance_id, 2);
247
248
249
250
251
252
            }
            _ => panic!("Expected Added event for instance-2"),
        }

        // Remove first instance
        registry.instances.lock().unwrap().retain(|i| match i {
253
254
            DiscoveryInstance::Endpoint(inst) => inst.instance_id != 1,
            DiscoveryInstance::ModelCard { instance_id, .. } => *instance_id != 1,
255
256
257
258
259
260
261
262
263
264
265
        });

        let event = stream.next().await.unwrap().unwrap();
        match event {
            DiscoveryEvent::Removed(instance_id) => {
                assert_eq!(instance_id, 1);
            }
            _ => panic!("Expected Removed event for instance-1"),
        }
    }
}