Skip to main content

tracevault_cli/commands/
flush.rs

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