kv_store.rs 27.9 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
6
// SPDX-License-Identifier: Apache-2.0

use std::pin::Pin;
use std::sync::Arc;

7
8
9
10
11
use anyhow::Result;
use async_trait::async_trait;
use futures::{Stream, StreamExt};
use tokio_util::sync::CancellationToken;

12
use super::{
13
    Discovery, DiscoveryEvent, DiscoveryInstance, DiscoveryInstanceId, DiscoveryQuery,
14
15
    DiscoverySpec, DiscoveryStream, EndpointInstanceId, EventChannelInstanceId,
    ModelCardInstanceId,
16
};
17
use crate::storage::kv;
18
19
20

const INSTANCES_BUCKET: &str = "v1/instances";
const MODELS_BUCKET: &str = "v1/mdc";
21
const EVENT_CHANNELS_BUCKET: &str = "v1/event_channels";
22

23
/// Discovery implementation backed by a kv::Store
24
pub struct KVStoreDiscovery {
25
    store: Arc<kv::Manager>,
26
27
28
29
    cancel_token: CancellationToken,
}

impl KVStoreDiscovery {
30
    pub fn new(store: kv::Manager, cancel_token: CancellationToken) -> Self {
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
        Self {
            store: Arc::new(store),
            cancel_token,
        }
    }

    /// Build the key path for an endpoint (relative to bucket, not absolute)
    fn endpoint_key(namespace: &str, component: &str, endpoint: &str, instance_id: u64) -> String {
        format!("{}/{}/{}/{:x}", namespace, component, endpoint, instance_id)
    }

    /// Build the key path for a model (relative to bucket, not absolute)
    fn model_key(namespace: &str, component: &str, endpoint: &str, instance_id: u64) -> String {
        format!("{}/{}/{}/{:x}", namespace, component, endpoint, instance_id)
    }

47
48
49
50
51
52
53
54
55
56
    /// Build the key path for an event channel relative to bucket, not absolute)
    fn event_channel_key(
        namespace: &str,
        component: &str,
        topic: &str,
        instance_id: u64,
    ) -> String {
        format!("{}/{}/{}/{:x}", namespace, component, topic, instance_id)
    }

57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
    /// Extract prefix for querying based on discovery query
    fn query_prefix(query: &DiscoveryQuery) -> String {
        match query {
            DiscoveryQuery::AllEndpoints => INSTANCES_BUCKET.to_string(),
            DiscoveryQuery::NamespacedEndpoints { namespace } => {
                format!("{}/{}", INSTANCES_BUCKET, namespace)
            }
            DiscoveryQuery::ComponentEndpoints {
                namespace,
                component,
            } => {
                format!("{}/{}/{}", INSTANCES_BUCKET, namespace, component)
            }
            DiscoveryQuery::Endpoint {
                namespace,
                component,
                endpoint,
            } => {
                format!(
                    "{}/{}/{}/{}",
                    INSTANCES_BUCKET, namespace, component, endpoint
                )
            }
            DiscoveryQuery::AllModels => MODELS_BUCKET.to_string(),
            DiscoveryQuery::NamespacedModels { namespace } => {
                format!("{}/{}", MODELS_BUCKET, namespace)
            }
            DiscoveryQuery::ComponentModels {
                namespace,
                component,
            } => {
                format!("{}/{}/{}", MODELS_BUCKET, namespace, component)
            }
            DiscoveryQuery::EndpointModels {
                namespace,
                component,
                endpoint,
            } => {
                format!("{}/{}/{}/{}", MODELS_BUCKET, namespace, component, endpoint)
            }
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
            DiscoveryQuery::EventChannels(query) => {
                let mut path = EVENT_CHANNELS_BUCKET.to_string();
                if let Some(ns) = &query.namespace {
                    path.push('/');
                    path.push_str(ns);
                    if let Some(comp) = &query.component {
                        path.push('/');
                        path.push_str(comp);
                        if let Some(topic) = &query.topic {
                            path.push('/');
                            path.push_str(topic);
                        }
                    }
                }
                path
            }
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
        }
    }

    /// Strip bucket prefix from a key if present, returning the relative path within the bucket
    /// For example: "v1/instances/ns/comp/ep" -> "ns/comp/ep"
    /// Or if already relative: "ns/comp/ep" -> "ns/comp/ep"
    fn strip_bucket_prefix<'a>(key: &'a str, bucket_name: &str) -> &'a str {
        // Try to strip "bucket_name/" from the beginning
        if let Some(stripped) = key.strip_prefix(bucket_name) {
            // Strip the leading slash if present
            stripped.strip_prefix('/').unwrap_or(stripped)
        } else {
            // Key is already relative to bucket
            key
        }
    }

    /// Check if a key matches the given prefix, handling both absolute and relative key formats
    /// This works regardless of whether keys include the bucket prefix (etcd) or not (memory)
    fn matches_prefix(key_str: &str, prefix: &str, bucket_name: &str) -> bool {
        // Normalize both the key and prefix to relative paths (without bucket prefix)
        let relative_key = Self::strip_bucket_prefix(key_str, bucket_name);
        let relative_prefix = Self::strip_bucket_prefix(prefix, bucket_name);

        // Empty prefix matches everything in the bucket
        if relative_prefix.is_empty() {
            return true;
        }

        // Check if the relative key starts with the relative prefix
        relative_key.starts_with(relative_prefix)
    }

    /// Parse and deserialize a discovery instance from KV store entry
    fn parse_instance(value: &[u8]) -> Result<DiscoveryInstance> {
        let instance: DiscoveryInstance = serde_json::from_slice(value)?;
        Ok(instance)
    }
}

#[async_trait]
impl Discovery for KVStoreDiscovery {
    fn instance_id(&self) -> u64 {
        self.store.connection_id()
    }

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

        let (bucket_name, key_path) = match &instance {
            DiscoveryInstance::Endpoint(inst) => {
                let key = Self::endpoint_key(
                    &inst.namespace,
                    &inst.component,
                    &inst.endpoint,
                    inst.instance_id,
                );
                tracing::debug!(
                    "KVStoreDiscovery::register: Registering endpoint instance_id={}, namespace={}, component={}, endpoint={}, key={}",
                    inst.instance_id,
                    inst.namespace,
                    inst.component,
                    inst.endpoint,
                    key
                );
                (INSTANCES_BUCKET, key)
            }
            DiscoveryInstance::Model {
                namespace,
                component,
                endpoint,
                instance_id,
186
                model_suffix,
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
217
218
                let mut key = Self::model_key(namespace, component, endpoint, *instance_id);

                // If there's a model_suffix (e.g., for LoRA adapters), append it after the instance_id
                // Key format: {namespace}/{component}/{endpoint}/{instance_id:x}/{model_suffix}
                if let Some(suffix) = model_suffix
                    && !suffix.is_empty()
                {
                    key = format!("{}/{}", key, suffix);
                    tracing::debug!(
                        "KVStoreDiscovery::register: Registering LoRA model with suffix={}, instance_id={}, namespace={}, component={}, endpoint={}, key={}",
                        suffix,
                        instance_id,
                        namespace,
                        component,
                        endpoint,
                        key
                    );
                }

                // Log for base models (no suffix or empty suffix)
                if model_suffix.as_ref().is_none_or(|s| s.is_empty()) {
                    tracing::debug!(
                        "KVStoreDiscovery::register: Registering base model instance_id={}, namespace={}, component={}, endpoint={}, key={}",
                        instance_id,
                        namespace,
                        component,
                        endpoint,
                        key
                    );
                }
219
220
                (MODELS_BUCKET, key)
            }
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
            DiscoveryInstance::EventChannel {
                namespace,
                component,
                topic,
                instance_id,
                ..
            } => {
                let key = Self::event_channel_key(namespace, component, topic, *instance_id);
                // TODO: bis - remove this info log
                tracing::info!(
                    "KVStoreDiscovery::register: EventChannel bucket={}, key={}",
                    EVENT_CHANNELS_BUCKET,
                    key
                );
                tracing::debug!(
                    "KVStoreDiscovery::register: Registering event channel instance_id={}, namespace={}, component={}, topic={}, key={}",
                    instance_id,
                    namespace,
                    component,
                    topic,
                    key
                );
                (EVENT_CHANNELS_BUCKET, key)
            }
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
        };

        // Serialize the instance
        let instance_json = serde_json::to_vec(&instance)?;
        tracing::debug!(
            "KVStoreDiscovery::register: Serialized instance to {} bytes for key={}",
            instance_json.len(),
            key_path
        );

        // Store in the KV store with no TTL (instances persist until explicitly removed)
        tracing::debug!(
            "KVStoreDiscovery::register: Getting/creating bucket={} for key={}",
            bucket_name,
            key_path
        );
        let bucket = self.store.get_or_create_bucket(bucket_name, None).await?;
262
        let key = kv::Key::new(key_path.clone());
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280

        tracing::debug!(
            "KVStoreDiscovery::register: Inserting into bucket={}, key={}",
            bucket_name,
            key_path
        );
        // Use revision 0 for initial registration
        let outcome = bucket.insert(&key, instance_json.into(), 0).await?;
        tracing::debug!(
            "KVStoreDiscovery::register: Successfully registered instance_id={}, key={}, outcome={:?}",
            instance_id,
            key_path,
            outcome
        );

        Ok(instance)
    }

281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
    async fn unregister(&self, instance: DiscoveryInstance) -> Result<()> {
        let (bucket_name, key_path) = match &instance {
            DiscoveryInstance::Endpoint(inst) => {
                let key = Self::endpoint_key(
                    &inst.namespace,
                    &inst.component,
                    &inst.endpoint,
                    inst.instance_id,
                );
                tracing::debug!(
                    "Unregistering endpoint instance_id={}, namespace={}, component={}, endpoint={}, key={}",
                    inst.instance_id,
                    inst.namespace,
                    inst.component,
                    inst.endpoint,
                    key
                );
                (INSTANCES_BUCKET, key)
            }
            DiscoveryInstance::Model {
                namespace,
                component,
                endpoint,
                instance_id,
305
                model_suffix,
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
                let mut key = Self::model_key(namespace, component, endpoint, *instance_id);

                // If there's a model_suffix (e.g., for LoRA adapters), append it after the instance_id
                if let Some(suffix) = model_suffix
                    && !suffix.is_empty()
                {
                    key = format!("{}/{}", key, suffix);
                    tracing::debug!(
                        "KVStoreDiscovery::unregister: Unregistering LoRA model with suffix={}, instance_id={}, namespace={}, component={}, endpoint={}, key={}",
                        suffix,
                        instance_id,
                        namespace,
                        component,
                        endpoint,
                        key
                    );
                }

                // Log for base models (no suffix or empty suffix)
                if model_suffix.as_ref().is_none_or(|s| s.is_empty()) {
                    tracing::debug!(
                        "Unregistering base model instance_id={}, namespace={}, component={}, endpoint={}, key={}",
                        instance_id,
                        namespace,
                        component,
                        endpoint,
                        key
                    );
                }
337
338
                (MODELS_BUCKET, key)
            }
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
            DiscoveryInstance::EventChannel {
                namespace,
                component,
                topic,
                instance_id,
                ..
            } => {
                let key = Self::event_channel_key(namespace, component, topic, *instance_id);
                tracing::debug!(
                    "KVStoreDiscovery::unregister: Unregistering event channel instance_id={}, namespace={}, component={}, topic={}, key={}",
                    instance_id,
                    namespace,
                    component,
                    topic,
                    key
                );
                (EVENT_CHANNELS_BUCKET, key)
            }
357
358
359
360
361
362
363
364
365
366
367
        };

        // Get the bucket - if it doesn't exist, the instance is already removed from the KV store
        let Some(bucket) = self.store.get_bucket(bucket_name).await? else {
            tracing::warn!(
                "Bucket {} does not exist, instance already removed",
                bucket_name
            );
            return Ok(());
        };

368
        let key = kv::Key::new(key_path.clone());
369
370
371
372
373
374
375

        // Delete the entry from the bucket
        bucket.delete(&key).await?;

        Ok(())
    }

376
377
378
379
    async fn list(&self, query: DiscoveryQuery) -> Result<Vec<DiscoveryInstance>> {
        let prefix = Self::query_prefix(&query);
        let bucket_name = if prefix.starts_with(INSTANCES_BUCKET) {
            INSTANCES_BUCKET
380
381
        } else if prefix.starts_with(EVENT_CHANNELS_BUCKET) {
            EVENT_CHANNELS_BUCKET
382
383
384
385
386
387
        } else {
            MODELS_BUCKET
        };

        // Get bucket - if it doesn't exist, return empty list
        let Some(bucket) = self.store.get_bucket(bucket_name).await? else {
388
389
390
391
392
393
            tracing::info!(
                "KVStoreDiscovery::list: bucket missing for query={:?}, prefix={}, bucket={}",
                query,
                prefix,
                bucket_name
            );
394
395
396
397
398
            return Ok(Vec::new());
        };

        // Get all entries from the bucket
        let entries = bucket.entries().await?;
399
400
401
402
403
404
405
        tracing::info!(
            "KVStoreDiscovery::list: query={:?}, prefix={}, bucket={}, entries={}",
            query,
            prefix,
            bucket_name,
            entries.len()
        );
406
407
408

        // Filter by prefix and deserialize
        let mut instances = Vec::new();
409
410
        for (key, value) in entries {
            if Self::matches_prefix(key.as_ref(), &prefix, bucket_name) {
411
412
413
                match Self::parse_instance(&value) {
                    Ok(instance) => instances.push(instance),
                    Err(e) => {
414
                        tracing::warn!(%key, error = %e, "Failed to parse discovery instance");
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
                    }
                }
            }
        }

        Ok(instances)
    }

    async fn list_and_watch(
        &self,
        query: DiscoveryQuery,
        cancel_token: Option<CancellationToken>,
    ) -> Result<DiscoveryStream> {
        let prefix = Self::query_prefix(&query);
        let bucket_name = if prefix.starts_with(INSTANCES_BUCKET) {
            INSTANCES_BUCKET
431
432
        } else if prefix.starts_with(EVENT_CHANNELS_BUCKET) {
            EVENT_CHANNELS_BUCKET
433
434
435
436
        } else {
            MODELS_BUCKET
        };

437
        tracing::trace!(
438
439
440
441
442
443
444
445
446
            "KVStoreDiscovery::list_and_watch: Starting watch for query={:?}, prefix={}, bucket={}",
            query,
            prefix,
            bucket_name
        );

        // Use the provided cancellation token, or fall back to the default token
        let cancel_token = cancel_token.unwrap_or_else(|| self.cancel_token.clone());

447
        // Use the kv::Manager's watch mechanism
448
449
450
451
452
453
454
455
456
457
        let (_, mut rx) = self.store.clone().watch(
            bucket_name,
            None, // No TTL
            cancel_token,
        );

        // Create a stream that filters and transforms WatchEvents to DiscoveryEvents
        let stream = async_stream::stream! {
            while let Some(event) = rx.recv().await {
                let discovery_event = match event {
458
                    kv::WatchEvent::Put(kv) => {
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
                        // Check if this key matches our prefix
                        if !Self::matches_prefix(kv.key_str(), &prefix, bucket_name) {
                            continue;
                        }

                        match Self::parse_instance(kv.value()) {
                            Ok(instance) => {
                                Some(DiscoveryEvent::Added(instance))
                            },
                            Err(e) => {
                                tracing::warn!(
                                    key = %kv.key_str(),
                                    error = %e,
                                    "Failed to parse discovery instance from watch event"
                                );
                                None
                            }
                        }
                    }
478
                    kv::WatchEvent::Delete(kv) => {
479
480
481
482
483
484
                        let key_str = kv.as_ref();
                        // Check if this key matches our prefix
                        if !Self::matches_prefix(key_str, &prefix, bucket_name) {
                            continue;
                        }

485
486
                        // Extract DiscoveryInstanceId from the key path
                        // Delete events have empty values in etcd, so we reconstruct the ID from the key
487
488
                        //
                        // Key format (relative to bucket, after stripping bucket prefix):
489
                        // - Endpoints: "namespace/component/endpoint/{instance_id:x}"
490
491
                        // - Models: "namespace/component/endpoint/{instance_id:x}"
                        // - LoRA models: "namespace/component/endpoint/{instance_id:x}/{lora_slug}"
492
                        // - EventChannels: "namespace/component/{instance_id:x}"
493
494
495
496
497
                        //
                        // Use strip_bucket_prefix for consistency with matches_prefix().
                        let relative_key = Self::strip_bucket_prefix(key_str, bucket_name);
                        let key_parts: Vec<&str> = relative_key.split('/').collect();

498
499
500
501
                        // EventChannels need 4 parts (namespace/component/topic/instance_id)
                        // Endpoints/Models need at least 4 parts
                        let min_parts = 4;
                        if key_parts.len() < min_parts {
502
503
504
505
                            tracing::warn!(
                                key = %key_str,
                                relative_key = %relative_key,
                                actual_parts = key_parts.len(),
506
507
                                expected_min = min_parts,
                                bucket = bucket_name,
508
509
510
511
512
513
514
                                "Delete event key doesn't have enough parts"
                            );
                            continue;
                        }

                        let namespace = key_parts[0].to_string();
                        let component = key_parts[1].to_string();
515
516
517
518
519
520
521
522
523

                        // Handle EventChannel (4 parts: namespace/component/topic/instance_id) vs Endpoints/Models
                        let id = if bucket_name == EVENT_CHANNELS_BUCKET {
                            // EventChannel keys: namespace/component/topic/{instance_id:x}
                            let topic = key_parts[2].to_string();
                            let instance_id_hex = key_parts[3];
                            match u64::from_str_radix(instance_id_hex, 16) {
                                Ok(instance_id) => {
                                    DiscoveryInstanceId::EventChannel(EventChannelInstanceId {
524
525
                                        namespace,
                                        component,
526
                                        topic,
527
528
                                        instance_id,
                                    })
529
530
531
532
533
534
535
536
537
538
                                }
                                Err(e) => {
                                    tracing::warn!(
                                        key = %key_str,
                                        error = %e,
                                        instance_id_hex = %instance_id_hex,
                                        "Failed to parse event channel instance_id hex"
                                    );
                                    continue;
                                }
539
                            }
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
                        } else {
                            let endpoint = key_parts[2].to_string();
                            let instance_id_hex = key_parts[3];

                            match u64::from_str_radix(instance_id_hex, 16) {
                                Ok(instance_id) => {
                                    // Construct the appropriate DiscoveryInstanceId based on bucket type
                                    if bucket_name == INSTANCES_BUCKET {
                                        DiscoveryInstanceId::Endpoint(EndpointInstanceId {
                                            namespace,
                                            component,
                                            endpoint,
                                            instance_id,
                                        })
                                    } else {
                                        // Model - check for LoRA suffix (5th part if present)
                                        let model_suffix = key_parts.get(4).map(|s| s.to_string());
                                        DiscoveryInstanceId::Model(ModelCardInstanceId {
                                            namespace,
                                            component,
                                            endpoint,
                                            instance_id,
                                            model_suffix,
                                        })
                                    }
                                }
                                Err(e) => {
                                    tracing::warn!(
                                        key = %key_str,
                                        error = %e,
                                        instance_id_hex = %instance_id_hex,
                                        "Failed to parse instance_id hex from deleted key"
                                    );
                                    continue;
                                }
575
                            }
576
577
578
579
580
581
582
583
                        };

                        tracing::debug!(
                            "KVStoreDiscovery::list_and_watch: Emitting Removed event for {:?}, key={}",
                            id,
                            key_str
                        );
                        Some(DiscoveryEvent::Removed(id))
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
                    }
                };

                if let Some(event) = discovery_event {
                    yield Ok(event);
                }
            }
        };
        Ok(Box::pin(stream))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::component::TransportType;

    #[tokio::test]
    async fn test_kv_store_discovery_register_endpoint() {
603
        let store = kv::Manager::memory();
604
605
606
607
608
609
610
        let cancel_token = CancellationToken::new();
        let client = KVStoreDiscovery::new(store, cancel_token);

        let spec = DiscoverySpec::Endpoint {
            namespace: "test".to_string(),
            component: "comp1".to_string(),
            endpoint: "ep1".to_string(),
611
            transport: TransportType::Nats("nats://localhost:4222".to_string()),
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
        };

        let instance = client.register(spec).await.unwrap();

        match instance {
            DiscoveryInstance::Endpoint(inst) => {
                assert_eq!(inst.namespace, "test");
                assert_eq!(inst.component, "comp1");
                assert_eq!(inst.endpoint, "ep1");
            }
            _ => panic!("Expected Endpoint instance"),
        }
    }

    #[tokio::test]
    async fn test_kv_store_discovery_list() {
628
        let store = kv::Manager::memory();
629
630
631
632
633
634
635
636
        let cancel_token = CancellationToken::new();
        let client = KVStoreDiscovery::new(store, cancel_token);

        // Register multiple endpoints
        let spec1 = DiscoverySpec::Endpoint {
            namespace: "ns1".to_string(),
            component: "comp1".to_string(),
            endpoint: "ep1".to_string(),
637
            transport: TransportType::Nats("nats://localhost:4222".to_string()),
638
639
640
641
642
643
644
        };
        client.register(spec1).await.unwrap();

        let spec2 = DiscoverySpec::Endpoint {
            namespace: "ns1".to_string(),
            component: "comp1".to_string(),
            endpoint: "ep2".to_string(),
645
            transport: TransportType::Nats("nats://localhost:4222".to_string()),
646
647
648
649
650
651
652
        };
        client.register(spec2).await.unwrap();

        let spec3 = DiscoverySpec::Endpoint {
            namespace: "ns2".to_string(),
            component: "comp2".to_string(),
            endpoint: "ep1".to_string(),
653
            transport: TransportType::Nats("nats://localhost:4222".to_string()),
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
        };
        client.register(spec3).await.unwrap();

        // List all endpoints
        let all = client.list(DiscoveryQuery::AllEndpoints).await.unwrap();
        assert_eq!(all.len(), 3);

        // List namespaced endpoints
        let ns1 = client
            .list(DiscoveryQuery::NamespacedEndpoints {
                namespace: "ns1".to_string(),
            })
            .await
            .unwrap();
        assert_eq!(ns1.len(), 2);

        // List component endpoints
        let comp1 = client
            .list(DiscoveryQuery::ComponentEndpoints {
                namespace: "ns1".to_string(),
                component: "comp1".to_string(),
            })
            .await
            .unwrap();
        assert_eq!(comp1.len(), 2);
    }

    #[tokio::test]
    async fn test_kv_store_discovery_watch() {
683
        let store = kv::Manager::memory();
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
        let cancel_token = CancellationToken::new();
        let client = Arc::new(KVStoreDiscovery::new(store, cancel_token.clone()));

        // Start watching before registering
        let mut stream = client
            .list_and_watch(DiscoveryQuery::AllEndpoints, None)
            .await
            .unwrap();

        let client_clone = client.clone();
        let register_task = tokio::spawn(async move {
            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;

            let spec = DiscoverySpec::Endpoint {
                namespace: "test".to_string(),
                component: "comp1".to_string(),
                endpoint: "ep1".to_string(),
701
                transport: TransportType::Nats("nats://localhost:4222".to_string()),
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
            };
            client_clone.register(spec).await.unwrap();
        });

        // Wait for the added event
        let event = stream.next().await.unwrap().unwrap();
        match event {
            DiscoveryEvent::Added(instance) => match instance {
                DiscoveryInstance::Endpoint(inst) => {
                    assert_eq!(inst.namespace, "test");
                    assert_eq!(inst.component, "comp1");
                    assert_eq!(inst.endpoint, "ep1");
                }
                _ => panic!("Expected Endpoint instance"),
            },
            _ => panic!("Expected Added event"),
        }

        register_task.await.unwrap();
        cancel_token.cancel();
    }
}