proclet 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
proclet/process.py ADDED
@@ -0,0 +1,1440 @@
1
+ """Command builder and runner, process types and the process observer protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ import queue
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ from asyncio import Task, create_task, gather
12
+ from collections.abc import AsyncIterator, Iterator, Sequence
13
+ from contextlib import suppress
14
+ from pathlib import Path
15
+ from threading import Thread
16
+ from typing import IO, NamedTuple, Protocol, Self, overload
17
+
18
+ from proclet._io import close
19
+ from proclet._platform import low_priority_hook, priority_creationflags, require_os
20
+ from proclet._streams import (
21
+ STDIN_CHUNK_SIZE,
22
+ dispatch_line,
23
+ encode_input,
24
+ needs_forwarding,
25
+ read_line,
26
+ )
27
+ from proclet.errors import CommandNotFound, ErrorReturnCode, TimeoutException
28
+ from proclet.redirect import RedirectIn, RedirectOut
29
+
30
+ # Type aliases for process types
31
+ type SyncProcess = subprocess.Popen[bytes]
32
+ type AsyncProcess = asyncio.subprocess.Process
33
+ type Process = SyncProcess | AsyncProcess
34
+
35
+
36
+ class _PipelineStage(NamedTuple):
37
+ """Bookkeeping for one spawned stage of a `Command.pipeline()` chain."""
38
+
39
+ process: SyncProcess
40
+ io_threads: list[Thread]
41
+ opened: list[IO[bytes]]
42
+
43
+
44
+ class _AsyncPipelineStage(NamedTuple):
45
+ """Bookkeeping for one spawned stage of a `Command.apipeline()` chain."""
46
+
47
+ process: AsyncProcess
48
+ io_tasks: list[Task[None]]
49
+ opened: list[IO[bytes]]
50
+
51
+
52
+ class ProcessObserver(Protocol):
53
+ """Observer notified at process spawn and exit.
54
+
55
+ Hooks run synchronously: on the caller's thread or event loop, except
56
+ `on_exit` after `exec(wait_completion=False)`, which runs on a background
57
+ thread. They must not raise, as an error there would escape the cleanup.
58
+ """
59
+
60
+ def on_spawn(self, process: Process) -> None:
61
+ """Called once the process is spawned, before waiting for it."""
62
+ ...
63
+
64
+ def on_exit(self, process: Process) -> None:
65
+ """Called once the process has exited (or been terminated) and cleaned up."""
66
+ ...
67
+
68
+
69
+ # Strong references to fire-and-forget tasks, so they can't be collected mid-run.
70
+ _background_tasks: set[Task[None]] = set()
71
+
72
+
73
+ class Command:
74
+ """Fluent builder and runner for one external command.
75
+
76
+ Configure it with the chainable setters (most double as a getter when
77
+ called without a value), then run it with `exec()`/`aexec()` or chain
78
+ commands with `pipeline()`/`apipeline()`.
79
+ """
80
+
81
+ def __init__(
82
+ self, cmd_path: str | Path, search_path: Sequence[str] | None = None
83
+ ) -> None:
84
+ """Init command.
85
+
86
+ Args:
87
+ cmd_path: command name or path.
88
+ search_path: directories to look the binary up in instead of the
89
+ inherited `PATH`. Ignored when `cmd_path` is a `Path`.
90
+ """
91
+ if isinstance(cmd_path, Path):
92
+ self.__cmd_path = cmd_path.as_posix()
93
+ else:
94
+ found_path = shutil.which(
95
+ cmd_path,
96
+ path=os.pathsep.join(search_path) if search_path is not None else None,
97
+ )
98
+ if found_path is None:
99
+ raise CommandNotFound(cmd_path)
100
+ self.__cmd_path = found_path
101
+ self.__cwd = Path.cwd()
102
+ # None inherits the parent's environment; {} is an empty one.
103
+ self.__env: dict[str, str] | None = None
104
+ self.__args: tuple[str, ...] = ()
105
+ self.__in: RedirectIn | None = None
106
+ self.__out: RedirectOut | None = None
107
+ self.__err: RedirectOut | None = None
108
+ self.__timeout: float | None = None
109
+ self.__ok_exit_codes: frozenset[int] = frozenset({0})
110
+ self.__user: str | int | None = None
111
+ self.__group: str | int | None = None
112
+ self.__extra_groups: list[str | int] | None = None
113
+ self.__nice: int | None = None
114
+ self.__observers: list[ProcessObserver] = []
115
+
116
+ @overload
117
+ def args(self) -> tuple[str, ...]: ...
118
+
119
+ @overload
120
+ def args(self, first: str, /, *values: str) -> Self: ...
121
+
122
+ def args(self, *values: str) -> tuple[str, ...] | Self:
123
+ """Returns current arguments if no value is provided, otherwise set arguments.
124
+
125
+ Setting replaces the previous arguments. Calling with no value reads
126
+ them, so arguments can't be cleared back to none this way.
127
+
128
+ Args:
129
+ *values: arguments to set.
130
+ Returns:
131
+ current arguments if no value is provided or self for chaining.
132
+ """
133
+ if not values:
134
+ return self.__args
135
+
136
+ self.__args = values
137
+ return self
138
+
139
+ @overload
140
+ def env(self) -> dict[str, str]: ...
141
+
142
+ @overload
143
+ def env(self, value: dict[str, str]) -> Self: ...
144
+
145
+ def env(self, value: dict[str, str] | None = None) -> dict[str, str] | Self:
146
+ """Returns current env vars if no value is provided, otherwise set env vars.
147
+
148
+ Until env vars are set, the command inherits the parent's environment
149
+ and the getter returns `{}`. Once set, the command gets exactly that
150
+ environment: an empty dict really runs it with no env vars, so build
151
+ on `EnvCmd.inherit()` to keep the parent's.
152
+
153
+ Args:
154
+ value: env vars to set.
155
+ Returns:
156
+ current env vars if no value is provided or self for chaining.
157
+ """
158
+ if value is None:
159
+ return {} if self.__env is None else self.__env.copy()
160
+
161
+ self.__env = dict(value)
162
+ return self
163
+
164
+ @overload
165
+ def cwd(self) -> Path: ...
166
+
167
+ @overload
168
+ def cwd(self, value: Path) -> Self: ...
169
+
170
+ def cwd(self, value: Path | None = None) -> Path | Self:
171
+ """Returns current cwd if no value is provided, otherwise set cwd.
172
+
173
+ Args:
174
+ value: cwd to set.
175
+ Returns:
176
+ current cwd if no value is provided or self for chaining.
177
+ """
178
+ if value is None:
179
+ return self.__cwd
180
+
181
+ self.__cwd = value
182
+ return self
183
+
184
+ @overload
185
+ def user(self) -> str | int | None: ...
186
+
187
+ @overload
188
+ def user(self, value: str | int) -> Self: ...
189
+
190
+ def user(self, value: str | int | None = None) -> str | int | None | Self:
191
+ """Returns current user if no value is provided, otherwise set user.
192
+
193
+ The user is passed straight through to `subprocess.Popen`/
194
+ `asyncio.create_subprocess_exec` (a username or uid), which drop
195
+ privileges to it before exec'ing - the calling process must have
196
+ the permissions to do so (typically running as root).
197
+
198
+ Args:
199
+ value: user (name or uid) to run the command as.
200
+ Returns:
201
+ current user if no value is provided or self for chaining.
202
+ Raises:
203
+ ValueError: if set on a non-POSIX platform.
204
+ """
205
+ if value is None:
206
+ return self.__user
207
+
208
+ require_os("user", "setreuid")
209
+ self.__user = value
210
+ return self
211
+
212
+ @overload
213
+ def group(self) -> str | int | None: ...
214
+
215
+ @overload
216
+ def group(self, value: str | int) -> Self: ...
217
+
218
+ def group(self, value: str | int | None = None) -> str | int | None | Self:
219
+ """Returns current group if no value is provided, otherwise set group.
220
+
221
+ Passed straight through to `subprocess.Popen`/
222
+ `asyncio.create_subprocess_exec` (a group name or gid), like `user`.
223
+
224
+ Args:
225
+ value: group (name or gid) to run the command as.
226
+ Returns:
227
+ current group if no value is provided or self for chaining.
228
+ Raises:
229
+ ValueError: if set on a non-POSIX platform.
230
+ """
231
+ if value is None:
232
+ return self.__group
233
+
234
+ require_os("group", "setregid")
235
+ self.__group = value
236
+ return self
237
+
238
+ @overload
239
+ def extra_groups(self) -> list[str | int] | None: ...
240
+
241
+ @overload
242
+ def extra_groups(self, value: Sequence[str | int]) -> Self: ...
243
+
244
+ def extra_groups(
245
+ self, value: Sequence[str | int] | None = None
246
+ ) -> list[str | int] | None | Self:
247
+ """Returns current supplementary groups if no value is provided, otherwise set them.
248
+
249
+ Unset (`None`) keeps the parent's supplementary groups; an empty list
250
+ drops them all, which is what a privilege drop wants. POSIX only.
251
+
252
+ Args:
253
+ value: supplementary groups (names or gids) to run the command with.
254
+ Returns:
255
+ current supplementary groups if no value is provided or self for chaining.
256
+ Raises:
257
+ ValueError: if set on a non-POSIX platform.
258
+ """
259
+ if value is None:
260
+ return None if self.__extra_groups is None else list(self.__extra_groups)
261
+
262
+ require_os("extra_groups", "setgroups")
263
+ self.__extra_groups = list(value)
264
+ return self
265
+
266
+ @overload
267
+ def nice(self) -> int | None: ...
268
+
269
+ @overload
270
+ def nice(self, value: int) -> Self: ...
271
+
272
+ def nice(self, value: int | None = None) -> int | None | Self:
273
+ """Returns current niceness if no value is provided, otherwise set it.
274
+
275
+ The child lowers its CPU priority to this niceness before exec (and,
276
+ on Linux, moves to the idle IO class on a best effort basis). Raising
277
+ priority (a negative value) needs privileges, like `nice(1)`. On
278
+ Windows the value maps to a priority class instead: >= 15 idle,
279
+ 1..14 below normal, -14..-1 above normal, <= -15 high.
280
+
281
+ Args:
282
+ value: niceness to run the command with, e.g. 19 for the lowest priority.
283
+ Returns:
284
+ current niceness if no value is provided or self for chaining.
285
+ """
286
+ if value is None:
287
+ return self.__nice
288
+
289
+ self.__nice = value
290
+ return self
291
+
292
+ @overload
293
+ def stdin(self) -> RedirectIn | None: ...
294
+
295
+ @overload
296
+ def stdin(self, value: RedirectIn) -> Self: ...
297
+
298
+ def stdin(self, value: RedirectIn | None = None) -> RedirectIn | None | Self:
299
+ """Returns current stdin if no value is provided, otherwise set stdin.
300
+
301
+ Accepts a `str` (encoded as UTF-8) or `bytes` payload, a file object
302
+ (one with a real fd is handed to the child, others such as `StringIO`
303
+ are read and fed), or a queue fed until it yields `None`: a
304
+ `queue.Queue` for `exec()`/`pipeline()`, an `asyncio.Queue` for
305
+ `aexec()`/`apipeline()`. Unset, the child reads from /dev/null.
306
+
307
+ Args:
308
+ value: stdin to set.
309
+ Returns:
310
+ current stdin if no value is provided or self for chaining.
311
+ """
312
+ if value is None:
313
+ return self.__in
314
+
315
+ self.__in = value
316
+ return self
317
+
318
+ @overload
319
+ def stdout(self) -> RedirectOut | None: ...
320
+
321
+ @overload
322
+ def stdout(self, value: RedirectOut) -> Self: ...
323
+
324
+ def stdout(self, value: RedirectOut | None = None) -> RedirectOut | None | Self:
325
+ """Returns current stdout if no value is provided, otherwise set stdout.
326
+
327
+ Accepts a `Path` (truncated and written; a relative one is resolved
328
+ against the current directory now, not against `cwd()`), a file object,
329
+ or a callable receiving each decoded line. Unset, output is discarded.
330
+
331
+ Args:
332
+ value: stdout to set.
333
+ Returns:
334
+ current stdout if no value is provided or self for chaining.
335
+ """
336
+ if value is None:
337
+ return self.__out
338
+ elif isinstance(value, Path):
339
+ self.__out = value.absolute()
340
+ else:
341
+ self.__out = value
342
+ return self
343
+
344
+ @overload
345
+ def stderr(self) -> RedirectOut | None: ...
346
+
347
+ @overload
348
+ def stderr(self, value: RedirectOut) -> Self: ...
349
+
350
+ def stderr(self, value: RedirectOut | None = None) -> RedirectOut | None | Self:
351
+ """Returns current stderr if no value is provided, otherwise set stderr.
352
+
353
+ Accepts the same targets as `stdout()`.
354
+
355
+ Args:
356
+ value: stderr to set.
357
+ Returns:
358
+ current stderr if no value is provided or self for chaining.
359
+ """
360
+ if value is None:
361
+ return self.__err
362
+ elif isinstance(value, Path):
363
+ self.__err = value.absolute()
364
+ else:
365
+ self.__err = value
366
+ return self
367
+
368
+ def inherit(self) -> Self:
369
+ """Inherit stdin, stdout and stderr from current process.
370
+
371
+ Returns:
372
+ self for chaining.
373
+ """
374
+ self.__in = sys.stdin
375
+ self.inherit_out()
376
+ return self
377
+
378
+ def inherit_out(self, if_unset: bool = False) -> Self:
379
+ """Inherit stdout and stderr from current process.
380
+
381
+ Args:
382
+ if_unset: when True, only inherit a stream if it is not already configured.
383
+ Returns:
384
+ self for chaining.
385
+ """
386
+ if not if_unset or self.__out is None:
387
+ self.__out = sys.stdout
388
+ if not if_unset or self.__err is None:
389
+ self.__err = sys.stderr
390
+ return self
391
+
392
+ def timeout(self, timeout: float) -> Self:
393
+ """Set how long a run may take before `TimeoutException` is raised.
394
+
395
+ The process is terminated once it elapses. Only enforced when the run
396
+ waits for completion: `exec(wait_completion=False)` and
397
+ `aexec(wait_completion=False)` ignore it. In a pipeline each stage keeps
398
+ its own timeout, counted from when the previous stage finished.
399
+
400
+ Args:
401
+ timeout: maximum run time, in seconds.
402
+ Returns:
403
+ self for chaining.
404
+ """
405
+ self.__timeout = timeout
406
+ return self
407
+
408
+ def ok_exit_codes(self, *codes: int) -> Self:
409
+ """Set the exit codes considered successful (default: only 0).
410
+
411
+ Any other exit code raises `ErrorReturnCode`. Useful for tools that use
412
+ non-zero codes for warnings, e.g. GNU tar exits 1 when a file changed
413
+ while being read.
414
+
415
+ Args:
416
+ *codes: the successful exit codes; they replace the current set.
417
+ Returns:
418
+ self for chaining.
419
+ Raises:
420
+ ValueError: if no code is given, which would make every run fail.
421
+ """
422
+ if not codes:
423
+ raise ValueError("ok_exit_codes() requires at least one exit code")
424
+ self.__ok_exit_codes = frozenset(codes)
425
+ return self
426
+
427
+ def binary_path(self) -> Path:
428
+ """Get the binary this command runs.
429
+
430
+ Returns:
431
+ the binary's path, as resolved at construction.
432
+ """
433
+ return Path(self.__cmd_path)
434
+
435
+ def add_observer(self, observer: ProcessObserver) -> Self:
436
+ """Register an observer to be notified on process spawn and exit."""
437
+ self.__observers.append(observer)
438
+ return self
439
+
440
+ def copy(self, cmd: Command) -> Self:
441
+ """Copy all parameters from another command, keeping this one's binary.
442
+
443
+ Collections are copied; redirect targets and observers are shared.
444
+
445
+ Args:
446
+ cmd: the command to copy parameters from.
447
+ Returns:
448
+ self for chaining.
449
+ """
450
+ self.__env = None if cmd.__env is None else cmd.__env.copy()
451
+ self.__cwd = cmd.__cwd
452
+ self.__args = cmd.__args
453
+ self.__in = cmd.__in
454
+ self.__out = cmd.__out
455
+ self.__err = cmd.__err
456
+ self.__timeout = cmd.__timeout
457
+ self.__ok_exit_codes = cmd.__ok_exit_codes
458
+ self.__user = cmd.__user
459
+ self.__group = cmd.__group
460
+ self.__extra_groups = (
461
+ None if cmd.__extra_groups is None else list(cmd.__extra_groups)
462
+ )
463
+ self.__nice = cmd.__nice
464
+ self.__observers = list(cmd.__observers)
465
+ return self
466
+
467
+ def _full_cmd(self) -> str:
468
+ """Build the "path arg1 arg2 ..." string used in raised exceptions."""
469
+ return f"{self.__cmd_path} {' '.join(self.__args)}"
470
+
471
+ @staticmethod
472
+ def _opened(*streams: int | IO[bytes]) -> list[IO[bytes]]:
473
+ """Pick out the streams that are real file objects (as opposed to fds/subprocess
474
+ constants) so callers know what needs closing once the process is done with it.
475
+ """
476
+ return [stream for stream in streams if not isinstance(stream, int)]
477
+
478
+ @staticmethod
479
+ def _notify_spawn(observers: list[ProcessObserver], process: Process) -> None:
480
+ """Notify observers that a process has been spawned."""
481
+ for obs in observers:
482
+ obs.on_spawn(process)
483
+
484
+ def _check_stdin_mode(self, *, asynchronous: bool) -> None:
485
+ """Reject a stdin queue that the requested execution mode can't consume.
486
+
487
+ Args:
488
+ asynchronous: whether the command is about to run through asyncio.
489
+ Raises:
490
+ TypeError: if stdin is a `queue.Queue` for an async run, or an
491
+ `asyncio.Queue` for a sync one.
492
+ """
493
+ if asynchronous and isinstance(self.__in, queue.Queue):
494
+ raise TypeError("async runs need an asyncio.Queue stdin, not a queue.Queue")
495
+ if not asynchronous and isinstance(self.__in, asyncio.Queue):
496
+ raise TypeError("sync runs need a queue.Queue stdin, not an asyncio.Queue")
497
+
498
+ def _prepare_stdin(self) -> int | None:
499
+ """Convert the configured stdin into a file descriptor or subprocess constant.
500
+
501
+ Returns:
502
+ fileno of a file object backed by a real fd, subprocess.PIPE for input
503
+ fed from Python (Queue, str, bytes or a file object without a real
504
+ fd, e.g. StringIO), or subprocess.DEVNULL when no stdin is configured.
505
+ """
506
+ if self.__in is None:
507
+ return subprocess.DEVNULL
508
+ if isinstance(self.__in, (queue.Queue, asyncio.Queue, str, bytes)):
509
+ return subprocess.PIPE
510
+ try:
511
+ return self.__in.fileno()
512
+ except (OSError, AttributeError):
513
+ return subprocess.PIPE
514
+
515
+ @staticmethod
516
+ def _prepare_redirect(
517
+ redirect: RedirectOut | None,
518
+ ) -> int | IO[bytes]:
519
+ """Prepare a stdout/stderr redirect for subprocess.
520
+
521
+ Args:
522
+ redirect: the redirect target.
523
+ Returns:
524
+ the opened file for a `Path`, otherwise see `_redirect_fd`.
525
+ """
526
+ if isinstance(redirect, Path):
527
+ return redirect.open("wb")
528
+ return Command._redirect_fd(redirect)
529
+
530
+ @staticmethod
531
+ def _redirect_fd(redirect: RedirectOut | None) -> int:
532
+ """Pick the fd or subprocess constant for a non-`Path` stdout/stderr redirect.
533
+
534
+ Shared by `_prepare_redirect()` and `_aprepare_redirect()`.
535
+
536
+ Args:
537
+ redirect: the redirect target.
538
+ Returns:
539
+ subprocess.PIPE for targets forwarded from Python (callables, file
540
+ objects without a real fd), the fd of other file objects, or
541
+ subprocess.DEVNULL when unset or unusable.
542
+ """
543
+ if needs_forwarding(redirect):
544
+ return subprocess.PIPE
545
+ try:
546
+ return redirect.fileno()
547
+ except (OSError, AttributeError):
548
+ return subprocess.DEVNULL
549
+
550
+ def _popen(
551
+ self,
552
+ stdin: int | IO[bytes] | None,
553
+ stdout: int | IO[bytes],
554
+ stderr: int | IO[bytes],
555
+ ) -> SyncProcess:
556
+ """Spawn this command with subprocess.Popen, translating a missing binary.
557
+
558
+ Args:
559
+ stdin: prepared stdin redirect.
560
+ stdout: prepared stdout redirect.
561
+ stderr: prepared stderr redirect.
562
+ Returns:
563
+ the spawned subprocess.
564
+ Raises:
565
+ CommandNotFound: if the binary can't be found.
566
+ """
567
+ try:
568
+ return subprocess.Popen(
569
+ [self.__cmd_path, *self.__args],
570
+ env=self.__env,
571
+ cwd=self.__cwd.as_posix(),
572
+ stdin=stdin,
573
+ stdout=stdout,
574
+ stderr=stderr,
575
+ bufsize=0, # Unbuffered binary mode
576
+ user=self.__user,
577
+ group=self.__group,
578
+ extra_groups=self.__extra_groups,
579
+ # Only plain syscalls, resolved before the fork (see low_priority_hook).
580
+ preexec_fn=low_priority_hook(self.__nice), # noqa: PLW1509
581
+ creationflags=priority_creationflags(self.__nice),
582
+ )
583
+ except FileNotFoundError as err:
584
+ raise CommandNotFound(self.__cmd_path) from err
585
+
586
+ def _handle_stdin(self, process: SyncProcess) -> Thread | None:
587
+ """Start a thread feeding stdin from a Queue, str, bytes or fd-less file.
588
+
589
+ Feeding happens off the calling thread so a child blocked on a full
590
+ stdout/stderr pipe can't deadlock the write. A child that exits
591
+ without reading all of its input, or a file that can't be read, just
592
+ stops the feeding.
593
+
594
+ Args:
595
+ process: the subprocess to feed stdin to.
596
+ Returns:
597
+ the started thread, or None when stdin isn't fed from Python.
598
+ """
599
+ stdin = process.stdin
600
+ source = self.__in
601
+ if stdin is None or source is None or isinstance(source, asyncio.Queue):
602
+ return None
603
+
604
+ def chunks() -> Iterator[bytes]:
605
+ if isinstance(source, (str, bytes)):
606
+ yield encode_input(source)
607
+ elif isinstance(source, queue.Queue):
608
+ while (data := source.get()) is not None:
609
+ yield encode_input(data)
610
+ else:
611
+ while data := source.read(STDIN_CHUNK_SIZE):
612
+ yield encode_input(data)
613
+
614
+ def forward() -> None:
615
+ with suppress(OSError):
616
+ for chunk in chunks():
617
+ stdin.write(chunk)
618
+ close([stdin])
619
+
620
+ thread = Thread(target=forward, daemon=True)
621
+ thread.start()
622
+ return thread
623
+
624
+ def _handle_stream(
625
+ self, stream: IO[bytes] | None, target: RedirectOut | None
626
+ ) -> Thread | None:
627
+ """Start a thread forwarding a stdout/stderr stream's lines, if it needs one.
628
+
629
+ Args:
630
+ stream: the process stream to forward from (stdout or stderr).
631
+ target: the configured redirect target for that stream, see
632
+ `dispatch_line`.
633
+ Returns:
634
+ the started thread, or None if this stream doesn't need forwarding.
635
+ """
636
+ if stream is None or target is None or not needs_forwarding(target):
637
+ return None
638
+
639
+ def forward() -> None:
640
+ try:
641
+ for line in iter(stream.readline, b""):
642
+ dispatch_line(target, line)
643
+ except (OSError, ValueError):
644
+ pass
645
+ finally:
646
+ stream.close()
647
+
648
+ thread = Thread(target=forward, daemon=True)
649
+ thread.start()
650
+ return thread
651
+
652
+ def _handle_stdout_stderr(self, process: SyncProcess) -> list[Thread]:
653
+ """Start forwarding threads for stdout and stderr.
654
+
655
+ Args:
656
+ process: the subprocess to forward output from.
657
+ Returns:
658
+ list of threads started for output forwarding.
659
+ """
660
+ threads: list[Thread] = []
661
+ for proc_stream, target in (
662
+ (process.stdout, self.__out),
663
+ (process.stderr, self.__err),
664
+ ):
665
+ thread = self._handle_stream(proc_stream, target)
666
+ if thread is not None:
667
+ threads.append(thread)
668
+ return threads
669
+
670
+ def _start_io(
671
+ self,
672
+ process: SyncProcess,
673
+ ) -> list[Thread]:
674
+ """Start threads for forwarding I/O to callbacks/StringIO."""
675
+ # Start draining stdout/stderr before feeding stdin
676
+ threads = self._handle_stdout_stderr(process)
677
+
678
+ stdin_thread = self._handle_stdin(process)
679
+ if stdin_thread is not None:
680
+ threads.append(stdin_thread)
681
+ return threads
682
+
683
+ @staticmethod
684
+ def _reap_in_background(
685
+ process: SyncProcess,
686
+ io_threads: list[Thread],
687
+ opened_files: list[IO[bytes]],
688
+ observers: list[ProcessObserver],
689
+ ) -> None:
690
+ """Start a background thread to clean up resources after process exits.
691
+
692
+ Args:
693
+ process: the subprocess to monitor.
694
+ io_threads: list of I/O forwarding threads to join.
695
+ opened_files: list of file handles to close.
696
+ observers: observers to notify once the process has exited.
697
+ """
698
+
699
+ def reap() -> None:
700
+ try:
701
+ process.wait()
702
+ except OSError:
703
+ pass
704
+ finally:
705
+ for th in io_threads:
706
+ with suppress(RuntimeError):
707
+ th.join(timeout=5)
708
+ close(opened_files)
709
+ for obs in observers:
710
+ obs.on_exit(process)
711
+
712
+ thread = Thread(target=reap, daemon=True)
713
+ thread.start()
714
+
715
+ @staticmethod
716
+ def _cleanup(
717
+ process: SyncProcess,
718
+ opened_files: list[IO[bytes]],
719
+ observers: list[ProcessObserver],
720
+ ) -> None:
721
+ """Close opened redirect files and terminate/kill a process if still alive.
722
+
723
+ Args:
724
+ process: the subprocess to clean up.
725
+ opened_files: file handles to close.
726
+ observers: observers to notify once the process has exited.
727
+ """
728
+ close(opened_files)
729
+ if process.poll() is None:
730
+ process.terminate()
731
+ try:
732
+ process.wait(timeout=10)
733
+ except subprocess.TimeoutExpired:
734
+ process.kill()
735
+ for obs in observers:
736
+ obs.on_exit(process)
737
+
738
+ @staticmethod
739
+ def _is_failure(returncode: int | None, ok_exit_codes: frozenset[int]) -> bool:
740
+ """Whether a finished process' exit code counts as a failure.
741
+
742
+ Shared by `_finish()` and `_afinish()`.
743
+ """
744
+ return returncode is not None and returncode not in ok_exit_codes
745
+
746
+ @staticmethod
747
+ def _finish(
748
+ process: SyncProcess,
749
+ full_cmd: str,
750
+ timeout: float | None,
751
+ io_threads: list[Thread],
752
+ opened_files: list[IO[bytes]],
753
+ observers: list[ProcessObserver],
754
+ ok_exit_codes: frozenset[int],
755
+ ) -> None:
756
+ """Wait for a spawned process, raise on timeout/failed exit, then clean up.
757
+
758
+ Shared by `exec()` and `pipeline()` so a lone command and every stage of
759
+ a pipeline get identical timeout/error/cleanup semantics.
760
+
761
+ Args:
762
+ process: the subprocess to wait for.
763
+ full_cmd: command string, used in raised exceptions.
764
+ timeout: timeout in seconds to wait for completion.
765
+ io_threads: I/O forwarding threads to join.
766
+ opened_files: file handles to close.
767
+ observers: observers to notify once the process has exited.
768
+ ok_exit_codes: exit codes considered successful.
769
+ """
770
+ try:
771
+ try:
772
+ process.wait(timeout=timeout)
773
+ except subprocess.TimeoutExpired as err:
774
+ raise TimeoutException(timeout=err.timeout, cmd=full_cmd) from err
775
+
776
+ for io_thread in io_threads:
777
+ io_thread.join()
778
+
779
+ if Command._is_failure(process.returncode, ok_exit_codes):
780
+ raise ErrorReturnCode(cmd=full_cmd, exit_code=process.returncode)
781
+ finally:
782
+ Command._cleanup(process, opened_files, observers)
783
+
784
+ def exec(self, wait_completion: bool = True) -> SyncProcess:
785
+ """Run the command.
786
+
787
+ By default this waits for the process and enforces `timeout()` and
788
+ `ok_exit_codes()`. With `wait_completion=False` it returns as soon as
789
+ the process is spawned: neither is enforced, and redirect files are
790
+ closed and observers' `on_exit` called from a background thread once
791
+ the process exits.
792
+
793
+ Args:
794
+ wait_completion: wait for the process to exit before returning.
795
+ Returns:
796
+ the subprocess.Popen process, finished when waited for.
797
+ Raises:
798
+ CommandNotFound: if the binary can't be found.
799
+ ErrorReturnCode: if the process exits with a code outside `ok_exit_codes`.
800
+ TimeoutException: if the configured timeout elapses.
801
+ TypeError: if stdin is an `asyncio.Queue`.
802
+ """
803
+ self._check_stdin_mode(asynchronous=False)
804
+ full_cmd = self._full_cmd()
805
+
806
+ stdout = self._prepare_redirect(self.__out)
807
+ stderr = self._prepare_redirect(self.__err)
808
+ opened_files = self._opened(stdout, stderr)
809
+
810
+ try:
811
+ process = self._popen(self._prepare_stdin(), stdout, stderr)
812
+ except CommandNotFound:
813
+ close(opened_files)
814
+ raise
815
+
816
+ # Start background threads to forward piped stdout/stderr to their targets
817
+ io_threads = self._start_io(process)
818
+ self._notify_spawn(self.__observers, process)
819
+
820
+ if wait_completion:
821
+ self._finish(
822
+ process,
823
+ full_cmd,
824
+ self.__timeout,
825
+ io_threads,
826
+ opened_files,
827
+ self.__observers,
828
+ self.__ok_exit_codes,
829
+ )
830
+ return process
831
+ else:
832
+ self._reap_in_background(
833
+ process, io_threads, opened_files, self.__observers
834
+ )
835
+ return process
836
+
837
+ def pipe(self, other: Command) -> SyncProcess:
838
+ """Run this command and pipe its stdout directly into `other`'s stdin, then run
839
+ `other` and wait for both processes to complete.
840
+
841
+ Shorthand for `pipeline(other)` - see its docstring for the full contract
842
+ (raw OS pipe, binary safety, what gets ignored/overwritten on each side,
843
+ error/timeout semantics). See `apipe()` for the asyncio equivalent.
844
+
845
+ Args:
846
+ other: the downstream command to receive this command's stdout as its stdin.
847
+ Returns:
848
+ the downstream command's completed subprocess.Popen.
849
+ Raises:
850
+ CommandNotFound: if either binary can't be found.
851
+ ErrorReturnCode: if either process exits with a code outside its `ok_exit_codes`.
852
+ TimeoutException: if either command's configured timeout elapses.
853
+ """
854
+ return self.pipeline(other)
855
+
856
+ def pipeline(self, *others: Command) -> SyncProcess:
857
+ """Run this command and each of `others` concurrently, piping every stage's
858
+ stdout directly into the next stage's stdin, then wait for all processes to
859
+ complete.
860
+
861
+ Generalizes `pipe()` to any number of stages, connected with raw OS pipes
862
+ rather than the thread-based stdout forwarding `exec()` uses for its redirect
863
+ targets, so this stays safe for binary payloads (e.g. streaming a dump
864
+ through a compressor into an upload) that decoding as text would corrupt.
865
+ Every stage's own configured stdout is ignored and always becomes the pipe
866
+ into the next stage, except the last stage's, which is honored normally.
867
+ Every stage's own configured stdin is ignored and always becomes the upstream
868
+ pipe, except the first stage's (self), which is honored normally. Every
869
+ stage's stderr, env, cwd, timeout, exit codes and observers are honored
870
+ normally.
871
+
872
+ Stages are waited on in order, so a stage's timeout counts from when the
873
+ previous stage finished. The first failure is raised and every stage
874
+ still running is then terminated.
875
+
876
+ See `apipeline()` for the asyncio equivalent.
877
+
878
+ Args:
879
+ others: the downstream commands to chain after this one, in order.
880
+ Returns:
881
+ the last command's completed subprocess.Popen.
882
+ Raises:
883
+ ValueError: if no downstream commands are given.
884
+ TypeError: if this command's stdin queue doesn't match the run mode.
885
+ CommandNotFound: if any binary can't be found.
886
+ ErrorReturnCode: if any process exits with a code outside its `ok_exit_codes`.
887
+ TimeoutException: if any command's configured timeout elapses.
888
+ """
889
+ if not others:
890
+ raise ValueError("pipeline() requires at least one downstream command")
891
+ self._check_stdin_mode(asynchronous=False)
892
+
893
+ stages: list[Command] = [self, *others]
894
+ last_index = len(stages) - 1
895
+ full_cmds = [stage._full_cmd() for stage in stages]
896
+
897
+ spawned: list[_PipelineStage] = []
898
+ finished = 0
899
+ try:
900
+ for index, stage in enumerate(stages):
901
+ is_first = index == 0
902
+ is_last = index == last_index
903
+
904
+ stderr = stage._prepare_redirect(stage.__err)
905
+ stdout = (
906
+ stage._prepare_redirect(stage.__out) if is_last else subprocess.PIPE
907
+ )
908
+ opened = stage._opened(stdout, stderr)
909
+
910
+ upstream = None if is_first else spawned[-1].process
911
+ stdin = stage._prepare_stdin() if upstream is None else upstream.stdout
912
+ try:
913
+ process = stage._popen(stdin, stdout, stderr)
914
+ except CommandNotFound:
915
+ close(opened)
916
+ raise
917
+ finally:
918
+ if upstream is not None:
919
+ # Allow the previous stage to receive SIGPIPE if this stage
920
+ # exits early: once this stage has its own copy of the pipe
921
+ # (or failed to spawn), the parent's copy must go so it isn't
922
+ # left as the pipe's last reader.
923
+ assert upstream.stdout is not None
924
+ upstream.stdout.close()
925
+
926
+ io_threads = self._start_stage_io(
927
+ stage, process, is_first=is_first, is_last=is_last
928
+ )
929
+ stage._notify_spawn(stage.__observers, process)
930
+ spawned.append(_PipelineStage(process, io_threads, opened))
931
+
932
+ for stage, run, full_cmd in zip(stages, spawned, full_cmds, strict=True):
933
+ finished += 1 # _finish() cleans its stage up even when it raises
934
+ stage._finish(
935
+ run.process,
936
+ full_cmd,
937
+ stage.__timeout,
938
+ run.io_threads,
939
+ run.opened,
940
+ stage.__observers,
941
+ stage.__ok_exit_codes,
942
+ )
943
+ return spawned[-1].process
944
+ finally:
945
+ # Clean up every spawned stage _finish() never got to, running or
946
+ # already exited, so its files are closed and observers notified.
947
+ # Nothing is left on the success path. zip() stops at `spawned`'s
948
+ # length, so a stage that never got spawned (e.g. because an earlier
949
+ # one raised CommandNotFound) is skipped.
950
+ for stage, run in zip(stages[finished:], spawned[finished:]):
951
+ stage._cleanup(run.process, run.opened, stage.__observers)
952
+
953
+ @staticmethod
954
+ def _start_stage_io(
955
+ stage: Command, process: SyncProcess, *, is_first: bool, is_last: bool
956
+ ) -> list[Thread]:
957
+ """Start the I/O forwarding threads a single `pipeline()` stage needs.
958
+
959
+ Every stage's stdin/stdout is a raw OS pipe to a neighboring stage and needs
960
+ no thread, except the first stage's stdin and the last stage's stdout, which
961
+ are the chain's only Python-facing ends. Every stage's stderr is independent
962
+ of the piped data flow (it's never piped between stages) and is always
963
+ handled the same way regardless of position.
964
+
965
+ Args:
966
+ stage: the stage that was just spawned.
967
+ process: the stage's spawned subprocess.
968
+ is_first: whether this is the first stage in the chain.
969
+ is_last: whether this is the last stage in the chain.
970
+ Returns:
971
+ the I/O forwarding threads started for this stage, if any.
972
+ """
973
+ threads: list[Thread] = []
974
+ if is_first:
975
+ stdin_thread = stage._handle_stdin(process)
976
+ if stdin_thread is not None:
977
+ threads.append(stdin_thread)
978
+ if is_last:
979
+ threads.extend(stage._handle_stdout_stderr(process))
980
+ else:
981
+ stderr_thread = stage._handle_stream(process.stderr, stage.__err)
982
+ if stderr_thread is not None:
983
+ threads.append(stderr_thread)
984
+ return threads
985
+
986
+ @staticmethod
987
+ async def _aprepare_redirect(
988
+ redirect: RedirectOut | None,
989
+ ) -> int | IO[bytes]:
990
+ """Async equivalent of `_prepare_redirect`, opening a `Path` off the event loop.
991
+
992
+ Args:
993
+ redirect: the redirect target.
994
+ Returns:
995
+ the opened file for a `Path`, otherwise see `_redirect_fd`.
996
+ """
997
+ if isinstance(redirect, Path):
998
+ return await asyncio.to_thread(redirect.open, "wb")
999
+ return Command._redirect_fd(redirect)
1000
+
1001
+ async def _apopen(
1002
+ self,
1003
+ stdin: int | IO[bytes] | None,
1004
+ stdout: int | IO[bytes],
1005
+ stderr: int | IO[bytes],
1006
+ ) -> AsyncProcess:
1007
+ """Spawn this command as an asyncio subprocess, translating a missing binary.
1008
+
1009
+ Args:
1010
+ stdin: prepared stdin redirect.
1011
+ stdout: prepared stdout redirect.
1012
+ stderr: prepared stderr redirect.
1013
+ Returns:
1014
+ the spawned asyncio subprocess.
1015
+ Raises:
1016
+ CommandNotFound: if the binary can't be found.
1017
+ """
1018
+ try:
1019
+ return await asyncio.create_subprocess_exec(
1020
+ self.__cmd_path,
1021
+ *self.__args,
1022
+ env=self.__env,
1023
+ cwd=self.__cwd.as_posix(),
1024
+ stdin=stdin,
1025
+ stdout=stdout,
1026
+ stderr=stderr,
1027
+ user=self.__user,
1028
+ group=self.__group,
1029
+ extra_groups=self.__extra_groups,
1030
+ preexec_fn=low_priority_hook(self.__nice),
1031
+ creationflags=priority_creationflags(self.__nice),
1032
+ )
1033
+ except FileNotFoundError as err:
1034
+ raise CommandNotFound(self.__cmd_path) from err
1035
+
1036
+ def _ahandle_stdin(self, process: AsyncProcess) -> Task[None] | None:
1037
+ """Start a task feeding stdin from a Queue, str, bytes or fd-less file.
1038
+
1039
+ Feeding happens in its own task so the configured timeout covers it.
1040
+ A child that exits without reading all of its input, or a file that
1041
+ can't be read, just stops the feeding.
1042
+
1043
+ Args:
1044
+ process: the asyncio subprocess to feed stdin to.
1045
+ Returns:
1046
+ the created task, or None when stdin isn't fed from Python.
1047
+ """
1048
+ stdin = process.stdin
1049
+ source = self.__in
1050
+ if stdin is None or source is None or isinstance(source, queue.Queue):
1051
+ return None
1052
+
1053
+ async def chunks() -> AsyncIterator[bytes]:
1054
+ if isinstance(source, (str, bytes)):
1055
+ yield encode_input(source)
1056
+ elif isinstance(source, asyncio.Queue):
1057
+ while (data := await source.get()) is not None:
1058
+ yield encode_input(data)
1059
+ else:
1060
+ while data := source.read(STDIN_CHUNK_SIZE):
1061
+ yield encode_input(data)
1062
+
1063
+ async def forward() -> None:
1064
+ with suppress(OSError):
1065
+ async for chunk in chunks():
1066
+ stdin.write(chunk)
1067
+ await stdin.drain()
1068
+ stdin.close()
1069
+ with suppress(OSError):
1070
+ await stdin.wait_closed()
1071
+
1072
+ return create_task(forward())
1073
+
1074
+ def _ahandle_stream(
1075
+ self, stream: asyncio.StreamReader | None, target: RedirectOut | None
1076
+ ) -> Task[None] | None:
1077
+ """Start a task forwarding a stdout/stderr stream's lines, if it needs one.
1078
+
1079
+ Args:
1080
+ stream: the process stream to forward from (stdout or stderr).
1081
+ target: the configured redirect target for that stream, see
1082
+ `dispatch_line`.
1083
+ Returns:
1084
+ the created task, or None if this stream doesn't need forwarding.
1085
+ """
1086
+ if stream is None or target is None or not needs_forwarding(target):
1087
+ return None
1088
+
1089
+ async def forward() -> None:
1090
+ try:
1091
+ while True:
1092
+ line = await read_line(stream)
1093
+ if not line:
1094
+ break
1095
+ dispatch_line(target, line)
1096
+ except (OSError, ValueError):
1097
+ pass
1098
+
1099
+ return create_task(forward())
1100
+
1101
+ def _ahandle_stdout_stderr(
1102
+ self,
1103
+ process: AsyncProcess,
1104
+ ) -> list[Task[None]]:
1105
+ """Create forwarding tasks for stdout and stderr.
1106
+
1107
+ Args:
1108
+ process: the asyncio subprocess to forward output from.
1109
+ Returns:
1110
+ list of tasks started for output forwarding.
1111
+ """
1112
+ tasks: list[Task[None]] = []
1113
+ for proc_stream, target in (
1114
+ (process.stdout, self.__out),
1115
+ (process.stderr, self.__err),
1116
+ ):
1117
+ task = self._ahandle_stream(proc_stream, target)
1118
+ if task is not None:
1119
+ tasks.append(task)
1120
+ return tasks
1121
+
1122
+ def _astart_io(
1123
+ self,
1124
+ process: AsyncProcess,
1125
+ ) -> list[Task[None]]:
1126
+ """Start tasks for forwarding I/O to callbacks/StringIO.
1127
+
1128
+ Args:
1129
+ process: the asyncio subprocess to forward I/O for.
1130
+ Returns:
1131
+ list of tasks started for I/O forwarding.
1132
+ """
1133
+ # Start draining stdout/stderr before feeding stdin
1134
+ tasks = self._ahandle_stdout_stderr(process)
1135
+
1136
+ stdin_task = self._ahandle_stdin(process)
1137
+ if stdin_task is not None:
1138
+ tasks.append(stdin_task)
1139
+ return tasks
1140
+
1141
+ @staticmethod
1142
+ def _areap_in_background(
1143
+ process: AsyncProcess,
1144
+ io_tasks: list[Task[None]],
1145
+ opened_files: list[IO[bytes]],
1146
+ observers: list[ProcessObserver],
1147
+ ) -> None:
1148
+ """Start a background task to clean up resources after process exits.
1149
+
1150
+ Args:
1151
+ process: the asyncio subprocess to wait for.
1152
+ io_tasks: list of I/O forwarding tasks to await.
1153
+ opened_files: list of file handles to close.
1154
+ observers: observers to notify once the process has exited.
1155
+ """
1156
+
1157
+ async def reap() -> None:
1158
+ try:
1159
+ await process.wait()
1160
+ except OSError:
1161
+ pass
1162
+ finally:
1163
+ await gather(
1164
+ *(asyncio.wait_for(task, timeout=5) for task in io_tasks),
1165
+ return_exceptions=True,
1166
+ )
1167
+ close(opened_files)
1168
+ for obs in observers:
1169
+ obs.on_exit(process)
1170
+
1171
+ # The event loop only keeps weak references to tasks.
1172
+ task = create_task(reap())
1173
+ _background_tasks.add(task)
1174
+ task.add_done_callback(_background_tasks.discard)
1175
+
1176
+ @staticmethod
1177
+ async def _acleanup(
1178
+ process: AsyncProcess,
1179
+ io_tasks: list[Task[None]],
1180
+ opened_files: list[IO[bytes]],
1181
+ observers: list[ProcessObserver],
1182
+ ) -> None:
1183
+ """Async equivalent of `_cleanup`: close opened redirect files,
1184
+ terminate/kill a process if still alive and cancel its pending I/O tasks.
1185
+
1186
+ Args:
1187
+ process: the asyncio subprocess to clean up.
1188
+ io_tasks: I/O forwarding tasks, cancelled if still pending (e.g. a
1189
+ stdin queue never fed its `None` sentinel).
1190
+ opened_files: file handles to close.
1191
+ observers: observers to notify once the process has exited.
1192
+ """
1193
+ close(opened_files)
1194
+ if process.returncode is None:
1195
+ process.terminate()
1196
+ try:
1197
+ await asyncio.wait_for(process.wait(), timeout=10)
1198
+ except TimeoutError:
1199
+ process.kill()
1200
+ for task in io_tasks:
1201
+ task.cancel()
1202
+ await gather(*io_tasks, return_exceptions=True)
1203
+ for obs in observers:
1204
+ obs.on_exit(process)
1205
+
1206
+ @staticmethod
1207
+ async def _afinish(
1208
+ process: AsyncProcess,
1209
+ full_cmd: str,
1210
+ timeout: float | None,
1211
+ io_tasks: list[Task[None]],
1212
+ opened_files: list[IO[bytes]],
1213
+ observers: list[ProcessObserver],
1214
+ ok_exit_codes: frozenset[int],
1215
+ ) -> None:
1216
+ """Async equivalent of `_finish`: wait for a spawned process, raise on
1217
+ timeout/failed exit, then clean up.
1218
+
1219
+ Shared by `aexec()` and `apipeline()`. Cleanup runs on every exit path,
1220
+ so a still-running process is terminated on a timeout, an error or a
1221
+ cancellation of the awaiting task alike.
1222
+
1223
+ Args:
1224
+ process: the asyncio subprocess to wait for.
1225
+ full_cmd: command string, used in raised exceptions.
1226
+ timeout: timeout in seconds to wait for completion.
1227
+ io_tasks: I/O forwarding tasks to await.
1228
+ opened_files: file handles to close.
1229
+ observers: observers to notify once the process has exited.
1230
+ ok_exit_codes: exit codes considered successful.
1231
+ """
1232
+ try:
1233
+ try:
1234
+ await asyncio.wait_for(process.wait(), timeout=timeout)
1235
+ except TimeoutError as err:
1236
+ assert timeout is not None
1237
+ raise TimeoutException(timeout=timeout, cmd=full_cmd) from err
1238
+
1239
+ await gather(*io_tasks)
1240
+
1241
+ if Command._is_failure(process.returncode, ok_exit_codes):
1242
+ raise ErrorReturnCode(cmd=full_cmd, exit_code=process.returncode)
1243
+ finally:
1244
+ await Command._acleanup(process, io_tasks, opened_files, observers)
1245
+
1246
+ async def aexec(self, wait_completion: bool = True) -> AsyncProcess:
1247
+ """Run the command with asyncio, the async equivalent of `exec()`.
1248
+
1249
+ With `wait_completion=False` the cleanup runs in a background task
1250
+ instead of a thread; see `exec()`.
1251
+
1252
+ Args:
1253
+ wait_completion: wait for the process to exit before returning.
1254
+ Returns:
1255
+ the asyncio.subprocess.Process, finished when waited for.
1256
+ Raises:
1257
+ CommandNotFound: if the binary can't be found.
1258
+ ErrorReturnCode: if the process exits with a code outside `ok_exit_codes`.
1259
+ TimeoutException: if the configured timeout elapses.
1260
+ TypeError: if stdin is a `queue.Queue`.
1261
+ """
1262
+ self._check_stdin_mode(asynchronous=True)
1263
+ full_cmd = self._full_cmd()
1264
+
1265
+ # Prepare subprocess args for async
1266
+ stdout, stderr = await gather(
1267
+ self._aprepare_redirect(self.__out),
1268
+ self._aprepare_redirect(self.__err),
1269
+ )
1270
+ opened_files = self._opened(stdout, stderr)
1271
+
1272
+ try:
1273
+ process = await self._apopen(self._prepare_stdin(), stdout, stderr)
1274
+ except CommandNotFound:
1275
+ close(opened_files)
1276
+ raise
1277
+
1278
+ # Handle I/O concurrently with waiting
1279
+ io_tasks = self._astart_io(process)
1280
+ self._notify_spawn(self.__observers, process)
1281
+
1282
+ if wait_completion:
1283
+ await self._afinish(
1284
+ process,
1285
+ full_cmd,
1286
+ self.__timeout,
1287
+ io_tasks,
1288
+ opened_files,
1289
+ self.__observers,
1290
+ self.__ok_exit_codes,
1291
+ )
1292
+ return process
1293
+ else:
1294
+ self._areap_in_background(process, io_tasks, opened_files, self.__observers)
1295
+ return process
1296
+
1297
+ async def apipe(self, other: Command) -> AsyncProcess:
1298
+ """Run this command and pipe its stdout directly into `other`'s stdin using
1299
+ asyncio subprocesses, then run `other` and wait for both processes to complete.
1300
+
1301
+ Shorthand for `apipeline(other)` - see its docstring for the full contract.
1302
+
1303
+ Args:
1304
+ other: the downstream command to receive this command's stdout as its stdin.
1305
+ Returns:
1306
+ the downstream command's completed asyncio.subprocess.Process.
1307
+ Raises:
1308
+ CommandNotFound: if either binary can't be found.
1309
+ ErrorReturnCode: if either process exits with a code outside its `ok_exit_codes`.
1310
+ TimeoutException: if either command's configured timeout elapses.
1311
+ """
1312
+ return await self.apipeline(other)
1313
+
1314
+ async def apipeline(self, *others: Command) -> AsyncProcess:
1315
+ """Run this command and each of `others` concurrently using asyncio
1316
+ subprocesses, piping every stage's stdout directly into the next stage's
1317
+ stdin, then wait for all processes to complete.
1318
+
1319
+ Async equivalent of `pipeline()` - see its docstring for the full contract
1320
+ (what gets ignored/overwritten on each stage, error/timeout semantics).
1321
+ asyncio subprocess streams are `StreamReader`/`StreamWriter` objects, not file
1322
+ objects that can be wired directly into another subprocess call the way
1323
+ `pipeline()` wires `subprocess.Popen` streams together, so this opens one OS
1324
+ pipe per internal edge with `os.pipe()` and hands one end to each neighboring
1325
+ stage - the same raw, binary-safe OS-level connection `pipeline()` uses,
1326
+ without decoding through Python.
1327
+
1328
+ Args:
1329
+ others: the downstream commands to chain after this one, in order.
1330
+ Returns:
1331
+ the last command's completed asyncio.subprocess.Process.
1332
+ Raises:
1333
+ ValueError: if no downstream commands are given.
1334
+ TypeError: if this command's stdin queue doesn't match the run mode.
1335
+ CommandNotFound: if any binary can't be found.
1336
+ ErrorReturnCode: if any process exits with a code outside its `ok_exit_codes`.
1337
+ TimeoutException: if any command's configured timeout elapses.
1338
+ """
1339
+ if not others:
1340
+ raise ValueError("apipeline() requires at least one downstream command")
1341
+ self._check_stdin_mode(asynchronous=True)
1342
+ stages: list[Command] = [self, *others]
1343
+ last_index = len(stages) - 1
1344
+ full_cmds = [stage._full_cmd() for stage in stages]
1345
+
1346
+ spawned: list[_AsyncPipelineStage] = []
1347
+ finished = 0
1348
+ pending_read_fd: int | None = None
1349
+ try:
1350
+ for index, stage in enumerate(stages):
1351
+ is_first = index == 0
1352
+ is_last = index == last_index
1353
+
1354
+ stderr = await stage._aprepare_redirect(stage.__err)
1355
+
1356
+ next_read_fd: int | None = None
1357
+ write_fd: int | None = None
1358
+ if is_last:
1359
+ stdout = await stage._aprepare_redirect(stage.__out)
1360
+ else:
1361
+ next_read_fd, write_fd = os.pipe()
1362
+ stdout = write_fd
1363
+
1364
+ opened = stage._opened(stdout, stderr)
1365
+ stdin = stage._prepare_stdin() if is_first else pending_read_fd
1366
+
1367
+ try:
1368
+ try:
1369
+ process = await stage._apopen(stdin, stdout, stderr)
1370
+ except CommandNotFound:
1371
+ close(opened)
1372
+ if next_read_fd is not None:
1373
+ os.close(next_read_fd)
1374
+ raise
1375
+ finally:
1376
+ # Same reasoning as in pipeline(): the parent's copy of each fd
1377
+ # handed to a child must go once that child has its own (or
1378
+ # failed to spawn), or the writer would never see SIGPIPE / the
1379
+ # parent would be left holding the pipe open.
1380
+ if write_fd is not None:
1381
+ os.close(write_fd)
1382
+ if not is_first:
1383
+ assert pending_read_fd is not None
1384
+ os.close(pending_read_fd)
1385
+
1386
+ io_tasks = self._astart_stage_io(
1387
+ stage, process, is_first=is_first, is_last=is_last
1388
+ )
1389
+ stage._notify_spawn(stage.__observers, process)
1390
+ spawned.append(_AsyncPipelineStage(process, io_tasks, opened))
1391
+ pending_read_fd = next_read_fd
1392
+
1393
+ for stage, run, full_cmd in zip(stages, spawned, full_cmds, strict=True):
1394
+ finished += 1 # _afinish() cleans its stage up even when it raises
1395
+ await stage._afinish(
1396
+ run.process,
1397
+ full_cmd,
1398
+ stage.__timeout,
1399
+ run.io_tasks,
1400
+ run.opened,
1401
+ stage.__observers,
1402
+ stage.__ok_exit_codes,
1403
+ )
1404
+ return spawned[-1].process
1405
+ finally:
1406
+ # Same as pipeline(): clean up every spawned stage _afinish() never
1407
+ # got to, running or already exited.
1408
+ for stage, run in zip(stages[finished:], spawned[finished:]):
1409
+ await stage._acleanup(
1410
+ run.process, run.io_tasks, run.opened, stage.__observers
1411
+ )
1412
+
1413
+ @staticmethod
1414
+ def _astart_stage_io(
1415
+ stage: Command, process: AsyncProcess, *, is_first: bool, is_last: bool
1416
+ ) -> list[Task[None]]:
1417
+ """Start the I/O forwarding tasks a single `apipeline()` stage needs.
1418
+
1419
+ Async equivalent of `_start_stage_io` - see its docstring.
1420
+
1421
+ Args:
1422
+ stage: the stage that was just spawned.
1423
+ process: the stage's spawned asyncio subprocess.
1424
+ is_first: whether this is the first stage in the chain.
1425
+ is_last: whether this is the last stage in the chain.
1426
+ Returns:
1427
+ the I/O forwarding tasks started for this stage, if any.
1428
+ """
1429
+ tasks: list[Task[None]] = []
1430
+ if is_first:
1431
+ stdin_task = stage._ahandle_stdin(process)
1432
+ if stdin_task is not None:
1433
+ tasks.append(stdin_task)
1434
+ if is_last:
1435
+ tasks.extend(stage._ahandle_stdout_stderr(process))
1436
+ else:
1437
+ stderr_task = stage._ahandle_stream(process.stderr, stage.__err)
1438
+ if stderr_task is not None:
1439
+ tasks.append(stderr_task)
1440
+ return tasks