1use std::collections::HashMap;
4use std::time::{Duration, Instant};
5
6use serde::{Deserialize, Serialize};
7
8use crate::task_watches::WatchPattern;
9
10pub const MAX_LINES_PER_NOTIFICATION: usize = 50;
11pub const MAX_NOTIFICATIONS_PER_MINUTE: usize = 12;
12pub const NOTIFICATION_WINDOW: Duration = Duration::from_secs(60);
13pub const MAX_LINE_BYTES: usize = 64 * 1024;
14pub const MASKING_LINE_CAP_BYTES: usize = 8 * 1024;
15pub const UNAVAILABLE_MATCH_SINGULAR: &str = "1 matching line over {limit} KiB was not shown; AFT can check lines only up to {limit} KiB for secrets.";
16pub const UNAVAILABLE_MATCH_PLURAL: &str = "{count} matching lines over {limit} KiB were not shown; AFT can check lines only up to {limit} KiB for secrets.";
17pub const UNAVAILABLE_PAGE_SINGULAR: &str = "1 line in this page over {limit} KiB was not shown; AFT can check lines only up to {limit} KiB for secrets.";
18pub const UNAVAILABLE_PAGE_PLURAL: &str = "{count} lines in this page over {limit} KiB were not shown; AFT can check lines only up to {limit} KiB for secrets.";
19
20pub fn unavailable_match_text(count: u64, limit: usize) -> String {
21 unavailable_text(
22 if count == 1 {
23 UNAVAILABLE_MATCH_SINGULAR
24 } else {
25 UNAVAILABLE_MATCH_PLURAL
26 },
27 count,
28 limit,
29 )
30}
31
32pub fn unavailable_page_text(count: u64) -> String {
33 unavailable_text(
34 if count == 1 {
35 UNAVAILABLE_PAGE_SINGULAR
36 } else {
37 UNAVAILABLE_PAGE_PLURAL
38 },
39 count,
40 MASKING_LINE_CAP_BYTES,
41 )
42}
43
44fn unavailable_text(template: &str, count: u64, limit: usize) -> String {
45 template
46 .replace("{count}", &count.to_string())
47 .replace("{limit}", &limit.div_ceil(1024).to_string())
48}
49pub const EACH_LINE_NEEDS_BACKGROUND: &str =
50 "bash_watch: deliver: \"each_line\" needs background: true.";
51
52#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct WatchLine {
54 pub stream: String,
55 pub offset: u64,
56 pub end_offset: u64,
57 pub text: String,
58 pub count: u64,
59 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
60 pub unavailable: bool,
61}
62
63#[derive(Debug, Clone, Default, Serialize, Deserialize)]
64pub struct RetryGap {
65 pub reason: String,
66 pub dropped_notifications: u64,
67 pub known_missing_occurrences: u64,
68 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub first_offset: Option<u64>,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub last_offset: Option<u64>,
72 #[serde(default, skip_serializing_if = "Option::is_none")]
73 pub stream: Option<String>,
74 #[serde(default)]
75 pub evicted_through: u64,
76 #[serde(default)]
77 pub eviction_epoch: String,
78 #[serde(default)]
79 pub last_match_version: u64,
80}
81
82#[derive(Debug, Clone, Default, Serialize, Deserialize)]
83pub struct LineBatch {
84 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub acknowledged_version: Option<u64>,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub retry_gap: Option<RetryGap>,
88 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub masking_limit_bytes: Option<u64>,
90 #[serde(default, skip_serializing_if = "Option::is_none")]
91 pub pending_id: Option<String>,
92 #[serde(default, skip_serializing_if = "Option::is_none")]
93 pub version: Option<u64>,
94 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
95 pub snapshot: bool,
96 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
97 pub terminal_summary: bool,
98 pub lines: Vec<WatchLine>,
99 pub dropped_lines: u64,
100 pub first_dropped_offset: Option<u64>,
101 pub first_dropped_stream: Option<String>,
102 pub skipped_long_lines: u64,
103}
104
105impl LineBatch {
106 pub fn has_matches(&self) -> bool {
107 !self.lines.is_empty() || self.dropped_lines > 0
108 }
109
110 pub fn merge(&mut self, next: LineBatch) {
111 if next.retry_gap.is_some() {
112 self.retry_gap = next.retry_gap.clone();
113 }
114 self.masking_limit_bytes = next.masking_limit_bytes.or(self.masking_limit_bytes);
115 self.terminal_summary = next.terminal_summary;
116 let mut retained = self.lines.iter().map(|line| line.count).sum::<u64>();
117 for mut line in next.lines {
118 let keep = line
119 .count
120 .min((MAX_LINES_PER_NOTIFICATION as u64).saturating_sub(retained));
121 let dropped = line.count - keep;
122 if dropped > 0 {
123 let offset = line.offset + keep * (line.end_offset - line.offset);
124 self.drop_line(&line.stream, offset);
125 self.dropped_lines = self.dropped_lines.saturating_add(dropped - 1);
126 }
127 if keep > 0 {
128 line.count = keep;
129 self.lines.push(line);
130 retained += keep;
131 }
132 }
133 self.dropped_lines = self.dropped_lines.saturating_add(next.dropped_lines);
134 self.skipped_long_lines = self
135 .skipped_long_lines
136 .saturating_add(next.skipped_long_lines);
137 if self.first_dropped_offset.is_none() {
138 self.first_dropped_offset = next.first_dropped_offset;
139 self.first_dropped_stream = next.first_dropped_stream;
140 }
141 }
142
143 fn drop_line(&mut self, stream: &str, offset: u64) {
144 self.dropped_lines = self.dropped_lines.saturating_add(1);
145 if self.first_dropped_offset.is_none() {
146 self.first_dropped_offset = Some(offset);
147 self.first_dropped_stream = Some(stream.to_string());
148 }
149 }
150
151 fn is_empty(&self) -> bool {
152 self.lines.is_empty()
153 && self.dropped_lines == 0
154 && self.skipped_long_lines == 0
155 && self
156 .retry_gap
157 .as_ref()
158 .is_none_or(|gap| gap.dropped_notifications == 0)
159 }
160}
161
162#[derive(Debug, Default)]
163struct PartialLine {
164 bytes: Vec<u8>,
165 offset: u64,
166 oversized: bool,
167}
168
169#[derive(Debug, Default)]
170pub(super) struct LineDelivery {
171 streams: HashMap<String, PartialLine>,
172 batch: LineBatch,
173 retained: usize,
174 window: Option<Instant>,
175 sent: usize,
176}
177
178impl LineDelivery {
179 pub fn replay_cursor(&self, stream: &str, cursor: u64) -> u64 {
180 let partial = self
181 .streams
182 .get(stream)
183 .filter(|line| !line.bytes.is_empty() || line.oversized)
184 .map(|line| line.offset)
185 .unwrap_or(cursor);
186 let dropped = if self.batch.first_dropped_stream.as_deref() == Some(stream) {
187 self.batch.first_dropped_offset.unwrap_or(cursor)
188 } else {
189 cursor
190 };
191 self.batch
192 .lines
193 .iter()
194 .filter(|line| line.stream == stream)
195 .map(|line| line.offset)
196 .fold(cursor.min(partial).min(dropped), u64::min)
197 }
198
199 pub fn scan(&mut self, stream: &str, bytes: &[u8], base: u64, pattern: &WatchPattern) {
200 let mut partial = self.streams.remove(stream).unwrap_or_else(|| PartialLine {
201 offset: base,
202 ..PartialLine::default()
203 });
204 let mut consumed = 0;
205 for fragment in bytes.split_inclusive(|byte| *byte == b'\n') {
206 let complete = fragment.last() == Some(&b'\n');
207 let content = if complete {
208 &fragment[..fragment.len() - 1]
209 } else {
210 fragment
211 };
212 if !partial.oversized {
213 if partial.bytes.len().saturating_add(content.len()) > MAX_LINE_BYTES {
214 partial.bytes.clear();
215 partial.oversized = true;
216 } else {
217 partial.bytes.extend_from_slice(content);
218 }
219 }
220 consumed += fragment.len();
221 if complete {
222 self.finish_line(stream, &partial, base + consumed as u64, pattern);
223 partial = PartialLine {
224 offset: base + consumed as u64,
225 ..PartialLine::default()
226 };
227 }
228 }
229 self.streams.insert(stream.to_string(), partial);
230 }
231
232 fn finish_line(
233 &mut self,
234 stream: &str,
235 partial: &PartialLine,
236 end: u64,
237 pattern: &WatchPattern,
238 ) {
239 if partial.oversized {
240 self.batch.skipped_long_lines = self.batch.skipped_long_lines.saturating_add(1);
241 if self.batch.first_dropped_offset.is_none() {
242 self.batch.first_dropped_offset = Some(partial.offset);
243 self.batch.first_dropped_stream = Some(stream.to_string());
244 }
245 return;
246 }
247 let text = String::from_utf8_lossy(&partial.bytes);
248 let matched = match pattern {
249 WatchPattern::Substring(needle) => !needle.is_empty() && text.contains(needle),
250 WatchPattern::Regex(regex) => regex.is_match(&text),
251 };
252 if !matched {
253 return;
254 }
255 if self.retained >= MAX_LINES_PER_NOTIFICATION {
257 self.batch.drop_line(stream, partial.offset);
258 return;
259 }
260 self.retained += 1;
261 if let Some(previous) = self.batch.lines.last_mut() {
262 if previous.stream == stream
263 && previous.offset.saturating_add(
264 previous
265 .count
266 .saturating_mul(previous.end_offset - previous.offset),
267 ) == partial.offset
268 && previous.text == text
269 {
270 previous.count = previous.count.saturating_add(1);
271 return;
272 }
273 }
274 self.batch.lines.push(WatchLine {
275 stream: stream.to_string(),
276 offset: partial.offset,
277 end_offset: end,
278 text: text.into_owned(),
279 count: 1,
280 unavailable: false,
281 });
282 }
283
284 pub fn take(
285 &mut self,
286 now: Instant,
287 terminal: bool,
288 pattern: &WatchPattern,
289 ) -> Option<LineBatch> {
290 if terminal {
291 for (stream, partial) in std::mem::take(&mut self.streams) {
292 if !partial.bytes.is_empty() || partial.oversized {
293 let end = partial.offset.saturating_add(partial.bytes.len() as u64);
294 self.finish_line(&stream, &partial, end, pattern);
295 }
296 }
297 }
298 if self
299 .window
300 .is_none_or(|start| now.saturating_duration_since(start) >= NOTIFICATION_WINDOW)
301 {
302 self.window = Some(now);
303 self.sent = 0;
304 }
305 if self.sent >= MAX_NOTIFICATIONS_PER_MINUTE {
306 for line in std::mem::take(&mut self.batch.lines) {
307 self.batch.drop_line(&line.stream, line.offset);
308 self.batch.dropped_lines = self.batch.dropped_lines.saturating_add(line.count - 1);
309 }
310 self.retained = 0;
311 if !terminal {
312 return None;
313 }
314 self.batch.terminal_summary = true;
315 }
316 if self.batch.is_empty() {
317 return None;
318 }
319 self.sent += 1;
320 self.retained = 0;
321 Some(std::mem::take(&mut self.batch))
322 }
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328
329 fn pattern() -> WatchPattern {
330 WatchPattern::Substring("ERROR".into())
331 }
332
333 #[test]
334 fn each_line_delivers_all_matches_in_one_block() {
335 for pattern in [pattern(), WatchPattern::regex("ERROR.*").unwrap()] {
336 let mut delivery = LineDelivery::default();
337 delivery.scan("stdout", b"ERROR a\nok\nERROR b\nERROR c\n", 0, &pattern);
338 let batch = delivery.take(Instant::now(), false, &pattern).unwrap();
339 assert_eq!(
340 batch
341 .lines
342 .iter()
343 .map(|line| (line.offset, line.text.as_str()))
344 .collect::<Vec<_>>(),
345 vec![(0, "ERROR a"), (11, "ERROR b"), (19, "ERROR c")]
346 );
347 }
348 }
349
350 #[test]
351 fn each_line_split_across_blocks_delivered_once() {
352 let mut delivery = LineDelivery::default();
353 delivery.scan("stdout", b"ER", 40, &pattern());
354 assert!(delivery.take(Instant::now(), false, &pattern()).is_none());
355 delivery.scan("stdout", b"ROR a\n", 42, &pattern());
356 let batch = delivery.take(Instant::now(), false, &pattern()).unwrap();
357 assert_eq!(batch.lines[0].text, "ERROR a");
358 assert_eq!(batch.lines[0].offset, 40);
359 assert!(delivery.take(Instant::now(), true, &pattern()).is_none());
360 }
361
362 #[test]
363 fn each_line_cap_reports_exact_count_and_offset() {
364 let mut delivery = LineDelivery::default();
365 for index in 0..53 {
366 delivery.scan("stderr", b"ERROR\n", index * 6, &pattern());
367 }
368 let batch = delivery.take(Instant::now(), false, &pattern()).unwrap();
369 assert_eq!(batch.lines.iter().map(|line| line.count).sum::<u64>(), 50);
370 assert_eq!(batch.dropped_lines, 3);
371 assert_eq!(batch.first_dropped_offset, Some(300));
372 assert_eq!(batch.first_dropped_stream.as_deref(), Some("stderr"));
373 }
374
375 #[test]
376 fn each_line_rate_cap_and_terminal_summary() {
377 let now = Instant::now();
378 let mut delivery = LineDelivery::default();
379 for index in 0..12 {
380 delivery.scan("stdout", b"ERROR\n", index * 6, &pattern());
381 assert!(delivery.take(now, false, &pattern()).is_some());
382 }
383 delivery.scan("stdout", b"ERROR\nERROR\n", 72, &pattern());
384 assert!(delivery.take(now, false, &pattern()).is_none());
385 let batch = delivery.take(now, true, &pattern()).unwrap();
386 assert_eq!(batch.dropped_lines, 2);
387 assert_eq!(batch.first_dropped_offset, Some(72));
388 assert!(batch.lines.is_empty());
389 assert!(delivery
390 .take(now + NOTIFICATION_WINDOW, false, &pattern())
391 .is_none());
392 delivery.scan("stdout", b"ERROR\n", 84, &pattern());
393 assert_eq!(
394 delivery
395 .take(now + NOTIFICATION_WINDOW, false, &pattern())
396 .unwrap()
397 .lines
398 .len(),
399 1
400 );
401 }
402
403 #[test]
404 fn each_line_folds_only_consecutive_identical_lines() {
405 let mut delivery = LineDelivery::default();
406 delivery.scan(
407 "stdout",
408 b"ERROR a\nERROR a\nignore\nERROR a\n",
409 0,
410 &pattern(),
411 );
412 let batch = delivery.take(Instant::now(), false, &pattern()).unwrap();
413 assert_eq!(batch.lines.len(), 2);
414 assert_eq!(batch.lines[0].count, 2);
415 assert_eq!(batch.lines[1].count, 1);
416 }
417
418 #[test]
419 fn each_line_oversized_line_is_bounded_and_explicit() {
420 let mut delivery = LineDelivery::default();
421 delivery.scan("stdout", &vec![b'x'; MAX_LINE_BYTES], 0, &pattern());
422 delivery.scan(
423 "stdout",
424 b"x\nERROR final",
425 MAX_LINE_BYTES as u64,
426 &pattern(),
427 );
428 let batch = delivery.take(Instant::now(), true, &pattern()).unwrap();
429 assert_eq!(batch.skipped_long_lines, 1);
430 assert_eq!(batch.first_dropped_offset, Some(0));
431 assert_eq!(batch.lines[0].text, "ERROR final");
432 }
433}
434pub fn format_watch_line_batch(task_id: &str, batch: &LineBatch) -> String {
436 let mut text = String::new();
437 for line in &batch.lines {
438 let body = if line.unavailable {
439 crate::task_watch_lines::unavailable_match_text(
440 line.count,
441 batch
442 .masking_limit_bytes
443 .map(|limit| limit as usize)
444 .unwrap_or(crate::task_watch_lines::MASKING_LINE_CAP_BYTES),
445 )
446 } else {
447 line.text.clone()
448 };
449 let repeats = if line.count > 1 {
450 format!(" ×{}", line.count)
451 } else {
452 String::new()
453 };
454 text.push_str(&format!(
455 "{} byte {}{repeats}: {}\n",
456 line.stream, line.offset, body
457 ));
458 }
459 if batch.dropped_lines > 0 || batch.skipped_long_lines > 0 {
460 let incomplete = if batch.skipped_long_lines > 0 {
461 format!(
462 " {} lines longer than 64 KiB were skipped, so the scan is incomplete.",
463 batch.skipped_long_lines
464 )
465 } else {
466 String::new()
467 };
468 let cursor = if batch.first_dropped_stream.as_deref() == Some("stderr") {
469 "stderr_offset"
470 } else {
471 "output_offset"
472 };
473 text.push_str(&format!("{} matching lines dropped.{incomplete} Read them with bash_status({{ task_id: {}, {cursor}: {} }}).\n", batch.dropped_lines, serde_json::to_string(task_id).unwrap_or_default(), batch.first_dropped_offset.unwrap_or(0)));
474 }
475 if let Some(gap) = &batch.retry_gap {
476 let missing = match gap.known_missing_occurrences {
477 0 => "Some matches may be missing.".to_string(),
478 1 => "At least 1 match is missing.".to_string(),
479 count => format!("At least {count} matches are missing."),
480 };
481 let cursor = if gap.stream.as_deref() == Some("stderr") {
482 "stderr_offset"
483 } else {
484 "output_offset"
485 };
486 text.push_str(&format!("Some watch notices were lost: a stalled connection dropped {} of them, and they cannot be recovered. {missing} Read the task output with bash_status({{ task_id: {}, {cursor}: {} }}).\n", gap.dropped_notifications, serde_json::to_string(task_id).unwrap_or_default(), gap.first_offset.unwrap_or(0)));
487 }
488 text.trim_end().to_string()
489}
490
491static NEXT_EVICTION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
492static EVICTION_EPOCH: std::sync::OnceLock<String> = std::sync::OnceLock::new();
493
494pub fn eviction_epoch() -> &'static str {
495 EVICTION_EPOCH.get_or_init(|| {
496 format!(
497 "{}:{}",
498 std::process::id(),
499 std::time::SystemTime::now()
500 .duration_since(std::time::UNIX_EPOCH)
501 .unwrap_or_default()
502 .as_nanos()
503 )
504 })
505}
506
507#[derive(Clone)]
508pub struct Candidate {
509 pub eviction_epoch: String,
510 pub last_eviction: u64,
511 pub fingerprint: Vec<u8>,
512 pub frame: crate::protocol::BashPatternMatchFrame,
513 pub notifications: u64,
514 pub first_version: u64,
515 pub last_version: u64,
516 pub first_offset: Option<u64>,
517 pub last_offset: Option<u64>,
518 pub stream: Option<String>,
519 pub same_generation: bool,
520 pub same_occurrence: bool,
521}
522
523impl Candidate {
524 pub fn new(mut frame: crate::protocol::BashPatternMatchFrame) -> Self {
525 use sha2::Digest;
526 let fingerprint = sha2::Sha256::digest(frame.match_text.as_bytes()).to_vec();
527 let (first_offset, last_offset, stream) = if let Some(batch) = &frame.batch {
528 let stream = batch.lines.first().map(|line| line.stream.clone());
529 if batch
530 .lines
531 .iter()
532 .all(|line| Some(&line.stream) == stream.as_ref())
533 {
534 (
535 batch
536 .lines
537 .first()
538 .map(|line| line.offset)
539 .or(batch.first_dropped_offset),
540 batch.lines.last().map(|line| {
541 line.offset.saturating_add(
542 line.count
543 .saturating_mul(line.end_offset.saturating_sub(line.offset)),
544 )
545 }),
546 stream.or(batch.first_dropped_stream.clone()),
547 )
548 } else {
549 (None, None, None)
550 }
551 } else {
552 (Some(frame.match_offset), Some(frame.match_offset), None)
553 };
554 let version = frame.match_offset;
555 frame.match_text = String::new();
556 frame.context = String::new();
557 if let Some(batch) = &mut frame.batch {
558 batch.lines = Vec::new();
559 }
560 Self {
561 eviction_epoch: eviction_epoch().to_string(),
562 last_eviction: NEXT_EVICTION.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
563 fingerprint,
564 frame,
565 notifications: 1,
566 first_version: version,
567 last_version: version,
568 first_offset,
569 last_offset,
570 stream,
571 same_generation: true,
572 same_occurrence: true,
573 }
574 }
575
576 pub fn merge(&mut self, next: Self) {
577 self.same_occurrence &= next.same_occurrence
578 && self.fingerprint == next.fingerprint
579 && self.first_version == next.first_version;
580 self.last_eviction = self.last_eviction.max(next.last_eviction);
581 self.notifications = self.notifications.saturating_add(next.notifications);
582 self.first_version = self.first_version.min(next.first_version);
583 self.last_version = self.last_version.max(next.last_version);
584 self.same_generation &= next.same_generation
585 && self
586 .frame
587 .batch
588 .as_ref()
589 .and_then(|b| b.pending_id.as_ref())
590 == next
591 .frame
592 .batch
593 .as_ref()
594 .and_then(|b| b.pending_id.as_ref());
595 if self.stream == next.stream {
596 self.first_offset = self
597 .first_offset
598 .zip(next.first_offset)
599 .map(|(a, b)| a.min(b));
600 self.last_offset = self
601 .last_offset
602 .zip(next.last_offset)
603 .map(|(a, b)| a.max(b));
604 } else {
605 self.first_offset = None;
606 self.last_offset = None;
607 self.stream = None;
608 }
609 }
610}