Skip to main content

switchyard_runner/
runner.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Named route table and server-facing route metadata.
5
6use std::collections::BTreeMap;
7use std::path::Path;
8
9use libsy::RoutingOutcome;
10use serde_json::Value;
11use switchyard_protocol::{ModelId, WireFormat};
12
13use crate::config;
14use crate::{ModelCapabilities, Route, RunnerError};
15
16/// Immutable named route table.
17pub struct Runner {
18    routes: Vec<(ModelId, Route)>,
19    fallback_base_url: Option<String>,
20    provider_api_keys: Vec<String>,
21}
22
23/// Borrowed model metadata returned while listing routes.
24pub struct ModelInfo<'a> {
25    pub id: &'a ModelId,
26    pub algorithm: &'a str,
27    pub capabilities: ModelCapabilities,
28}
29
30/// Fully resolved routing decision.
31pub struct DecisionDescription {
32    pub selected: DecisionTarget,
33    pub fallbacks: Vec<DecisionTarget>,
34}
35
36/// Non-secret configured target details returned by the decision endpoint.
37#[derive(Clone)]
38pub struct DecisionTarget {
39    pub target: String,
40    pub model: ModelId,
41    pub format: WireFormat,
42    pub base_url: String,
43    pub extra_body: BTreeMap<String, Value>,
44}
45
46impl Runner {
47    /// Loads and validates a version-1 deployment TOML file.
48    pub fn load(path: impl AsRef<Path>) -> Result<Self, RunnerError> {
49        config::load_runner(path)
50    }
51
52    /// Loads and validates a version-1 deployment TOML document.
53    ///
54    /// Use [`Self::load`] when the deployment is stored in a file.
55    pub fn from_toml(source: &str) -> Result<Self, RunnerError> {
56        config::runner_from_toml(source)
57    }
58
59    /// Builds a runner from named routes in caller-provided order.
60    /// Pre-condition: There must be at least one route.
61    pub fn new(routes: Vec<(ModelId, Route)>) -> Self {
62        Self {
63            routes,
64            fallback_base_url: None,
65            provider_api_keys: Vec::new(),
66        }
67    }
68
69    /// Registers deployment-owned API keys for serving-surface output redaction.
70    /// TOML loading registers these automatically; programmatic hosts must supply them.
71    pub fn with_provider_api_keys(mut self, keys: Vec<String>) -> Self {
72        self.provider_api_keys = keys;
73        self
74    }
75
76    /// Returns deployment-owned secrets for serving-surface output redactors.
77    pub fn provider_api_keys(&self) -> &[String] {
78        &self.provider_api_keys
79    }
80
81    pub(crate) fn with_fallback_url(mut self, fallback_base_url: Option<String>) -> Self {
82        self.fallback_base_url = fallback_base_url;
83        self
84    }
85
86    /// Returns the route registered for a model.
87    pub fn route(&self, model: &str) -> Option<&Route> {
88        self.routes
89            .iter()
90            .find(|(id, _)| id.as_str() == model)
91            .map(|(_, route)| route)
92    }
93
94    /// Iterates over configured routes in caller-provided order.
95    pub fn models(&self) -> impl Iterator<Item = ModelInfo<'_>> {
96        self.routes.iter().map(|(id, route)| ModelInfo {
97            id,
98            algorithm: route.algorithm_name(),
99            capabilities: route.capabilities(),
100        })
101    }
102
103    /// Returns the validated API root used for unmatched HTTP requests.
104    pub fn fallback_base_url(&self) -> Option<&str> {
105        self.fallback_base_url.as_deref()
106    }
107
108    /// Resolves an outcome to configured target names and non-secret client settings.
109    pub fn describe_decision(
110        &self,
111        model: &ModelId,
112        outcome: &RoutingOutcome,
113    ) -> Option<DecisionDescription> {
114        let route = self.route(model.as_str())?;
115        let resolve = |selected: &ModelId| {
116            let mut target = route.decision_target(selected)?;
117            let mut url = reqwest::Url::parse(&target.base_url).ok()?;
118            let query: Vec<_> = url
119                .query_pairs()
120                .filter(|(name, _)| !matches!(name.as_ref(), "key" | "api_key"))
121                .map(|(name, value)| (name.into_owned(), value.into_owned()))
122                .collect();
123            if query.len() != url.query_pairs().count() {
124                url.set_query(None);
125                if !query.is_empty() {
126                    url.query_pairs_mut().extend_pairs(query);
127                }
128                // Only the returned metadata changes; inference still needs its credentials.
129                target.base_url = url.into();
130            }
131            Some(target)
132        };
133        let mut model_ids = outcome.selected_model_ids.iter();
134        Some(DecisionDescription {
135            selected: resolve(model_ids.next()?)?,
136            fallbacks: model_ids.map(resolve).collect::<Option<Vec<_>>>()?,
137        })
138    }
139}