Skip to main content

tracevault_cli/commands/
migrate.rs

1//! Directory-scoped project binding (VIS-1256): resolving a project NAME to
2//! the `project_id` a `.visdom/tracing.toml` carries, and migrating the
3//! legacy `default_project` name to it.
4//!
5//! The workspace tier of the capture chain reads `project_id` (a UUID)
6//! locally, so the per-event stream hook never needs the network. A NAME is
7//! resolved exactly once, by a command that already talks to the server and
8//! may write config: `tracevault init` (any mode that has a project config)
9//! and `tracevault sync`. Ingest never resolves names; until a config is
10//! migrated its `default_project` contributes nothing, and `project status` /
11//! `status` say so ([`legacy_default_project_notice`]).
12
13use crate::api_client::{ApiClient, ProjectListItem};
14use crate::config::TracevaultConfig;
15use crate::program::CLI;
16
17/// Exact, case-sensitive name → the one project carrying it. An unknown
18/// name lists the available ones; a name several projects share is an
19/// error naming their ids, never a guess.
20pub fn resolve_unique_project<'a>(
21    items: &'a [ProjectListItem],
22    name: &str,
23) -> Result<&'a ProjectListItem, String> {
24    let matches: Vec<&ProjectListItem> = items.iter().filter(|p| p.name == name).collect();
25    match matches.as_slice() {
26        [one] => Ok(one),
27        [] => {
28            let mut names: Vec<&str> = items.iter().map(|p| p.name.as_str()).collect();
29            names.sort_unstable();
30            names.dedup();
31            Err(format!(
32                "project '{name}' not found. Available: {}",
33                if names.is_empty() {
34                    "(none visible to this account)".to_string()
35                } else {
36                    names.join(", ")
37                }
38            ))
39        }
40        many => {
41            let ids: Vec<String> = many.iter().map(|p| p.id.to_string()).collect();
42            Err(format!(
43                "project name '{name}' is ambiguous: {} projects carry it ({}); set \
44                 `project_id = \"<id>\"` in .visdom/tracing.toml by hand",
45                many.len(),
46                ids.join(", ")
47            ))
48        }
49    }
50}
51
52/// Why a name could not be turned into a `project_id`.
53#[derive(Debug)]
54pub enum ResolveNameError {
55    /// The project list could not be fetched (network, auth, 5xx). The
56    /// caller decides whether that stops it; the config is left unchanged.
57    Unreachable(String),
58    /// The server answered, and the name is unknown or ambiguous. Always an
59    /// error: the config is left unchanged.
60    Name(String),
61}
62
63impl std::fmt::Display for ResolveNameError {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        match self {
66            ResolveNameError::Unreachable(e) => write!(f, "could not list projects: {e}"),
67            ResolveNameError::Name(e) => f.write_str(e),
68        }
69    }
70}
71
72/// Look `name` up once against the server's project list.
73pub async fn resolve_project_by_name(
74    client: &ApiClient,
75    name: &str,
76) -> Result<ProjectListItem, ResolveNameError> {
77    let items = client
78        .list_projects()
79        .await
80        .map_err(|e| ResolveNameError::Unreachable(e.to_string()))?;
81    resolve_unique_project(&items, name)
82        .map(|p| ProjectListItem {
83            id: p.id,
84            name: p.name.clone(),
85        })
86        .map_err(ResolveNameError::Name)
87}
88
89/// Whether the config carries a `project_id` the capture path would use (a
90/// UUID). Only such an id is authoritative over a legacy `default_project`:
91/// a garbage one must not cost the name that can repair it.
92fn has_valid_project_id(config: &TracevaultConfig) -> bool {
93    crate::resolution::project_from_config(config)
94        .as_ref()
95        .and_then(crate::resolution::capture_project_id)
96        .is_some()
97}
98
99/// What [`migrate_default_project`] did to the in-memory config.
100#[derive(Debug, PartialEq, Eq)]
101pub enum Migration {
102    /// No legacy `default_project` in the config: nothing to do.
103    NotNeeded,
104    /// `default_project` was resolved and replaced by `project_id` +
105    /// `project_name`.
106    Migrated {
107        name: String,
108        project_id: uuid::Uuid,
109    },
110    /// The config already had a `project_id`, which is authoritative; the
111    /// stale `default_project` was dropped without a lookup.
112    DroppedLegacy { name: String },
113}
114
115/// Migrate a config's legacy `default_project` NAME to `project_id` +
116/// `project_name`, in memory: the caller saves. On any error the config is
117/// left exactly as it was.
118///
119/// A config that already carries a `project_id` keeps it (it is what the
120/// capture chain already reads) and only loses the legacy key — no lookup.
121pub async fn migrate_default_project(
122    config: &mut TracevaultConfig,
123    client: &ApiClient,
124) -> Result<Migration, ResolveNameError> {
125    let Some(name) = config.default_project.clone() else {
126        return Ok(Migration::NotNeeded);
127    };
128    if has_valid_project_id(config) {
129        config.default_project = None;
130        return Ok(Migration::DroppedLegacy { name });
131    }
132    let project = resolve_project_by_name(client, &name)
133        .await
134        .map_err(|e| match e {
135            ResolveNameError::Name(msg) => {
136                ResolveNameError::Name(format!("cannot migrate default_project '{name}': {msg}"))
137            }
138            other => other,
139        })?;
140    config.project_id = Some(project.id.to_string());
141    config.project_name = Some(project.name);
142    config.default_project = None;
143    Ok(Migration::Migrated {
144        name,
145        project_id: project.id,
146    })
147}
148
149/// The one line a command prints after a migration, or `None` when nothing
150/// changed.
151pub fn migration_report(migration: &Migration) -> Option<String> {
152    match migration {
153        Migration::NotNeeded => None,
154        Migration::Migrated { name, project_id } => Some(format!(
155            "Migrated .visdom/tracing.toml: default_project '{name}' -> project_id {project_id}"
156        )),
157        Migration::DroppedLegacy { name } => Some(format!(
158            "Removed the legacy default_project '{name}' from .visdom/tracing.toml \
159             (its project_id is what attribution uses)"
160        )),
161    }
162}
163
164/// The status notice for a config that still carries the legacy
165/// `default_project`: the name is never used for capture, so `project
166/// status` and `status` say so instead of reporting it as effective (VIS-316:
167/// status must match ingest). `None` when the config has no legacy key.
168pub fn legacy_default_project_notice(config: &TracevaultConfig) -> Option<String> {
169    let name = config.default_project.as_deref()?;
170    Some(if has_valid_project_id(config) {
171        format!(
172            "default_project \"{name}\" in .visdom/tracing.toml is ignored (its project_id \
173             wins); run `{CLI} sync` to remove it"
174        )
175    } else {
176        format!(
177            "default_project \"{name}\" is not used for capture until migrated; run \
178             `{CLI} sync`"
179        )
180    })
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186    use crate::test_helpers::{http_json, spawn_seq};
187
188    fn item(id: u128, name: &str) -> ProjectListItem {
189        ProjectListItem {
190            id: uuid::Uuid::from_u128(id),
191            name: name.into(),
192        }
193    }
194
195    #[test]
196    fn resolve_unique_project_exact_unknown_and_ambiguous() {
197        let items = vec![item(1, "visdom"), item(2, "web"), item(3, "web")];
198        assert_eq!(
199            resolve_unique_project(&items, "visdom").unwrap().id,
200            uuid::Uuid::from_u128(1)
201        );
202        let unknown = resolve_unique_project(&items, "Visdom").unwrap_err();
203        assert!(unknown.contains("'Visdom' not found"), "{unknown}");
204        assert!(unknown.contains("visdom, web"), "{unknown}");
205        let ambiguous = resolve_unique_project(&items, "web").unwrap_err();
206        assert!(ambiguous.contains("ambiguous"), "{ambiguous}");
207        assert!(
208            ambiguous.contains(&uuid::Uuid::from_u128(2).to_string())
209                && ambiguous.contains(&uuid::Uuid::from_u128(3).to_string()),
210            "{ambiguous}"
211        );
212    }
213
214    const LIST: &str = r#"[{"id":"00000000-0000-4000-8000-0000000000aa","name":"visdom"},{"id":"00000000-0000-4000-8000-0000000000bb","name":"dup"},{"id":"00000000-0000-4000-8000-0000000000cc","name":"dup"}]"#;
215
216    #[tokio::test]
217    async fn migrate_resolves_the_name_and_drops_the_legacy_key() {
218        let (base, _rx) = spawn_seq(vec![http_json("200 OK", LIST)]);
219        let client = ApiClient::with_credential(&base, None);
220        let mut cfg = TracevaultConfig {
221            default_project: Some("visdom".into()),
222            ..Default::default()
223        };
224        let got = migrate_default_project(&mut cfg, &client).await.unwrap();
225        let id: uuid::Uuid = "00000000-0000-4000-8000-0000000000aa".parse().unwrap();
226        assert_eq!(
227            got,
228            Migration::Migrated {
229                name: "visdom".into(),
230                project_id: id
231            }
232        );
233        assert_eq!(cfg.project_id.as_deref(), Some(id.to_string().as_str()));
234        assert_eq!(cfg.project_name.as_deref(), Some("visdom"));
235        assert_eq!(cfg.default_project, None);
236    }
237
238    #[tokio::test]
239    async fn migrate_unknown_or_ambiguous_name_errors_and_leaves_config_unchanged() {
240        for name in ["nope", "dup"] {
241            let (base, _rx) = spawn_seq(vec![http_json("200 OK", LIST)]);
242            let client = ApiClient::with_credential(&base, None);
243            let mut cfg = TracevaultConfig {
244                default_project: Some(name.into()),
245                ..Default::default()
246            };
247            let err = migrate_default_project(&mut cfg, &client)
248                .await
249                .unwrap_err();
250            assert!(matches!(err, ResolveNameError::Name(_)), "{err}");
251            assert!(err.to_string().contains(&format!("'{name}'")), "{err}");
252            assert_eq!(cfg.default_project.as_deref(), Some(name));
253            assert_eq!(cfg.project_id, None);
254            assert_eq!(cfg.project_name, None);
255        }
256    }
257
258    #[tokio::test]
259    async fn migrate_unreachable_server_leaves_config_unchanged() {
260        let (base, _rx) = spawn_seq(vec![http_json("500 Internal Server Error", "{}")]);
261        let client = ApiClient::with_credential(&base, None);
262        let mut cfg = TracevaultConfig {
263            default_project: Some("visdom".into()),
264            ..Default::default()
265        };
266        let err = migrate_default_project(&mut cfg, &client)
267            .await
268            .unwrap_err();
269        assert!(matches!(err, ResolveNameError::Unreachable(_)), "{err}");
270        assert_eq!(cfg.default_project.as_deref(), Some("visdom"));
271        assert_eq!(cfg.project_id, None);
272    }
273
274    #[tokio::test]
275    async fn migrate_with_project_id_present_drops_legacy_without_a_lookup() {
276        // No server at all: a request would fail the test with Unreachable.
277        let client = ApiClient::with_credential("http://127.0.0.1:9", None);
278        let mut cfg = TracevaultConfig {
279            default_project: Some("old".into()),
280            project_id: Some("00000000-0000-4000-8000-0000000000aa".into()),
281            project_name: Some("visdom".into()),
282            ..Default::default()
283        };
284        let got = migrate_default_project(&mut cfg, &client).await.unwrap();
285        assert_eq!(got, Migration::DroppedLegacy { name: "old".into() });
286        assert_eq!(cfg.default_project, None);
287        assert_eq!(cfg.project_name.as_deref(), Some("visdom"));
288    }
289
290    /// A non-UUID `project_id` is not authoritative: the name is migrated
291    /// over it instead of being dropped.
292    #[tokio::test]
293    async fn migrate_with_an_invalid_project_id_resolves_the_name() {
294        let (base, _rx) = spawn_seq(vec![http_json("200 OK", LIST)]);
295        let client = ApiClient::with_credential(&base, None);
296        let mut cfg = TracevaultConfig {
297            default_project: Some("visdom".into()),
298            project_id: Some("not-a-uuid".into()),
299            ..Default::default()
300        };
301        let got = migrate_default_project(&mut cfg, &client).await.unwrap();
302        assert!(matches!(got, Migration::Migrated { .. }), "{got:?}");
303        assert_eq!(
304            cfg.project_id.as_deref(),
305            Some("00000000-0000-4000-8000-0000000000aa")
306        );
307        assert_eq!(cfg.default_project, None);
308        // and status calls it unmigrated, not shadowed, until then
309        let unmigrated = TracevaultConfig {
310            default_project: Some("visdom".into()),
311            project_id: Some("not-a-uuid".into()),
312            ..Default::default()
313        };
314        assert!(legacy_default_project_notice(&unmigrated)
315            .unwrap()
316            .contains("until migrated"));
317    }
318
319    #[tokio::test]
320    async fn migrate_without_legacy_key_is_a_no_op() {
321        let client = ApiClient::with_credential("http://127.0.0.1:9", None);
322        let mut cfg = TracevaultConfig::default();
323        assert_eq!(
324            migrate_default_project(&mut cfg, &client).await.unwrap(),
325            Migration::NotNeeded
326        );
327    }
328
329    #[test]
330    fn legacy_notice_unmigrated_vs_shadowed() {
331        let mut cfg = TracevaultConfig {
332            default_project: Some("visdom".into()),
333            ..Default::default()
334        };
335        assert_eq!(
336            legacy_default_project_notice(&cfg).unwrap(),
337            "default_project \"visdom\" is not used for capture until migrated; run `tracevault sync`"
338        );
339        cfg.project_id = Some("00000000-0000-4000-8000-0000000000aa".into());
340        assert!(legacy_default_project_notice(&cfg)
341            .unwrap()
342            .contains("ignored (its project_id wins)"));
343        cfg.default_project = None;
344        assert_eq!(legacy_default_project_notice(&cfg), None);
345    }
346}