1use std::collections::{HashMap, HashSet, VecDeque};
2use std::io::{self, Write};
3use std::sync::{Arc, Mutex};
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}
185
186pub type PushManifestSink = Arc<Mutex<Vec<(String, String)>>>;
188
189pub type RemoteRunnerArc = Arc<dyn super::remote::RemoteRunner>;
194
195pub const CHUNK_SIZE: usize = 8192;
197
198const MIN_RING_CAPACITY: usize = 1024;
200
201pub(crate) struct SlidingWindow {
204 pub(crate) needle: Vec<u8>,
205 ring: VecDeque<u8>,
206 pub matched: bool,
207}
208
209impl SlidingWindow {
210 pub fn new(needle: Vec<u8>) -> Self {
211 Self {
212 ring: VecDeque::with_capacity(needle.len().max(MIN_RING_CAPACITY)),
213 needle,
214 matched: false,
215 }
216 }
217
218 pub fn push_chunk(&mut self, chunk: &[u8]) {
219 if self.matched {
220 return;
221 }
222 let limit = self.needle.len().max(MIN_RING_CAPACITY);
224 for &byte in chunk {
225 self.ring.push_back(byte);
226 if self.ring.len() > limit {
227 self.ring.pop_front();
228 }
229 self.check_match();
230 }
231 }
232
233 pub fn update_needle(&mut self, new_needle: Vec<u8>) {
236 if self.matched {
237 return;
238 }
239 self.needle = new_needle;
240 self.check_match();
241 }
242
243 fn check_match(&mut self) {
244 if self.matched || self.ring.len() < self.needle.len() {
245 return;
246 }
247 let start = self.ring.len() - self.needle.len();
248 if self
249 .ring
250 .iter()
251 .skip(start)
252 .zip(self.needle.iter())
253 .all(|(a, b)| a == b)
254 {
255 self.matched = true;
256 }
257 }
258
259 pub fn ring_buffer(&self) -> Vec<u8> {
261 self.ring.iter().copied().collect()
262 }
263}
264
265#[derive(Clone)]
266pub(super) enum StreamHandle {
267 Stream(SharedOutput),
268 #[cfg(not(miri))]
272 Os(OsPipeWriter),
273}
274
275impl StreamHandle {
276 pub(super) fn to_stdout(&self) -> CommandStdout {
277 match self {
278 StreamHandle::Stream(writer) => CommandStdout::Stream(writer.clone()),
279 #[cfg(not(miri))]
280 StreamHandle::Os(writer) => CommandStdout::OsPipe(writer.clone()),
281 }
282 }
283
284 pub(super) fn to_stderr(&self) -> CommandStderr {
285 match self {
286 StreamHandle::Stream(writer) => CommandStderr::Stream(writer.clone()),
287 #[cfg(not(miri))]
288 StreamHandle::Os(writer) => CommandStderr::OsPipe(writer.clone()),
289 }
290 }
291}
292
293pub(super) fn write_stdout<F>(handle: Option<StreamHandle>, op: F) -> Result<()>
294where
295 F: FnOnce(&mut dyn Write) -> Result<()>,
296{
297 match handle {
298 Some(StreamHandle::Stream(writer)) => {
299 if let Ok(mut guard) = writer.lock() {
300 op(&mut *guard)?;
301 }
302 Ok(())
303 }
304 #[cfg(not(miri))]
308 Some(StreamHandle::Os(_)) => {
309 bail!("cannot write DSL output to a live OS pipe")
310 }
311 None => {
314 let mut stdout = io::stdout();
315 op(&mut stdout)
316 }
317 }
318}
319
320pub struct PipeStream {
335 reader: Option<SharedInput>,
336 writer: Option<SharedOutput>,
337}
338
339impl PipeStream {
340 pub fn reader(reader: SharedInput) -> Self {
342 Self {
343 reader: Some(reader),
344 writer: None,
345 }
346 }
347
348 pub fn writer(writer: SharedOutput) -> Self {
350 Self {
351 reader: None,
352 writer: Some(writer),
353 }
354 }
355
356 pub fn pair(reader: SharedInput, writer: SharedOutput) -> Self {
358 Self {
359 reader: Some(reader),
360 writer: Some(writer),
361 }
362 }
363}
364
365impl std::io::Read for PipeStream {
366 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
367 let Some(reader) = &self.reader else {
368 return Err(std::io::Error::new(
369 std::io::ErrorKind::NotConnected,
370 "pipe stream has no reader half",
371 ));
372 };
373 let mut guard = reader
374 .lock()
375 .map_err(|_| std::io::Error::other("pipe reader lock poisoned"))?;
376 guard.read(buf)
377 }
378}
379
380impl std::io::Write for PipeStream {
381 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
382 let Some(writer) = &self.writer else {
383 return Err(std::io::Error::new(
384 std::io::ErrorKind::NotConnected,
385 "pipe stream has no writer half",
386 ));
387 };
388 let mut guard = writer
389 .lock()
390 .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
391 guard.write(buf)
392 }
393
394 fn flush(&mut self) -> std::io::Result<()> {
395 let Some(writer) = &self.writer else {
396 return Err(std::io::Error::new(
397 std::io::ErrorKind::NotConnected,
398 "pipe stream has no writer half",
399 ));
400 };
401 let mut guard = writer
402 .lock()
403 .map_err(|_| std::io::Error::other("pipe writer lock poisoned"))?;
404 guard.flush()
405 }
406}
407
408pub(crate) const EXACT_STDOUT_CAP: usize = 8 * 1024 * 1024;
412
413pub(crate) struct ExactCapture {
418 pub(crate) bytes: Vec<u8>,
419 pub(crate) overflowed: bool,
420}
421
422impl ExactCapture {
423 pub fn new() -> Self {
424 Self {
425 bytes: Vec::new(),
426 overflowed: false,
427 }
428 }
429
430 pub fn push_chunk(&mut self, chunk: &[u8]) {
431 if self.overflowed {
432 return;
433 }
434 if self.bytes.len() + chunk.len() > EXACT_STDOUT_CAP {
435 self.overflowed = true;
436 return;
437 }
438 self.bytes.extend_from_slice(chunk);
439 }
440}
441
442#[derive(Clone, Copy)]
444enum TeeStream {
445 Stdout,
446 Stderr,
447}
448
449struct TeeWriter {
454 inner: Option<SharedOutput>,
455 stream: TeeStream,
456 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
457 exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
458}
459
460impl Write for TeeWriter {
461 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
462 match &self.inner {
464 Some(inner) => {
465 let mut guard = inner
466 .lock()
467 .map_err(|_| io::Error::other("stdout sink poisoned"))?;
468 guard.write_all(buf)?;
469 }
470 None => match self.stream {
471 TeeStream::Stdout => io::stdout().write_all(buf)?,
472 TeeStream::Stderr => io::stderr().write_all(buf)?,
473 },
474 }
475 if let Ok(mut windows) = self.windows.lock() {
477 for window in windows.values_mut() {
478 window.push_chunk(buf);
479 }
480 }
481 if let Ok(mut exact) = self.exact.lock() {
482 for capture in exact.values_mut() {
483 capture.push_chunk(buf);
484 }
485 }
486 Ok(buf.len())
487 }
488
489 fn flush(&mut self) -> io::Result<()> {
490 match &self.inner {
491 Some(inner) => {
492 let mut guard = inner
493 .lock()
494 .map_err(|_| io::Error::other("stdout sink poisoned"))?;
495 guard.flush()?;
496 }
497 None => match self.stream {
498 TeeStream::Stdout => io::stdout().flush()?,
499 TeeStream::Stderr => io::stderr().flush()?,
500 },
501 }
502 Ok(())
503 }
504}
505
506pub(crate) fn teed_stdout(
508 sink: Option<SharedOutput>,
509 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
510 exact: Arc<Mutex<HashMap<usize, ExactCapture>>>,
511) -> SharedOutput {
512 Arc::new(Mutex::new(TeeWriter {
513 inner: sink,
514 stream: TeeStream::Stdout,
515 windows,
516 exact,
517 }))
518}
519
520pub(crate) fn teed_stderr(
524 sink: Option<SharedOutput>,
525 windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
526) -> SharedOutput {
527 Arc::new(Mutex::new(TeeWriter {
528 inner: sink,
529 stream: TeeStream::Stderr,
530 windows,
531 exact: Arc::new(Mutex::new(HashMap::new())),
532 }))
533}
534
535impl ExecIo {
536 pub fn new() -> Self {
537 Self::default()
538 }
539
540 pub fn set_stdin(&mut self, stdin: Option<SharedInput>) {
541 self.stdin = stdin;
542 }
543
544 pub fn set_stdout(&mut self, stdout: Option<SharedOutput>) {
545 self.stdout = stdout.clone();
546 if self.stderr.is_none() {
547 self.stderr = stdout;
548 }
549 }
550
551 pub fn set_stderr(&mut self, stderr: Option<SharedOutput>) {
552 self.stderr = stderr;
553 }
554
555 pub fn set_remote_runner_for_target(
560 &mut self,
561 target: String,
562 runner: RemoteRunnerArc,
563 ) -> &mut Self {
564 self.remote_runners.insert(target, runner);
565 self
566 }
567
568 pub fn remote_runner(&self, target: &str) -> Option<RemoteRunnerArc> {
571 self.remote_runners.get(target).cloned()
572 }
573
574 pub fn set_remote_runner(&mut self, runner: RemoteRunnerArc) -> &mut Self {
577 self.set_remote_runner_for_target(String::new(), runner)
578 }
579
580 pub fn set_remote_guest(&mut self, guest: bool) -> &mut Self {
587 self.remote_guest = guest;
588 self
589 }
590
591 pub fn is_remote_guest(&self) -> bool {
593 self.remote_guest
594 }
595
596 pub fn set_push_manifest_sink(&mut self, sink: PushManifestSink) -> &mut Self {
600 self.push_manifest_sink = Some(sink);
601 self
602 }
603
604 pub(super) fn push_manifest_sink(&self) -> Option<PushManifestSink> {
606 self.push_manifest_sink.clone()
607 }
608
609 pub fn insert_inherit_env<S: Into<String>, V: Into<String>>(&mut self, key: S, value: V) {
610 let key = key.into();
611 self.inherit_env_removed.remove(&key);
612 self.inherit_env_overrides.insert(key, value.into());
613 }
614
615 pub fn remove_inherit_env<S: Into<String>>(&mut self, key: S) {
616 let key = key.into();
617 self.inherit_env_overrides.remove(&key);
618 self.inherit_env_removed.insert(key);
619 }
620
621 pub fn inherit_env_value(&self, key: &str) -> Option<&String> {
622 self.inherit_env_overrides.get(key)
623 }
624
625 pub fn inherit_env_is_removed(&self, key: &str) -> bool {
626 self.inherit_env_removed.contains(key)
627 }
628
629 pub fn inherit_env_overrides(&self) -> &std::collections::HashMap<String, String> {
630 &self.inherit_env_overrides
631 }
632
633 pub(super) fn ensure_handle(&self, handle: &PipeHandle, promote: bool) -> Result<()> {
638 PipeRegistry::ensure_handle(handle, promote)
639 }
640
641 pub(super) fn inspect_pipe(&self, handle: &PipeHandle) -> PipeInfo {
643 PipeRegistry::inspect_pipe(handle)
644 }
645
646 pub fn peek_pipe_content(&self, handle: &PipeHandle) -> Result<Vec<u8>> {
654 PipeRegistry::peek_pipe_content(handle)
655 }
656
657 pub(super) fn pin_keeper(&self, handle: &PipeHandle) -> Result<Option<KeeperGuard>> {
662 PipeRegistry::pin_keeper(handle)
663 }
664
665 pub(super) fn resolve_stdin(
668 &self,
669 idx: usize,
670 handle: &PipeHandle,
671 direct: bool,
672 promote: bool,
673 ) -> Result<(CommandStdin, Option<Arc<PipeInner>>)> {
674 PipeRegistry::resolve_stdin(idx, handle, direct, promote)
675 }
676
677 pub(super) fn resolve_stdout(
680 &self,
681 idx: usize,
682 handle: &PipeHandle,
683 direct: bool,
684 promote: bool,
685 ) -> Result<(StreamHandle, Option<Arc<PipeInner>>)> {
686 PipeRegistry::resolve_stdout(idx, handle, direct, promote)
687 }
688
689 pub(super) fn resolve_stderr(
691 &self,
692 idx: usize,
693 handle: &PipeHandle,
694 direct: bool,
695 promote: bool,
696 ) -> Result<StreamHandle> {
697 PipeRegistry::resolve_stderr(idx, handle, direct, promote)
698 }
699
700 pub fn stdin(&self) -> Option<SharedInput> {
701 self.stdin.clone()
702 }
703
704 pub fn stdout(&self) -> Option<SharedOutput> {
705 self.stdout.clone()
706 }
707
708 pub fn stderr(&self) -> Option<SharedOutput> {
709 self.stderr.clone().or_else(|| self.stdout.clone())
710 }
711}
712
713pub(super) fn assemble_default_io(
714 stdin: Option<SharedInput>,
715 stdout: Option<SharedOutput>,
716) -> ExecIo {
717 let mut io = ExecIo::new();
718 io.set_stdin(stdin);
719 io.set_stdout(stdout.clone());
720 io.set_stderr(stdout);
721 io
722}