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
16#[derive(Clone, Default)]
23pub(super) struct PipeRegistry;
24
25#[cfg(not(miri))]
31fn spent_handle(idx: usize) -> anyhow::Error {
32 anyhow::anyhow!(
33 "step {}: OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session",
34 idx + 1,
35 )
36}
37
38impl PipeRegistry {
39 pub(super) fn ensure_handle(handle: &PipeHandle, promote: bool) -> Result<()> {
44 materialize(handle, promote)?;
45 Ok(())
46 }
47
48 pub fn peek_pipe_content(handle: &PipeHandle) -> Result<Vec<u8>> {
57 peek_handle(handle)
58 }
59
60 pub(super) fn inspect_pipe(handle: &PipeHandle) -> PipeInfo {
62 inspect_handle(handle)
63 }
64
65 pub(super) fn pin_keeper(handle: &PipeHandle) -> Result<Option<KeeperGuard>> {
71 Ok(script_backend(handle).map(KeeperGuard::new))
72 }
73
74 pub(super) fn resolve_stdin(
81 idx: usize,
82 handle: &PipeHandle,
83 direct: bool,
84 promote: bool,
85 ) -> Result<(CommandStdin, Option<Arc<PipeInner>>)> {
86 let _ = idx;
89 let _ = direct;
90 match materialize(handle, promote)? {
91 Materialized::Script(backend) => {
92 Ok((CommandStdin::Stream(backend.reader_handle()), Some(backend)))
93 }
94 #[cfg(not(miri))]
95 Materialized::Os(entry) => {
96 if direct {
97 return Ok((CommandStdin::OsPipe(entry.reader.clone()), None));
98 }
99 let owned = entry.reader.take().map_err(|_| spent_handle(idx))?;
100 Ok((
101 CommandStdin::Stream(Arc::new(std::sync::Mutex::new(owned))),
102 None,
103 ))
104 }
105 }
106 }
107
108 pub(super) fn resolve_stdout(
113 idx: usize,
114 handle: &PipeHandle,
115 direct: bool,
116 promote: bool,
117 ) -> Result<(StreamHandle, Option<Arc<PipeInner>>)> {
118 let _ = idx;
121 let _ = direct;
122 match materialize(handle, promote)? {
123 Materialized::Script(backend) => {
124 Ok((StreamHandle::Stream(backend.writer_handle()), Some(backend)))
125 }
126 #[cfg(not(miri))]
127 Materialized::Os(entry) => {
128 if direct {
129 return Ok((StreamHandle::Os(entry.writer.clone()), None));
130 }
131 let owned = entry.writer.take().map_err(|_| spent_handle(idx))?;
132 Ok((
133 StreamHandle::Stream(Arc::new(std::sync::Mutex::new(owned))),
134 None,
135 ))
136 }
137 }
138 }
139
140 pub(super) fn resolve_stderr(
147 idx: usize,
148 handle: &PipeHandle,
149 direct: bool,
150 promote: bool,
151 ) -> Result<StreamHandle> {
152 let _ = idx;
155 let _ = direct;
156 match materialize(handle, promote)? {
157 Materialized::Script(backend) => Ok(StreamHandle::Stream(backend.writer_handle())),
158 #[cfg(not(miri))]
159 Materialized::Os(entry) => {
160 if direct {
161 return Ok(StreamHandle::Os(entry.writer.clone()));
162 }
163 let owned = entry.writer.take().map_err(|_| spent_handle(idx))?;
164 Ok(StreamHandle::Stream(Arc::new(std::sync::Mutex::new(owned))))
165 }
166 }
167 }
168}
169
170#[derive(Clone, Default)]
171pub struct ExecIo {
172 stdin: Option<SharedInput>,
173 stdout: Option<SharedOutput>,
174 stderr: Option<SharedOutput>,
175 inherit_env_overrides: HashMap<String, String>,
176 inherit_env_removed: HashSet<String>,
177 remote_runners: HashMap<String, RemoteRunnerArc>,
178 remote_guest: bool,
179 push_manifest_sink: Option<PushManifestSink>,
184 worker_counter: Arc<AtomicU64>,
188}
189
190pub type PushManifestSink = Arc<Mutex<Vec<(String, String)>>>;
192
193pub type RemoteRunnerArc = Arc<dyn super::remote::RemoteRunner>;
198
199pub const CHUNK_SIZE: usize = 8192;
201
202const MIN_RING_CAPACITY: usize = 1024;
204
205pub(crate) struct SlidingWindow {
208 pub(crate) needle: Vec<u8>,
209 ring: VecDeque<u8>,
210 pub matched: bool,
211}
212
213impl SlidingWindow {
214 pub fn new(needle: Vec<u8>) -> Self {
215 Self {
216 ring: VecDeque::with_capacity(needle.len().max(MIN_RING_CAPACITY)),
217 needle,
218 matched: false,
219 }
220 }
221
222 pub fn push_chunk(&mut self, chunk: &[u8]) {
223 if self.matched {
224 return;
225 }
226 let limit = self.needle.len().max(MIN_RING_CAPACITY);
228 for &byte in chunk {
229 self.ring.push_back(byte);
230 if self.ring.len() > limit {
231 self.ring.pop_front();
232 }
233 self.check_match();
234 }
235 }
236
237 pub fn update_needle(&mut self, new_needle: Vec<u8>) {
240 if self.matched {
241 return;
242 }
243 self.needle = new_needle;
244 self.check_match();
245 }
246
247 fn check_match(&mut self) {
248 if self.matched || self.ring.len() < self.needle.len() {
249 return;
250 }
251 let start = self.ring.len() - self.needle.len();
252 if self
253 .ring
254 .iter()
255 .skip(start)
256 .zip(self.needle.iter())
257 .all(|(a, b)| a == b)
258 {
259 self.matched = true;
260 }
261 }
262
263 pub fn ring_buffer(&self) -> Vec<u8> {
265 self.ring.iter().copied().collect()
266 }
267}
268
269#[derive(Clone)]
270pub(super) enum StreamHandle {
271 Stream(SharedOutput),
272 #[cfg(not(miri))]
276 Os(OsPipeWriter),
277}
278
279impl StreamHandle {
280 pub(super) fn to_stdout(&self) -> CommandStdout {
281 match self {
282 StreamHandle::Stream(writer) => CommandStdout::Stream(writer.clone()),
283 #[cfg(not(miri))]
284 StreamHandle::Os(writer) => CommandStdout::OsPipe(writer.clone()),
285 }
286 }
287
288 pub(super) fn to_stderr(&self) -> CommandStderr {
289 match self {
290 StreamHandle::Stream(writer) => CommandStderr::Stream(writer.clone()),
291 #[cfg(not(miri))]
292 StreamHandle::Os(writer) => CommandStderr::OsPipe(writer.clone()),
293 }
294 }
295}
296
297pub(super) fn write_stdout<F>(handle: Option<StreamHandle>, op: F) -> Result<()>
298where
299 F: FnOnce(&mut dyn Write) -> Result<()>,
300{
301 match handle {
302 Some(StreamHandle::Stream(writer)) => {
303 if let Ok(mut guard) = writer.lock() {
304 op(&mut *guard)?;
305 }
306 Ok(())
307 }
308 #[cfg(not(miri))]
312 Some(StreamHandle::Os(_)) => {
313 bail!("cannot write DSL output to a live OS pipe")
314 }
315 None => {
318 let mut stdout = io::stdout();
319 op(&mut stdout)
320 }
321 }
322}
323
324pub struct PipeStream {
339 reader: Option<SharedInput>,
340 writer: Option<SharedOutput>,
341}
342
343impl PipeStream {
344 pub fn reader(reader: SharedInput) -> Self {
346 Self {
347 reader: Some(reader),
348 writer: None,
349 }
350 }
351
352 pub fn writer(writer: SharedOutput) -> Self {
354 Self {
355 reader: None,
356 writer: Some(writer),
357 }
358 }
359
360 pub fn pair(reader: SharedInput, writer: SharedOutput) -> Self {
362 Self {
363 reader: Some(reader),
364 writer: Some(writer),
365 }
366 }
367}
368
369impl std::io::Read for PipeStream {
370 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
371 let Some(reader) = &self.reader else {
372 return Err(std::io::Error::new(
373 std::io::ErrorKind::NotConnected,
374 "pipe stream has no reader half",
375 ));
376 };
377 let mut guard = reader
378 .lock()
379 .map_err(|_| std::io::Error::other("pipe reader lock poisoned"))?;
380 guard.read(buf)
381 }
382}
383
384impl std::io::Write for PipeStream {
385 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
386 let Some(writer) = &self.writer else {
387 return Err(std::io::Error::new(
388 std::io::ErrorKind::NotConnected,
389 "pipe stream has no writer half",
390 ));
391 };
392 let mut guard = writer
393 .lock()
394 .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
395 guard.write(buf)
396 }
397
398 fn flush(&mut self) -> std::io::Result<()> {
399 let Some(writer) = &self.writer else {
400 return Err(std::io::Error::new(
401 std::io::ErrorKind::NotConnected,
402 "pipe stream has no writer half",
403 ));
404 };
405 let mut guard = writer
406 .lock()
407 .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
408 guard.flush()
409 }
410}
411
412pub(crate) const EXACT_STDOUT_CAP: usize = 8 * 1024 * 1024;
416
417pub(crate) struct ExactCapture {
422 pub(crate) bytes: Vec<u8>,
423 pub(crate) overflowed: bool,
424}
425
426impl ExactCapture {
427 pub fn new() -> Self {
428 Self {
429 bytes: Vec::new(),
430 overflowed: false,
431 }
432 }
433
434 pub fn push_chunk(&mut self, chunk: &[u8]) {
435 if self.overflowed {
436 return;
437 }
438 if self.bytes.len() + chunk.len() > EXACT_STDOUT_CAP {
439 self.overflowed = true;
440 return;
441 }
442 self.bytes.extend_from_slice(chunk);
443 }
444}
445
446#[derive(Clone, Copy)]
448enum TeeStream {
449 Stdout,
450 Stderr,
451}
452
453struct TeeWriter {
458 inner: Option<SharedOutput>,
459 stream: TeeStream,
460 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
461 exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
462}
463
464impl Write for TeeWriter {
465 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
466 match &self.inner {
468 Some(inner) => {
469 let mut guard = inner
470 .lock()
471 .map_err(|_| io::Error::other("stdout sink poisoned"))?;
472 guard.write_all(buf)?;
473 }
474 None => match self.stream {
475 TeeStream::Stdout => io::stdout().write_all(buf)?,
476 TeeStream::Stderr => io::stderr().write_all(buf)?,
477 },
478 }
479 if let Ok(mut windows) = self.windows.lock() {
481 for window in windows.values_mut() {
482 window.push_chunk(buf);
483 }
484 }
485 if let Ok(mut exact) = self.exact.lock() {
486 for capture in exact.values_mut() {
487 capture.push_chunk(buf);
488 }
489 }
490 Ok(buf.len())
491 }
492
493 fn flush(&mut self) -> io::Result<()> {
494 match &self.inner {
495 Some(inner) => {
496 let mut guard = inner
497 .lock()
498 .map_err(|_| io::Error::other("stdout sink poisoned"))?;
499 guard.flush()?;
500 }
501 None => match self.stream {
502 TeeStream::Stdout => io::stdout().flush()?,
503 TeeStream::Stderr => io::stderr().flush()?,
504 },
505 }
506 Ok(())
507 }
508}
509
510pub(crate) fn teed_stdout(
512 sink: Option<SharedOutput>,
513 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
514 exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
515) -> SharedOutput {
516 Arc::new(Mutex::new(TeeWriter {
517 inner: sink,
518 stream: TeeStream::Stdout,
519 windows,
520 exact,
521 }))
522}
523
524pub(crate) fn teed_stderr(
528 sink: Option<SharedOutput>,
529 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
530) -> SharedOutput {
531 Arc::new(Mutex::new(TeeWriter {
532 inner: sink,
533 stream: TeeStream::Stderr,
534 windows,
535 exact: Arc::new(Mutex::new(HashMap::new())),
536 }))
537}
538
539impl ExecIo {
540 pub fn new() -> Self {
541 Self::default()
542 }
543
544 pub fn set_stdin(&mut self, stdin: Option<SharedInput>) {
545 self.stdin = stdin;
546 }
547
548 pub fn set_stdout(&mut self, stdout: Option<SharedOutput>) {
549 self.stdout = stdout.clone();
550 if self.stderr.is_none() {
551 self.stderr = stdout;
552 }
553 }
554
555 pub fn set_stderr(&mut self, stderr: Option<SharedOutput>) {
556 self.stderr = stderr;
557 }
558
559 pub fn set_worker_counter(&mut self, counter: Arc<AtomicU64>) -> &mut Self {
561 self.worker_counter = counter;
562 self
563 }
564
565 pub fn worker_counter(&self) -> Arc<AtomicU64> {
567 Arc::clone(&self.worker_counter)
568 }
569
570 pub fn set_remote_runner_for_target(
575 &mut self,
576 target: String,
577 runner: RemoteRunnerArc,
578 ) -> &mut Self {
579 self.remote_runners.insert(target, runner);
580 self
581 }
582
583 pub fn remote_runner(&self, target: &str) -> Option<RemoteRunnerArc> {
586 self.remote_runners.get(target).cloned()
587 }
588
589 pub fn set_remote_runner(&mut self, runner: RemoteRunnerArc) -> &mut Self {
592 self.set_remote_runner_for_target(String::new(), runner)
593 }
594
595 pub fn set_remote_guest(&mut self, guest: bool) -> &mut Self {
602 self.remote_guest = guest;
603 self
604 }
605
606 pub fn is_remote_guest(&self) -> bool {
608 self.remote_guest
609 }
610
611 pub fn set_push_manifest_sink(&mut self, sink: PushManifestSink) -> &mut Self {
615 self.push_manifest_sink = Some(sink);
616 self
617 }
618
619 pub(super) fn push_manifest_sink(&self) -> Option<PushManifestSink> {
621 self.push_manifest_sink.clone()
622 }
623
624 pub fn insert_inherit_env<S: Into<String>, V: Into<String>>(&mut self, key: S, value: V) {
625 let key = key.into();
626 self.inherit_env_removed.remove(&key);
627 self.inherit_env_overrides.insert(key, value.into());
628 }
629
630 pub fn remove_inherit_env<S: Into<String>>(&mut self, key: S) {
631 let key = key.into();
632 self.inherit_env_overrides.remove(&key);
633 self.inherit_env_removed.insert(key);
634 }
635
636 pub fn inherit_env_value(&self, key: &str) -> Option<&String> {
637 self.inherit_env_overrides.get(key)
638 }
639
640 pub fn inherit_env_is_removed(&self, key: &str) -> bool {
641 self.inherit_env_removed.contains(key)
642 }
643
644 pub fn inherit_env_overrides(&self) -> &std::collections::HashMap<String, String> {
645 &self.inherit_env_overrides
646 }
647
648 pub(super) fn ensure_handle(&self, handle: &PipeHandle, promote: bool) -> Result<()> {
653 PipeRegistry::ensure_handle(handle, promote)
654 }
655
656 pub(super) fn inspect_pipe(&self, handle: &PipeHandle) -> PipeInfo {
658 PipeRegistry::inspect_pipe(handle)
659 }
660
661 pub fn peek_pipe_content(&self, handle: &PipeHandle) -> Result<Vec<u8>> {
669 PipeRegistry::peek_pipe_content(handle)
670 }
671
672 pub(super) fn pin_keeper(&self, handle: &PipeHandle) -> Result<Option<KeeperGuard>> {
677 PipeRegistry::pin_keeper(handle)
678 }
679
680 pub(super) fn resolve_stdin(
683 &self,
684 idx: usize,
685 handle: &PipeHandle,
686 direct: bool,
687 promote: bool,
688 ) -> Result<(CommandStdin, Option<Arc<PipeInner>>)> {
689 PipeRegistry::resolve_stdin(idx, handle, direct, promote)
690 }
691
692 pub(super) fn resolve_stdout(
695 &self,
696 idx: usize,
697 handle: &PipeHandle,
698 direct: bool,
699 promote: bool,
700 ) -> Result<(StreamHandle, Option<Arc<PipeInner>>)> {
701 PipeRegistry::resolve_stdout(idx, handle, direct, promote)
702 }
703
704 pub(super) fn resolve_stderr(
706 &self,
707 idx: usize,
708 handle: &PipeHandle,
709 direct: bool,
710 promote: bool,
711 ) -> Result<StreamHandle> {
712 PipeRegistry::resolve_stderr(idx, handle, direct, promote)
713 }
714
715 pub fn stdin(&self) -> Option<SharedInput> {
716 self.stdin.clone()
717 }
718
719 pub fn stdout(&self) -> Option<SharedOutput> {
720 self.stdout.clone()
721 }
722
723 pub fn stderr(&self) -> Option<SharedOutput> {
724 self.stderr.clone().or_else(|| self.stdout.clone())
725 }
726}
727
728pub(super) fn assemble_default_io(
729 stdin: Option<SharedInput>,
730 stdout: Option<SharedOutput>,
731) -> ExecIo {
732 let mut io = ExecIo::new();
733 io.set_stdin(stdin);
734 io.set_stdout(stdout.clone());
735 io.set_stderr(stdout);
736 io
737}