1use crate::api_client::{ApiClient, ProjectListItem};
14use crate::config::TracevaultConfig;
15
16pub 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#[derive(Debug)]
53pub enum ResolveNameError {
54 Unreachable(String),
57 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
71pub 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
88fn 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#[derive(Debug, PartialEq, Eq)]
100pub enum Migration {
101 NotNeeded,
103 Migrated {
106 name: String,
107 project_id: uuid::Uuid,
108 },
109 DroppedLegacy { name: String },
112}
113
114pub 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
148pub 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
163pub 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 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 #[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 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}