a2a_protocol_server/tool_loop/
trace.rs1use std::sync::{Mutex, PoisonError};
8
9pub const TRACE_LINE_LIMIT: usize = 16 * 1024;
17
18pub(super) fn line(name: &str, arguments: &str, content: &str) -> String {
20 let full = format!("{name}({arguments}) -> {content}");
21 if full.len() <= TRACE_LINE_LIMIT {
22 return full;
23 }
24 let mut end = TRACE_LINE_LIMIT;
25 while !full.is_char_boundary(end) {
26 end -= 1;
27 }
28 format!("{}… [{} more bytes]", &full[..end], full.len() - end)
29}
30
31#[derive(Default)]
36pub(super) struct Sink(Mutex<Vec<String>>);
37
38impl Sink {
39 pub(super) fn push(&self, line: String) {
40 self.0
41 .lock()
42 .unwrap_or_else(PoisonError::into_inner)
43 .push(line);
44 }
45
46 pub(super) fn take(&self) -> Vec<String> {
47 std::mem::take(&mut *self.0.lock().unwrap_or_else(PoisonError::into_inner))
48 }
49}
50
51pub(super) fn record(trace: &mut Vec<String>, sink: Option<&Sink>, line: String) {
54 if let Some(sink) = sink {
55 sink.push(line.clone());
56 }
57 trace.push(line);
58}
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63
64 #[test]
68 fn the_limit_is_sixteen_kibibytes_and_a_line_inside_it_is_whole() {
69 assert_eq!(TRACE_LINE_LIMIT, 16_384);
70 let body = "r".repeat(5_000);
71 assert_eq!(line("t", "{}", &body), format!("t({{}}) -> {body}"));
72 }
73
74 #[test]
76 fn a_short_line_is_name_arguments_and_result() {
77 assert_eq!(line("t", "{}", "ok"), "t({}) -> ok");
78 let fits = "x".repeat(TRACE_LINE_LIMIT - "t({}) -> ".len());
80 let whole = line("t", "{}", &fits);
81 assert_eq!(whole.len(), TRACE_LINE_LIMIT);
82 assert!(!whole.contains("more bytes"));
83 }
84
85 #[test]
87 fn a_line_over_the_limit_is_cut_and_says_how_much() {
88 let over = "x".repeat(TRACE_LINE_LIMIT - "t({}) -> ".len() + 1);
89 let cut = line("t", "{}", &over);
90 let kept = format!("t({{}}) -> {}", &over[..over.len() - 1]);
91 assert_eq!(cut, format!("{kept}… [1 more bytes]"));
92 let huge = line("t", "{}", &"y".repeat(8 * 1024 * 1024));
93 assert!(huge.len() < TRACE_LINE_LIMIT + 32, "{}", huge.len());
94 assert!(huge.ends_with("more bytes]"));
95 }
96
97 #[test]
100 fn the_cut_never_splits_a_character() {
101 let prefix = "t({}) -> ";
102 let content = format!("{}€€", "x".repeat(TRACE_LINE_LIMIT - prefix.len() - 1));
104 let cut = line("t", "{}", &content);
105 assert!(cut.is_char_boundary(cut.len()));
106 assert_eq!(
107 cut,
108 format!(
109 "{prefix}{}… [6 more bytes]",
110 "x".repeat(TRACE_LINE_LIMIT - prefix.len() - 1)
111 )
112 );
113 }
114
115 #[test]
117 fn the_sink_keeps_lines_in_order_and_gives_them_up_once() {
118 let sink = Sink::default();
119 let mut trace = Vec::new();
120 record(&mut trace, Some(&sink), "a".to_owned());
121 record(&mut trace, Some(&sink), "b".to_owned());
122 record(&mut trace, None, "c".to_owned());
123 assert_eq!(trace, ["a", "b", "c"]);
124 assert_eq!(sink.take(), ["a", "b"]);
125 assert_eq!(sink.take(), Vec::<String>::new());
126 }
127}