Skip to main content

ProcessSubscription

Struct ProcessSubscription 

Source
pub struct ProcessSubscription<M: Send + 'static> { /* private fields */ }
Expand description

A subscription that spawns and monitors an external process.

Captures stdout/stderr line-by-line and sends ProcessEvent messages. Termination is requested when the subscription’s StopSignal fires or when the optional timeout expires. ProcessEvent::Killed requires a successful kill request and confirmed reaping (with SIGKILL status on Unix). Failed or unconfirmed cleanup produces ProcessEvent::Error.

Normal exit waits for stdout/stderr forwarding to finish, including bounded channel backpressure. The timeout remains active during that drain. If the drain is canceled after the child exits, an error describes the exit and incomplete output. Cancellation can reject an unsent line, preview, or final status when the model queue is full; final-status delivery is not guaranteed. Each UTF-8 line is limited to MAX_PROCESS_LINE_BYTES payload bytes. LF and its immediately preceding CR are excluded from the limit. An unterminated final line is delivered at EOF (preserving any trailing CR). Opt-in partial_output also previews growing valid prefixes before the next read blocks. It does not change completed lines. Oversized lines, invalid UTF-8, and read failures stop forwarding, request termination of the immediate child, and produce one error instead of a normal exit. That error reports incomplete output and the cleanup outcome. Monitoring and input failures use the same cleanup path. After an accepted kill request, foreground reaping is limited to 500 ms; a rejected request never leads to a blocking foreground wait. If ownership remains safe, an unconfirmed child is handed to a background reaper. If that thread cannot start, the error says so; a later wait failure is logged and leaves restart disabled. Late reaping does not turn the earlier error into success. Linux retains a pidfd when available; after a wait error, targets without a retained process handle refuse further waits and signals for that PID. On Unix, parent pipe endpoints use nonblocking I/O and readiness waits; cancellation stops the workers even if descendants retain their endpoints. Other targets still use blocking pipes and bounded joins, so an inherited endpoint can keep a detached worker alive after cancellation. Input is closed by default; stdin enables a bounded input worker. Over pipes, descendants are neither terminated nor reaped on any target. pty runs the child on a pseudo-terminal in its own session, and ends its whole process group with the run. Cancellation is not an atomic write boundary: a prefix may already have reached the child, and an I/O syscall can race with the stop request. Optional control admits interrupts independently of those queues. Its generation belongs to one run. Restart only after that run’s terminal event and confirmed child cleanup, using a fresh control handle.

Implementations§

Source§

impl<M: Send + 'static> ProcessSubscription<M>

Source

pub fn new( program: impl Into<String>, make_msg: impl Fn(ProcessEvent) -> M + Send + Sync + 'static, ) -> Self

Create a new process subscription for the given program.

The make_msg closure converts ProcessEvent into your model’s message type.

Source

pub fn arg(self, arg: impl Into<String>) -> Self

Add a command-line argument.

Source

pub fn args(self, args: impl IntoIterator<Item = impl Into<String>>) -> Self

Add multiple command-line arguments.

Source

pub fn env(self, key: impl Into<String>, value: impl Into<String>) -> Self

Set an environment variable for the child process.

Source

pub fn timeout(self, duration: Duration) -> Self

Set a timeout after which the process is killed.

Source

pub fn stdin(self, input: ProcessInput) -> Self

Connect bounded input for this process run.

Reuse clones of the same handle when rebuilding subscriptions. A new handle changes the automatic subscription ID. An already-used handle produces an error before spawning; use a new handle for a restart.

Source

pub fn control(self, control: ProcessControl) -> Self

Attach supervisor-owned interrupt control for this run.

Clones preserve the automatic subscription ID. A fresh handle changes it, including when stdin is disabled. A used handle cannot spawn again.

Source

pub fn partial_output(self, enabled: bool) -> Self

Preview pending stdout/stderr lines before LF or EOF (default: false).

Each nonempty preview replaces the prior preview for that stream. It contains the original cumulative valid UTF-8 prefix, including controls; sanitize the whole prefix when rendering, rather than individual pieces. An incomplete UTF-8 scalar and one possible CRLF delimiter are retained until resolved. Completed ProcessEvent::Stdout and ProcessEvent::Stderr events remain unchanged, including trailing CR at EOF. Clear previews on completed lines and terminal events.

Previews share the bounded, interruptible output queue and the 64 KiB line bound; they can be delayed by backpressure. Earlier prefixes may already be visible when a later read fails UTF-8 or size validation. This does not force an unflushed child to write or provide arbitrary binary streaming. Unix pipe cancellation is independent of this setting; other targets can still block in OS reads. Changing this setting changes the automatic subscription ID.

Source

pub fn pty(self, enabled: bool) -> Self

Run the child on a pseudo-terminal instead of pipes (Unix; default: false).

The child’s stdout and stderr are the PTY, so isatty holds and programs keep their terminal behavior: color, line-buffered output, progress lines. Both streams arrive as ProcessEvent::Stdout and ProcessEvent::StdoutPartial, and standalone carriage returns (\r) rewind the active line so TTY progress updates replace the current preview rather than accumulating across frames. With stdin, stdin is the PTY as well, each line is written as typed input (chunked with canonical VEOF flushes so lines up to MAX_PROCESS_LINE_BYTES are not truncated by the kernel’s 4095-byte canonical buffer), and closing input sends one end-of-file (Ctrl-D). Without it, stdin is /dev/null. Echo is off and LF is not translated to CRLF; a child may change that.

The child leads a new session with no controlling terminal, so it cannot reach the host terminal through /dev/tty. Its process group belongs to the run: ProcessControl::request_interrupt sends SIGINT to the whole group, as Ctrl-C would. When the leader exits, and before it is reaped, every process left in the group receives SIGKILL, which also lets output reach end-of-file. Cancellation and timeout kill the group the same way. A descendant that starts its own session or group is not followed.

The PTY starts at the size given by ProcessControl::request_resize before spawn, else at the host terminal’s size (stdout, then stdin), else 80x24. Off Unix the run ends with ProcessEvent::Error before spawning. Changing this setting changes the automatic subscription ID.

Source

pub fn with_id(self, id: SubId) -> Self

Override the subscription ID (for explicit deduplication control).

Trait Implementations§

Source§

impl<M: Send + 'static> Subscription<M> for ProcessSubscription<M>

Source§

fn id(&self) -> SubId

Unique identifier for deduplication. Read more
Source§

fn run(&self, sender: SubscriptionSender<M>, stop: StopSignal)

Start the subscription, sending messages through the channel. Read more

Auto Trait Implementations§

§

impl<M> !RefUnwindSafe for ProcessSubscription<M>

§

impl<M> !UnwindSafe for ProcessSubscription<M>

§

impl<M> Freeze for ProcessSubscription<M>
where Arc<dyn Fn(ProcessEvent) -> M + Send + Sync>: Freeze,

§

impl<M> Send for ProcessSubscription<M>
where Arc<dyn Fn(ProcessEvent) -> M + Send + Sync>: Send,

§

impl<M> Sync for ProcessSubscription<M>
where Arc<dyn Fn(ProcessEvent) -> M + Send + Sync>: Sync,

§

impl<M> Unpin for ProcessSubscription<M>
where Arc<dyn Fn(ProcessEvent) -> M + Send + Sync>: Unpin,

§

impl<M> UnsafeUnpin for ProcessSubscription<M>
where Arc<dyn Fn(ProcessEvent) -> M + Send + Sync>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more