mod.rs 6.42 KB
Newer Older
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

4
use crate::CancellationToken;
5
use crate::Result;
6
use crate::component::TransportType;
7
8
9
10
11
12
use async_trait::async_trait;
use futures::Stream;
use serde::{Deserialize, Serialize};
use std::pin::Pin;

mod mock;
13
14
15
16
pub use mock::{MockDiscovery, SharedMockRegistry};

mod kv_store;
pub use kv_store::KVStoreDiscovery;
17

18
19
20
pub mod utils;
pub use utils::watch_and_extract_field;

21
22
23
/// Query key for prefix-based discovery queries
/// Supports hierarchical queries from all endpoints down to specific endpoints
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
24
pub enum DiscoveryQuery {
25
26
27
    /// Query all endpoints in the system
    AllEndpoints,
    /// Query all endpoints in a specific namespace
28
29
30
    NamespacedEndpoints {
        namespace: String,
    },
31
32
33
34
35
36
37
38
39
40
41
    /// Query all endpoints in a namespace/component
    ComponentEndpoints {
        namespace: String,
        component: String,
    },
    /// Query a specific endpoint
    Endpoint {
        namespace: String,
        component: String,
        endpoint: String,
    },
42
43
    AllModels,
    NamespacedModels {
44
45
        namespace: String,
    },
46
    ComponentModels {
47
48
49
        namespace: String,
        component: String,
    },
50
    EndpointModels {
51
52
53
54
        namespace: String,
        component: String,
        endpoint: String,
    },
55
56
57
58
}

/// Specification for registering objects in the discovery plane
/// Represents the input to the register() operation
59
#[derive(Debug, Clone, PartialEq, Eq)]
60
61
62
63
64
65
pub enum DiscoverySpec {
    /// Endpoint specification for registration
    Endpoint {
        namespace: String,
        component: String,
        endpoint: String,
66
67
68
        /// Transport type and routing information
        transport: TransportType,
    },
69
    Model {
70
71
72
73
74
        namespace: String,
        component: String,
        endpoint: String,
        /// ModelDeploymentCard serialized as JSON
        /// This allows lib/runtime to remain independent of lib/llm types
75
        /// DiscoverySpec.from_model() and DiscoveryInstance.deserialize_model() are ergonomic helpers to create and deserialize the model card.
76
        card_json: serde_json::Value,
77
78
79
80
    },
}

impl DiscoverySpec {
81
    /// Creates a Model discovery spec from a serializable type
82
    /// The card will be serialized to JSON to avoid cross-crate dependencies
83
    pub fn from_model<T>(
84
85
86
87
88
89
90
91
92
        namespace: String,
        component: String,
        endpoint: String,
        card: &T,
    ) -> crate::Result<Self>
    where
        T: Serialize,
    {
        let card_json = serde_json::to_value(card)?;
93
        Ok(Self::Model {
94
95
96
97
98
99
100
            namespace,
            component,
            endpoint,
            card_json,
        })
    }

101
102
103
104
105
106
107
    /// Attaches an instance ID to create a DiscoveryInstance
    pub fn with_instance_id(self, instance_id: u64) -> DiscoveryInstance {
        match self {
            Self::Endpoint {
                namespace,
                component,
                endpoint,
108
109
110
111
112
113
114
115
                transport,
            } => DiscoveryInstance::Endpoint(crate::component::Instance {
                namespace,
                component,
                endpoint,
                instance_id,
                transport,
            }),
116
            Self::Model {
117
118
119
120
                namespace,
                component,
                endpoint,
                card_json,
121
            } => DiscoveryInstance::Model {
122
123
124
125
                namespace,
                component,
                endpoint,
                instance_id,
126
                card_json,
127
128
129
130
131
132
133
            },
        }
    }
}

/// Registered instances in the discovery plane
/// Represents objects that have been successfully registered with an instance ID
134
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
135
136
#[serde(tag = "type")]
pub enum DiscoveryInstance {
137
138
    /// Registered endpoint instance - wraps the component::Instance directly
    Endpoint(crate::component::Instance),
139
    Model {
140
141
142
143
        namespace: String,
        component: String,
        endpoint: String,
        instance_id: u64,
144
145
146
        /// ModelDeploymentCard serialized as JSON
        /// This allows lib/runtime to remain independent of lib/llm types
        card_json: serde_json::Value,
147
    },
148
149
150
151
152
153
154
}

impl DiscoveryInstance {
    /// Returns the instance ID for this discovery instance
    pub fn instance_id(&self) -> u64 {
        match self {
            Self::Endpoint(inst) => inst.instance_id,
155
            Self::Model { instance_id, .. } => *instance_id,
156
157
158
        }
    }

159
160
161
    /// Deserializes the model JSON into the specified type T
    /// Returns an error if this is not a Model instance or if deserialization fails
    pub fn deserialize_model<T>(&self) -> crate::Result<T>
162
163
164
165
    where
        T: for<'de> Deserialize<'de>,
    {
        match self {
166
            Self::Model { card_json, .. } => Ok(serde_json::from_value(card_json.clone())?),
167
            Self::Endpoint(_) => {
168
                crate::raise!("Cannot deserialize model from Endpoint instance")
169
170
171
            }
        }
    }
172
173
}

174
/// Events emitted by the discovery watch stream
175
176
177
178
179
180
181
182
183
184
185
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiscoveryEvent {
    /// A new instance was added
    Added(DiscoveryInstance),
    /// An instance was removed (identified by instance_id)
    Removed(u64),
}

/// Stream type for discovery events
pub type DiscoveryStream = Pin<Box<dyn Stream<Item = Result<DiscoveryEvent>> + Send>>;

186
/// Discovery trait for service discovery across different backends
187
#[async_trait]
188
pub trait Discovery: Send + Sync {
189
190
191
192
193
194
195
    /// Returns a unique identifier for this worker (e.g lease id if using etcd or generated id for memory store)
    /// Discovery objects created by this worker will be associated with this id.
    fn instance_id(&self) -> u64;

    /// Registers an object in the discovery plane with the instance id
    async fn register(&self, spec: DiscoverySpec) -> Result<DiscoveryInstance>;

196
    /// Returns a list of currently registered instances for the given discovery query
197
    /// This is a one-time snapshot without watching for changes
198
199
200
201
202
203
204
205
206
    async fn list(&self, query: DiscoveryQuery) -> Result<Vec<DiscoveryInstance>>;

    /// Returns a stream of discovery events (Added/Removed) for the given discovery query
    /// The optional cancellation token can be used to stop the watch stream
    async fn list_and_watch(
        &self,
        query: DiscoveryQuery,
        cancel_token: Option<CancellationToken>,
    ) -> Result<DiscoveryStream>;
207
}