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/// Shared spelling of the offline-queue filenames. These are the ONLY place
9/// the shape is written down: `commands::stream` builds names from them and
10/// this module parses names with them, so the writer and the reader cannot
11/// drift apart. Drift would be silent — a name this module fails to classify
12/// is skipped, stranding the queue while `status` keeps counting it.
13pub(crate) const QUEUE_PREFIX: &str = "pending-";
14/// Repo-less queues. Note this EXTENDS `QUEUE_PREFIX`, which is what makes an
15/// older CLI skip these files rather than mis-drain them.
16pub(crate) const PROJECT_QUEUE_PREFIX: &str = "pending-project-";
17pub(crate) const QUEUE_SUFFIX: &str = ".jsonl";
18
19/// Extract the repo id from a per-repo pending queue filename
20/// (`pending-<repo_id>.jsonl`). Returns None for anything else (e.g. a legacy
21/// `pending.jsonl`).
22///
23/// Note this also matches a repo-less `pending-project-<uuid>.jsonl` and
24/// yields `project-<uuid>`, which is not a UUID. That is deliberate and is
25/// what keeps an older CLI from mis-draining those queues; callers here must
26/// try [`project_id_from_pending_filename`] FIRST.
27pub(crate) fn repo_id_from_pending_filename(name: &str) -> Option<&str> {
28    name.strip_prefix(QUEUE_PREFIX)?
29        .strip_suffix(QUEUE_SUFFIX)
30        .filter(|s| !s.is_empty())
31}
32
33/// Extract the project id from a repo-less pending queue filename
34/// (`pending-project-<project_id>.jsonl`), written by the stream hook when a
35/// session has a project binding but no usable repo binding.
36pub(crate) fn project_id_from_pending_filename(name: &str) -> Option<&str> {
37    name.strip_prefix(PROJECT_QUEUE_PREFIX)?
38        .strip_suffix(QUEUE_SUFFIX)
39        .filter(|s| !s.is_empty())
40}
41
42/// Which endpoint a pending queue file drains to.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub(crate) enum QueueTarget {
45    Repo(String),
46    Project(uuid::Uuid),
47}
48
49/// Classify one directory entry's filename into a queue target. Project
50/// queues are tested first: `pending-project-<uuid>.jsonl` also satisfies the
51/// repo pattern (yielding a non-UUID `project-<uuid>`), so checking repo
52/// first would reject it outright and strand the queue.
53pub(crate) fn queue_target_from_filename(name: &str) -> Option<QueueTarget> {
54    if let Some(pid) = project_id_from_pending_filename(name) {
55        return uuid::Uuid::parse_str(pid).ok().map(QueueTarget::Project);
56    }
57    let repo_id = repo_id_from_pending_filename(name)?;
58    // Validate repo_id is a UUID (guards against corrupted/hand-created files)
59    uuid::Uuid::parse_str(repo_id).ok()?;
60    Some(QueueTarget::Repo(repo_id.to_string()))
61}
62
63/// Classify a session dir's pending queue files. Returns
64/// `(path, QueueTarget)` pairs: per-repo and repo-less project files each
65/// carry their own id (see [`queue_target_from_filename`]), and the legacy
66/// `pending.jsonl` is attributed to `bound_repo_id` (skipped entirely when
67/// None). Files whose embedded id is not a valid UUID are excluded.
68fn pending_queues_in(
69    session_dir: &Path,
70    bound_repo_id: Option<&str>,
71) -> std::io::Result<Vec<(std::path::PathBuf, QueueTarget)>> {
72    let mut pending_queues: Vec<(std::path::PathBuf, QueueTarget)> = fs::read_dir(session_dir)?
73        .filter_map(|e| e.ok())
74        .filter_map(|e| {
75            let path = e.path();
76            let name = path.file_name()?.to_str()?.to_string();
77            Some((path, queue_target_from_filename(&name)?))
78        })
79        .collect();
80
81    // Back-compat: releases before per-repo queue files existed wrote a
82    // single `pending.jsonl`, implicitly attributed to the bound
83    // `config.repo_id`. `status` counts these, so `flush` must be able to
84    // drain them or they're stuck forever. If there's no bound repo_id,
85    // skip it — there's nothing to attribute it to (best-effort).
86    let legacy_path = session_dir.join("pending.jsonl");
87    if legacy_path.exists() {
88        if let Some(repo_id) = bound_repo_id {
89            pending_queues.push((legacy_path, QueueTarget::Repo(repo_id.to_string())));
90        }
91    }
92
93    Ok(pending_queues)
94}
95
96/// The progress line uses a short prefix of the session id for display; guards
97/// against a prior `[..8]` panic on session ids shorter than 8 bytes.
98fn short_session_id(id: &str) -> &str {
99    id.get(..8).unwrap_or(id)
100}
101
102pub async fn run_flush(project_root: &Path) -> Result<(), Box<dyn std::error::Error>> {
103    let (server_url, credential) = resolve_credentials(project_root)?;
104    let server_url = server_url.ok_or("server_url not configured")?;
105    let client = ApiClient::with_credential(&server_url, credential);
106
107    // Lenient config load: used only to attribute the legacy `pending.jsonl`
108    // (written by releases before per-repo queue files existed) to the bound
109    // repo id, if any. Best-effort — a missing/malformed config just means
110    // any legacy queue can't be attributed and is left in place.
111    let bound_repo_id = crate::config::TracevaultConfig::load(project_root).and_then(|c| c.repo_id);
112
113    let sessions_dir = project_root.join(".tracevault").join("sessions");
114    if !sessions_dir.exists() {
115        println!("No sessions directory found. Nothing to flush.");
116        return Ok(());
117    }
118
119    let mut total_sent = 0u64;
120    let mut total_failed = 0u64;
121
122    let session_entries: Vec<_> = fs::read_dir(&sessions_dir)?
123        .filter_map(|e| e.ok())
124        .filter(|e| e.path().is_dir())
125        .collect();
126
127    for session_entry in session_entries {
128        // Collect (path, QueueTarget) pairs for every pending queue in this
129        // session directory before draining, to keep the borrow/async loop
130        // below simple.
131        let pending_queues = pending_queues_in(&session_entry.path(), bound_repo_id.as_deref())?;
132
133        for (pending_path, target) in pending_queues {
134            let events = drain_pending(&pending_path)?;
135            if events.is_empty() {
136                continue;
137            }
138
139            let event_total = events.len();
140            let mut failed_events: Vec<StreamEventRequest> = Vec::new();
141
142            for (i, mut event) in events.into_iter().enumerate() {
143                eprint!(
144                    "\r  Session {} — event {}/{} ...",
145                    short_session_id(&event.session_id),
146                    i + 1,
147                    event_total
148                );
149                event.truncate_large_fields();
150                let sent = match &target {
151                    QueueTarget::Repo(repo_id) => client.stream_event(repo_id, &event).await,
152                    // Repo-less queue: drain to the project endpoint with no
153                    // repo_id, the same shape the stream hook buffered it as.
154                    QueueTarget::Project(pid) => {
155                        client.stream_event_for_project(*pid, None, &event).await
156                    }
157                };
158                match sent {
159                    Ok(_) => {
160                        total_sent += 1;
161                    }
162                    Err(e) => {
163                        eprintln!();
164                        let err_str = e.to_string();
165                        if err_str.contains("413") {
166                            // Payload too large even after truncation — drop it.
167                            eprintln!(
168                                "  Warning: dropped event (session {}) — still too large after truncation",
169                                event.session_id
170                            );
171                            total_failed += 1;
172                        } else {
173                            eprintln!(
174                                "  Warning: failed to send event (session {}): {e}",
175                                event.session_id
176                            );
177                            failed_events.push(event);
178                            total_failed += 1;
179                        }
180                    }
181                }
182            }
183            eprintln!();
184
185            // Re-enqueue transiently failed events (not 413s) to the SAME
186            // per-repo file.
187            if !failed_events.is_empty() {
188                append_pending(&pending_path, &failed_events)?;
189            }
190        }
191    }
192
193    println!("Flush complete: {total_sent} sent, {total_failed} failed");
194    Ok(())
195}
196
197/// Read and remove all events from a pending.jsonl file.
198fn drain_pending(path: &Path) -> Result<Vec<StreamEventRequest>, Box<dyn std::error::Error>> {
199    let file = fs::File::open(path)?;
200    let reader = BufReader::new(file);
201    let mut events = Vec::new();
202
203    for line in reader.lines() {
204        let line = line?;
205        let trimmed = line.trim();
206        if trimmed.is_empty() {
207            continue;
208        }
209        match serde_json::from_str::<StreamEventRequest>(trimmed) {
210            Ok(event) => events.push(event),
211            Err(e) => {
212                eprintln!("Warning: skipping malformed pending event: {e}");
213            }
214        }
215    }
216
217    // Truncate the file after reading
218    fs::write(path, "")?;
219
220    Ok(events)
221}
222
223/// Append events back to a pending.jsonl file (for re-enqueuing failures).
224fn append_pending(
225    path: &Path,
226    events: &[StreamEventRequest],
227) -> Result<(), Box<dyn std::error::Error>> {
228    let mut file = fs::OpenOptions::new()
229        .create(true)
230        .append(true)
231        .open(path)?;
232
233    for event in events {
234        let json = serde_json::to_string(event)?;
235        writeln!(file, "{json}")?;
236    }
237
238    Ok(())
239}
240
241// ---------------------------------------------------------------------------
242// Tests
243// ---------------------------------------------------------------------------
244
245#[cfg(test)]
246mod tests {
247    use super::{pending_queues_in, repo_id_from_pending_filename, short_session_id, QueueTarget};
248    use crate::paths::resolve_project_root;
249    use crate::test_helpers::{add_worktree, init_git_repo};
250    use std::fs;
251
252    #[test]
253    fn repo_id_from_pending_filename_extracts_id() {
254        assert_eq!(
255            repo_id_from_pending_filename("pending-abc.jsonl"),
256            Some("abc")
257        );
258    }
259
260    #[test]
261    fn repo_id_from_pending_filename_none_for_legacy_name() {
262        assert_eq!(repo_id_from_pending_filename("pending.jsonl"), None);
263    }
264
265    #[test]
266    fn repo_id_from_pending_filename_none_for_unrelated_name() {
267        assert_eq!(repo_id_from_pending_filename("events.jsonl"), None);
268        assert_eq!(repo_id_from_pending_filename("pending-abc.txt"), None);
269    }
270
271    #[test]
272    fn repo_id_from_pending_filename_none_for_empty_id() {
273        assert_eq!(repo_id_from_pending_filename("pending-.jsonl"), None);
274    }
275
276    /// From a sibling worktree the resolved project root must point at the
277    /// PRIMARY checkout, so `flush` looks for sessions under
278    /// `<primary>/.tracevault/sessions/` rather than a non-existent sibling dir.
279    ///
280    /// This test asserts only the resolution layer — draining the queue requires
281    /// a live server, so the full end-to-end drain path is not exercised here.
282    #[test]
283    fn sessions_dir_from_sibling_worktree_is_under_primary() {
284        let tmp = tempfile::tempdir().unwrap();
285        let repo = tmp.path().join("repo");
286        let wt = tmp.path().join("sibling-wt");
287
288        fs::create_dir_all(&repo).unwrap();
289        init_git_repo(&repo);
290        add_worktree(&repo, &wt);
291
292        // Place a pending.jsonl in the primary sessions dir.
293        let session_id = "aabbccdd-0000-0000-0000-000000000001";
294        let sessions_dir = repo.join(".tracevault").join("sessions").join(session_id);
295        fs::create_dir_all(&sessions_dir).unwrap();
296        fs::write(sessions_dir.join("pending.jsonl"), "").unwrap();
297
298        // Simulate what main.rs now does: resolve from the SIBLING worktree cwd.
299        let resolved_root = resolve_project_root(&wt).root;
300        let expected_sessions = repo
301            .canonicalize()
302            .unwrap()
303            .join(".tracevault")
304            .join("sessions");
305        let got_sessions = resolved_root
306            .canonicalize()
307            .unwrap()
308            .join(".tracevault")
309            .join("sessions");
310
311        assert_eq!(
312            got_sessions, expected_sessions,
313            "flush must look for sessions under the PRIMARY repo, not the sibling worktree dir"
314        );
315    }
316
317    // ── pending_queues_in: per-session pending-queue enumeration ─────────────
318
319    fn setup_session_dir_with_pending_files() -> tempfile::TempDir {
320        let dir = tempfile::tempdir().unwrap();
321        fs::write(
322            dir.path()
323                .join("pending-0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b.jsonl"),
324            "",
325        )
326        .unwrap();
327        fs::write(
328            dir.path()
329                .join("pending-550e8400-e29b-41d4-a716-446655440000.jsonl"),
330            "",
331        )
332        .unwrap();
333        fs::write(dir.path().join("pending.jsonl"), "").unwrap();
334        fs::write(dir.path().join("notes.txt"), "").unwrap();
335        fs::write(dir.path().join("pending-.jsonl"), "").unwrap();
336        fs::write(dir.path().join("pending-not-a-uuid.jsonl"), "").unwrap();
337        // A repo-less session's queue, written by the stream hook when only a
338        // project binding resolved.
339        fs::write(
340            dir.path()
341                .join("pending-project-018f0000-0000-7000-8000-000000000abc.jsonl"),
342            "",
343        )
344        .unwrap();
345        dir
346    }
347
348    /// Render a classified target as a sortable label so the assertions below
349    /// can compare whole queue sets, and so a repo queue and a project queue
350    /// that happened to share an id would still be distinguishable.
351    fn label(t: &QueueTarget) -> String {
352        match t {
353            QueueTarget::Repo(id) => id.clone(),
354            QueueTarget::Project(id) => format!("project:{id}"),
355        }
356    }
357
358    fn sorted_labels(got: &[(std::path::PathBuf, QueueTarget)]) -> Vec<String> {
359        let mut v: Vec<String> = got.iter().map(|(_, t)| label(t)).collect();
360        v.sort();
361        v
362    }
363
364    #[test]
365    fn pending_queues_in_with_bound_repo_includes_legacy() {
366        let dir = setup_session_dir_with_pending_files();
367        let got =
368            pending_queues_in(dir.path(), Some("550e8400-e29b-41d4-a716-446655440001")).unwrap();
369        assert_eq!(
370            sorted_labels(&got),
371            vec![
372                "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b",
373                "550e8400-e29b-41d4-a716-446655440000",
374                "550e8400-e29b-41d4-a716-446655440001",
375                "project:018f0000-0000-7000-8000-000000000abc",
376            ]
377        );
378
379        let legacy = got
380            .iter()
381            .find(|(_, t)| matches!(t, QueueTarget::Repo(id) if id == "550e8400-e29b-41d4-a716-446655440001"))
382            .unwrap();
383        assert_eq!(legacy.0, dir.path().join("pending.jsonl"));
384    }
385
386    #[test]
387    fn pending_queues_in_without_bound_repo_skips_legacy() {
388        let dir = setup_session_dir_with_pending_files();
389        let got = pending_queues_in(dir.path(), None).unwrap();
390        assert_eq!(
391            sorted_labels(&got),
392            vec![
393                "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b",
394                "550e8400-e29b-41d4-a716-446655440000",
395                "project:018f0000-0000-7000-8000-000000000abc",
396            ]
397        );
398    }
399
400    #[test]
401    fn pending_queues_in_ignores_unrelated_and_malformed_names() {
402        let dir = setup_session_dir_with_pending_files();
403        let got =
404            pending_queues_in(dir.path(), Some("550e8400-e29b-41d4-a716-446655440001")).unwrap();
405
406        assert!(!got.iter().any(|(p, _)| p.ends_with("notes.txt")));
407        assert!(!got.iter().any(|(p, _)| p.ends_with("pending-.jsonl")));
408        // Non-UUID repo_ids are silently skipped (guards against corrupted files)
409        assert!(!got
410            .iter()
411            .any(|(p, _)| p.ends_with("pending-not-a-uuid.jsonl")));
412    }
413
414    #[test]
415    fn pending_queues_in_validates_uuid_in_per_repo_files() {
416        let dir = setup_session_dir_with_pending_files();
417        let got = pending_queues_in(dir.path(), None).unwrap();
418
419        // Valid UUIDs are included
420        assert!(got
421            .iter()
422            .any(|(p, _)| p.ends_with("pending-0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b.jsonl")));
423        assert!(got
424            .iter()
425            .any(|(p, _)| p.ends_with("pending-550e8400-e29b-41d4-a716-446655440000.jsonl")));
426        // Non-UUID files are NOT included
427        assert!(!got
428            .iter()
429            .any(|(p, _)| p.ends_with("pending-not-a-uuid.jsonl")));
430    }
431
432    // ── short_session_id: display-only truncation, no panic on short ids ─────
433
434    #[test]
435    fn short_session_id_truncates_long_id() {
436        assert_eq!(
437            short_session_id("0190a1b2-cccc-dddd-eeee-ffffffffffff"),
438            "0190a1b2"
439        );
440    }
441
442    #[test]
443    fn short_session_id_returns_whole_string_when_shorter_than_8() {
444        assert_eq!(short_session_id("x"), "x");
445    }
446
447    #[test]
448    fn short_session_id_handles_empty_string() {
449        assert_eq!(short_session_id(""), "");
450    }
451}
452
453#[cfg(test)]
454mod queue_target_tests {
455    use super::*;
456
457    /// A repo-less queue must classify as a PROJECT target. The repo pattern
458    /// also matches this filename (yielding `project-<uuid>`), so ordering
459    /// inside `queue_target_from_filename` is what makes this pass.
460    #[test]
461    fn project_queue_classifies_as_project_not_repo() {
462        let pid = uuid::Uuid::new_v4();
463        assert_eq!(
464            queue_target_from_filename(&format!("pending-project-{pid}.jsonl")),
465            Some(QueueTarget::Project(pid))
466        );
467    }
468
469    #[test]
470    fn repo_queue_still_classifies_as_repo() {
471        let repo = uuid::Uuid::new_v4();
472        assert_eq!(
473            queue_target_from_filename(&format!("pending-{repo}.jsonl")),
474            Some(QueueTarget::Repo(repo.to_string()))
475        );
476    }
477
478    /// The writer (`Attribution::pending_file_name`, in `commands::stream`)
479    /// and the reader (`queue_target_from_filename`, here) are the two halves
480    /// of one format that live in different modules. Nothing else fails if
481    /// they diverge — an unparsable name is silently skipped, stranding the
482    /// queue while `status` still counts it — so pin the round trip.
483    #[test]
484    fn every_attribution_round_trips_through_its_queue_filename() {
485        use crate::commands::stream::Attribution;
486
487        let repo = uuid::Uuid::new_v4();
488        assert_eq!(
489            queue_target_from_filename(
490                &Attribution::Repo {
491                    repo_id: repo.to_string(),
492                    project: Some(uuid::Uuid::new_v4()),
493                }
494                .pending_file_name()
495            ),
496            Some(QueueTarget::Repo(repo.to_string())),
497            "a repo queue must classify back to the same repo"
498        );
499
500        let pid = uuid::Uuid::new_v4();
501        assert_eq!(
502            queue_target_from_filename(
503                &Attribution::ProjectOnly { project_id: pid }.pending_file_name()
504            ),
505            Some(QueueTarget::Project(pid)),
506            "a repo-less queue must classify back to the same project, NOT to a repo"
507        );
508    }
509
510    /// Traversal-shaped names are rejected by the UUID parse on both arms.
511    /// `pending_queues_in` builds its paths from `fs::read_dir`, which never
512    /// yields `.` or `..` as entries, so a traversal component cannot reach
513    /// here in the first place — this pins the second line of defence, the
514    /// one that would still hold if the source of the names ever changed.
515    #[test]
516    fn traversal_shaped_names_are_rejected() {
517        for name in [
518            "pending-../../etc/passwd.jsonl",
519            "pending-project-../../etc/passwd.jsonl",
520            "pending-..%2f..%2fetc.jsonl",
521            "pending-/etc/passwd.jsonl",
522        ] {
523            assert_eq!(queue_target_from_filename(name), None, "accepted: {name}");
524        }
525    }
526
527    /// Non-UUID ids are rejected on both arms — these names can only come
528    /// from a corrupted or hand-created file.
529    #[test]
530    fn non_uuid_ids_are_rejected() {
531        assert_eq!(queue_target_from_filename("pending-nope.jsonl"), None);
532        assert_eq!(
533            queue_target_from_filename("pending-project-nope.jsonl"),
534            None
535        );
536        assert_eq!(queue_target_from_filename("pending-.jsonl"), None);
537        assert_eq!(queue_target_from_filename("pending.jsonl"), None);
538    }
539}