"launch/dynamo-run/vscode:/vscode.git/clone" did not exist on "e75bcf6704471bbc3277bdd776bc1d84b2b7ff1c"
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 anyhow::Result;
5
6
7
8
use async_trait::async_trait;
use futures::Stream;
use serde::{Deserialize, Serialize};
use std::pin::Pin;
9
use tokio_util::sync::CancellationToken;
10
11

mod mock;
12
13
14
pub use mock::{MockDiscovery, SharedMockRegistry};
mod kv_store;
pub use kv_store::KVStoreDiscovery;
15
pub mod utils;
16
use crate::component::TransportType;
17
18
pub use utils::watch_and_extract_field;

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

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

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

99
100
101
102
103
104
105
    /// 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,
106
107
108
109
110
111
112
113
                transport,
            } => DiscoveryInstance::Endpoint(crate::component::Instance {
                namespace,
                component,
                endpoint,
                instance_id,
                transport,
            }),
114
            Self::Model {
115
116
117
118
                namespace,
                component,
                endpoint,
                card_json,
119
            } => DiscoveryInstance::Model {
120
121
122
123
                namespace,
                component,
                endpoint,
                instance_id,
124
                card_json,
125
126
127
128
129
130
131
            },
        }
    }
}

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

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

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

172
/// Events emitted by the discovery watch stream
173
174
175
176
177
178
179
180
181
182
183
#[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>>;

184
/// Discovery trait for service discovery across different backends
185
#[async_trait]
186
pub trait Discovery: Send + Sync {
187
188
189
190
191
192
193
    /// 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>;

194
    /// Returns a list of currently registered instances for the given discovery query
195
    /// This is a one-time snapshot without watching for changes
196
197
198
199
200
201
202
203
204
    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>;
205
}