1use std::collections::{HashMap, HashSet, VecDeque};
2use std::io::{self, Write};
3use std::sync::{Arc, Mutex, atomic::AtomicU64};
4
5use anyhow::Result;
6use oxdock_diagnostics::DiagnosticResult;
7#[cfg(not(miri))]
8use oxdock_pipe::OsPipeWriter;
9use oxdock_pipe::{
10 KeeperGuard, Materialized, PipeHandle, PipeInfo, PipeInner, SharedInput, SharedOutput,
11 inspect as inspect_handle, materialize, peek as peek_handle, script_backend,
12};
13use oxdock_process::{CommandStderr, CommandStdin, CommandStdout};
14
15pub(super) struct TaskTee {
21 parent: Option<StreamHandle>,
22 tails: Arc<Mutex<super::state::TaskTails>>,
23 stream: TeeStream,
24}
25
26impl TaskTee {
27 pub(super) fn wrap(
30 parent: Option<StreamHandle>,
31 tails: &Arc<Mutex<super::state::TaskTails>>,
32 stream: TeeStream,
33 ) -> Option<StreamHandle> {
34 Some(StreamHandle::Stream(Arc::new(Mutex::new(Self {
35 parent,
36 tails: Arc::clone(tails),
37 stream,
38 }))))
39 }
40}
41
42impl Write for TaskTee {
43 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
44 match &self.parent {
45 Some(StreamHandle::Stream(writer)) => {
46 if let Ok(mut guard) = writer.lock() {
47 guard.write_all(buf)?;
48 }
49 }
50 #[cfg(not(miri))]
51 Some(StreamHandle::Os(_)) => {
52 return Err(io::Error::other(
53 "cannot write DSL output to a live OS pipe",
54 ));
55 }
56 None => match self.stream {
57 TeeStream::Stdout => io::stdout().write_all(buf)?,
58 TeeStream::Stderr => io::stderr().write_all(buf)?,
59 },
60 }
61 if let Ok(mut tails) = self.tails.lock() {
62 tails.push(self.stream, buf);
63 }
64 Ok(buf.len())
65 }
66
67 fn flush(&mut self) -> io::Result<()> {
68 Ok(())
69 }
70}
71
72#[derive(Clone, Default)]
79pub(super) struct PipeRegistry;
80
81#[cfg(not(miri))]
87fn spent_handle() -> oxdock_diagnostics::Diagnostic {
88 super::diagnostics::std_pipe_handle_spent()
89}
90
91impl PipeRegistry {
92 pub(super) fn ensure_handle(handle: &PipeHandle, promote: bool) -> DiagnosticResult<()> {
97 materialize(handle, promote)?;
98 Ok(())
99 }
100
101 pub fn peek_pipe_content(handle: &PipeHandle) -> DiagnosticResult<Vec<u8>> {
110 peek_handle(handle)
111 }
112
113 pub(super) fn inspect_pipe(handle: &PipeHandle) -> PipeInfo {
115 inspect_handle(handle)
116 }
117
118 pub(super) fn pin_keeper(handle: &PipeHandle) -> DiagnosticResult<Option<KeeperGuard>> {
124 Ok(script_backend(handle).map(KeeperGuard::new))
125 }
126
127 pub(super) fn resolve_stdin(
134 handle: &PipeHandle,
135 direct: bool,
136 promote: bool,
137 ) -> DiagnosticResult<(CommandStdin, Option<Arc<PipeInner>>)> {
138 let _ = direct;
141 match materialize(handle, promote)? {
142 Materialized::Script(backend) => {
143 Ok((CommandStdin::Stream(backend.reader_handle()), Some(backend)))
144 }
145 #[cfg(not(miri))]
146 Materialized::Os(entry) => {
147 if direct {
148 return Ok((CommandStdin::OsPipe(entry.reader.clone()), None));
149 }
150 let owned = entry.reader.take().map_err(|_| spent_handle())?;
151 Ok((
152 CommandStdin::Stream(Arc::new(std::sync::Mutex::new(owned))),
153 None,
154 ))
155 }
156 }
157 }
158
159 pub(super) fn resolve_stdout(
164 handle: &PipeHandle,
165 direct: bool,
166 promote: bool,
167 ) -> DiagnosticResult<(StreamHandle, Option<Arc<PipeInner>>)> {
168 let _ = direct;
171 match materialize(handle, promote)? {
172 Materialized::Script(backend) => {
173 Ok((StreamHandle::Stream(backend.writer_handle()), Some(backend)))
174 }
175 #[cfg(not(miri))]
176 Materialized::Os(entry) => {
177 if direct {
178 return Ok((StreamHandle::Os(entry.writer.clone()), None));
179 }
180 let owned = entry.writer.take().map_err(|_| spent_handle())?;
181 Ok((
182 StreamHandle::Stream(Arc::new(std::sync::Mutex::new(owned))),
183 None,
184 ))
185 }
186 }
187 }
188
189 pub(super) fn resolve_stderr(
196 handle: &PipeHandle,
197 direct: bool,
198 promote: bool,
199 ) -> DiagnosticResult<StreamHandle> {
200 let _ = direct;
203 match materialize(handle, promote)? {
204 Materialized::Script(backend) => Ok(StreamHandle::Stream(backend.writer_handle())),
205 #[cfg(not(miri))]
206 Materialized::Os(entry) => {
207 if direct {
208 return Ok(StreamHandle::Os(entry.writer.clone()));
209 }
210 let owned = entry.writer.take().map_err(|_| spent_handle())?;
211 Ok(StreamHandle::Stream(Arc::new(std::sync::Mutex::new(owned))))
212 }
213 }
214 }
215}
216
217#[derive(Clone, Default)]
218pub struct ExecIo {
219 stdin: Option<SharedInput>,
220 stdout: Option<SharedOutput>,
221 stderr: Option<SharedOutput>,
222 inherit_env_overrides: HashMap<String, String>,
223 inherit_env_removed: HashSet<String>,
224 remote_runners: HashMap<String, RemoteRunnerArc>,
225 remote_guest: bool,
226 push_manifest_sink: Option<PushManifestSink>,
231 worker_counter: Arc<AtomicU64>,
235 interpreter_override: Option<String>,
240 script_args: Vec<String>,
244}
245
246pub type PushManifestSink = Arc<Mutex<Vec<(String, String)>>>;
248
249pub type RemoteRunnerArc = Arc<dyn super::remote::RemoteRunner>;
254
255pub const CHUNK_SIZE: usize = 8192;
257
258const MIN_RING_CAPACITY: usize = 1024;
260
261pub(crate) struct SlidingWindow {
264 pub(crate) needle: Vec<u8>,
265 ring: VecDeque<u8>,
266 pub matched: bool,
267}
268
269impl SlidingWindow {
270 pub fn new(needle: Vec<u8>) -> Self {
271 Self {
272 ring: VecDeque::with_capacity(needle.len().max(MIN_RING_CAPACITY)),
273 needle,
274 matched: false,
275 }
276 }
277
278 pub fn push_chunk(&mut self, chunk: &[u8]) {
279 if self.matched {
280 return;
281 }
282 let limit = self.needle.len().max(MIN_RING_CAPACITY);
284 for &byte in chunk {
285 self.ring.push_back(byte);
286 if self.ring.len() > limit {
287 self.ring.pop_front();
288 }
289 self.check_match();
290 }
291 }
292
293 pub fn update_needle(&mut self, new_needle: Vec<u8>) {
296 if self.matched {
297 return;
298 }
299 self.needle = new_needle;
300 self.check_match();
301 }
302
303 fn check_match(&mut self) {
304 if self.matched || self.ring.len() < self.needle.len() {
305 return;
306 }
307 let start = self.ring.len() - self.needle.len();
308 if self
309 .ring
310 .iter()
311 .skip(start)
312 .zip(self.needle.iter())
313 .all(|(a, b)| a == b)
314 {
315 self.matched = true;
316 }
317 }
318
319 pub fn ring_buffer(&self) -> Vec<u8> {
321 self.ring.iter().copied().collect()
322 }
323}
324
325#[derive(Clone)]
326pub(super) enum StreamHandle {
327 Stream(SharedOutput),
328 #[cfg(not(miri))]
332 Os(OsPipeWriter),
333}
334
335impl StreamHandle {
336 pub(super) fn to_stdout(&self) -> CommandStdout {
337 match self {
338 StreamHandle::Stream(writer) => CommandStdout::Stream(writer.clone()),
339 #[cfg(not(miri))]
340 StreamHandle::Os(writer) => CommandStdout::OsPipe(writer.clone()),
341 }
342 }
343
344 pub(super) fn to_stderr(&self) -> CommandStderr {
345 match self {
346 StreamHandle::Stream(writer) => CommandStderr::Stream(writer.clone()),
347 #[cfg(not(miri))]
348 StreamHandle::Os(writer) => CommandStderr::OsPipe(writer.clone()),
349 }
350 }
351}
352
353pub(super) fn write_stdout<F>(handle: Option<StreamHandle>, op: F) -> Result<()>
354where
355 F: FnOnce(&mut dyn Write) -> Result<()>,
356{
357 match handle {
358 Some(StreamHandle::Stream(writer)) => {
359 if let Ok(mut guard) = writer.lock() {
360 op(&mut *guard)?;
361 }
362 Ok(())
363 }
364 #[cfg(not(miri))]
368 Some(StreamHandle::Os(_)) => Err(anyhow::Error::new(
369 super::diagnostics::eval_write_live_pipe("stdout"),
370 )),
371 None => {
374 let mut stdout = io::stdout();
375 op(&mut stdout)
376 }
377 }
378}
379
380pub(super) fn write_stderr<F>(handle: Option<StreamHandle>, op: F) -> Result<()>
381where
382 F: FnOnce(&mut dyn Write) -> Result<()>,
383{
384 match handle {
385 Some(StreamHandle::Stream(writer)) => {
386 if let Ok(mut guard) = writer.lock() {
387 op(&mut *guard)?;
388 }
389 Ok(())
390 }
391 #[cfg(not(miri))]
392 Some(StreamHandle::Os(_)) => Err(anyhow::Error::new(
393 super::diagnostics::eval_write_live_pipe("stderr"),
394 )),
395 None => {
396 let mut stderr = io::stderr();
397 op(&mut stderr)
398 }
399 }
400}
401
402pub struct PipeStream {
417 reader: Option<SharedInput>,
418 writer: Option<SharedOutput>,
419}
420
421impl PipeStream {
422 pub fn reader(reader: SharedInput) -> Self {
424 Self {
425 reader: Some(reader),
426 writer: None,
427 }
428 }
429
430 pub fn writer(writer: SharedOutput) -> Self {
432 Self {
433 reader: None,
434 writer: Some(writer),
435 }
436 }
437
438 pub fn pair(reader: SharedInput, writer: SharedOutput) -> Self {
440 Self {
441 reader: Some(reader),
442 writer: Some(writer),
443 }
444 }
445}
446
447impl std::io::Read for PipeStream {
448 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
449 let Some(reader) = &self.reader else {
450 return Err(std::io::Error::new(
451 std::io::ErrorKind::NotConnected,
452 "pipe stream has no reader half",
453 ));
454 };
455 let mut guard = reader
456 .lock()
457 .map_err(|_| std::io::Error::other("pipe reader lock poisoned"))?;
458 guard.read(buf)
459 }
460}
461
462impl std::io::Write for PipeStream {
463 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
464 let Some(writer) = &self.writer else {
465 return Err(std::io::Error::new(
466 std::io::ErrorKind::NotConnected,
467 "pipe stream has no writer half",
468 ));
469 };
470 let mut guard = writer
471 .lock()
472 .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
473 guard.write(buf)
474 }
475
476 fn flush(&mut self) -> std::io::Result<()> {
477 let Some(writer) = &self.writer else {
478 return Err(std::io::Error::new(
479 std::io::ErrorKind::NotConnected,
480 "pipe stream has no writer half",
481 ));
482 };
483 let mut guard = writer
484 .lock()
485 .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
486 guard.flush()
487 }
488}
489
490pub(crate) const EXACT_STDOUT_CAP: usize = 8 * 1024 * 1024;
494
495pub(crate) struct ExactCapture {
500 pub(crate) bytes: Vec<u8>,
501 pub(crate) overflowed: bool,
502}
503
504impl ExactCapture {
505 pub fn new() -> Self {
506 Self {
507 bytes: Vec::new(),
508 overflowed: false,
509 }
510 }
511
512 pub fn push_chunk(&mut self, chunk: &[u8]) {
513 if self.overflowed {
514 return;
515 }
516 if self.bytes.len() + chunk.len() > EXACT_STDOUT_CAP {
517 self.overflowed = true;
518 return;
519 }
520 self.bytes.extend_from_slice(chunk);
521 }
522}
523
524#[derive(Clone, Copy, PartialEq, Eq, Debug)]
526pub enum TeeStream {
527 Stdout,
528 Stderr,
529}
530
531#[derive(Clone, Debug)]
535pub struct StreamChunk {
536 pub kind: TeeStream,
538 pub bytes: Vec<u8>,
540}
541
542#[derive(Clone, Debug)]
548pub struct StreamHook {
549 pub tx: std::sync::mpsc::SyncSender<StreamChunk>,
551 pub dropped: std::sync::Arc<std::sync::atomic::AtomicUsize>,
554}
555
556struct TeeWriter {
561 inner: Option<SharedOutput>,
562 stream: TeeStream,
563 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
564 exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
565 hook: Option<StreamHook>,
566}
567
568impl Write for TeeWriter {
569 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
570 match &self.inner {
572 Some(inner) => {
573 let mut guard = inner
574 .lock()
575 .map_err(|_| io::Error::other("stdout sink poisoned"))?;
576 guard.write_all(buf)?;
577 }
578 None => match self.stream {
579 TeeStream::Stdout => io::stdout().write_all(buf)?,
580 TeeStream::Stderr => io::stderr().write_all(buf)?,
581 },
582 }
583 if let Ok(mut windows) = self.windows.lock() {
585 for window in windows.values_mut() {
586 window.push_chunk(buf);
587 }
588 }
589 if let Ok(mut exact) = self.exact.lock() {
590 for capture in exact.values_mut() {
591 capture.push_chunk(buf);
592 }
593 }
594 if let Some(hook) = &self.hook {
599 let chunk = StreamChunk {
600 kind: self.stream,
601 bytes: buf.to_vec(),
602 };
603 if hook.tx.try_send(chunk).is_err() {
604 hook.dropped
605 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
606 }
607 }
608 Ok(buf.len())
609 }
610
611 fn flush(&mut self) -> io::Result<()> {
612 match &self.inner {
613 Some(inner) => {
614 let mut guard = inner
615 .lock()
616 .map_err(|_| io::Error::other("stdout sink poisoned"))?;
617 guard.flush()?;
618 }
619 None => match self.stream {
620 TeeStream::Stdout => io::stdout().flush()?,
621 TeeStream::Stderr => io::stderr().flush()?,
622 },
623 }
624 Ok(())
625 }
626}
627
628pub(crate) fn teed_stdout(
630 sink: Option<SharedOutput>,
631 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
632 exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
633 hook: Option<StreamHook>,
634) -> SharedOutput {
635 Arc::new(Mutex::new(TeeWriter {
636 inner: sink,
637 stream: TeeStream::Stdout,
638 windows,
639 exact,
640 hook,
641 }))
642}
643
644pub(crate) fn teed_stderr(
648 sink: Option<SharedOutput>,
649 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
650 hook: Option<StreamHook>,
651) -> SharedOutput {
652 Arc::new(Mutex::new(TeeWriter {
653 inner: sink,
654 stream: TeeStream::Stderr,
655 windows,
656 exact: Arc::new(Mutex::new(HashMap::new())),
657 hook,
658 }))
659}
660
661impl ExecIo {
662 pub fn new() -> Self {
663 Self::default()
664 }
665
666 pub fn set_stdin(&mut self, stdin: Option<SharedInput>) {
667 self.stdin = stdin;
668 }
669
670 pub fn set_stdout(&mut self, stdout: Option<SharedOutput>) {
671 self.stdout = stdout.clone();
672 if self.stderr.is_none() {
673 self.stderr = stdout;
674 }
675 }
676
677 pub fn set_stderr(&mut self, stderr: Option<SharedOutput>) {
678 self.stderr = stderr;
679 }
680
681 pub fn set_worker_counter(&mut self, counter: Arc<AtomicU64>) -> &mut Self {
683 self.worker_counter = counter;
684 self
685 }
686
687 pub fn worker_counter(&self) -> Arc<AtomicU64> {
689 Arc::clone(&self.worker_counter)
690 }
691
692 pub fn set_interpreter<S: Into<String>>(&mut self, path: S) -> &mut Self {
697 self.interpreter_override = Some(path.into());
698 self
699 }
700
701 pub fn interpreter_override(&self) -> Option<String> {
704 self.interpreter_override.clone()
705 }
706
707 pub fn set_script_args<I, S>(&mut self, args: I) -> &mut Self
711 where
712 I: IntoIterator<Item = S>,
713 S: Into<String>,
714 {
715 self.script_args = args.into_iter().map(Into::into).collect();
716 self
717 }
718
719 pub fn script_args(&self) -> &[String] {
721 &self.script_args
722 }
723
724 pub fn set_remote_runner_for_target(
729 &mut self,
730 target: String,
731 runner: RemoteRunnerArc,
732 ) -> &mut Self {
733 self.remote_runners.insert(target, runner);
734 self
735 }
736
737 pub fn remote_runner(&self, target: &str) -> Option<RemoteRunnerArc> {
740 self.remote_runners.get(target).cloned()
741 }
742
743 pub fn set_remote_runner(&mut self, runner: RemoteRunnerArc) -> &mut Self {
746 self.set_remote_runner_for_target(String::new(), runner)
747 }
748
749 pub fn set_remote_guest(&mut self, guest: bool) -> &mut Self {
756 self.remote_guest = guest;
757 self
758 }
759
760 pub fn is_remote_guest(&self) -> bool {
762 self.remote_guest
763 }
764
765 pub fn set_push_manifest_sink(&mut self, sink: PushManifestSink) -> &mut Self {
769 self.push_manifest_sink = Some(sink);
770 self
771 }
772
773 pub(super) fn push_manifest_sink(&self) -> Option<PushManifestSink> {
775 self.push_manifest_sink.clone()
776 }
777
778 pub fn insert_inherit_env<S: Into<String>, V: Into<String>>(&mut self, key: S, value: V) {
779 let key = key.into();
780 self.inherit_env_removed.remove(&key);
781 self.inherit_env_overrides.insert(key, value.into());
782 }
783
784 pub fn remove_inherit_env<S: Into<String>>(&mut self, key: S) {
785 let key = key.into();
786 self.inherit_env_overrides.remove(&key);
787 self.inherit_env_removed.insert(key);
788 }
789
790 pub fn inherit_env_value(&self, key: &str) -> Option<&String> {
791 self.inherit_env_overrides.get(key)
792 }
793
794 pub fn inherit_env_is_removed(&self, key: &str) -> bool {
795 self.inherit_env_removed.contains(key)
796 }
797
798 pub fn inherit_env_overrides(&self) -> &std::collections::HashMap<String, String> {
799 &self.inherit_env_overrides
800 }
801
802 pub(super) fn ensure_handle(&self, handle: &PipeHandle, promote: bool) -> DiagnosticResult<()> {
807 PipeRegistry::ensure_handle(handle, promote)
808 }
809
810 pub(super) fn inspect_pipe(&self, handle: &PipeHandle) -> PipeInfo {
812 PipeRegistry::inspect_pipe(handle)
813 }
814
815 pub fn peek_pipe_content(&self, handle: &PipeHandle) -> DiagnosticResult<Vec<u8>> {
823 PipeRegistry::peek_pipe_content(handle)
824 }
825
826 pub(super) fn pin_keeper(&self, handle: &PipeHandle) -> DiagnosticResult<Option<KeeperGuard>> {
831 PipeRegistry::pin_keeper(handle)
832 }
833
834 pub(super) fn resolve_stdin(
837 &self,
838 handle: &PipeHandle,
839 direct: bool,
840 promote: bool,
841 ) -> DiagnosticResult<(CommandStdin, Option<Arc<PipeInner>>)> {
842 PipeRegistry::resolve_stdin(handle, direct, promote)
843 }
844
845 pub(super) fn resolve_stdout(
848 &self,
849 handle: &PipeHandle,
850 direct: bool,
851 promote: bool,
852 ) -> DiagnosticResult<(StreamHandle, Option<Arc<PipeInner>>)> {
853 PipeRegistry::resolve_stdout(handle, direct, promote)
854 }
855
856 pub(super) fn resolve_stderr(
858 &self,
859 handle: &PipeHandle,
860 direct: bool,
861 promote: bool,
862 ) -> DiagnosticResult<StreamHandle> {
863 PipeRegistry::resolve_stderr(handle, direct, promote)
864 }
865
866 pub fn stdin(&self) -> Option<SharedInput> {
867 self.stdin.clone()
868 }
869
870 pub fn stdout(&self) -> Option<SharedOutput> {
871 self.stdout.clone()
872 }
873
874 pub fn stderr(&self) -> Option<SharedOutput> {
875 self.stderr.clone().or_else(|| self.stdout.clone())
876 }
877}
878
879pub(super) fn assemble_default_io(
880 stdin: Option<SharedInput>,
881 stdout: Option<SharedOutput>,
882) -> ExecIo {
883 let mut io = ExecIo::new();
884 io.set_stdin(stdin);
885 io.set_stdout(stdout.clone());
886 io.set_stderr(stdout);
887 io
888}
889
890#[cfg(test)]
891mod tests {
892 use super::*;
893
894 type TestTee = (
896 TeeWriter,
897 std::sync::mpsc::Receiver<StreamChunk>,
898 Arc<std::sync::atomic::AtomicUsize>,
899 Arc<Mutex<Vec<u8>>>,
900 );
901
902 fn tee_with_hook(stream: TeeStream, bound: usize) -> TestTee {
903 let vec: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::<u8>::new()));
904 let sink: SharedOutput = vec.clone();
905 let (tx, rx) = std::sync::mpsc::sync_channel(bound);
906 let dropped = Arc::new(std::sync::atomic::AtomicUsize::new(0));
907 let tee = TeeWriter {
908 inner: Some(sink),
909 stream,
910 windows: Arc::new(Mutex::new(HashMap::new())),
911 exact: Arc::new(Mutex::new(HashMap::new())),
912 hook: Some(StreamHook {
913 tx,
914 dropped: dropped.clone(),
915 }),
916 };
917 (tee, rx, dropped, vec)
918 }
919
920 #[test]
921 fn hook_receives_stderr_kind_and_sink_still_gets_bytes() {
922 let (mut tee, rx, dropped, sink) = tee_with_hook(TeeStream::Stderr, 8);
923 tee.write_all(b"oops\n").expect("write");
924 tee.flush().expect("flush");
925 let chunk = rx.try_recv().expect("one chunk streamed");
926 assert_eq!(chunk.kind, TeeStream::Stderr);
927 assert_eq!(chunk.bytes, b"oops\n");
928 assert_eq!(dropped.load(std::sync::atomic::Ordering::Relaxed), 0);
929 let guard = sink.lock().expect("sink lock");
930 assert_eq!(guard.as_slice(), b"oops\n");
931 }
932
933 #[test]
934 fn full_channel_drops_and_counts_without_blocking() {
935 let (mut tee, rx, dropped, _sink) = tee_with_hook(TeeStream::Stdout, 1);
936 tee.write_all(b"first\n").expect("write");
937 tee.write_all(b"second\n")
938 .expect("write must not block on full");
939 assert_eq!(dropped.load(std::sync::atomic::Ordering::Relaxed), 1);
940 let kept = rx.try_recv().expect("first chunk kept");
941 assert_eq!(kept.bytes, b"first\n");
942 }
943}