Skip to main content

tracevault_cli/commands/
flush.rs

1use crate::api_client::{resolve_credentials, ApiClient};
2use std::fs;
3use std::io::{BufRead, BufReader, Write};
4use std::path::Path;
5use tracevault_protocol::streaming::StreamEventRequest;
6
7/// Extract the repo id from a per-repo pending queue filename
8/// (`pending-<repo_id>.jsonl`). Returns None for anything else (e.g. a legacy
9/// `pending.jsonl`).
10pub(crate) fn repo_id_from_pending_filename(name: &str) -> Option<&str> {
11    name.strip_prefix("pending-")?
12        .strip_suffix(".jsonl")
13        .filter(|s| !s.is_empty())
14}
15
16/// Classify a session dir's pending queue files. Returns (path, repo_id) pairs;
17/// per-repo files carry their own id, the legacy `pending.jsonl` is attributed
18/// to `bound_repo_id` (skipped entirely when None).
19/// Per-repo files are only included if their derived repo_id is a valid UUID.
20fn pending_queues_in(
21    session_dir: &Path,
22    bound_repo_id: Option<&str>,
23) -> std::io::Result<Vec<(std::path::PathBuf, String)>> {
24    let mut pending_queues: Vec<(std::path::PathBuf, String)> = fs::read_dir(session_dir)?
25        .filter_map(|e| e.ok())
26        .filter_map(|e| {
27            let path = e.path();
28            let name = path.file_name()?.to_str()?.to_string();
29            let repo_id = repo_id_from_pending_filename(&name)?.to_string();
30            // Validate repo_id is a UUID (guards against corrupted/hand-created files)
31            if uuid::Uuid::parse_str(&repo_id).is_ok() {
32                Some((path, repo_id))
33            } else {
34                None
35            }
36        })
37        .collect();
38
39    // Back-compat: releases before per-repo queue files existed wrote a
40    // single `pending.jsonl`, implicitly attributed to the bound
41    // `config.repo_id`. `status` counts these, so `flush` must be able to
42    // drain them or they're stuck forever. If there's no bound repo_id,
43    // skip it — there's nothing to attribute it to (best-effort).
44    let legacy_path = session_dir.join("pending.jsonl");
45    if legacy_path.exists() {
46        if let Some(repo_id) = bound_repo_id {
47            pending_queues.push((legacy_path, repo_id.to_string()));
48        }
49    }
50
51    Ok(pending_queues)
52}
53
54/// The progress line uses a short prefix of the session id for display; guards
55/// against a prior `[..8]` panic on session ids shorter than 8 bytes.
56fn short_session_id(id: &str) -> &str {
57    id.get(..8).unwrap_or(id)
58}
59
60pub async fn run_flush(project_root: &Path) -> Result<(), Box<dyn std::error::Error>> {
61    let org_slug = crate::resolution::org_slug_for(project_root)
62        .ok_or("no org configured (set TRACEVAULT_ORG_SLUG, log in, or run in a bound repo)")?;
63
64    let (server_url, token) = resolve_credentials(project_root);
65    let server_url = server_url.ok_or("server_url not configured")?;
66    let client = ApiClient::new(&server_url, token.as_deref());
67
68    // Lenient config load: used only to attribute the legacy `pending.jsonl`
69    // (written by releases before per-repo queue files existed) to the bound
70    // repo id, if any. Best-effort — a missing/malformed config just means
71    // any legacy queue can't be attributed and is left in place.
72    let bound_repo_id = crate::config::TracevaultConfig::load(project_root).and_then(|c| c.repo_id);
73
74    let sessions_dir = project_root.join(".tracevault").join("sessions");
75    if !sessions_dir.exists() {
76        println!("No sessions directory found. Nothing to flush.");
77        return Ok(());
78    }
79
80    let mut total_sent = 0u64;
81    let mut total_failed = 0u64;
82
83    let session_entries: Vec<_> = fs::read_dir(&sessions_dir)?
84        .filter_map(|e| e.ok())
85        .filter(|e| e.path().is_dir())
86        .collect();
87
88    for session_entry in session_entries {
89        // Collect (path, repo_id) pairs for every pending queue in this
90        // session directory before draining, to keep the borrow/async loop
91        // below simple.
92        let pending_queues = pending_queues_in(&session_entry.path(), bound_repo_id.as_deref())?;
93
94        for (pending_path, repo_id) in pending_queues {
95            let events = drain_pending(&pending_path)?;
96            if events.is_empty() {
97                continue;
98            }
99
100            let event_total = events.len();
101            let mut failed_events: Vec<StreamEventRequest> = Vec::new();
102
103            for (i, mut event) in events.into_iter().enumerate() {
104                eprint!(
105                    "\r  Session {} — event {}/{} ...",
106                    short_session_id(&event.session_id),
107                    i + 1,
108                    event_total
109                );
110                event.truncate_large_fields();
111                match client.stream_event(&org_slug, &repo_id, &event).await {
112                    Ok(_) => {
113                        total_sent += 1;
114                    }
115                    Err(e) => {
116                        eprintln!();
117                        let err_str = e.to_string();
118                        if err_str.contains("413") {
119                            // Payload too large even after truncation — drop it.
120                            eprintln!(
121                                "  Warning: dropped event (session {}) — still too large after truncation",
122                                event.session_id
123                            );
124                            total_failed += 1;
125                        } else {
126                            eprintln!(
127                                "  Warning: failed to send event (session {}): {e}",
128                                event.session_id
129                            );
130                            failed_events.push(event);
131                            total_failed += 1;
132                        }
133                    }
134                }
135            }
136            eprintln!();
137
138            // Re-enqueue transiently failed events (not 413s) to the SAME
139            // per-repo file.
140            if !failed_events.is_empty() {
141                append_pending(&pending_path, &failed_events)?;
142            }
143        }
144    }
145
146    println!("Flush complete: {total_sent} sent, {total_failed} failed");
147    Ok(())
148}
149
150/// Read and remove all events from a pending.jsonl file.
151fn drain_pending(path: &Path) -> Result<Vec<StreamEventRequest>, Box<dyn std::error::Error>> {
152    let file = fs::File::open(path)?;
153    let reader = BufReader::new(file);
154    let mut events = Vec::new();
155
156    for line in reader.lines() {
157        let line = line?;
158        let trimmed = line.trim();
159        if trimmed.is_empty() {
160            continue;
161        }
162        match serde_json::from_str::<StreamEventRequest>(trimmed) {
163            Ok(event) => events.push(event),
164            Err(e) => {
165                eprintln!("Warning: skipping malformed pending event: {e}");
166            }
167        }
168    }
169
170    // Truncate the file after reading
171    fs::write(path, "")?;
172
173    Ok(events)
174}
175
176/// Append events back to a pending.jsonl file (for re-enqueuing failures).
177fn append_pending(
178    path: &Path,
179    events: &[StreamEventRequest],
180) -> Result<(), Box<dyn std::error::Error>> {
181    let mut file = fs::OpenOptions::new()
182        .create(true)
183        .append(true)
184        .open(path)?;
185
186    for event in events {
187        let json = serde_json::to_string(event)?;
188        writeln!(file, "{json}")?;
189    }
190
191    Ok(())
192}
193
194// ---------------------------------------------------------------------------
195// Tests
196// ---------------------------------------------------------------------------
197
198#[cfg(test)]
199mod tests {
200    use super::{pending_queues_in, repo_id_from_pending_filename, short_session_id};
201    use crate::paths::resolve_project_root;
202    use crate::test_helpers::{add_worktree, init_git_repo};
203    use std::fs;
204
205    #[test]
206    fn repo_id_from_pending_filename_extracts_id() {
207        assert_eq!(
208            repo_id_from_pending_filename("pending-abc.jsonl"),
209            Some("abc")
210        );
211    }
212
213    #[test]
214    fn repo_id_from_pending_filename_none_for_legacy_name() {
215        assert_eq!(repo_id_from_pending_filename("pending.jsonl"), None);
216    }
217
218    #[test]
219    fn repo_id_from_pending_filename_none_for_unrelated_name() {
220        assert_eq!(repo_id_from_pending_filename("events.jsonl"), None);
221        assert_eq!(repo_id_from_pending_filename("pending-abc.txt"), None);
222    }
223
224    #[test]
225    fn repo_id_from_pending_filename_none_for_empty_id() {
226        assert_eq!(repo_id_from_pending_filename("pending-.jsonl"), None);
227    }
228
229    /// From a sibling worktree the resolved project root must point at the
230    /// PRIMARY checkout, so `flush` looks for sessions under
231    /// `<primary>/.tracevault/sessions/` rather than a non-existent sibling dir.
232    ///
233    /// This test asserts only the resolution layer — draining the queue requires
234    /// a live server, so the full end-to-end drain path is not exercised here.
235    #[test]
236    fn sessions_dir_from_sibling_worktree_is_under_primary() {
237        let tmp = tempfile::tempdir().unwrap();
238        let repo = tmp.path().join("repo");
239        let wt = tmp.path().join("sibling-wt");
240
241        fs::create_dir_all(&repo).unwrap();
242        init_git_repo(&repo);
243        add_worktree(&repo, &wt);
244
245        // Place a pending.jsonl in the primary sessions dir.
246        let session_id = "aabbccdd-0000-0000-0000-000000000001";
247        let sessions_dir = repo.join(".tracevault").join("sessions").join(session_id);
248        fs::create_dir_all(&sessions_dir).unwrap();
249        fs::write(sessions_dir.join("pending.jsonl"), "").unwrap();
250
251        // Simulate what main.rs now does: resolve from the SIBLING worktree cwd.
252        let resolved_root = resolve_project_root(&wt).root;
253        let expected_sessions = repo
254            .canonicalize()
255            .unwrap()
256            .join(".tracevault")
257            .join("sessions");
258        let got_sessions = resolved_root
259            .canonicalize()
260            .unwrap()
261            .join(".tracevault")
262            .join("sessions");
263
264        assert_eq!(
265            got_sessions, expected_sessions,
266            "flush must look for sessions under the PRIMARY repo, not the sibling worktree dir"
267        );
268    }
269
270    // ── pending_queues_in: per-session pending-queue enumeration ─────────────
271
272    fn setup_session_dir_with_pending_files() -> tempfile::TempDir {
273        let dir = tempfile::tempdir().unwrap();
274        fs::write(
275            dir.path()
276                .join("pending-0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b.jsonl"),
277            "",
278        )
279        .unwrap();
280        fs::write(
281            dir.path()
282                .join("pending-550e8400-e29b-41d4-a716-446655440000.jsonl"),
283            "",
284        )
285        .unwrap();
286        fs::write(dir.path().join("pending.jsonl"), "").unwrap();
287        fs::write(dir.path().join("notes.txt"), "").unwrap();
288        fs::write(dir.path().join("pending-.jsonl"), "").unwrap();
289        fs::write(dir.path().join("pending-not-a-uuid.jsonl"), "").unwrap();
290        dir
291    }
292
293    #[test]
294    fn pending_queues_in_with_bound_repo_includes_legacy() {
295        let dir = setup_session_dir_with_pending_files();
296        let mut got =
297            pending_queues_in(dir.path(), Some("550e8400-e29b-41d4-a716-446655440001")).unwrap();
298        got.sort_by(|a, b| a.1.cmp(&b.1));
299
300        let repo_ids: Vec<&str> = got.iter().map(|(_, id)| id.as_str()).collect();
301        assert_eq!(
302            repo_ids,
303            vec![
304                "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b",
305                "550e8400-e29b-41d4-a716-446655440000",
306                "550e8400-e29b-41d4-a716-446655440001"
307            ]
308        );
309
310        let legacy = got
311            .iter()
312            .find(|(_, id)| id == "550e8400-e29b-41d4-a716-446655440001")
313            .unwrap();
314        assert_eq!(legacy.0, dir.path().join("pending.jsonl"));
315    }
316
317    #[test]
318    fn pending_queues_in_without_bound_repo_skips_legacy() {
319        let dir = setup_session_dir_with_pending_files();
320        let mut got = pending_queues_in(dir.path(), None).unwrap();
321        got.sort_by(|a, b| a.1.cmp(&b.1));
322
323        let repo_ids: Vec<&str> = got.iter().map(|(_, id)| id.as_str()).collect();
324        assert_eq!(
325            repo_ids,
326            vec![
327                "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b",
328                "550e8400-e29b-41d4-a716-446655440000"
329            ]
330        );
331    }
332
333    #[test]
334    fn pending_queues_in_ignores_unrelated_and_malformed_names() {
335        let dir = setup_session_dir_with_pending_files();
336        let got =
337            pending_queues_in(dir.path(), Some("550e8400-e29b-41d4-a716-446655440001")).unwrap();
338
339        assert!(!got.iter().any(|(p, _)| p.ends_with("notes.txt")));
340        assert!(!got.iter().any(|(p, _)| p.ends_with("pending-.jsonl")));
341        // Non-UUID repo_ids are silently skipped (guards against corrupted files)
342        assert!(!got
343            .iter()
344            .any(|(p, _)| p.ends_with("pending-not-a-uuid.jsonl")));
345    }
346
347    #[test]
348    fn pending_queues_in_validates_uuid_in_per_repo_files() {
349        let dir = setup_session_dir_with_pending_files();
350        let got = pending_queues_in(dir.path(), None).unwrap();
351
352        // Valid UUIDs are included
353        assert!(got
354            .iter()
355            .any(|(p, _)| p.ends_with("pending-0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b.jsonl")));
356        assert!(got
357            .iter()
358            .any(|(p, _)| p.ends_with("pending-550e8400-e29b-41d4-a716-446655440000.jsonl")));
359        // Non-UUID files are NOT included
360        assert!(!got
361            .iter()
362            .any(|(p, _)| p.ends_with("pending-not-a-uuid.jsonl")));
363    }
364
365    // ── short_session_id: display-only truncation, no panic on short ids ─────
366
367    #[test]
368    fn short_session_id_truncates_long_id() {
369        assert_eq!(
370            short_session_id("0190a1b2-cccc-dddd-eeee-ffffffffffff"),
371            "0190a1b2"
372        );
373    }
374
375    #[test]
376    fn short_session_id_returns_whole_string_when_shorter_than_8() {
377        assert_eq!(short_session_id("x"), "x");
378    }
379
380    #[test]
381    fn short_session_id_handles_empty_string() {
382        assert_eq!(short_session_id(""), "");
383    }
384}