Skip to main content

visdom_cli/
suite.rs

1//! Where the rest of the Visdom suite is, and what its workspace allows.
2//!
3//! `visdom` is told one address, the tracing server's. That server publishes
4//! the others (its public config's suite map); Control Plane, found that way,
5//! says how the workspace's LLM traffic must flow.
6
7use std::path::{Path, PathBuf};
8
9use serde::{Deserialize, Serialize};
10
11use crate::components::bazaar::is_http_url;
12use crate::mode::TrafficPolicy;
13
14/// The suite's other products, as the tracing server publishes them. A
15/// product that is not there (or not published) is `None`.
16#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
17pub struct SuiteMap {
18    /// Control Plane's public URL.
19    #[serde(default)]
20    pub control_plane_url: Option<String>,
21    /// The AI Gateway console's public URL.
22    #[serde(default)]
23    pub ai_gateway_url: Option<String>,
24    /// The bazaar MCP endpoint.
25    #[serde(default)]
26    pub bazaar_mcp_url: Option<String>,
27}
28
29impl SuiteMap {
30    /// Without the entries that are not plain http(s) URLs: what a server
31    /// says is not trusted to be an address.
32    fn only_urls(self) -> SuiteMap {
33        let url = |v: Option<String>| v.filter(|u| is_http_url(u));
34        SuiteMap {
35            control_plane_url: url(self.control_plane_url).map(trim_slash),
36            ai_gateway_url: url(self.ai_gateway_url).map(trim_slash),
37            bazaar_mcp_url: url(self.bazaar_mcp_url),
38        }
39    }
40}
41
42fn trim_slash(url: String) -> String {
43    url.trim_end_matches('/').to_string()
44}
45
46/// The suite map of the tracing server at `server_url`. A server that
47/// publishes none (an older one, or one without SSO) gives an empty map;
48/// `Err` (with the reason) only when it could not be asked.
49pub async fn fetch_suite_map(http: &reqwest::Client, server_url: &str) -> Result<SuiteMap, String> {
50    let url = format!(
51        "{}/api/v1/auth/public-config",
52        server_url.trim_end_matches('/')
53    );
54    let failed = |why: String| format!("{server_url} could not be asked for it: {why}");
55    let response = http
56        .get(&url)
57        .send()
58        .await
59        .map_err(|e| failed(e.to_string()))?;
60    if !response.status().is_success() {
61        return Err(failed(format!("HTTP {}", response.status().as_u16())));
62    }
63    let map: SuiteMap = response
64        .json()
65        .await
66        .map_err(|e| failed(format!("unreadable answer ({e})")))?;
67    Ok(map.only_urls())
68}
69
70/// A small JSON file of answers remembered per address, so that using a
71/// second installation does not forget the first one's.
72fn load_remembered<T: for<'de> Deserialize<'de>>(path: &Path, address: &str) -> Option<T> {
73    let text = std::fs::read_to_string(path).ok()?;
74    let mut all: std::collections::BTreeMap<String, T> = serde_json::from_str(&text).ok()?;
75    all.remove(&trim_slash(address.to_string()))
76}
77
78/// Best effort: an answer that cannot be written only means no fallback
79/// later. Entries that no longer read (another version's) are dropped.
80///
81/// Sessions starting side by side each remember their own installation's
82/// answer: reading, changing and writing happen under a lock, and the file is
83/// replaced in one move, so neither loses the other's entry nor reads half a
84/// file. An answer already remembered is not written again.
85fn save_remembered<T: Serialize + for<'de> Deserialize<'de>>(path: &Path, address: &str, value: T) {
86    let Some(dir) = path.parent() else {
87        return;
88    };
89    let _ = std::fs::create_dir_all(dir);
90    // Nothing is written without the lock: it would be over what another
91    // session is writing.
92    let Ok(_lock) = std::fs::OpenOptions::new()
93        .create(true)
94        .truncate(false)
95        .write(true)
96        .open(path.with_extension("lock"))
97        .and_then(|file| file.lock().map(|()| file))
98    else {
99        return;
100    };
101    let mut all: std::collections::BTreeMap<String, serde_json::Value> =
102        std::fs::read_to_string(path)
103            .ok()
104            .and_then(|text| serde_json::from_str(&text).ok())
105            .unwrap_or_default();
106    all.retain(|_, entry| serde_json::from_value::<T>(entry.clone()).is_ok());
107    let Ok(value) = serde_json::to_value(value) else {
108        return;
109    };
110    let address = trim_slash(address.to_string());
111    if all.get(&address) == Some(&value) {
112        return;
113    }
114    all.insert(address, value);
115    if let Ok(text) = serde_json::to_string(&all) {
116        let tmp = path.with_extension(format!("tmp{}", std::process::id()));
117        if std::fs::write(&tmp, text)
118            .and_then(|()| std::fs::rename(&tmp, path))
119            .is_err()
120        {
121            let _ = std::fs::remove_file(&tmp);
122        }
123    }
124}
125
126/// Where the suite maps last read from tracing servers are kept, so that the
127/// rest of the suite — and with it a workspace policy that requires the
128/// gateway — is still found while a server cannot be asked.
129pub fn suite_cache_path_in(config_root: &Path) -> PathBuf {
130    config_root.join("visdom").join("suite.json")
131}
132
133/// The remembered suite map of `server_url`.
134pub fn load_cached_suite(path: &Path, server_url: &str) -> Option<SuiteMap> {
135    load_remembered::<SuiteMap>(path, server_url).map(SuiteMap::only_urls)
136}
137
138pub fn save_cached_suite(path: &Path, server_url: &str, map: &SuiteMap) {
139    save_remembered(path, server_url, map.clone());
140}
141
142/// The suite map to work with, given what the tracing server at `server_url`
143/// just said: its answer (which is then remembered), or, when it could not be
144/// asked, the one it gave last time.
145pub fn suite_map_or_remembered(
146    published: &Result<SuiteMap, String>,
147    server_url: &str,
148    cache: &Path,
149) -> SuiteMap {
150    match published {
151        Ok(map) => {
152            save_cached_suite(cache, server_url, map);
153            map.clone()
154        }
155        Err(_) => load_cached_suite(cache, server_url).unwrap_or_default(),
156    }
157}
158
159/// The workspace's AI traffic policy, from Control Plane at `control_plane_url`
160/// with the developer's own token. Any signed-in person may read it.
161pub async fn fetch_policy(
162    http: &reqwest::Client,
163    control_plane_url: &str,
164    token: &str,
165) -> Result<TrafficPolicy, String> {
166    #[derive(Deserialize)]
167    struct Settings {
168        ai_traffic_policy: TrafficPolicy,
169    }
170    let url = format!(
171        "{}/api/v1/workspace/settings",
172        control_plane_url.trim_end_matches('/')
173    );
174    let response = http
175        .get(&url)
176        .bearer_auth(token)
177        .send()
178        .await
179        .map_err(|e| format!("Control Plane ({control_plane_url}) did not answer: {e}"))?;
180    let status = response.status();
181    if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
182        return Err(format!(
183            "Control Plane refused this login (HTTP {}); log in again with `visdom login`",
184            status.as_u16()
185        ));
186    }
187    if !status.is_success() {
188        return Err(format!("Control Plane answered HTTP {}", status.as_u16()));
189    }
190    response
191        .json::<Settings>()
192        .await
193        .map(|s| s.ai_traffic_policy)
194        .map_err(|e| format!("Control Plane's settings could not be read ({e})"))
195}
196
197/// Where the policies last read from Control Planes are kept, so that an
198/// enforced policy still holds while Control Plane cannot be reached.
199pub fn policy_cache_path_in(config_root: &Path) -> PathBuf {
200    config_root.join("visdom").join("policy.json")
201}
202
203/// The remembered policy of `control_plane_url`.
204pub fn load_cached_policy(path: &Path, control_plane_url: &str) -> Option<TrafficPolicy> {
205    load_remembered(path, control_plane_url)
206}
207
208pub fn save_cached_policy(path: &Path, control_plane_url: &str, policy: TrafficPolicy) {
209    save_remembered(path, control_plane_url, policy);
210}
211
212/// What is known about the workspace policy for one run.
213#[derive(Clone, Debug, PartialEq, Eq)]
214pub enum PolicyState {
215    /// Read from Control Plane just now.
216    Fresh(TrafficPolicy),
217    /// Control Plane could not be asked (the reason); this is its last answer.
218    Remembered(TrafficPolicy, String),
219    /// Not known, and why: no Control Plane, no login it accepts, no answer.
220    Unknown(String),
221}
222
223impl PolicyState {
224    pub fn policy(&self) -> Option<TrafficPolicy> {
225        match self {
226            PolicyState::Fresh(p) | PolicyState::Remembered(p, _) => Some(*p),
227            PolicyState::Unknown(_) => None,
228        }
229    }
230}
231
232/// Read the policy, falling back to the remembered one, and remember a fresh
233/// answer. `token` is the developer's Keycloak access token; `None` when they
234/// have none (not logged in, or an API key, which is never sent elsewhere).
235pub async fn resolve_policy(
236    http: &reqwest::Client,
237    control_plane_url: Option<&str>,
238    token: Option<&str>,
239    cache: &Path,
240) -> PolicyState {
241    let Some(cp) = control_plane_url else {
242        return PolicyState::Unknown("this installation names no Control Plane".to_string());
243    };
244    let outcome = match token {
245        Some(token) => fetch_policy(http, cp, token).await,
246        None => Err("not logged in with a Visdom account".to_string()),
247    };
248    match outcome {
249        Ok(policy) => {
250            save_cached_policy(cache, cp, policy);
251            PolicyState::Fresh(policy)
252        }
253        Err(why) => match load_cached_policy(cache, cp) {
254            Some(policy) => PolicyState::Remembered(policy, why),
255            None => PolicyState::Unknown(why),
256        },
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use crate::test_http::MockServer;
264
265    const CONFIG: &str = "GET /api/v1/auth/public-config";
266    const SETTINGS: &str = "GET /api/v1/workspace/settings";
267
268    #[tokio::test]
269    async fn the_suite_map_is_what_the_server_publishes() {
270        let http = reqwest::Client::new();
271        let server = MockServer::start(&[(
272            CONFIG,
273            200,
274            r#"{"oidc_enabled":true,"issuer":"https://idp.test/realms/v","cli_client_id":"c",
275                "control_plane_url":"https://cp.example.com/",
276                "ai_gateway_url":"https://gw.example.com",
277                "bazaar_mcp_url":"https://ctx.example.com/mcp/"}"#,
278        )]);
279        assert_eq!(
280            fetch_suite_map(&http, &format!("{}/", server.url)).await,
281            Ok(SuiteMap {
282                control_plane_url: Some("https://cp.example.com".to_string()),
283                ai_gateway_url: Some("https://gw.example.com".to_string()),
284                // An endpoint keeps its path as published.
285                bazaar_mcp_url: Some("https://ctx.example.com/mcp/".to_string()),
286            })
287        );
288    }
289
290    #[tokio::test]
291    async fn a_server_without_a_suite_map_gives_an_empty_one() {
292        let http = reqwest::Client::new();
293        for body in [
294            r#"{"oidc_enabled":false}"#,
295            r#"{"oidc_enabled":true,"issuer":"https://idp.test/realms/v","cli_client_id":"c"}"#,
296        ] {
297            let server = MockServer::start(&[(CONFIG, 200, body)]);
298            assert_eq!(
299                fetch_suite_map(&http, &server.url).await,
300                Ok(SuiteMap::default())
301            );
302        }
303    }
304
305    #[tokio::test]
306    async fn what_is_not_an_http_url_is_dropped() {
307        let http = reqwest::Client::new();
308        let server = MockServer::start(&[(
309            CONFIG,
310            200,
311            r#"{"oidc_enabled":true,"control_plane_url":"javascript:alert(1)",
312                "ai_gateway_url":"--flag","bazaar_mcp_url":"https://ctx.example.com/mcp"}"#,
313        )]);
314        assert_eq!(
315            fetch_suite_map(&http, &server.url).await,
316            Ok(SuiteMap {
317                bazaar_mcp_url: Some("https://ctx.example.com/mcp".to_string()),
318                ..SuiteMap::default()
319            })
320        );
321    }
322
323    #[tokio::test]
324    async fn a_server_that_cannot_be_asked_is_an_error_with_the_reason() {
325        let http = reqwest::Client::new();
326        let err = fetch_suite_map(&http, "http://127.0.0.1:1")
327            .await
328            .unwrap_err();
329        assert!(err.contains("http://127.0.0.1:1"), "{err}");
330        let server = MockServer::start(&[(CONFIG, 500, "{}")]);
331        let err = fetch_suite_map(&http, &server.url).await.unwrap_err();
332        assert!(err.contains("HTTP 500"), "{err}");
333    }
334
335    #[tokio::test]
336    async fn the_policy_is_read_with_the_persons_token() {
337        let http = reqwest::Client::new();
338        let server = MockServer::start(&[(
339            SETTINGS,
340            200,
341            r#"{"timezone":"Europe/Warsaw","ai_traffic_policy":"enforced"}"#,
342        )]);
343        assert_eq!(
344            fetch_policy(&http, &server.url, "tok").await,
345            Ok(TrafficPolicy::Enforced)
346        );
347        assert_eq!(
348            server.requests()[0].authorization.as_deref(),
349            Some("Bearer tok")
350        );
351    }
352
353    #[tokio::test]
354    async fn a_refused_login_and_a_broken_answer_are_told_apart() {
355        let http = reqwest::Client::new();
356        let server = MockServer::start(&[(SETTINGS, 401, "{}")]);
357        let err = fetch_policy(&http, &server.url, "tok").await.unwrap_err();
358        assert!(err.contains("log in again"), "{err}");
359        let server = MockServer::start(&[(SETTINGS, 200, r#"{"timezone":"UTC"}"#)]);
360        let err = fetch_policy(&http, &server.url, "tok").await.unwrap_err();
361        assert!(err.contains("could not be read"), "{err}");
362        let server = MockServer::start(&[(SETTINGS, 200, r#"{"ai_traffic_policy":"new"}"#)]);
363        assert!(fetch_policy(&http, &server.url, "tok").await.is_err());
364    }
365
366    /// Sessions starting side by side, each with its own installation: every
367    /// answer is kept, and the file never reads as anything but whole.
368    #[test]
369    fn answers_remembered_at_the_same_time_are_all_kept() {
370        let tmp = tempfile::tempdir().unwrap();
371        let cache = policy_cache_path_in(tmp.path());
372        let address = |i: usize| format!("https://cp-{i}.example.com");
373        std::thread::scope(|scope| {
374            for i in 0..16 {
375                let cache = &cache;
376                scope.spawn(move || {
377                    save_cached_policy(cache, &address(i), TrafficPolicy::Enforced);
378                    let text = std::fs::read_to_string(cache).unwrap();
379                    serde_json::from_str::<serde_json::Value>(&text).expect("a whole file");
380                });
381            }
382        });
383        for i in 0..16 {
384            assert_eq!(
385                load_cached_policy(&cache, &address(i)),
386                Some(TrafficPolicy::Enforced),
387                "{i}"
388            );
389        }
390        let left: Vec<_> = std::fs::read_dir(cache.parent().unwrap())
391            .unwrap()
392            .map(|e| e.unwrap().file_name().into_string().unwrap())
393            .filter(|name| name.contains("tmp"))
394            .collect();
395        assert!(left.is_empty(), "{left:?}");
396    }
397
398    #[test]
399    fn nothing_is_remembered_while_the_cache_cannot_be_locked() {
400        let tmp = tempfile::tempdir().unwrap();
401        let cache = policy_cache_path_in(tmp.path());
402        save_cached_policy(&cache, "https://cp.example.com", TrafficPolicy::Enforced);
403        // The lock file cannot be opened: a directory is in its place.
404        std::fs::remove_file(cache.with_extension("lock")).unwrap();
405        std::fs::create_dir(cache.with_extension("lock")).unwrap();
406        save_cached_policy(&cache, "https://other.example.com", TrafficPolicy::Direct);
407        assert_eq!(
408            load_cached_policy(&cache, "https://cp.example.com"),
409            Some(TrafficPolicy::Enforced)
410        );
411        assert_eq!(
412            load_cached_policy(&cache, "https://other.example.com"),
413            None
414        );
415    }
416
417    #[tokio::test]
418    async fn a_fresh_policy_is_remembered_for_when_control_plane_is_away() {
419        let http = reqwest::Client::new();
420        let tmp = tempfile::tempdir().unwrap();
421        let cache = policy_cache_path_in(tmp.path());
422        let server = MockServer::start(&[
423            (SETTINGS, 200, r#"{"ai_traffic_policy":"enforced"}"#),
424            (SETTINGS, 503, "{}"),
425        ]);
426        let cp = Some(server.url.as_str());
427        assert_eq!(
428            resolve_policy(&http, cp, Some("tok"), &cache).await,
429            PolicyState::Fresh(TrafficPolicy::Enforced)
430        );
431        // Control Plane is down: its last answer still holds.
432        match resolve_policy(&http, cp, Some("tok"), &cache).await {
433            PolicyState::Remembered(TrafficPolicy::Enforced, why) => {
434                assert!(why.contains("HTTP 503"), "{why}")
435            }
436            other => panic!("{other:?}"),
437        }
438        // Logged out: the same.
439        assert_eq!(
440            resolve_policy(&http, cp, None, &cache).await.policy(),
441            Some(TrafficPolicy::Enforced)
442        );
443        // Another Control Plane's policy was never read.
444        match resolve_policy(&http, Some("http://127.0.0.1:1"), Some("tok"), &cache).await {
445            PolicyState::Unknown(_) => {}
446            other => panic!("{other:?}"),
447        }
448    }
449
450    #[test]
451    fn a_server_that_cannot_be_asked_leaves_its_last_suite_map() {
452        let tmp = tempfile::tempdir().unwrap();
453        let cache = suite_cache_path_in(tmp.path());
454        let server = "https://tracing.example.com";
455        let down = Err("no answer".to_string());
456        // Never asked successfully: nothing to fall back to.
457        assert_eq!(
458            suite_map_or_remembered(&down, server, &cache),
459            SuiteMap::default()
460        );
461        let map = SuiteMap {
462            control_plane_url: Some("https://cp.example.com".to_string()),
463            ai_gateway_url: Some("https://gw.example.com".to_string()),
464            bazaar_mcp_url: None,
465        };
466        assert_eq!(
467            suite_map_or_remembered(&Ok(map.clone()), server, &cache),
468            map
469        );
470        // Now it is away: what it said last holds, for that server only.
471        assert_eq!(suite_map_or_remembered(&down, server, &cache), map);
472        assert_eq!(
473            suite_map_or_remembered(&down, &format!("{server}/"), &cache),
474            map
475        );
476        assert_eq!(
477            suite_map_or_remembered(&down, "https://other.example.com", &cache),
478            SuiteMap::default()
479        );
480        // Another installation's answer is kept beside it, not in its place.
481        let other = SuiteMap {
482            control_plane_url: Some("https://cp.other.example.com".to_string()),
483            ..SuiteMap::default()
484        };
485        let elsewhere = "https://tracing.other.example.com";
486        suite_map_or_remembered(&Ok(other.clone()), elsewhere, &cache);
487        assert_eq!(suite_map_or_remembered(&down, server, &cache), map);
488        assert_eq!(suite_map_or_remembered(&down, elsewhere, &cache), other);
489        // A later answer replaces it, an empty one included.
490        suite_map_or_remembered(&Ok(SuiteMap::default()), server, &cache);
491        assert_eq!(
492            suite_map_or_remembered(&down, server, &cache),
493            SuiteMap::default()
494        );
495    }
496
497    #[tokio::test]
498    async fn no_control_plane_means_no_policy() {
499        let http = reqwest::Client::new();
500        let tmp = tempfile::tempdir().unwrap();
501        let state = resolve_policy(&http, None, Some("tok"), &tmp.path().join("p.json")).await;
502        assert_eq!(state.policy(), None);
503        assert!(matches!(state, PolicyState::Unknown(_)));
504    }
505}