1use std::collections::{HashMap, HashSet, VecDeque};
2use std::io::{self, Write};
3use std::sync::{Arc, Mutex, atomic::AtomicU64};
4
5use anyhow::Result;
6#[cfg(not(miri))]
7use anyhow::bail;
8#[cfg(not(miri))]
9use oxdock_pipe::OsPipeWriter;
10use oxdock_pipe::{
11 KeeperGuard, Materialized, PipeHandle, PipeInfo, PipeInner, SharedInput, SharedOutput,
12 inspect as inspect_handle, materialize, peek as peek_handle, script_backend,
13};
14use oxdock_process::{CommandStderr, CommandStdin, CommandStdout};
15
16pub(super) struct TaskTee {
22 parent: Option<StreamHandle>,
23 tails: Arc<Mutex<super::state::TaskTails>>,
24 stream: TeeStream,
25}
26
27impl TaskTee {
28 pub(super) fn wrap(
31 parent: Option<StreamHandle>,
32 tails: &Arc<Mutex<super::state::TaskTails>>,
33 stream: TeeStream,
34 ) -> Option<StreamHandle> {
35 Some(StreamHandle::Stream(Arc::new(Mutex::new(Self {
36 parent,
37 tails: Arc::clone(tails),
38 stream,
39 }))))
40 }
41}
42
43impl Write for TaskTee {
44 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
45 match &self.parent {
46 Some(StreamHandle::Stream(writer)) => {
47 if let Ok(mut guard) = writer.lock() {
48 guard.write_all(buf)?;
49 }
50 }
51 #[cfg(not(miri))]
52 Some(StreamHandle::Os(_)) => {
53 return Err(io::Error::other(
54 "cannot write DSL output to a live OS pipe",
55 ));
56 }
57 None => match self.stream {
58 TeeStream::Stdout => io::stdout().write_all(buf)?,
59 TeeStream::Stderr => io::stderr().write_all(buf)?,
60 },
61 }
62 if let Ok(mut tails) = self.tails.lock() {
63 tails.push(self.stream, buf);
64 }
65 Ok(buf.len())
66 }
67
68 fn flush(&mut self) -> io::Result<()> {
69 Ok(())
70 }
71}
72
73#[derive(Clone, Default)]
80pub(super) struct PipeRegistry;
81
82#[cfg(not(miri))]
88fn spent_handle() -> anyhow::Error {
89 anyhow::anyhow!(
90 "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session",
91 )
92}
93
94impl PipeRegistry {
95 pub(super) fn ensure_handle(handle: &PipeHandle, promote: bool) -> Result<()> {
100 materialize(handle, promote)?;
101 Ok(())
102 }
103
104 pub fn peek_pipe_content(handle: &PipeHandle) -> Result<Vec<u8>> {
113 peek_handle(handle)
114 }
115
116 pub(super) fn inspect_pipe(handle: &PipeHandle) -> PipeInfo {
118 inspect_handle(handle)
119 }
120
121 pub(super) fn pin_keeper(handle: &PipeHandle) -> Result<Option<KeeperGuard>> {
127 Ok(script_backend(handle).map(KeeperGuard::new))
128 }
129
130 pub(super) fn resolve_stdin(
137 handle: &PipeHandle,
138 direct: bool,
139 promote: bool,
140 ) -> Result<(CommandStdin, Option<Arc<PipeInner>>)> {
141 let _ = direct;
144 match materialize(handle, promote)? {
145 Materialized::Script(backend) => {
146 Ok((CommandStdin::Stream(backend.reader_handle()), Some(backend)))
147 }
148 #[cfg(not(miri))]
149 Materialized::Os(entry) => {
150 if direct {
151 return Ok((CommandStdin::OsPipe(entry.reader.clone()), None));
152 }
153 let owned = entry.reader.take().map_err(|_| spent_handle())?;
154 Ok((
155 CommandStdin::Stream(Arc::new(std::sync::Mutex::new(owned))),
156 None,
157 ))
158 }
159 }
160 }
161
162 pub(super) fn resolve_stdout(
167 handle: &PipeHandle,
168 direct: bool,
169 promote: bool,
170 ) -> Result<(StreamHandle, Option<Arc<PipeInner>>)> {
171 let _ = direct;
174 match materialize(handle, promote)? {
175 Materialized::Script(backend) => {
176 Ok((StreamHandle::Stream(backend.writer_handle()), Some(backend)))
177 }
178 #[cfg(not(miri))]
179 Materialized::Os(entry) => {
180 if direct {
181 return Ok((StreamHandle::Os(entry.writer.clone()), None));
182 }
183 let owned = entry.writer.take().map_err(|_| spent_handle())?;
184 Ok((
185 StreamHandle::Stream(Arc::new(std::sync::Mutex::new(owned))),
186 None,
187 ))
188 }
189 }
190 }
191
192 pub(super) fn resolve_stderr(
199 handle: &PipeHandle,
200 direct: bool,
201 promote: bool,
202 ) -> Result<StreamHandle> {
203 let _ = direct;
206 match materialize(handle, promote)? {
207 Materialized::Script(backend) => Ok(StreamHandle::Stream(backend.writer_handle())),
208 #[cfg(not(miri))]
209 Materialized::Os(entry) => {
210 if direct {
211 return Ok(StreamHandle::Os(entry.writer.clone()));
212 }
213 let owned = entry.writer.take().map_err(|_| spent_handle())?;
214 Ok(StreamHandle::Stream(Arc::new(std::sync::Mutex::new(owned))))
215 }
216 }
217 }
218}
219
220#[derive(Clone, Default)]
221pub struct ExecIo {
222 stdin: Option<SharedInput>,
223 stdout: Option<SharedOutput>,
224 stderr: Option<SharedOutput>,
225 inherit_env_overrides: HashMap<String, String>,
226 inherit_env_removed: HashSet<String>,
227 remote_runners: HashMap<String, RemoteRunnerArc>,
228 remote_guest: bool,
229 push_manifest_sink: Option<PushManifestSink>,
234 worker_counter: Arc<AtomicU64>,
238 interpreter_override: Option<String>,
243 script_args: Vec<String>,
247}
248
249pub type PushManifestSink = Arc<Mutex<Vec<(String, String)>>>;
251
252pub type RemoteRunnerArc = Arc<dyn super::remote::RemoteRunner>;
257
258pub const CHUNK_SIZE: usize = 8192;
260
261const MIN_RING_CAPACITY: usize = 1024;
263
264pub(crate) struct SlidingWindow {
267 pub(crate) needle: Vec<u8>,
268 ring: VecDeque<u8>,
269 pub matched: bool,
270}
271
272impl SlidingWindow {
273 pub fn new(needle: Vec<u8>) -> Self {
274 Self {
275 ring: VecDeque::with_capacity(needle.len().max(MIN_RING_CAPACITY)),
276 needle,
277 matched: false,
278 }
279 }
280
281 pub fn push_chunk(&mut self, chunk: &[u8]) {
282 if self.matched {
283 return;
284 }
285 let limit = self.needle.len().max(MIN_RING_CAPACITY);
287 for &byte in chunk {
288 self.ring.push_back(byte);
289 if self.ring.len() > limit {
290 self.ring.pop_front();
291 }
292 self.check_match();
293 }
294 }
295
296 pub fn update_needle(&mut self, new_needle: Vec<u8>) {
299 if self.matched {
300 return;
301 }
302 self.needle = new_needle;
303 self.check_match();
304 }
305
306 fn check_match(&mut self) {
307 if self.matched || self.ring.len() < self.needle.len() {
308 return;
309 }
310 let start = self.ring.len() - self.needle.len();
311 if self
312 .ring
313 .iter()
314 .skip(start)
315 .zip(self.needle.iter())
316 .all(|(a, b)| a == b)
317 {
318 self.matched = true;
319 }
320 }
321
322 pub fn ring_buffer(&self) -> Vec<u8> {
324 self.ring.iter().copied().collect()
325 }
326}
327
328#[derive(Clone)]
329pub(super) enum StreamHandle {
330 Stream(SharedOutput),
331 #[cfg(not(miri))]
335 Os(OsPipeWriter),
336}
337
338impl StreamHandle {
339 pub(super) fn to_stdout(&self) -> CommandStdout {
340 match self {
341 StreamHandle::Stream(writer) => CommandStdout::Stream(writer.clone()),
342 #[cfg(not(miri))]
343 StreamHandle::Os(writer) => CommandStdout::OsPipe(writer.clone()),
344 }
345 }
346
347 pub(super) fn to_stderr(&self) -> CommandStderr {
348 match self {
349 StreamHandle::Stream(writer) => CommandStderr::Stream(writer.clone()),
350 #[cfg(not(miri))]
351 StreamHandle::Os(writer) => CommandStderr::OsPipe(writer.clone()),
352 }
353 }
354}
355
356pub(super) fn write_stdout<F>(handle: Option<StreamHandle>, op: F) -> Result<()>
357where
358 F: FnOnce(&mut dyn Write) -> Result<()>,
359{
360 match handle {
361 Some(StreamHandle::Stream(writer)) => {
362 if let Ok(mut guard) = writer.lock() {
363 op(&mut *guard)?;
364 }
365 Ok(())
366 }
367 #[cfg(not(miri))]
371 Some(StreamHandle::Os(_)) => {
372 bail!("cannot write DSL output to a live OS pipe")
373 }
374 None => {
377 let mut stdout = io::stdout();
378 op(&mut stdout)
379 }
380 }
381}
382
383pub(super) fn write_stderr<F>(handle: Option<StreamHandle>, op: F) -> Result<()>
384where
385 F: FnOnce(&mut dyn Write) -> Result<()>,
386{
387 match handle {
388 Some(StreamHandle::Stream(writer)) => {
389 if let Ok(mut guard) = writer.lock() {
390 op(&mut *guard)?;
391 }
392 Ok(())
393 }
394 #[cfg(not(miri))]
395 Some(StreamHandle::Os(_)) => {
396 bail!("cannot write DSL output to a live OS pipe")
397 }
398 None => {
399 let mut stderr = io::stderr();
400 op(&mut stderr)
401 }
402 }
403}
404
405pub struct PipeStream {
420 reader: Option<SharedInput>,
421 writer: Option<SharedOutput>,
422}
423
424impl PipeStream {
425 pub fn reader(reader: SharedInput) -> Self {
427 Self {
428 reader: Some(reader),
429 writer: None,
430 }
431 }
432
433 pub fn writer(writer: SharedOutput) -> Self {
435 Self {
436 reader: None,
437 writer: Some(writer),
438 }
439 }
440
441 pub fn pair(reader: SharedInput, writer: SharedOutput) -> Self {
443 Self {
444 reader: Some(reader),
445 writer: Some(writer),
446 }
447 }
448}
449
450impl std::io::Read for PipeStream {
451 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
452 let Some(reader) = &self.reader else {
453 return Err(std::io::Error::new(
454 std::io::ErrorKind::NotConnected,
455 "pipe stream has no reader half",
456 ));
457 };
458 let mut guard = reader
459 .lock()
460 .map_err(|_| std::io::Error::other("pipe reader lock poisoned"))?;
461 guard.read(buf)
462 }
463}
464
465impl std::io::Write for PipeStream {
466 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
467 let Some(writer) = &self.writer else {
468 return Err(std::io::Error::new(
469 std::io::ErrorKind::NotConnected,
470 "pipe stream has no writer half",
471 ));
472 };
473 let mut guard = writer
474 .lock()
475 .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
476 guard.write(buf)
477 }
478
479 fn flush(&mut self) -> std::io::Result<()> {
480 let Some(writer) = &self.writer else {
481 return Err(std::io::Error::new(
482 std::io::ErrorKind::NotConnected,
483 "pipe stream has no writer half",
484 ));
485 };
486 let mut guard = writer
487 .lock()
488 .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
489 guard.flush()
490 }
491}
492
493pub(crate) const EXACT_STDOUT_CAP: usize = 8 * 1024 * 1024;
497
498pub(crate) struct ExactCapture {
503 pub(crate) bytes: Vec<u8>,
504 pub(crate) overflowed: bool,
505}
506
507impl ExactCapture {
508 pub fn new() -> Self {
509 Self {
510 bytes: Vec::new(),
511 overflowed: false,
512 }
513 }
514
515 pub fn push_chunk(&mut self, chunk: &[u8]) {
516 if self.overflowed {
517 return;
518 }
519 if self.bytes.len() + chunk.len() > EXACT_STDOUT_CAP {
520 self.overflowed = true;
521 return;
522 }
523 self.bytes.extend_from_slice(chunk);
524 }
525}
526
527#[derive(Clone, Copy, PartialEq, Eq, Debug)]
529pub enum TeeStream {
530 Stdout,
531 Stderr,
532}
533
534#[derive(Clone, Debug)]
538pub struct StreamChunk {
539 pub kind: TeeStream,
541 pub bytes: Vec<u8>,
543}
544
545#[derive(Clone, Debug)]
551pub struct StreamHook {
552 pub tx: std::sync::mpsc::SyncSender<StreamChunk>,
554 pub dropped: std::sync::Arc<std::sync::atomic::AtomicUsize>,
557}
558
559struct TeeWriter {
564 inner: Option<SharedOutput>,
565 stream: TeeStream,
566 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
567 exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
568 hook: Option<StreamHook>,
569}
570
571impl Write for TeeWriter {
572 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
573 match &self.inner {
575 Some(inner) => {
576 let mut guard = inner
577 .lock()
578 .map_err(|_| io::Error::other("stdout sink poisoned"))?;
579 guard.write_all(buf)?;
580 }
581 None => match self.stream {
582 TeeStream::Stdout => io::stdout().write_all(buf)?,
583 TeeStream::Stderr => io::stderr().write_all(buf)?,
584 },
585 }
586 if let Ok(mut windows) = self.windows.lock() {
588 for window in windows.values_mut() {
589 window.push_chunk(buf);
590 }
591 }
592 if let Ok(mut exact) = self.exact.lock() {
593 for capture in exact.values_mut() {
594 capture.push_chunk(buf);
595 }
596 }
597 if let Some(hook) = &self.hook {
602 let chunk = StreamChunk {
603 kind: self.stream,
604 bytes: buf.to_vec(),
605 };
606 if hook.tx.try_send(chunk).is_err() {
607 hook.dropped
608 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
609 }
610 }
611 Ok(buf.len())
612 }
613
614 fn flush(&mut self) -> io::Result<()> {
615 match &self.inner {
616 Some(inner) => {
617 let mut guard = inner
618 .lock()
619 .map_err(|_| io::Error::other("stdout sink poisoned"))?;
620 guard.flush()?;
621 }
622 None => match self.stream {
623 TeeStream::Stdout => io::stdout().flush()?,
624 TeeStream::Stderr => io::stderr().flush()?,
625 },
626 }
627 Ok(())
628 }
629}
630
631pub(crate) fn teed_stdout(
633 sink: Option<SharedOutput>,
634 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
635 exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
636 hook: Option<StreamHook>,
637) -> SharedOutput {
638 Arc::new(Mutex::new(TeeWriter {
639 inner: sink,
640 stream: TeeStream::Stdout,
641 windows,
642 exact,
643 hook,
644 }))
645}
646
647pub(crate) fn teed_stderr(
651 sink: Option<SharedOutput>,
652 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
653 hook: Option<StreamHook>,
654) -> SharedOutput {
655 Arc::new(Mutex::new(TeeWriter {
656 inner: sink,
657 stream: TeeStream::Stderr,
658 windows,
659 exact: Arc::new(Mutex::new(HashMap::new())),
660 hook,
661 }))
662}
663
664impl ExecIo {
665 pub fn new() -> Self {
666 Self::default()
667 }
668
669 pub fn set_stdin(&mut self, stdin: Option<SharedInput>) {
670 self.stdin = stdin;
671 }
672
673 pub fn set_stdout(&mut self, stdout: Option<SharedOutput>) {
674 self.stdout = stdout.clone();
675 if self.stderr.is_none() {
676 self.stderr = stdout;
677 }
678 }
679
680 pub fn set_stderr(&mut self, stderr: Option<SharedOutput>) {
681 self.stderr = stderr;
682 }
683
684 pub fn set_worker_counter(&mut self, counter: Arc<AtomicU64>) -> &mut Self {
686 self.worker_counter = counter;
687 self
688 }
689
690 pub fn worker_counter(&self) -> Arc<AtomicU64> {
692 Arc::clone(&self.worker_counter)
693 }
694
695 pub fn set_interpreter<S: Into<String>>(&mut self, path: S) -> &mut Self {
700 self.interpreter_override = Some(path.into());
701 self
702 }
703
704 pub fn interpreter_override(&self) -> Option<String> {
707 self.interpreter_override.clone()
708 }
709
710 pub fn set_script_args<I, S>(&mut self, args: I) -> &mut Self
714 where
715 I: IntoIterator<Item = S>,
716 S: Into<String>,
717 {
718 self.script_args = args.into_iter().map(Into::into).collect();
719 self
720 }
721
722 pub fn script_args(&self) -> &[String] {
724 &self.script_args
725 }
726
727 pub fn set_remote_runner_for_target(
732 &mut self,
733 target: String,
734 runner: RemoteRunnerArc,
735 ) -> &mut Self {
736 self.remote_runners.insert(target, runner);
737 self
738 }
739
740 pub fn remote_runner(&self, target: &str) -> Option<RemoteRunnerArc> {
743 self.remote_runners.get(target).cloned()
744 }
745
746 pub fn set_remote_runner(&mut self, runner: RemoteRunnerArc) -> &mut Self {
749 self.set_remote_runner_for_target(String::new(), runner)
750 }
751
752 pub fn set_remote_guest(&mut self, guest: bool) -> &mut Self {
759 self.remote_guest = guest;
760 self
761 }
762
763 pub fn is_remote_guest(&self) -> bool {
765 self.remote_guest
766 }
767
768 pub fn set_push_manifest_sink(&mut self, sink: PushManifestSink) -> &mut Self {
772 self.push_manifest_sink = Some(sink);
773 self
774 }
775
776 pub(super) fn push_manifest_sink(&self) -> Option<PushManifestSink> {
778 self.push_manifest_sink.clone()
779 }
780
781 pub fn insert_inherit_env<S: Into<String>, V: Into<String>>(&mut self, key: S, value: V) {
782 let key = key.into();
783 self.inherit_env_removed.remove(&key);
784 self.inherit_env_overrides.insert(key, value.into());
785 }
786
787 pub fn remove_inherit_env<S: Into<String>>(&mut self, key: S) {
788 let key = key.into();
789 self.inherit_env_overrides.remove(&key);
790 self.inherit_env_removed.insert(key);
791 }
792
793 pub fn inherit_env_value(&self, key: &str) -> Option<&String> {
794 self.inherit_env_overrides.get(key)
795 }
796
797 pub fn inherit_env_is_removed(&self, key: &str) -> bool {
798 self.inherit_env_removed.contains(key)
799 }
800
801 pub fn inherit_env_overrides(&self) -> &std::collections::HashMap<String, String> {
802 &self.inherit_env_overrides
803 }
804
805 pub(super) fn ensure_handle(&self, handle: &PipeHandle, promote: bool) -> Result<()> {
810 PipeRegistry::ensure_handle(handle, promote)
811 }
812
813 pub(super) fn inspect_pipe(&self, handle: &PipeHandle) -> PipeInfo {
815 PipeRegistry::inspect_pipe(handle)
816 }
817
818 pub fn peek_pipe_content(&self, handle: &PipeHandle) -> Result<Vec<u8>> {
826 PipeRegistry::peek_pipe_content(handle)
827 }
828
829 pub(super) fn pin_keeper(&self, handle: &PipeHandle) -> Result<Option<KeeperGuard>> {
834 PipeRegistry::pin_keeper(handle)
835 }
836
837 pub(super) fn resolve_stdin(
840 &self,
841 handle: &PipeHandle,
842 direct: bool,
843 promote: bool,
844 ) -> Result<(CommandStdin, Option<Arc<PipeInner>>)> {
845 PipeRegistry::resolve_stdin(handle, direct, promote)
846 }
847
848 pub(super) fn resolve_stdout(
851 &self,
852 handle: &PipeHandle,
853 direct: bool,
854 promote: bool,
855 ) -> Result<(StreamHandle, Option<Arc<PipeInner>>)> {
856 PipeRegistry::resolve_stdout(handle, direct, promote)
857 }
858
859 pub(super) fn resolve_stderr(
861 &self,
862 handle: &PipeHandle,
863 direct: bool,
864 promote: bool,
865 ) -> Result<StreamHandle> {
866 PipeRegistry::resolve_stderr(handle, direct, promote)
867 }
868
869 pub fn stdin(&self) -> Option<SharedInput> {
870 self.stdin.clone()
871 }
872
873 pub fn stdout(&self) -> Option<SharedOutput> {
874 self.stdout.clone()
875 }
876
877 pub fn stderr(&self) -> Option<SharedOutput> {
878 self.stderr.clone().or_else(|| self.stdout.clone())
879 }
880}
881
882pub(super) fn assemble_default_io(
883 stdin: Option<SharedInput>,
884 stdout: Option<SharedOutput>,
885) -> ExecIo {
886 let mut io = ExecIo::new();
887 io.set_stdin(stdin);
888 io.set_stdout(stdout.clone());
889 io.set_stderr(stdout);
890 io
891}
892
893#[cfg(test)]
894mod tests {
895 use super::*;
896
897 type TestTee = (
899 TeeWriter,
900 std::sync::mpsc::Receiver<StreamChunk>,
901 Arc<std::sync::atomic::AtomicUsize>,
902 Arc<Mutex<Vec<u8>>>,
903 );
904
905 fn tee_with_hook(stream: TeeStream, bound: usize) -> TestTee {
906 let vec: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::<u8>::new()));
907 let sink: SharedOutput = vec.clone();
908 let (tx, rx) = std::sync::mpsc::sync_channel(bound);
909 let dropped = Arc::new(std::sync::atomic::AtomicUsize::new(0));
910 let tee = TeeWriter {
911 inner: Some(sink),
912 stream,
913 windows: Arc::new(Mutex::new(HashMap::new())),
914 exact: Arc::new(Mutex::new(HashMap::new())),
915 hook: Some(StreamHook {
916 tx,
917 dropped: dropped.clone(),
918 }),
919 };
920 (tee, rx, dropped, vec)
921 }
922
923 #[test]
924 fn hook_receives_stderr_kind_and_sink_still_gets_bytes() {
925 let (mut tee, rx, dropped, sink) = tee_with_hook(TeeStream::Stderr, 8);
926 tee.write_all(b"oops\n").expect("write");
927 tee.flush().expect("flush");
928 let chunk = rx.try_recv().expect("one chunk streamed");
929 assert_eq!(chunk.kind, TeeStream::Stderr);
930 assert_eq!(chunk.bytes, b"oops\n");
931 assert_eq!(dropped.load(std::sync::atomic::Ordering::Relaxed), 0);
932 let guard = sink.lock().expect("sink lock");
933 assert_eq!(guard.as_slice(), b"oops\n");
934 }
935
936 #[test]
937 fn full_channel_drops_and_counts_without_blocking() {
938 let (mut tee, rx, dropped, _sink) = tee_with_hook(TeeStream::Stdout, 1);
939 tee.write_all(b"first\n").expect("write");
940 tee.write_all(b"second\n")
941 .expect("write must not block on full");
942 assert_eq!(dropped.load(std::sync::atomic::Ordering::Relaxed), 1);
943 let kept = rx.try_recv().expect("first chunk kept");
944 assert_eq!(kept.bytes, b"first\n");
945 }
946}