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