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