1use std::sync::Arc;
16
17use crate::backend::storage::filestore::FileStore;
18use crate::backend::storage::store::Store;
19use crate::backend::transcript::source::{Tail, TranscriptSource};
20
21const FIRST_WINDOW: i64 = 256 * 1024;
23
24pub struct TailLines {
26 pub lines: Vec<String>,
28 pub truncated: bool,
30}
31
32pub async fn off_worker<T: Default + Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
35 tokio::task::spawn_blocking(f).await.unwrap_or_default()
36}
37
38fn last_lines(bytes: &[u8], requested: usize, complete: bool) -> Option<TailLines> {
43 let text = String::from_utf8_lossy(bytes);
44 let mut lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
45 if !complete && !lines.is_empty() {
46 lines.remove(0);
47 }
48 if !complete && lines.len() <= requested {
49 return None;
50 }
51 let truncated = lines.len() > requested;
52 let from = lines.len().saturating_sub(requested);
53 Some(TailLines { lines: lines[from..].iter().map(|l| l.to_string()).collect(), truncated })
54}
55
56fn live_tail_lines(src: &TranscriptSource<'_>, requested: usize) -> Option<TailLines> {
60 tail_lines_with(|window| src.tail(window), requested)
61}
62
63fn tail_lines_with(mut read: impl FnMut(i64) -> Option<Tail>, requested: usize) -> Option<TailLines> {
65 let mut window = FIRST_WINDOW;
66 loop {
67 let tail = read(window)?;
68 if let Some(found) = last_lines(&tail.bytes, requested, tail.size <= window) {
69 return Some(found);
70 }
71 window = window.saturating_mul(4);
72 }
73}
74
75pub fn tail_lines(
78 mstore: &Arc<Store>,
79 filestore: &Arc<FileStore>,
80 block_id: &str,
81 requested: usize,
82) -> Result<TailLines, String> {
83 let mut found = unvetted_tail_lines(mstore, filestore, block_id, requested)?;
84 let owner = crate::backend::transcript::origin_sig::owner_for_block(mstore, block_id);
85 crate::backend::transcript::attribution::vet_for_viewer(mstore, filestore, &owner, &mut found.lines);
86 Ok(found)
87}
88
89pub fn tail_lines_for_readers(
92 mstore: &Arc<Store>,
93 filestore: &Arc<FileStore>,
94 block_id: &str,
95 requested: usize,
96) -> Result<TailLines, String> {
97 let mut found = tail_lines(mstore, filestore, block_id, requested)?;
98 crate::backend::transcript::withhold::in_place(&mut found.lines);
99 Ok(found)
100}
101
102fn unvetted_tail_lines(
103 mstore: &Arc<Store>,
104 filestore: &Arc<FileStore>,
105 block_id: &str,
106 requested: usize,
107) -> Result<TailLines, String> {
108 if let Some(found) = live_tail_lines(&TranscriptSource::resolve(filestore, mstore, block_id), requested) {
109 return Ok(found);
110 }
111 let (raw, _) = crate::backend::session_archive::read_session_output(mstore, filestore, block_id)?;
112 Ok(last_lines(&raw, requested, true).unwrap_or(TailLines { lines: Vec::new(), truncated: false }))
113}
114
115#[cfg(test)]
116mod tests {
117 use super::*;
118 use crate::backend::storage::filestore::{FileMeta, FileOpts};
119
120 const BLOCK: &str = "blk-tail";
121
122 fn store_with(lines: impl Iterator<Item = String>) -> (FileStore, Store) {
123 store_with_cache(lines, None)
124 }
125
126 fn store_with_cache(lines: impl Iterator<Item = String>, cache_cap: Option<usize>) -> (FileStore, Store) {
128 let fs = match cache_cap {
129 Some(cap) => FileStore::open_in_memory_with_cap(cap).unwrap(),
130 None => FileStore::open_in_memory().unwrap(),
131 };
132 let mstore = Store::open_in_memory().unwrap();
133 fs.make_file(BLOCK, "output", FileMeta::default(), FileOpts::default()).unwrap();
134 let mut chunk = String::new();
135 for l in lines {
136 chunk.push_str(&l);
137 chunk.push('\n');
138 if chunk.len() > 1 << 20 {
139 fs.append_lines(BLOCK, "output", chunk.as_bytes()).unwrap();
140 chunk.clear();
141 }
142 }
143 if !chunk.is_empty() {
144 fs.append_lines(BLOCK, "output", chunk.as_bytes()).unwrap();
145 }
146 (fs, mstore)
147 }
148
149 fn whole_file(fs: &FileStore, requested: usize) -> TailLines {
151 let raw = fs.read_file(BLOCK, "output").unwrap().unwrap_or_default();
152 last_lines(&raw, requested, true).unwrap()
153 }
154
155 fn tail(fs: &FileStore, mstore: &Store, requested: usize) -> TailLines {
156 live_tail_lines(&TranscriptSource::resolve_with(fs, None, mstore, BLOCK), requested).expect("a live file")
157 }
158
159 fn same(a: &TailLines, b: &TailLines) {
160 assert_eq!((&a.lines, a.truncated), (&b.lines, b.truncated));
161 }
162
163 #[test]
164 fn a_short_transcript_is_returned_whole() {
165 let (fs, m) = store_with(["{\"a\":1}", "", "{\"a\":2}"].into_iter().map(String::from));
166 let got = tail(&fs, &m, 100);
167 assert_eq!(got.lines, ["{\"a\":1}", "{\"a\":2}"]);
168 assert!(!got.truncated);
169 same(&got, &whole_file(&fs, 100));
170 }
171
172 #[test]
173 fn a_long_transcript_gives_the_same_last_lines_as_reading_all_of_it() {
174 let (fs, m) = store_with((0..30_000).map(|i| format!("{{\"n\":{i},\"pad\":\"{}\"}}", "x".repeat(180))));
176 for requested in [1, 5, 100, 500] {
177 let (got, want) = (tail(&fs, &m, requested), whole_file(&fs, requested));
178 same(&got, &want);
179 assert_eq!(got.lines.len(), requested);
180 assert!(got.truncated);
181 assert!(got.lines.last().unwrap().starts_with("{\"n\":29999,"));
182 }
183 }
184
185 #[test]
186 fn lines_longer_than_the_first_window_widen_it() {
187 let (fs, m) = store_with((0..60).map(|i| format!("{{\"n\":{i},\"pad\":\"{}\"}}", "y".repeat(100_000))));
189 let got = tail(&fs, &m, 10);
190 same(&got, &whole_file(&fs, 10));
191 assert_eq!(got.lines.len(), 10);
192 assert!(got.lines[0].starts_with("{\"n\":50,") && got.truncated);
193 }
194
195 #[test]
196 fn exactly_the_requested_lines_in_a_file_bigger_than_the_window_are_not_truncated() {
197 let (fs, m) = store_with((0..50).map(|i| format!("{{\"n\":{i},\"pad\":\"{}\"}}", "z".repeat(20_000))));
198 let got = tail(&fs, &m, 50);
199 same(&got, &whole_file(&fs, 50));
200 assert_eq!((got.lines.len(), got.truncated), (50, false));
201 }
202
203 #[test]
204 fn a_large_transcript_is_read_through_one_bounded_window() {
205 let (fs, m) = store_with((0..30_000).map(|i| format!("{{\"n\":{i},\"pad\":\"{}\"}}", "x".repeat(180))));
207 let src = TranscriptSource::resolve_with(&fs, None, &m, BLOCK);
208 let (mut windows, mut read) = (Vec::new(), 0usize);
209 let got = tail_lines_with(
210 |w| {
211 windows.push(w);
212 let t = src.tail(w);
213 read += t.as_ref().map_or(0, |t| t.bytes.len());
214 t
215 },
216 100,
217 )
218 .unwrap();
219 assert_eq!(windows, [FIRST_WINDOW], "no wider read than the first window");
220 assert!(read as i64 <= FIRST_WINDOW, "{read} bytes read of a ~6 MB file");
221 assert_eq!(got.lines.len(), 100);
222 }
223
224 #[tokio::test(flavor = "current_thread")]
225 async fn work_in_off_worker_does_not_stop_the_runtime() {
226 let t = std::time::Instant::now();
227 let work = tokio::spawn(off_worker(|| {
228 std::thread::sleep(std::time::Duration::from_millis(400));
229 7u32
230 }));
231 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
232 assert!(t.elapsed() < std::time::Duration::from_millis(250), "the runtime was held for {:?}", t.elapsed());
233 assert_eq!(work.await.unwrap(), 7);
234 }
235
236 #[test]
237 fn no_file_means_the_caller_falls_back() {
238 let (fs, m) = (FileStore::open_in_memory().unwrap(), Store::open_in_memory().unwrap());
239 assert!(live_tail_lines(&TranscriptSource::resolve_with(&fs, None, &m, BLOCK), 10).is_none());
240 }
241
242 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
246 #[ignore = "a measurement, not a check"]
247 async fn bench_a_96_mb_transcript() {
248 use std::sync::Arc;
249 use std::time::{Duration, Instant};
250 let lines = (0..96_000).map(|i| format!("{{\"n\":{i},\"pad\":\"{}\"}}", "w".repeat(1000)));
252 let (fs, m) = store_with_cache(lines, Some(1 << 20));
253 let (fs, m) = (Arc::new(fs), Arc::new(m));
254 let old = |fs: &FileStore| whole_file(fs, 100);
255
256 let t = Instant::now();
257 for _ in 0..3 {
258 old(&fs);
259 }
260 println!("one read, before (whole file): {:>7.1} ms (mean of 3)", t.elapsed().as_secs_f64() * 1e3 / 3.0);
261 let t = Instant::now();
262 let mut n = 0;
263 for _ in 0..3 {
264 n = tail(&fs, &m, 100).lines.len();
265 }
266 println!("one read, after (bounded tail): {:>7.1} ms (mean of 3, {n} lines)", t.elapsed().as_secs_f64() * 1e3 / 3.0);
267
268 async fn probe_while(work: impl std::future::Future<Output = ()>) -> u128 {
270 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
271 let flag = stop.clone();
272 let probe = tokio::spawn(async move {
273 let mut worst = 0u128;
274 while !flag.load(std::sync::atomic::Ordering::Relaxed) {
275 let t = Instant::now();
276 tokio::time::sleep(Duration::from_millis(10)).await;
277 worst = worst.max(t.elapsed().as_millis() - 10);
278 }
279 worst
280 });
281 tokio::time::sleep(Duration::from_millis(50)).await;
282 work.await;
283 stop.store(true, std::sync::atomic::Ordering::Relaxed);
284 probe.await.unwrap()
285 }
286 let before = probe_while(async {
287 let tasks: Vec<_> = (0..4).map(|_| { let fs = fs.clone(); tokio::spawn(async move { old(&fs); }) }).collect();
288 for t in tasks { t.await.unwrap(); }
289 })
290 .await;
291 println!("runtime unresponsive, before (4 reads on the workers): {before} ms");
292 let after = probe_while(async {
293 let tasks: Vec<_> = (0..4)
294 .map(|_| {
295 let (fs, m) = (fs.clone(), m.clone());
296 tokio::spawn(async move { off_worker(move || { tail_lines_live(&fs, &m); Some(()) }).await; })
297 })
298 .collect();
299 for t in tasks { t.await.unwrap(); }
300 })
301 .await;
302 println!("runtime unresponsive, after (4 tail reads, off-worker): {after} ms");
303 }
304
305 fn tail_lines_live(fs: &FileStore, m: &Store) -> usize {
306 tail(fs, m, 100).lines.len()
307 }
308}