1use regex::{Regex, RegexBuilder};
2use serde::Serialize;
3use std::collections::{HashMap, HashSet};
4use std::time::Instant;
5
6use crate::task_watch_lines::{LineBatch, LineDelivery};
7
8const MAX_WATCHES_PER_TASK: usize = 8;
9const CONTEXT_BEFORE: usize = 100;
10const CONTEXT_AFTER: usize = 500;
11pub const SCAN_OVERLAP_BYTES: usize = 8 * 1024;
14
15pub const WATCH_TARGET_ERASED_TEXT: &str = "watch target erased";
16pub const WATCH_TARGET_ERASED_CONTEXT: &str =
17 "watch target erased: the background task row was erased before the watch reached a normal terminal result";
18pub const WATCH_TASK_EXIT_TEXT: &str = "watch task exited";
19pub const MORE_MATCHES_TEXT: &str =
22 "{n} more matches followed in the same output; read them with bash_status.";
23
24pub fn more_matches_line(more: u64) -> Option<String> {
26 (more > 0).then(|| MORE_MATCHES_TEXT.replace("{n}", &more.to_string()))
27}
28
29#[derive(Debug, Clone)]
30pub struct WatchSpec {
31 pub watch_id: String,
32 pub task_id: String,
33 pub pattern: WatchPattern,
34 pub once: bool,
35}
36
37#[derive(Debug, Clone)]
38pub enum WatchPattern {
39 Substring(String),
40 Regex(Regex),
41}
42
43impl WatchPattern {
44 pub fn regex(pattern: &str) -> Result<Self, regex::Error> {
45 RegexBuilder::new(pattern)
46 .multi_line(true)
47 .build()
48 .map(Self::Regex)
49 }
50
51 pub fn kind_name(&self) -> &'static str {
52 match self {
53 Self::Substring(_) => "substring",
54 Self::Regex(_) => "regex",
55 }
56 }
57
58 pub fn pattern_text(&self) -> &str {
59 match self {
60 Self::Substring(text) => text,
61 Self::Regex(regex) => regex.as_str(),
62 }
63 }
64
65 pub fn from_persisted(kind: &str, pattern: &str) -> Result<Self, String> {
66 match kind {
67 "substring" => Ok(Self::Substring(pattern.to_string())),
68 "regex" => Self::regex(pattern).map_err(|error| error.to_string()),
69 other => Err(format!("unknown pattern kind {other}")),
70 }
71 }
72}
73
74#[derive(Debug, Clone, Serialize)]
75pub struct PatternMatch {
76 pub watch_id: String,
77 pub task_id: String,
78 pub match_text: String,
79 pub match_offset: u64,
80 pub context: String,
81 pub once: bool,
82 #[serde(skip_serializing_if = "Option::is_none")]
83 pub batch: Option<LineBatch>,
84 #[serde(skip)]
88 pub literal_pattern: bool,
89}
90
91impl PatternMatch {
92 pub fn copy_delivery_identity(&mut self, persisted: &Self) {
93 if let (Some(live), Some(saved)) = (self.batch.as_mut(), persisted.batch.as_ref()) {
94 self.match_offset = persisted.match_offset;
95 live.pending_id = saved.pending_id.clone();
96 live.version = saved.version;
97 }
98 }
99}
100
101#[derive(Debug, Default)]
102pub struct WatchRegistry {
103 line_delivery: HashMap<String, LineDelivery>,
104 watches: HashMap<String, Vec<WatchSpec>>,
105 scan_cursors: HashMap<String, u64>,
106 scan_overlaps: HashMap<String, Vec<u8>>,
107 held_ends: HashSet<String>,
110 controlled_tasks: HashSet<String>,
111 matched_tasks: HashSet<String>,
112 erased_notifications: HashSet<String>,
115 next_watch: u64,
116}
117
118impl WatchRegistry {
119 pub fn enable_each_line(&mut self, watch_id: &str) {
120 self.line_delivery.entry(watch_id.to_string()).or_default();
121 }
122
123 pub fn is_each_line(&self, watch_id: &str) -> bool {
124 self.line_delivery.contains_key(watch_id)
125 }
126
127 pub fn replay_cursor(&self, task_id: &str, stream: &str, cursor: u64) -> u64 {
128 self.watch_ids(task_id)
129 .iter()
130 .filter_map(|id| self.line_delivery.get(id))
131 .fold(cursor, |cursor, delivery| {
132 delivery.replay_cursor(stream, cursor)
133 })
134 }
135
136 pub fn take_line_batches(&mut self, task_id: &str, terminal: bool) -> Vec<PatternMatch> {
137 self.take_line_batches_at(task_id, terminal, Instant::now())
138 }
139
140 fn take_line_batches_at(
141 &mut self,
142 task_id: &str,
143 terminal: bool,
144 now: Instant,
145 ) -> Vec<PatternMatch> {
146 let mut found = Vec::new();
147 for watch in self.watch_specs(task_id) {
148 let Some(delivery) = self.line_delivery.get_mut(&watch.watch_id) else {
149 continue;
150 };
151 let Some(batch) = delivery.take(now, terminal, &watch.pattern) else {
152 continue;
153 };
154 let matched = batch.has_matches();
155 let offset = batch
156 .lines
157 .first()
158 .map(|line| line.offset)
159 .or(batch.first_dropped_offset)
160 .unwrap_or(0);
161 if matched {
162 self.matched_tasks.insert(task_id.to_string());
163 }
164 found.push(PatternMatch {
165 watch_id: watch.watch_id.clone(),
166 task_id: task_id.to_string(),
167 match_text: "matching lines".to_string(),
168 match_offset: offset,
169 context: String::new(),
170 once: watch.once && matched,
171 batch: Some(batch),
172 literal_pattern: false,
174 });
175 if watch.once && matched {
176 self.unregister(task_id, &watch.watch_id);
177 }
178 }
179 found
180 }
181 pub fn register(
182 &mut self,
183 task_id: String,
184 pattern: WatchPattern,
185 once: bool,
186 ) -> Result<String, &'static str> {
187 let watches = self.watches.entry(task_id.clone()).or_default();
188 if watches.len() >= MAX_WATCHES_PER_TASK {
189 return Err("too_many_watches");
190 }
191 self.controlled_tasks.insert(task_id.clone());
192 self.next_watch = self.next_watch.wrapping_add(1);
193 let watch_id = format!("watch-{:08x}", self.next_watch);
194 watches.push(WatchSpec {
195 watch_id: watch_id.clone(),
196 task_id,
197 pattern,
198 once,
199 });
200 Ok(watch_id)
201 }
202
203 pub fn restore(
208 &mut self,
209 watch_id: String,
210 task_id: String,
211 pattern: WatchPattern,
212 once: bool,
213 scanning: bool,
214 ) -> Result<(), &'static str> {
215 self.note_restored_watch_id(&watch_id);
216 self.controlled_tasks.insert(task_id.clone());
217 if !scanning {
218 self.matched_tasks.insert(task_id);
219 return Ok(());
220 }
221 let watches = self.watches.entry(task_id.clone()).or_default();
222 if watches.iter().any(|watch| watch.watch_id == watch_id) {
223 return Ok(());
224 }
225 if watches.len() >= MAX_WATCHES_PER_TASK {
226 return Err("too_many_watches");
227 }
228 watches.push(WatchSpec {
229 watch_id,
230 task_id,
231 pattern,
232 once,
233 });
234 Ok(())
235 }
236
237 fn note_restored_watch_id(&mut self, watch_id: &str) {
238 let Some(hex) = watch_id.strip_prefix("watch-") else {
239 return;
240 };
241 if let Ok(value) = u64::from_str_radix(hex, 16) {
242 if value >= self.next_watch {
243 self.next_watch = value;
244 }
245 }
246 }
247
248 pub fn unregister(&mut self, task_id: &str, watch_id: &str) {
249 self.line_delivery.remove(watch_id);
250 if let Some(watches) = self.watches.get_mut(task_id) {
251 watches.retain(|watch| watch.watch_id != watch_id);
252 if watches.is_empty() {
253 self.watches.remove(task_id);
254 }
255 }
256 }
257
258 pub fn file_cursor(&self, cursor_key: &str) -> Option<u64> {
259 self.scan_cursors.get(cursor_key).copied()
260 }
261
262 pub fn watch_ids(&self, task_id: &str) -> Vec<String> {
263 self.watches
264 .get(task_id)
265 .map(|watches| watches.iter().map(|watch| watch.watch_id.clone()).collect())
266 .unwrap_or_default()
267 }
268
269 pub fn watched_task_ids(&self) -> Vec<String> {
270 self.watches.keys().cloned().collect()
271 }
272
273 pub fn watch_specs(&self, task_id: &str) -> Vec<WatchSpec> {
274 self.watches.get(task_id).cloned().unwrap_or_default()
275 }
276
277 pub fn reconcile_watch_ids(
279 &mut self,
280 task_id: &str,
281 keep: &HashSet<String>,
282 has_pending_match: bool,
283 ) {
284 for watch_id in self.watch_ids(task_id) {
285 if !keep.contains(&watch_id) {
286 self.line_delivery.remove(&watch_id);
287 }
288 }
289 let watches_empty = if let Some(watches) = self.watches.get_mut(task_id) {
290 watches.retain(|watch| keep.contains(&watch.watch_id));
291 watches.is_empty()
292 } else {
293 true
294 };
295 if watches_empty {
296 self.clear_task(task_id);
297 } else if has_pending_match {
298 self.matched_tasks.insert(task_id.to_string());
299 } else {
300 self.matched_tasks.remove(task_id);
301 }
302 }
303
304 pub fn clear_task(&mut self, task_id: &str) {
305 for watch_id in self.watch_ids(task_id) {
306 self.line_delivery.remove(&watch_id);
307 }
308 self.watches.remove(task_id);
309 self.controlled_tasks.remove(task_id);
310 self.matched_tasks.remove(task_id);
311 let prefix = format!("{task_id}:");
312 self.scan_cursors
313 .retain(|key, _| key != task_id && !key.starts_with(&prefix));
314 self.scan_overlaps
315 .retain(|key, _| key != task_id && !key.starts_with(&prefix));
316 self.held_ends
317 .retain(|key| key != task_id && !key.starts_with(&prefix));
318 }
319
320 pub fn terminalize_erased_task(&mut self, task_id: &str) -> Vec<String> {
321 let watch_ids = self.watch_ids(task_id);
322 self.clear_task(task_id);
323 watch_ids
324 .into_iter()
325 .filter(|watch_id| {
326 self.erased_notifications
327 .insert(format!("{task_id}:{watch_id}"))
328 })
329 .collect()
330 }
331
332 pub fn has_erased_task(&self, task_id: &str) -> bool {
333 let prefix = format!("{task_id}:");
334 self.erased_notifications
335 .iter()
336 .any(|notification| notification.starts_with(&prefix))
337 }
338
339 pub fn forget_erased_task(&mut self, task_id: &str) {
340 let prefix = format!("{task_id}:");
341 self.erased_notifications
342 .retain(|notification| !notification.starts_with(&prefix));
343 }
344
345 pub fn has_controlled_task(&self, task_id: &str) -> bool {
346 self.controlled_tasks.contains(task_id)
347 }
348
349 pub fn has_matched_task(&self, task_id: &str) -> bool {
350 self.matched_tasks.contains(task_id)
351 }
352
353 pub fn active_count(&self, task_id: &str) -> usize {
354 self.watches.get(task_id).map_or(0, Vec::len)
355 }
356
357 pub fn set_file_cursor(&mut self, cursor_key: &str, offset: u64) {
358 self.scan_cursors.insert(cursor_key.to_string(), offset);
359 self.scan_overlaps.remove(cursor_key);
360 self.held_ends.remove(cursor_key);
361 }
362
363 pub fn restore_file_cursor(
375 &mut self,
376 cursor_key: &str,
377 offset: u64,
378 before: &[u8],
379 running: bool,
380 ) {
381 self.set_file_cursor(cursor_key, offset);
382 let keep = before.len().min(SCAN_OVERLAP_BYTES);
383 if keep == 0 {
384 return;
385 }
386 self.scan_overlaps.insert(
387 cursor_key.to_string(),
388 before[before.len() - keep..].to_vec(),
389 );
390 if running {
391 self.held_ends.insert(cursor_key.to_string());
392 }
393 }
394
395 pub fn scan_chunk(
403 &mut self,
404 cursor_key: &str,
405 task_id: &str,
406 bytes: &[u8],
407 start: u64,
408 at_end: bool,
409 render: &mut dyn FnMut(&str, usize, usize, u64, u64) -> (String, String),
410 ) -> Vec<(PatternMatch, u64)> {
411 if bytes.is_empty() && !self.held_ends.contains(cursor_key) {
412 return Vec::new();
413 }
414 self.scan_cursors.insert(
415 cursor_key.to_string(),
416 start.saturating_add(bytes.len() as u64),
417 );
418 self.scan_new_bytes_at(cursor_key, task_id, bytes, start, at_end, render)
419 }
420
421 pub fn scan_new_bytes(&mut self, task_id: &str, bytes: &[u8]) -> Vec<PatternMatch> {
422 let base = self.scan_cursors.get(task_id).copied().unwrap_or(0);
423 self.scan_cursors
424 .insert(task_id.to_string(), base.saturating_add(bytes.len() as u64));
425 self.scan_new_bytes_at(
426 task_id,
427 task_id,
428 bytes,
429 base,
430 false,
431 &mut |text, start, end, _, _| {
432 (
433 text[start..end].to_string(),
434 context_snippet(text, start, end),
435 )
436 },
437 )
438 .into_iter()
439 .map(|(found, _)| found)
440 .collect()
441 }
442
443 fn scan_new_bytes_at(
444 &mut self,
445 cursor_key: &str,
446 task_id: &str,
447 bytes: &[u8],
448 base_offset: u64,
449 at_end: bool,
450 render: &mut dyn FnMut(&str, usize, usize, u64, u64) -> (String, String),
451 ) -> Vec<(PatternMatch, u64)> {
452 let Some(watches) = self.watches.get(task_id).cloned() else {
453 return Vec::new();
454 };
455 let end_held = self.held_ends.remove(cursor_key);
456 let mut held = false;
457 let overlap = self
458 .scan_overlaps
459 .get(cursor_key)
460 .cloned()
461 .unwrap_or_default();
462 let prefix_len = overlap.len();
463 let mut scan_bytes = Vec::with_capacity(prefix_len.saturating_add(bytes.len()));
464 scan_bytes.extend_from_slice(&overlap);
465 scan_bytes.extend_from_slice(bytes);
466 let text = String::from_utf8_lossy(&scan_bytes);
467 let offsets = LossyOffsets::new(&scan_bytes);
468 let scan_base_offset = base_offset.saturating_sub(prefix_len as u64);
469 let mut matches = Vec::new();
470 let mut remove_once = Vec::new();
471 for watch in watches {
472 if let Some(delivery) = self.line_delivery.get_mut(&watch.watch_id) {
473 let stream = cursor_key.rsplit(':').next().unwrap_or("stdout");
474 delivery.scan(stream, bytes, base_offset, &watch.pattern);
475 continue;
476 }
477 if let Some(((text_start, text_end, source_start, source_end), more)) = find_match(
478 &watch.pattern,
479 &text,
480 &offsets,
481 prefix_len,
482 end_held,
483 at_end,
484 !watch.once,
485 &mut held,
486 ) {
487 self.matched_tasks.insert(task_id.to_string());
488 let (rendered_match, context) = render(
489 &text,
490 text_start,
491 text_end,
492 scan_base_offset.saturating_add(source_start as u64),
493 scan_base_offset.saturating_add(source_end as u64),
494 );
495 let (match_text, literal_pattern) = match &watch.pattern {
499 WatchPattern::Substring(needle) => (needle.clone(), true),
500 WatchPattern::Regex(_) => (rendered_match, false),
501 };
502 matches.push((
503 PatternMatch {
504 watch_id: watch.watch_id.clone(),
505 task_id: watch.task_id.clone(),
506 match_text,
507 match_offset: scan_base_offset.saturating_add(source_start as u64),
508 context,
509 once: watch.once,
510 batch: None,
511 literal_pattern,
512 },
513 more,
514 ));
515 if watch.once {
516 remove_once.push(watch.watch_id);
517 }
518 }
519 }
520 for watch_id in remove_once {
521 self.unregister(task_id, &watch_id);
522 }
523 if held {
524 self.held_ends.insert(cursor_key.to_string());
525 }
526 let keep = scan_bytes.len().min(SCAN_OVERLAP_BYTES);
527 self.scan_overlaps.insert(
528 cursor_key.to_string(),
529 scan_bytes[scan_bytes.len().saturating_sub(keep)..].to_vec(),
530 );
531 matches
532 }
533}
534
535#[allow(clippy::too_many_arguments)]
545fn find_match(
546 pattern: &WatchPattern,
547 text: &str,
548 offsets: &LossyOffsets,
549 prefix_len: usize,
550 end_held: bool,
551 at_end: bool,
552 count_more: bool,
553 held: &mut bool,
554) -> Option<((usize, usize, usize, usize), u64)> {
555 let regex = matches!(pattern, WatchPattern::Regex(_));
556 let min_source_end_exclusive = if regex && end_held {
557 prefix_len.saturating_sub(1)
558 } else {
559 prefix_len
560 };
561 let still_written = |end: usize| regex && !at_end && end == text.len();
562 let mut candidates: Box<dyn Iterator<Item = (usize, usize)>> = match pattern {
563 WatchPattern::Substring(needle) if needle.is_empty() => return None,
564 WatchPattern::Substring(needle) => Box::new(
565 text.match_indices(needle.as_str())
566 .map(|(start, matched)| (start, start + matched.len())),
567 ),
568 WatchPattern::Regex(regex) => Box::new(
569 regex
570 .find_iter(text)
571 .map(|found| (found.start(), found.end())),
572 ),
573 };
574 let first = candidates.by_ref().find_map(|(start, end)| {
575 if still_written(end) {
576 *held = true;
577 return None;
578 }
579 let source_end = offsets.source_offset(end);
580 (source_end > min_source_end_exclusive)
581 .then(|| (start, end, offsets.source_offset(start), source_end))
582 })?;
583 let more = if count_more {
587 candidates
588 .filter(|&(_, end)| {
589 let written = !still_written(end);
590 *held |= !written;
591 written
592 })
593 .count() as u64
594 } else {
595 0
596 };
597 Some((first, more))
598}
599
600struct LossyOffsets {
604 runs: Vec<LossyRun>,
607 source_len: usize,
608}
609
610struct LossyRun {
611 rendered: usize,
612 source: usize,
613 valid: usize,
614 invalid: usize,
616}
617
618impl LossyOffsets {
619 fn new(source: &[u8]) -> Self {
620 let replacement = '\u{FFFD}'.len_utf8();
621 let mut runs = Vec::new();
622 let (mut source_start, mut rendered_start) = (0, 0);
623 while source_start < source.len() {
624 #[cfg(test)]
625 count_validated_bytes(source.len() - source_start);
626 match std::str::from_utf8(&source[source_start..]) {
627 Ok(valid) => {
628 runs.push(LossyRun {
629 rendered: rendered_start,
630 source: source_start,
631 valid: valid.len(),
632 invalid: 0,
633 });
634 break;
635 }
636 Err(error) => {
637 let valid = error.valid_up_to();
638 let invalid = error
639 .error_len()
640 .unwrap_or(source.len() - source_start - valid);
641 runs.push(LossyRun {
642 rendered: rendered_start,
643 source: source_start,
644 valid,
645 invalid,
646 });
647 source_start += valid + invalid;
648 rendered_start += valid + replacement;
649 }
650 }
651 }
652 Self {
653 runs,
654 source_len: source.len(),
655 }
656 }
657
658 fn source_offset(&self, lossy_offset: usize) -> usize {
662 let Some(run) = self
663 .runs
664 .partition_point(|run| run.rendered <= lossy_offset)
665 .checked_sub(1)
666 .map(|index| &self.runs[index])
667 else {
668 return self.source_len;
669 };
670 let offset = lossy_offset - run.rendered;
671 if run.invalid == 0 {
672 run.source + offset.min(run.valid)
673 } else if offset <= run.valid {
674 run.source + offset
675 } else if offset < run.valid + '\u{FFFD}'.len_utf8() {
676 run.source + run.valid
677 } else {
678 run.source + run.valid + run.invalid
679 }
680 }
681}
682
683#[cfg(test)]
684thread_local! {
685 static VALIDATED_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
686}
687
688#[cfg(test)]
690fn count_validated_bytes(bytes: usize) {
691 VALIDATED_BYTES.with(|count| count.set(count.get() + bytes));
692}
693
694pub fn context_snippet(text: &str, start: usize, end: usize) -> String {
695 text[context_range(text, start, end)].replace('\r', "")
696}
697
698pub fn context_range(text: &str, start: usize, end: usize) -> std::ops::Range<usize> {
699 let before_start = text[..start]
700 .char_indices()
701 .rev()
702 .nth(CONTEXT_BEFORE)
703 .map(|(idx, _)| idx)
704 .unwrap_or(0);
705 let after_end = text[end..]
706 .char_indices()
707 .nth(CONTEXT_AFTER)
708 .map(|(idx, _)| end + idx)
709 .unwrap_or(text.len());
710 before_start..after_end
711}
712
713#[cfg(test)]
714mod tests {
715 #[test]
716 fn each_line_default_frame_is_unchanged() {
717 let mut registry = super::WatchRegistry::default();
718 registry
719 .register(
720 "task".into(),
721 super::WatchPattern::Substring("ERROR".into()),
722 false,
723 )
724 .unwrap();
725 let found = registry.scan_new_bytes("task", b"ERROR a\nERROR b\n");
726 assert_eq!(
727 serde_json::to_string(&found).unwrap(),
728 r#"[{"watch_id":"watch-00000001","task_id":"task","match_text":"ERROR","match_offset":0,"context":"ERROR a\nERROR b\n","once":false}]"#
729 );
730 }
731
732 #[test]
733 fn each_line_registry_batches_across_pages() {
734 let mut registry = super::WatchRegistry::default();
735 let id = registry
736 .register(
737 "task".into(),
738 super::WatchPattern::Substring("ERROR".into()),
739 false,
740 )
741 .unwrap();
742 registry.enable_each_line(&id);
743 registry.scan_new_bytes("task", b"ERROR a\nER");
744 registry.scan_new_bytes("task", b"ROR b\n");
745 let found = registry.take_line_batches("task", false);
746 assert_eq!(found.len(), 1);
747 assert_eq!(found[0].batch.as_ref().unwrap().lines.len(), 2);
748 }
749 use super::*;
750
751 #[test]
752 fn once_watch_self_removes_after_match() {
753 let mut registry = WatchRegistry::default();
754 let task_id = "bash-1".to_string();
755 registry
756 .register(
757 task_id.clone(),
758 WatchPattern::Substring("READY".into()),
759 true,
760 )
761 .unwrap();
762 assert_eq!(registry.scan_new_bytes(&task_id, b"READY\n").len(), 1);
763 assert_eq!(registry.active_count(&task_id), 0);
764 }
765
766 #[test]
767 fn sticky_watch_fires_multiple_times() {
768 let mut registry = WatchRegistry::default();
769 let task_id = "bash-1".to_string();
770 registry
771 .register(
772 task_id.clone(),
773 WatchPattern::Substring("READY".into()),
774 false,
775 )
776 .unwrap();
777 assert_eq!(registry.scan_new_bytes(&task_id, b"READY\n").len(), 1);
778 assert_eq!(registry.scan_new_bytes(&task_id, b"READY\n").len(), 1);
779 assert_eq!(registry.active_count(&task_id), 1);
780 }
781
782 #[test]
783 fn cap_8_watches_per_task_rejects_9th() {
784 let mut registry = WatchRegistry::default();
785 for _ in 0..8 {
786 registry
787 .register("bash-1".into(), WatchPattern::Substring("x".into()), true)
788 .unwrap();
789 }
790 assert_eq!(
791 registry.register("bash-1".into(), WatchPattern::Substring("x".into()), true),
792 Err("too_many_watches")
793 );
794 }
795
796 #[test]
797 fn regex_pattern_matches_with_capture() {
798 let mut registry = WatchRegistry::default();
799 let task_id = "bash-1".to_string();
800 registry
801 .register(
802 task_id.clone(),
803 WatchPattern::regex("port (\\d+)").unwrap(),
804 true,
805 )
806 .unwrap();
807 let hits = registry.scan_new_bytes(&task_id, b"listening on port 3000\n");
808 assert_eq!(hits[0].match_text, "port 3000");
809 }
810
811 #[test]
812 fn substring_pattern_can_span_scans() {
813 let mut registry = WatchRegistry::default();
814 let task_id = "bash-1".to_string();
815 registry
816 .register(
817 task_id.clone(),
818 WatchPattern::Substring("READY".into()),
819 true,
820 )
821 .unwrap();
822
823 assert!(registry.scan_new_bytes(&task_id, b"RE").is_empty());
824 let hits = registry.scan_new_bytes(&task_id, b"ADY\n");
825
826 assert_eq!(hits.len(), 1);
827 assert_eq!(hits[0].match_text, "READY");
828 assert_eq!(hits[0].match_offset, 0);
829 }
830
831 #[test]
832 fn regex_pattern_can_span_scans() {
833 let mut registry = WatchRegistry::default();
834 let task_id = "bash-1".to_string();
835 registry
836 .register(
837 task_id.clone(),
838 WatchPattern::regex("ready: \\d{4}").unwrap(),
839 true,
840 )
841 .unwrap();
842
843 assert!(registry
844 .scan_new_bytes(&task_id, b"prefix ready: 4")
845 .is_empty());
846 let hits = registry.scan_new_bytes(&task_id, b"242\n");
847
848 assert_eq!(hits.len(), 1);
849 assert_eq!(hits[0].match_text, "ready: 4242");
850 assert_eq!(hits[0].match_offset, 7);
851 }
852
853 #[test]
854 fn overlap_does_not_repeat_fully_previous_match() {
855 let mut registry = WatchRegistry::default();
856 let task_id = "bash-1".to_string();
857 registry
858 .register(
859 task_id.clone(),
860 WatchPattern::Substring("READY".into()),
861 false,
862 )
863 .unwrap();
864
865 assert_eq!(registry.scan_new_bytes(&task_id, b"READY").len(), 1);
866 assert!(registry.scan_new_bytes(&task_id, b"\n").is_empty());
867 }
868
869 #[test]
870 fn lossy_utf8_indices_are_mapped_back_to_source_offsets() {
871 let mut registry = WatchRegistry::default();
872 let task_id = "bash-1".to_string();
873 registry
874 .register(
875 task_id.clone(),
876 WatchPattern::Substring("READY".into()),
877 false,
878 )
879 .unwrap();
880
881 let hits = registry.scan_new_bytes(&task_id, b"\xffREADY");
882
883 assert_eq!(hits.len(), 1);
884 assert_eq!(hits[0].match_offset, 1);
885 assert!(registry.scan_new_bytes(&task_id, b"\n").is_empty());
886 }
887
888 fn regex_watch(pattern: &str, once: bool) -> WatchRegistry {
889 let mut registry = WatchRegistry::default();
890 registry
891 .register("bash-1".into(), WatchPattern::regex(pattern).unwrap(), once)
892 .unwrap();
893 registry
894 }
895
896 fn texts(hits: &[PatternMatch]) -> Vec<(String, u64)> {
897 hits.iter()
898 .map(|hit| (hit.match_text.clone(), hit.match_offset))
899 .collect()
900 }
901
902 #[test]
903 fn regex_match_reaching_the_read_end_waits_for_the_rest_of_its_value() {
904 let mut registry = regex_watch(r"port (\d+)", true);
905 assert!(registry
906 .scan_new_bytes("bash-1", b"listening on port 30")
907 .is_empty());
908 let hits = registry.scan_new_bytes("bash-1", b"00\n");
909 assert_eq!(texts(&hits), vec![("port 3000".to_string(), 13)]);
910 }
911
912 #[test]
913 fn regex_end_anchor_does_not_match_a_line_still_being_written() {
914 let mut registry = regex_watch(r"^READY$", true);
915 assert!(registry.scan_new_bytes("bash-1", b"boot\nREADY").is_empty());
916 assert!(registry
917 .scan_new_bytes("bash-1", b"ING to start\n")
918 .is_empty());
919 assert_eq!(registry.active_count("bash-1"), 1);
920 assert!(registry.scan_new_bytes("bash-1", b"READY").is_empty());
921 let hits = registry.scan_new_bytes("bash-1", b"\n");
922 assert_eq!(texts(&hits), vec![("READY".to_string(), 23)]);
923 }
924
925 #[test]
926 fn sticky_regex_reports_a_growing_token_once() {
927 let mut registry = regex_watch(r"id=\d+", false);
928 assert!(registry.scan_new_bytes("bash-1", b"job id=12").is_empty());
929 let hits = registry.scan_new_bytes("bash-1", b"34 queued\n");
930 assert_eq!(texts(&hits), vec![("id=1234".to_string(), 4)]);
931 assert!(registry.scan_new_bytes("bash-1", b"done\n").is_empty());
932 }
933
934 #[test]
935 fn held_regex_match_is_reported_once_when_the_stream_ends() {
936 let mut registry = regex_watch(r"READY$", false);
937 let mut render = |text: &str, start: usize, end: usize, _: u64, _: u64| {
938 (text[start..end].to_string(), String::new())
939 };
940 let key = "bash-1:stdout";
941 assert!(registry
942 .scan_chunk(key, "bash-1", b"boot\nREADY", 0, false, &mut render)
943 .is_empty());
944 let hits = found(registry.scan_chunk(key, "bash-1", b"", 10, true, &mut render));
945 assert_eq!(texts(&hits), vec![("READY".to_string(), 5)]);
946 assert!(registry
947 .scan_chunk(key, "bash-1", b"", 10, true, &mut render)
948 .is_empty());
949 let mut registry = regex_watch(r"READY$", false);
951 let hits = found(registry.scan_chunk(key, "bash-1", b"boot\nREADY", 0, true, &mut render));
952 assert_eq!(texts(&hits), vec![("READY".to_string(), 5)]);
953 }
954
955 fn found(hits: Vec<(PatternMatch, u64)>) -> Vec<PatternMatch> {
956 hits.into_iter().map(|(hit, _)| hit).collect()
957 }
958
959 fn decoded_source_offset(source: &[u8], lossy_offset: usize) -> usize {
962 let (mut source_start, mut rendered_start) = (0, 0);
963 while source_start < source.len() {
964 match std::str::from_utf8(&source[source_start..]) {
965 Ok(valid) => {
966 return source_start
967 + lossy_offset.saturating_sub(rendered_start).min(valid.len());
968 }
969 Err(error) => {
970 let valid_len = error.valid_up_to();
971 if lossy_offset <= rendered_start + valid_len {
972 return source_start + lossy_offset.saturating_sub(rendered_start);
973 }
974 source_start += valid_len;
975 rendered_start += valid_len;
976 let invalid_len = error.error_len().unwrap_or(source.len() - source_start);
977 if lossy_offset < rendered_start + 3 {
978 return source_start;
979 }
980 source_start += invalid_len;
981 rendered_start += 3;
982 }
983 }
984 }
985 source.len()
986 }
987
988 #[test]
989 fn lossy_offsets_match_a_fresh_decode_at_every_offset() {
990 let mut seed = 0x5eed_u64;
991 for round in 0..300 {
992 let mut source = Vec::new();
993 for _ in 0..(round % 40) {
994 seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
995 source.push(match (seed >> 33) % 8 {
997 0 => 0xe2,
998 1 => 0x82,
999 2 => 0xff,
1000 3 => 0xc3,
1001 _ => b'a' + (seed >> 40) as u8 % 26,
1002 });
1003 }
1004 let offsets = LossyOffsets::new(&source);
1005 let rendered = String::from_utf8_lossy(&source).len();
1006 for lossy in 0..=rendered + 4 {
1007 assert_eq!(
1008 offsets.source_offset(lossy),
1009 decoded_source_offset(&source, lossy),
1010 "{source:?} at {lossy}"
1011 );
1012 }
1013 }
1014 }
1015
1016 #[test]
1017 fn dense_matches_in_the_overlap_cost_one_decode_per_scan() {
1018 let mut registry = WatchRegistry::default();
1019 registry
1020 .register("bash-1".into(), WatchPattern::Substring("a".into()), false)
1021 .unwrap();
1022 let chunk = vec![b'a'; 64 * 1024];
1023 registry.scan_new_bytes("bash-1", &chunk);
1024 VALIDATED_BYTES.with(|count| count.set(0));
1025 assert_eq!(registry.scan_new_bytes("bash-1", &chunk).len(), 1);
1027 let validated = VALIDATED_BYTES.with(std::cell::Cell::get);
1028 let scanned = chunk.len() + SCAN_OVERLAP_BYTES;
1029 assert!(
1030 validated <= scanned,
1031 "decoded {validated} bytes to scan {scanned}"
1032 );
1033 }
1034
1035 fn chunk(registry: &mut WatchRegistry, bytes: &[u8], start: u64) -> Vec<(String, u64)> {
1036 let mut render = |text: &str, start: usize, end: usize, _: u64, _: u64| {
1037 (text[start..end].to_string(), String::new())
1038 };
1039 registry
1040 .scan_chunk("bash-1:stdout", "bash-1", bytes, start, false, &mut render)
1041 .into_iter()
1042 .map(|(hit, more)| (hit.match_text, more))
1043 .collect()
1044 }
1045
1046 #[test]
1047 fn sticky_watch_counts_the_matches_its_notification_stands_for() {
1048 let mut registry = WatchRegistry::default();
1049 registry
1050 .register(
1051 "bash-1".into(),
1052 WatchPattern::Substring("READY".into()),
1053 false,
1054 )
1055 .unwrap();
1056 let three = b"READY 1\nREADY 2\nREADY 3\n";
1057 assert_eq!(
1058 chunk(&mut registry, three, 0),
1059 vec![("READY".to_string(), 2)]
1060 );
1061 assert_eq!(
1062 chunk(&mut registry, b"READY 4\n", three.len() as u64),
1063 vec![("READY".to_string(), 0)]
1064 );
1065 let mut registry = regex_watch(r"READY \d", true);
1067 assert_eq!(
1068 chunk(&mut registry, three, 0),
1069 vec![("READY 1".to_string(), 0)]
1070 );
1071 }
1072
1073 #[test]
1074 fn sticky_regex_holds_a_later_match_still_being_written() {
1075 let mut registry = regex_watch(r"port \d+", false);
1076 let first = b"port 80\nport 44";
1078 assert_eq!(
1079 chunk(&mut registry, first, 0),
1080 vec![("port 80".to_string(), 0)]
1081 );
1082 assert_eq!(
1083 chunk(&mut registry, b"3\n", first.len() as u64),
1084 vec![("port 443".to_string(), 0)]
1085 );
1086 }
1087}