agentmux_srv/server/app_api/
blockfile_read.rs1use super::*;
8
9type FileStoreRef = Arc<crate::backend::storage::filestore::FileStore>;
10
11pub(super) struct RangeRead<'a> {
13 pub(super) cmd: &'a CommandBlockfileReadRangeData,
14 pub(super) stores: (&'a crate::backend::storage::store::Store, &'a crate::backend::storage::filestore::FileStore),
16 pub(super) offset: usize,
17 pub(super) stream: String,
18 pub(super) owner: Option<String>,
20 pub(super) gen_before: Option<String>,
22}
23
24pub(super) fn mismatch(stream: &str, gen: Option<String>) -> BlockfileReadRangeResult {
26 BlockfileReadRangeResult { stream: Some(stream.to_string()), gen, gen_mismatch: Some(true), ..Default::default() }
27}
28
29impl RangeRead<'_> {
30 pub(super) fn finish(&self, mut result: BlockfileReadRangeResult, gen_after: Option<String>) -> BlockfileReadRangeResult {
32 let cmd = self.cmd;
33 if let Some(owner) = &self.owner {
34 crate::backend::transcript::attribution::vet_for_viewer(self.stores.0, self.stores.1, owner, &mut result.lines);
35 }
36 if let Some(turns) = cmd.tail_turns.filter(|t| *t > 0) {
37 trim_to_last_turns(&mut result, self.offset as u64, turns as usize);
38 }
39 if let Some(bytes) = cmd.tail_bytes.filter(|b| *b > 0) {
40 trim_to_tail_bytes(&mut result, self.offset as u64, bytes as usize);
41 }
42 if self.gen_before.is_some() && gen_after == self.gen_before {
43 result.stream = Some(self.stream.clone());
44 result.gen = self.gen_before.clone();
45 result
46 } else if cmd.expect_gen.is_some() {
47 mismatch(&self.stream, gen_after)
48 } else {
49 result
50 }
51 }
52}
53
54pub(super) async fn indexed_window(
56 filestore: &FileStoreRef,
57 read_block: &str,
58 block_id: &str,
59 offset: usize,
60 limit: usize,
61 clock: &mut ReadRangeClock,
62) -> Option<BlockfileReadRangeResult> {
63 let idx_clock = std::sync::Arc::new(std::sync::Mutex::new(IndexClock::default()));
70 let idx_result: Option<BlockfileReadRangeResult> = {
71 let filestore = filestore.clone();
72 let read_block = read_block.to_string();
73 let idx_clock = idx_clock.clone();
74 let spawned = std::time::Instant::now();
75 let compute = move || read_from_index(&filestore, &read_block, offset, limit, &idx_clock, spawned);
76 match tokio::task::spawn_blocking(compute).await {
80 Ok(v) => v,
81 Err(e) => {
82 tracing::warn!(
83 block_id = %block_id,
84 error = %e,
85 "blockfile:read_range: output.idx task failed; falling back"
86 );
87 None
88 }
89 }
90 };
91 clock.index = Some(std::mem::take(&mut *idx_clock.lock().unwrap()));
92 idx_result
93}
94
95const INDEX_COUNT_WAIT: std::time::Duration = std::time::Duration::from_secs(20);
97
98fn read_from_index(
100 filestore: &FileStoreRef,
101 read_block: &str,
102 offset: usize,
103 limit: usize,
104 idx_clock: &std::sync::Mutex<IndexClock>,
105 spawned: std::time::Instant,
106) -> Option<BlockfileReadRangeResult> {
107 use crate::backend::blockcontroller::shell::{extend_output_idx, read_via_index, read_via_stale_index};
108 idx_clock.lock().unwrap().queued_ms = ms_since(spawned);
109 let run = std::time::Instant::now();
110 let out_stat = filestore.stat(read_block, "output").ok()??;
111 if out_stat.opts.circular {
112 return None; }
114 if !crate::backend::transcript::counting::ensure_counted(filestore, read_block, INDEX_COUNT_WAIT) {
120 return None;
121 }
122 let read = match read_via_index(filestore, read_block, offset as u64, limit as u64) {
138 Some(read) => read,
139 None => {
140 let extend = std::time::Instant::now();
141 let extended = extend_output_idx(filestore, read_block);
142 idx_clock.lock().unwrap().extend_ms = Some(ms_since(extend));
143 extended?;
148 match read_via_index(filestore, read_block, offset as u64, limit as u64) {
149 Some(read) => read,
150 None => {
158 let read = read_via_stale_index(filestore, read_block, offset as u64, limit as u64)?;
159 idx_clock.lock().unwrap().stale = true;
160 read
161 }
162 }
163 }
164 };
165 idx_clock.lock().unwrap().run_ms = ms_since(run);
166 let total_lines = read.total;
167
168 if read.line_offsets.is_empty() {
170 return Some(BlockfileReadRangeResult { lines: vec![], total: total_lines, ..Default::default() });
171 }
172 let raw = read.raw;
173 let text = String::from_utf8_lossy(&raw);
174 let lines: Vec<String> = text
175 .lines()
176 .filter(|l| !l.trim().is_empty())
177 .map(|l| l.to_string())
178 .collect();
179
180 let stamps = read.stamps.filter(|s| s.len() == lines.len());
186
187 Some(BlockfileReadRangeResult { lines, total: total_lines, stamps, ..Default::default() })
188}
189
190
191pub(super) fn ring_buffer_lines(broker: &Arc<crate::backend::mps::Broker>, cmd: &CommandBlockfileReadRangeData) -> Vec<String> {
193 let scope = format!("block:{}", cmd.block_id);
198 let events = broker.read_event_history(
199 crate::backend::mps::EVENT_BLOCK_FILE,
200 &scope,
201 usize::MAX, );
203
204 let mut lines: Vec<String> = Vec::new();
205 for event in events {
206 let Some(ref event_data) = event.data else { continue };
207 let ev_filename = event_data.get("filename")
208 .and_then(|v| v.as_str()).unwrap_or("");
209 if ev_filename != cmd.filename {
210 continue;
211 }
212 let Some(data64) = event_data.get("data64").and_then(|v| v.as_str()) else { continue };
213 let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(data64) else { continue };
214 let text = String::from_utf8_lossy(&bytes);
215 for line in text.lines() {
216 if !line.trim().is_empty() {
217 lines.push(line.to_string());
218 }
219 }
220 }
221 lines
222}
223
224
225pub(super) fn whole_file_lines(
228 filestore: &FileStoreRef,
229 read_block: &str,
230 cmd: &CommandBlockfileReadRangeData,
231 started: std::time::Instant,
232) -> Result<Option<Vec<String>>, String> {
233 Ok(match filestore.stat(read_block, &cmd.filename) {
234 Ok(Some(ref wf)) if wf.size > 0 => {
235 if !whole_file_read_allowed(&cmd.filename, wf.opts.circular, wf.size) {
236 tracing::warn!(
237 block_id = %cmd.block_id,
238 size = wf.size,
239 total_ms = ms_since(started),
240 "blockfile:read_range: output.idx can't serve this read and the transcript is too large to read whole; refusing"
241 );
242 return Err(format!(
243 "blockfile:read_range: the transcript index for {} is unavailable right now; retry",
244 cmd.block_id
245 ));
246 }
247 if wf.size >= WHOLE_FILE_WARN_BYTES {
248 tracing::warn!(
249 block_id = %cmd.block_id,
250 filename = %cmd.filename,
251 size = wf.size,
252 "blockfile:read_range: reading the whole file (no usable output.idx)"
253 );
254 }
255 match filestore.read_file(read_block, &cmd.filename) {
256 Ok(Some(bytes)) => {
257 let text = String::from_utf8_lossy(&bytes);
258 let lines: Vec<String> = text.lines()
259 .filter(|l| !l.trim().is_empty())
260 .map(|l| l.to_string())
261 .collect();
262 Some(lines)
263 }
264 Ok(None) => None,
265 Err(e) => {
266 tracing::warn!(
267 block_id = %cmd.block_id,
268 filename = %cmd.filename,
269 error = %e,
270 "blockfile:read_range: filestore read failed, falling back to ring buffer"
271 );
272 None
273 }
274 }
275 }
276 Ok(_) => None, Err(e) => {
278 tracing::warn!(
279 block_id = %cmd.block_id,
280 error = %e,
281 "blockfile:read_range: filestore stat failed, falling back to ring buffer"
282 );
283 None
284 }
285 })
286}