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