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 struct PipeStream {
398 reader: Option<SharedInput>,
399 writer: Option<SharedOutput>,
400}
401
402impl PipeStream {
403 pub fn reader(reader: SharedInput) -> Self {
405 Self {
406 reader: Some(reader),
407 writer: None,
408 }
409 }
410
411 pub fn writer(writer: SharedOutput) -> Self {
413 Self {
414 reader: None,
415 writer: Some(writer),
416 }
417 }
418
419 pub fn pair(reader: SharedInput, writer: SharedOutput) -> Self {
421 Self {
422 reader: Some(reader),
423 writer: Some(writer),
424 }
425 }
426}
427
428impl std::io::Read for PipeStream {
429 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
430 let Some(reader) = &self.reader else {
431 return Err(std::io::Error::new(
432 std::io::ErrorKind::NotConnected,
433 "pipe stream has no reader half",
434 ));
435 };
436 let mut guard = reader
437 .lock()
438 .map_err(|_| std::io::Error::other("pipe reader lock poisoned"))?;
439 guard.read(buf)
440 }
441}
442
443impl std::io::Write for PipeStream {
444 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
445 let Some(writer) = &self.writer else {
446 return Err(std::io::Error::new(
447 std::io::ErrorKind::NotConnected,
448 "pipe stream has no writer half",
449 ));
450 };
451 let mut guard = writer
452 .lock()
453 .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
454 guard.write(buf)
455 }
456
457 fn flush(&mut self) -> std::io::Result<()> {
458 let Some(writer) = &self.writer else {
459 return Err(std::io::Error::new(
460 std::io::ErrorKind::NotConnected,
461 "pipe stream has no writer half",
462 ));
463 };
464 let mut guard = writer
465 .lock()
466 .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
467 guard.flush()
468 }
469}
470
471pub(crate) const EXACT_STDOUT_CAP: usize = 8 * 1024 * 1024;
475
476pub(crate) struct ExactCapture {
481 pub(crate) bytes: Vec<u8>,
482 pub(crate) overflowed: bool,
483}
484
485impl ExactCapture {
486 pub fn new() -> Self {
487 Self {
488 bytes: Vec::new(),
489 overflowed: false,
490 }
491 }
492
493 pub fn push_chunk(&mut self, chunk: &[u8]) {
494 if self.overflowed {
495 return;
496 }
497 if self.bytes.len() + chunk.len() > EXACT_STDOUT_CAP {
498 self.overflowed = true;
499 return;
500 }
501 self.bytes.extend_from_slice(chunk);
502 }
503}
504
505#[derive(Clone, Copy, PartialEq, Eq, Debug)]
507pub enum TeeStream {
508 Stdout,
509 Stderr,
510}
511
512#[derive(Clone, Debug)]
516pub struct StreamChunk {
517 pub kind: TeeStream,
519 pub bytes: Vec<u8>,
521}
522
523#[derive(Clone, Debug)]
529pub struct StreamHook {
530 pub tx: std::sync::mpsc::SyncSender<StreamChunk>,
532 pub dropped: std::sync::Arc<std::sync::atomic::AtomicUsize>,
535}
536
537struct TeeWriter {
542 inner: Option<SharedOutput>,
543 stream: TeeStream,
544 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
545 exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
546 hook: Option<StreamHook>,
547}
548
549impl Write for TeeWriter {
550 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
551 match &self.inner {
553 Some(inner) => {
554 let mut guard = inner
555 .lock()
556 .map_err(|_| io::Error::other("stdout sink poisoned"))?;
557 guard.write_all(buf)?;
558 }
559 None => match self.stream {
560 TeeStream::Stdout => io::stdout().write_all(buf)?,
561 TeeStream::Stderr => io::stderr().write_all(buf)?,
562 },
563 }
564 if let Ok(mut windows) = self.windows.lock() {
566 for window in windows.values_mut() {
567 window.push_chunk(buf);
568 }
569 }
570 if let Ok(mut exact) = self.exact.lock() {
571 for capture in exact.values_mut() {
572 capture.push_chunk(buf);
573 }
574 }
575 if let Some(hook) = &self.hook {
580 let chunk = StreamChunk {
581 kind: self.stream,
582 bytes: buf.to_vec(),
583 };
584 if hook.tx.try_send(chunk).is_err() {
585 hook.dropped
586 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
587 }
588 }
589 Ok(buf.len())
590 }
591
592 fn flush(&mut self) -> io::Result<()> {
593 match &self.inner {
594 Some(inner) => {
595 let mut guard = inner
596 .lock()
597 .map_err(|_| io::Error::other("stdout sink poisoned"))?;
598 guard.flush()?;
599 }
600 None => match self.stream {
601 TeeStream::Stdout => io::stdout().flush()?,
602 TeeStream::Stderr => io::stderr().flush()?,
603 },
604 }
605 Ok(())
606 }
607}
608
609pub(crate) fn teed_stdout(
611 sink: Option<SharedOutput>,
612 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
613 exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
614 hook: Option<StreamHook>,
615) -> SharedOutput {
616 Arc::new(Mutex::new(TeeWriter {
617 inner: sink,
618 stream: TeeStream::Stdout,
619 windows,
620 exact,
621 hook,
622 }))
623}
624
625pub(crate) fn teed_stderr(
629 sink: Option<SharedOutput>,
630 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
631 hook: Option<StreamHook>,
632) -> SharedOutput {
633 Arc::new(Mutex::new(TeeWriter {
634 inner: sink,
635 stream: TeeStream::Stderr,
636 windows,
637 exact: Arc::new(Mutex::new(HashMap::new())),
638 hook,
639 }))
640}
641
642impl ExecIo {
643 pub fn new() -> Self {
644 Self::default()
645 }
646
647 pub fn set_stdin(&mut self, stdin: Option<SharedInput>) {
648 self.stdin = stdin;
649 }
650
651 pub fn set_stdout(&mut self, stdout: Option<SharedOutput>) {
652 self.stdout = stdout.clone();
653 if self.stderr.is_none() {
654 self.stderr = stdout;
655 }
656 }
657
658 pub fn set_stderr(&mut self, stderr: Option<SharedOutput>) {
659 self.stderr = stderr;
660 }
661
662 pub fn set_worker_counter(&mut self, counter: Arc<AtomicU64>) -> &mut Self {
664 self.worker_counter = counter;
665 self
666 }
667
668 pub fn worker_counter(&self) -> Arc<AtomicU64> {
670 Arc::clone(&self.worker_counter)
671 }
672
673 pub fn set_interpreter<S: Into<String>>(&mut self, path: S) -> &mut Self {
678 self.interpreter_override = Some(path.into());
679 self
680 }
681
682 pub fn interpreter_override(&self) -> Option<String> {
685 self.interpreter_override.clone()
686 }
687
688 pub fn set_script_args<I, S>(&mut self, args: I) -> &mut Self
692 where
693 I: IntoIterator<Item = S>,
694 S: Into<String>,
695 {
696 self.script_args = args.into_iter().map(Into::into).collect();
697 self
698 }
699
700 pub fn script_args(&self) -> &[String] {
702 &self.script_args
703 }
704
705 pub fn set_remote_runner_for_target(
710 &mut self,
711 target: String,
712 runner: RemoteRunnerArc,
713 ) -> &mut Self {
714 self.remote_runners.insert(target, runner);
715 self
716 }
717
718 pub fn remote_runner(&self, target: &str) -> Option<RemoteRunnerArc> {
721 self.remote_runners.get(target).cloned()
722 }
723
724 pub fn set_remote_runner(&mut self, runner: RemoteRunnerArc) -> &mut Self {
727 self.set_remote_runner_for_target(String::new(), runner)
728 }
729
730 pub fn set_remote_guest(&mut self, guest: bool) -> &mut Self {
737 self.remote_guest = guest;
738 self
739 }
740
741 pub fn is_remote_guest(&self) -> bool {
743 self.remote_guest
744 }
745
746 pub fn set_push_manifest_sink(&mut self, sink: PushManifestSink) -> &mut Self {
750 self.push_manifest_sink = Some(sink);
751 self
752 }
753
754 pub(super) fn push_manifest_sink(&self) -> Option<PushManifestSink> {
756 self.push_manifest_sink.clone()
757 }
758
759 pub fn insert_inherit_env<S: Into<String>, V: Into<String>>(&mut self, key: S, value: V) {
760 let key = key.into();
761 self.inherit_env_removed.remove(&key);
762 self.inherit_env_overrides.insert(key, value.into());
763 }
764
765 pub fn remove_inherit_env<S: Into<String>>(&mut self, key: S) {
766 let key = key.into();
767 self.inherit_env_overrides.remove(&key);
768 self.inherit_env_removed.insert(key);
769 }
770
771 pub fn inherit_env_value(&self, key: &str) -> Option<&String> {
772 self.inherit_env_overrides.get(key)
773 }
774
775 pub fn inherit_env_is_removed(&self, key: &str) -> bool {
776 self.inherit_env_removed.contains(key)
777 }
778
779 pub fn inherit_env_overrides(&self) -> &std::collections::HashMap<String, String> {
780 &self.inherit_env_overrides
781 }
782
783 pub(super) fn ensure_handle(&self, handle: &PipeHandle, promote: bool) -> Result<()> {
788 PipeRegistry::ensure_handle(handle, promote)
789 }
790
791 pub(super) fn inspect_pipe(&self, handle: &PipeHandle) -> PipeInfo {
793 PipeRegistry::inspect_pipe(handle)
794 }
795
796 pub fn peek_pipe_content(&self, handle: &PipeHandle) -> Result<Vec<u8>> {
804 PipeRegistry::peek_pipe_content(handle)
805 }
806
807 pub(super) fn pin_keeper(&self, handle: &PipeHandle) -> Result<Option<KeeperGuard>> {
812 PipeRegistry::pin_keeper(handle)
813 }
814
815 pub(super) fn resolve_stdin(
818 &self,
819 handle: &PipeHandle,
820 direct: bool,
821 promote: bool,
822 ) -> Result<(CommandStdin, Option<Arc<PipeInner>>)> {
823 PipeRegistry::resolve_stdin(handle, direct, promote)
824 }
825
826 pub(super) fn resolve_stdout(
829 &self,
830 handle: &PipeHandle,
831 direct: bool,
832 promote: bool,
833 ) -> Result<(StreamHandle, Option<Arc<PipeInner>>)> {
834 PipeRegistry::resolve_stdout(handle, direct, promote)
835 }
836
837 pub(super) fn resolve_stderr(
839 &self,
840 handle: &PipeHandle,
841 direct: bool,
842 promote: bool,
843 ) -> Result<StreamHandle> {
844 PipeRegistry::resolve_stderr(handle, direct, promote)
845 }
846
847 pub fn stdin(&self) -> Option<SharedInput> {
848 self.stdin.clone()
849 }
850
851 pub fn stdout(&self) -> Option<SharedOutput> {
852 self.stdout.clone()
853 }
854
855 pub fn stderr(&self) -> Option<SharedOutput> {
856 self.stderr.clone().or_else(|| self.stdout.clone())
857 }
858}
859
860pub(super) fn assemble_default_io(
861 stdin: Option<SharedInput>,
862 stdout: Option<SharedOutput>,
863) -> ExecIo {
864 let mut io = ExecIo::new();
865 io.set_stdin(stdin);
866 io.set_stdout(stdout.clone());
867 io.set_stderr(stdout);
868 io
869}
870
871#[cfg(test)]
872mod tests {
873 use super::*;
874
875 type TestTee = (
877 TeeWriter,
878 std::sync::mpsc::Receiver<StreamChunk>,
879 Arc<std::sync::atomic::AtomicUsize>,
880 Arc<Mutex<Vec<u8>>>,
881 );
882
883 fn tee_with_hook(stream: TeeStream, bound: usize) -> TestTee {
884 let vec: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::<u8>::new()));
885 let sink: SharedOutput = vec.clone();
886 let (tx, rx) = std::sync::mpsc::sync_channel(bound);
887 let dropped = Arc::new(std::sync::atomic::AtomicUsize::new(0));
888 let tee = TeeWriter {
889 inner: Some(sink),
890 stream,
891 windows: Arc::new(Mutex::new(HashMap::new())),
892 exact: Arc::new(Mutex::new(HashMap::new())),
893 hook: Some(StreamHook {
894 tx,
895 dropped: dropped.clone(),
896 }),
897 };
898 (tee, rx, dropped, vec)
899 }
900
901 #[test]
902 fn hook_receives_stderr_kind_and_sink_still_gets_bytes() {
903 let (mut tee, rx, dropped, sink) = tee_with_hook(TeeStream::Stderr, 8);
904 tee.write_all(b"oops\n").expect("write");
905 tee.flush().expect("flush");
906 let chunk = rx.try_recv().expect("one chunk streamed");
907 assert_eq!(chunk.kind, TeeStream::Stderr);
908 assert_eq!(chunk.bytes, b"oops\n");
909 assert_eq!(dropped.load(std::sync::atomic::Ordering::Relaxed), 0);
910 let guard = sink.lock().expect("sink lock");
911 assert_eq!(guard.as_slice(), b"oops\n");
912 }
913
914 #[test]
915 fn full_channel_drops_and_counts_without_blocking() {
916 let (mut tee, rx, dropped, _sink) = tee_with_hook(TeeStream::Stdout, 1);
917 tee.write_all(b"first\n").expect("write");
918 tee.write_all(b"second\n")
919 .expect("write must not block on full");
920 assert_eq!(dropped.load(std::sync::atomic::Ordering::Relaxed), 1);
921 let kept = rx.try_recv().expect("first chunk kept");
922 assert_eq!(kept.bytes, b"first\n");
923 }
924}