diff --git a/docs/index.md b/docs/index.md index 585c8eb..e77b94d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -31,6 +31,9 @@ pb run demo.py # compile the script, send it, and run it `pb run` stays with the program: what it prints appears as it prints it, and what you type goes to the hub, so `input()` works and ++ctrl+c++ interrupts. +Input piped in works too, for driving a program from a script: +`printf 'a\n' | pb run demo.py`. Inside a loop that reads its own input, use +`pb run -n` so the program does not take the rest of it. Press ++esc++ ++esc++ to stop the program — one key, twice, so it is there when a robot is heading for the edge of the table. Press ++ctrl+"]"++ ++q++ to diff --git a/packages/pb-cli/CHANGELOG.md b/packages/pb-cli/CHANGELOG.md index 0490301..2f78b32 100644 --- a/packages/pb-cli/CHANGELOG.md +++ b/packages/pb-cli/CHANGELOG.md @@ -5,6 +5,19 @@ Notable changes to `pybricks-cli`, the `pb` command. The format is based on ## [Unreleased] +### Added + +- `pb run -n` and `pb start -n` leave stdin alone, for use inside a loop that + reads its own input, as with `ssh -n`. + +### Changed + +- Without a terminal, `pb run` and `pb start --wait` send piped or redirected + stdin to the program, so `input()` works in a script: + `printf 'a\n' | pb run prog.py`. Line endings become `\r`. A program used to + wait in `input()` for ever. A `pb run` inside a loop that reads its own input + now takes the rest of it; use `-n` there. + ## [1.0.0b2] - 2026-11-23 ### Changed diff --git a/packages/pb-cli/src/pb_cli/_piped_windows.py b/packages/pb-cli/src/pb_cli/_piped_windows.py new file mode 100644 index 0000000..e72ec60 --- /dev/null +++ b/packages/pb-cli/src/pb_cli/_piped_windows.py @@ -0,0 +1,391 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 The Pybricks Authors + +"""Piped standard input on Windows. See :mod:`pb_cli.piped` for the why. + +The pipe a shell gives a command is made by ``CreatePipe``, which never opens it +for overlapped I/O, so nothing an event loop has will wait on it: the proactor +wants an overlapped handle, the handle itself is signalled whenever no I/O is +pending rather than when data arrives, and ``ReOpenFile`` with +``FILE_FLAG_OVERLAPPED`` is refused with ``ERROR_PIPE_BUSY``. Measured, all +three. + +What is left is libuv's answer, the one every Node program reading a piped +stdin on Windows runs on: **a thread does a zero-byte ``ReadFile``.** On a pipe +that blocks until data arrives or the writer closes, and takes nothing, so the +bytes are then read on the loop by a read that cannot block. And it can be +released: ``CancelSynchronousIo`` aborts it with ``ERROR_OPERATION_ABORTED`` and +leaves the pipe working. Measured, both -- which is what this has over a thread +parked in a real read, and the opposite of what the console does (see +:mod:`pb_cli.console.windows`, where cancelling a read breaks the console). + +**One race, closed the way libuv closes it.** A thread that has said it is about +to read but has not yet entered ``ReadFile`` has no I/O to cancel, and +``CancelSynchronousIo`` says ``ERROR_NOT_FOUND``. Worse, it may be doing some +*other* synchronous I/O in that window -- a garbage-collection finalizer +writing to a full stderr pipe -- and then the cancel lands on that, reports +success, and the read it was meant for starts afterwards with nothing left to +cancel it. So a success proves nothing either. Releasing the thread keeps +cancelling, yielding the processor in between with ``SwitchToThread``, until +the thread itself says it is past the read -- whatever each cancel returned. +That is what libuv's ``uv__pipe_interrupt_read`` does, and why. The loop runs +only while a wait is being cancelled, and only for the instructions between +saying and reading -- it waits for nothing, so it is not the poll rule 7 +forbids. A thread held up in that window by something slow and not +cancellable, such as a finalizer taking a lock, keeps it spinning for as long; +there is no way to wait for a thread to reach a system call. + +That finalizer case has one corner this cannot close. When the I/O a cancel +lands on ends and the thread starts its read *the instant* it does, Windows can +make the ``CancelSynchronousIo`` call itself wait for that read to finish -- +measured with plain threads and no code from here, in about one run in fifteen +with nothing in between the two, and never with fifty microseconds between +them. The release is then stuck inside the call, not in its loop, until stdin +has data or ends. Only blocking I/O run by a finalizer in that window leads +there; libuv has the same exposure. + +**While the zero-byte read is waiting, the pipe is busy.** A synchronous handle +lets one call at a time through, so ``PeekNamedPipe`` and +``NtQueryInformationFile`` on it from another thread, and a child process +started with it as stdin, wait until data arrives or the writer closes -- +measured, a Python child did not even start. Nothing here does any of those +during a wait, and nothing can be done about it short of overlapped I/O, which +this pipe does not have; libuv has the same limit. So a subprocess started +while a session is running must be given a stdin of its own, such as +``subprocess.DEVNULL``, never inherit this one. +""" + +from __future__ import annotations + +import ctypes +import ctypes.wintypes as wintypes +import logging +import msvcrt +import os +import threading +from typing import Final + +import anyio +import anyio.to_thread + +from pb_cli import piped + +__all__ = ["reader"] + +logger = logging.getLogger(__name__) + +_FILE_TYPE_DISK: Final = 0x0001 +_FILE_TYPE_PIPE: Final = 0x0003 +_THREAD_TERMINATE: Final = 0x0001 +"""The access ``CancelSynchronousIo`` needs to the thread it cancels.""" + +_ERROR_BROKEN_PIPE: Final = 109 +_ERROR_NOT_FOUND: Final = 1168 + +# ctypes rather than pywin32, for the reason given in pb_cli.console.windows. +_kernel32: Final = ctypes.WinDLL("kernel32", use_last_error=True) + +_GetFileType: Final = _kernel32.GetFileType +_GetFileType.argtypes = (wintypes.HANDLE,) +_GetFileType.restype = wintypes.DWORD + +_PeekNamedPipe: Final = _kernel32.PeekNamedPipe +_PeekNamedPipe.argtypes = ( + wintypes.HANDLE, + wintypes.LPVOID, + wintypes.DWORD, + wintypes.LPDWORD, + wintypes.LPDWORD, + wintypes.LPDWORD, +) +_PeekNamedPipe.restype = wintypes.BOOL + +_ReadFile: Final = _kernel32.ReadFile +_ReadFile.argtypes = ( + wintypes.HANDLE, + wintypes.LPVOID, + wintypes.DWORD, + wintypes.LPDWORD, + wintypes.LPVOID, +) +_ReadFile.restype = wintypes.BOOL + +_OpenThread: Final = _kernel32.OpenThread +_OpenThread.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD) +_OpenThread.restype = wintypes.HANDLE + +_GetCurrentThreadId: Final = _kernel32.GetCurrentThreadId +_GetCurrentThreadId.argtypes = () +_GetCurrentThreadId.restype = wintypes.DWORD + +_CancelSynchronousIo: Final = _kernel32.CancelSynchronousIo +_CancelSynchronousIo.argtypes = (wintypes.HANDLE,) +_CancelSynchronousIo.restype = wintypes.BOOL + +_CloseHandle: Final = _kernel32.CloseHandle +_CloseHandle.argtypes = (wintypes.HANDLE,) +_CloseHandle.restype = wintypes.BOOL + +_SwitchToThread: Final = _kernel32.SwitchToThread +_SwitchToThread.argtypes = () +_SwitchToThread.restype = wintypes.BOOL + +_FILE_MODE_INFORMATION: Final = 16 +"""``FileModeInformation``, the class that says how a handle was opened.""" + +_FILE_SYNCHRONOUS_IO: Final = 0x0010 | 0x0020 +"""``FILE_SYNCHRONOUS_IO_ALERT`` and ``FILE_SYNCHRONOUS_IO_NONALERT``. + +A handle with neither was opened for overlapped I/O. +""" + + +class _IoStatusBlock(ctypes.Structure): + _fields_ = (("Status", ctypes.c_void_p), ("Information", ctypes.c_size_t)) + + +_ntdll: Final = ctypes.WinDLL("ntdll") + +_NtQueryInformationFile: Final = _ntdll.NtQueryInformationFile +_NtQueryInformationFile.argtypes = ( + wintypes.HANDLE, + ctypes.POINTER(_IoStatusBlock), + wintypes.LPVOID, + wintypes.ULONG, + ctypes.c_int, +) +_NtQueryInformationFile.restype = wintypes.LONG + + +def _synchronous(handle: int) -> bool: + """Whether a handle was opened for ordinary, blocking I/O. + + The pipe a shell makes always is. One handed over by something else -- + another program that made the pipe itself -- may be overlapped, and then a + read without an ``OVERLAPPED`` is not a read that blocks: ``ReadFile`` + documents that it may report completion at once. The zero-byte wait would + return immediately, every time, and the wait would become a spin. libuv + asks the same question for the same reason. + + Args: + handle: The handle to ask about. + + Returns: + True if every read on it blocks until it completes. + """ + status = _IoStatusBlock() + mode = wintypes.ULONG() + result = _NtQueryInformationFile( + handle, + ctypes.byref(status), + ctypes.byref(mode), + ctypes.sizeof(mode), + _FILE_MODE_INFORMATION, + ) + + # A negative NTSTATUS is an error. Not knowing is treated as not + # synchronous, since guessing wrong the other way is a spinning core. + return result >= 0 and bool(mode.value & _FILE_SYNCHRONOUS_IO) + + +class _ZeroReadPipe: + """An anonymous pipe, waited on by a zero-byte read in a thread.""" + + def __init__(self, fd: int, handle: int) -> None: + """Hold the descriptor and the handle behind it. + + Args: + fd: Standard input, for reading. + handle: The same, for waiting and asking. + """ + self._fd = fd + self._handle = handle + self._nothing = ctypes.create_string_buffer(1) + """Somewhere for a read of no bytes to put them.""" + + self._lock = threading.Lock() + """Guards the two below, and keeps the thread's handle open while it + is being cancelled: the thread clears it under this lock before + closing it.""" + + self._waiter: int | None = None + """The thread in the read, or about to be.""" + + self._stopping = False + """Set once the wait is over, so a thread not yet started skips it.""" + + async def read(self) -> bytes: + """Wait until there is input, then take it. + + Returns: + The bytes, or empty once the writer has closed its end and + everything it wrote has been read. + """ + + while True: + waiting = self._waiting() + if waiting is None: + return b"" + + if waiting: + # No more than is there, so the read cannot block. + return os.read(self._fd, min(waiting, piped.READ_LIMIT)) + + # A wait can end with nothing to read -- cancelled, or woken by a + # write of nothing -- so ask again rather than assume. + await self._wait() + + def _waiting(self) -> int | None: + """Ask how much is in the pipe, without taking any of it. + + Returns: + The byte count, or None once the writer has gone and the pipe is + empty. + + Raises: + OSError: If the pipe cannot be asked at all. + """ + count = wintypes.DWORD() + + if not _PeekNamedPipe(self._handle, None, 0, None, ctypes.byref(count), None): + error = ctypes.get_last_error() + if error == _ERROR_BROKEN_PIPE: + return None + + raise ctypes.WinError(error) + + return count.value + + async def _wait(self) -> None: + """Wait until the pipe has data or has ended, or this task is cancelled. + + The same shape as the console's wait: the thread is inside the task + tree, because whichever way this returns -- data, the end of the pipe, + or a cancellation -- it does not return until the thread has. + """ + + with self._lock: + self._stopping = False + + async with anyio.create_task_group() as tg: + + async def watch() -> None: + # abandon_on_cancel=False: a cancel waits for the thread, which + # is safe because the finally below is about to release it. + await anyio.to_thread.run_sync(self._block, abandon_on_cancel=False) + tg.cancel_scope.cancel() + + tg.start_soon(watch) + + try: + await anyio.sleep_forever() + + finally: + # Synchronous, so a cancelled scope cannot skip it. + self._release() + + def _block(self) -> None: + """Block in a zero-byte read until the pipe has something to say. + + Runs in a worker thread. ctypes releases the interpreter lock around + the read, so nothing else is held up by it. How the read ended is not + looked at: :meth:`read` asks the pipe afresh either way. + """ + me = _OpenThread(_THREAD_TERMINATE, False, _GetCurrentThreadId()) + if not me: + raise ctypes.WinError(ctypes.get_last_error()) + + try: + with self._lock: + if self._stopping: + return + + self._waiter = me + + try: + _ReadFile( + self._handle, self._nothing, 0, ctypes.byref(wintypes.DWORD()), None + ) + finally: + with self._lock: + self._waiter = None + finally: + _CloseHandle(me) + + def _release(self) -> None: + """Get the thread out of its read, or stop it from starting one. + + Returns only once the thread has said it is past the read: a cancel + that succeeded may have hit some other I/O of the thread's instead. + See the module docstring. Never raises, because it runs in a finally + during cancellation, and raising there would lose the cancellation and + still leave the thread in its read. + """ + + warned = False + + while True: + error = 0 + + with self._lock: + self._stopping = True + + if self._waiter is None: + # Not started, so it will see _stopping; or done. + return + + if not _CancelSynchronousIo(self._waiter): + error = ctypes.get_last_error() + + if error not in (0, _ERROR_NOT_FOUND) and not warned: + # Not expected: the handle was opened with the access this + # needs. Retrying is still the only way out. Said outside the + # lock, because logging can block on a full stderr pipe, and + # the thread needs the lock to say it is done. + logger.warning( + "cancelling the stdin wait failed: %s", ctypes.FormatError(error) + ) + warned = True + + # Let the thread run the few instructions into the read, where the + # next cancel will find it, or out of it, where it clears _waiter. + _SwitchToThread() + + +def reader(fd: int) -> piped.Piped | None: + """Choose how to read standard input on Windows. + + Args: + fd: Standard input, already known not to be a terminal. + + Returns: + A reader, or None for something this does not read -- a console that + isatty missed, the NUL device, which has nothing to say anyway, a + handle opened for overlapped I/O, which nothing here can wait on, or a + pipe that cannot be read from at all. + """ + handle = msvcrt.get_osfhandle(fd) + kind = _GetFileType(handle) + + if not _synchronous(handle): + logger.info("standard input was opened for overlapped I/O; not forwarding it") + return None + + if kind == _FILE_TYPE_PIPE: + pipe = _ZeroReadPipe(fd, handle) + + try: + # Asked once now, so that a pipe with nothing readable about it -- + # the write end, as in pb run x.py 0<&1 | more -- is left alone + # rather than ending the session on its first read. + pipe._waiting() # pyright: ignore[reportPrivateUsage] + except OSError as exc: + logger.info("standard input is a pipe that cannot be read: %s", exc) + return None + + return pipe + + if kind == _FILE_TYPE_DISK: + return piped.ready(fd) + + return None diff --git a/packages/pb-cli/src/pb_cli/commands/program.py b/packages/pb-cli/src/pb_cli/commands/program.py index d5428b1..d6cfa43 100644 --- a/packages/pb-cli/src/pb_cli/commands/program.py +++ b/packages/pb-cli/src/pb_cli/commands/program.py @@ -39,6 +39,27 @@ a program its firmware cannot run, and the first is far more likely. """ +NoInput = Annotated[ + bool, + cyclopts.Parameter( + name=["--no-input", "-n"], + help=( + "Do not send piped or redirected input to the program. For a pb " + "command inside a loop that reads its own input, as with ssh -n." + ), + show_default=False, + # A flag that turns one thing off: --no-no-input would be absurd. + negative=(), + ), +] +"""Leave standard input alone. + +Without a terminal, whatever stdin is goes to the program, the way ``ssh`` +sends it. So ``while read hub; do pb run --hub "$hub" x.py; done < hubs.txt`` +would hand the rest of ``hubs.txt`` to the first program and the loop would +run once. This is the way out, named after ``ssh``'s for the same reason. +""" + @app.command(name="run", group=PROGRAM_COMMANDS, sort_key=0) async def run_cmd( @@ -51,6 +72,7 @@ async def run_cmd( hub: str | None = None, slot: int | None = None, wait: bool | None = None, + no_input: NoInput = False, verbose: Verbose = (), ) -> int: """Compile a script, send it to a hub, and run it. @@ -59,7 +81,9 @@ async def run_cmd( and on a terminal the keyboard goes to the hub, so Ctrl-C interrupts and input() reads what you type. Press Escape twice to stop the program; Ctrl-] q leaves, and Ctrl-] h lists the rest. Without a terminal -- in a - pipeline or a build -- the output still comes through, on stdout. + pipeline or a build -- the output still comes through, on stdout, and + input piped or redirected into pb run goes to the program. Use -n inside + a loop that reads its own input, or the program will take the rest of it. Args: script: The Python file to run. Leave it out when using --command. @@ -72,6 +96,9 @@ async def run_cmd( only prints the output, which is what a script wants. --no-wait starts the program and returns, for setting a robot going and walking away. + no_input: Do not send piped or redirected input to the program. For + a pb command inside a loop that reads its own input, as with + ssh -n. verbose: Increase log detail. """ @@ -82,7 +109,7 @@ async def run_cmd( ) configure_logging(verbose) - return await errors.run(_run, script, command, hub, slot, wait) + return await errors.run(_run, script, command, hub, slot, wait, not no_input) async def _run( @@ -91,6 +118,7 @@ async def _run( hub: str | None, slot: int | None, wait: bool | None, + forward_input: bool, ) -> int: err = ui.console(err=True) compiled: pb_client.CompiledProgram | None = None @@ -121,7 +149,13 @@ async def _run( # --wait by name is asking for less than that: it says stay, and # says nothing about wanting the terminal taken over, so it is # taken to mean the plain form. - return await _stay_with_it(service, hub, slot, terminal=wait is None) + return await _stay_with_it( + service, + hub, + slot, + terminal=wait is None, + forward_input=forward_input, + ) with ui.spinner(err, "Starting..."): await service.start_program(hub_id=hub, slot=slot, wait=False) @@ -198,6 +232,7 @@ async def start_cmd( hub: str | None = None, slot: int | None = None, wait: bool | None = None, + no_input: NoInput = False, verbose: Verbose = (), ) -> int: """Start a program that is already on the hub. @@ -215,13 +250,18 @@ async def start_cmd( since a script starting a stored program is setting a robot going. --wait stays either way, leaving the terminal alone and printing only the output. --no-wait always returns as soon as it starts. + no_input: Do not send piped or redirected input to the program. For + a pb command inside a loop that reads its own input, as with + ssh -n. verbose: Increase log detail. """ configure_logging(verbose) - return await errors.run(_start, hub, slot, wait, hints=_START_HINTS) + return await errors.run(_start, hub, slot, wait, not no_input, hints=_START_HINTS) -async def _start(hub: str | None, slot: int | None, wait: bool | None) -> int: +async def _start( + hub: str | None, slot: int | None, wait: bool | None, forward_input: bool +) -> int: err = ui.console(err=True) if wait is None and not session.have_terminal(): @@ -235,7 +275,13 @@ async def _start(hub: str | None, slot: int | None, wait: bool | None) -> int: async with pb_client.connect(autostart=False) as service: if wait is not False: - return await _stay_with_it(service, hub, slot, terminal=wait is None) + return await _stay_with_it( + service, + hub, + slot, + terminal=wait is None, + forward_input=forward_input, + ) await service.start_program(hub_id=hub, slot=slot) @@ -244,7 +290,12 @@ async def _start(hub: str | None, slot: int | None, wait: bool | None) -> int: async def _stay_with_it( - service: pb_client.Service, hub: str | None, slot: int | None, *, terminal: bool + service: pb_client.Service, + hub: str | None, + slot: int | None, + *, + terminal: bool, + forward_input: bool, ) -> int: """Start a program and stay with it until it ends. @@ -266,6 +317,8 @@ async def _stay_with_it( slot: Which program slot, or None for the hub's own choice. terminal: Whether taking the terminal over is wanted at all. A script run from a terminal is still a script. + forward_input: Whether piped or redirected stdin goes to the program + when there is no terminal. A terminal's keyboard always does. Returns: The exit code: three if the program ended in an exception, since a @@ -291,9 +344,20 @@ async def start(announce: session.Announce) -> bool: return True # Both have to hold: something to take over, and a reason to. - use_terminal = terminal and session.have_terminal() - stay = session.attached if use_terminal else session.streamed - return await stay(service, info, hub, replay=0, running=running, start=start) + if terminal and session.have_terminal(): + return await session.attached( + service, info, hub, replay=0, running=running, start=start + ) + + return await session.streamed( + service, + info, + hub, + replay=0, + running=running, + start=start, + forward_input=forward_input, + ) @app.command(name="stop", group=PROGRAM_COMMANDS, sort_key=4) diff --git a/packages/pb-cli/src/pb_cli/piped.py b/packages/pb-cli/src/pb_cli/piped.py new file mode 100644 index 0000000..629c961 --- /dev/null +++ b/packages/pb-cli/src/pb_cli/piped.py @@ -0,0 +1,181 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 The Pybricks Authors + +r"""Standard input that is not a terminal, read without ever blocking the loop. + +``printf 'a\n' | pb run prog.py`` and ``pb run prog.py < answers.txt`` should +hand the program on the hub what was piped in, the way ``ssh`` or +``docker run -i`` would. That is a different job from :mod:`pb_cli.console`: +no raw mode, no keys to sort, just bytes -- but the same rule about waiting. +Every read here either waits for the platform to say there is input or cannot +block in the first place, so it can always be cancelled, and nothing is left +behind in a thread when the program ends before the input does. + +What kind of thing stdin is decides how: + +- **A pipe, socket or device on POSIX** is a file descriptor the event loop + can wait on, so it does. A device the selector refuses, such as + ``/dev/null``, is always ready, and is then read like a file. +- **A regular file**, on either platform, never blocks on a read, and is read + straight through. (POSIX selectors refuse regular files outright, which is + why this is told apart rather than tried.) +- **A pipe on Windows** has nothing an event loop will wait on, so a worker + thread waits instead, in a zero-byte read that takes nothing and can be + cancelled. See :mod:`pb_cli._piped_windows`. +- **A terminal** is left alone. Reading one in cooked mode from a background + job stops the whole process with ``SIGTTIN``, and a command run with its + output redirected is often exactly that. +""" + +from __future__ import annotations + +import os +import stat +import sys +from typing import Final, Protocol + +import anyio +import anyio.lowlevel + +__all__ = ["Piped", "piped_stdin"] + +READ_LIMIT: Final = 4096 +"""Bytes to take in one read. + +The service breaks whatever it is given into what the hub accepts, so this only +bounds how much is held here at once. +""" + + +class Piped(Protocol): + """Standard input, readable without blocking anything else.""" + + async def read(self) -> bytes: + """Wait for some input and take it. + + Returns: + What arrived, or empty once there will never be any more. + """ + ... + + +class _Ready: + """Input that is always ready: a regular file, read straight through.""" + + def __init__(self, fd: int) -> None: + """Hold the descriptor. + + Args: + fd: Standard input. + """ + self._fd = fd + + async def read(self) -> bytes: + """Take the next piece of the file. + + Returns: + The bytes, or empty at the end. + """ + # A read of a file does not wait for anything, but a large one read in + # a loop would otherwise never give the rest of the session a turn. + await anyio.lowlevel.checkpoint() + return os.read(self._fd, READ_LIMIT) + + +class _Waitable: + """A POSIX pipe, socket or device, waited on by the event loop.""" + + def __init__(self, fd: int, *, device: bool) -> None: + """Hold the descriptor. + + Args: + fd: Standard input. + device: Whether it is a character device, which the selector may + refuse. A pipe or socket it may not: one refused would be a + real error, and reading it as though ready could block. + """ + self._fd = fd + self._device = device + self._always_ready = False + """Set once the selector has refused the descriptor.""" + + async def read(self) -> bytes: + """Wait until there is input, then take it. + + Returns: + The bytes, or empty once the writer has closed its end. + """ + + if self._always_ready: + await anyio.lowlevel.checkpoint() + else: + try: + await anyio.wait_readable(self._fd) + except OSError: + if not self._device: + raise + + # A device with no way to wait on it, such as /dev/null or + # /dev/zero. select() calls those always readable, and they + # are, so a read returns at once, the same as a file. Linux's + # epoll refuses them with EPERM -- measured, for /dev/null, + # /dev/zero and /dev/urandom -- and macOS's kqueue refuses some + # /dev files with EINVAL, which is why libuv probes for that + # and falls back to select() for them. + self._always_ready = True + await anyio.lowlevel.checkpoint() + + # Readable means a read returns at once: with data, or empty at EOF. + return os.read(self._fd, READ_LIMIT) + + +def piped_stdin() -> Piped | None: + """Find out whether standard input has anything to forward, and how. + + Returns: + A reader for it, or None when there is no stdin, it is a terminal, or + it is something this cannot read without blocking. + """ + + try: + fd = sys.stdin.fileno() + except (AttributeError, ValueError, OSError): + # No stdin at all (pythonw), or one replaced by something with no + # descriptor behind it, as pytest does. + return None + + if os.isatty(fd): + return None + + if sys.platform == "win32": + from pb_cli import _piped_windows + + return _piped_windows.reader(fd) + + mode = os.fstat(fd).st_mode + + if stat.S_ISFIFO(mode) or stat.S_ISSOCK(mode): + return _Waitable(fd, device=False) + + if stat.S_ISCHR(mode): + # One that can be waited on is, and one that cannot -- /dev/null, + # which is what stdin is under most service managers and CI runners -- + # is found out on the first wait. + return _Waitable(fd, device=True) + + if stat.S_ISREG(mode): + return _Ready(fd) + + return None + + +def ready(fd: int) -> Piped: + """Read a descriptor that never makes a read wait. + + Args: + fd: The descriptor. + + Returns: + A reader for it. + """ + return _Ready(fd) diff --git a/packages/pb-cli/src/pb_cli/session.py b/packages/pb-cli/src/pb_cli/session.py index c8f1960..0e1e0ff 100644 --- a/packages/pb-cli/src/pb_cli/session.py +++ b/packages/pb-cli/src/pb_cli/session.py @@ -31,6 +31,7 @@ import sys from collections.abc import AsyncIterator, Awaitable, Callable from dataclasses import dataclass, replace +from typing import TYPE_CHECKING, cast import anyio from anyio.abc import TaskGroup @@ -39,9 +40,13 @@ import pb_client from pb_cli import banner as banner_module from pb_cli import console as console_module -from pb_cli import escape, ui +from pb_cli import escape, piped, ui from pb_cli.errors import EXIT_HUB_ERROR, EXIT_INTERRUPTED, EXIT_OK from pb_cli.escape import Action +from pb_core.jsonrpc import ErrorCode + +if TYPE_CHECKING: + from rich.console import Console logger = logging.getLogger(__name__) @@ -422,14 +427,21 @@ async def streamed( replay: int = 0, running: Running, start: StartFunc, + forward_input: bool = True, ) -> int: - """Stay with a program when there is no terminal to do it on. + r"""Stay with a program when there is no terminal to do it on. + + What is left of a session when there is nowhere to draw: the program's + output as it is printed, and how it ended. This is what a command in a + pipeline or a build gets, and it is why that output goes to stdout -- ``pb + run demo.py > log.txt`` should capture what the program printed and nothing + else. - What is left of a session when there is nowhere to draw and nothing to type - at: the program's output as it is printed, and how it ended. This is what a - command in a pipeline or a build gets, and it is why that output goes to - stdout -- ``pb run demo.py > log.txt`` should capture what the program - printed and nothing else. + Standard input that is a pipe or a file goes to the hub, the way it would + with ``ssh``: ``printf 'a\n' | pb run prog.py`` answers the program's + ``input()``. The end of that input is not the end of the program, which + goes on until it finishes by itself. A terminal is left alone -- see + :mod:`pb_cli.piped`. Args: service: The connected service. @@ -439,6 +451,8 @@ async def streamed( replay: How much earlier output to print first, in bytes. running: What the session expects to be talking to. start: Starts it, once the output is being listened for. + forward_input: Whether to send stdin to the program at all. False + for ``pb run -n``, inside a loop that reads stdin itself. Returns: The exit code: zero unless the hub went away or the program failed. @@ -447,27 +461,40 @@ async def streamed( err = ui.console(err=True) out = sys.stdout.buffer disconnected = False + source = piped.piped_stdin() if forward_input else None + arrived = anyio.Event() async with service.attach(hub_id=hub, replay_bytes=replay) as events: try: if await start(err.print): running = running.we_started_it() - async for event in events: - if isinstance(event, pb_client.Output): - running = running.saw(event.data) - out.write(event.data) - out.flush() - elif isinstance(event, pb_client.Status): - running = running.note(event) - if running.gone: + async with anyio.create_task_group() as tg: + if source is not None: + tg.start_soon(_forward_piped, service, hub, source, arrived, err) + + async for event in events: + if isinstance(event, pb_client.Output): + running = running.saw(event.data) + out.write(event.data) + out.flush() + elif isinstance(event, pb_client.Status): + running = running.note(event) + if running.arrived: + arrived.set() + if running.gone: + break + elif not event.connected and event.state == "disconnected": + err.print( + "The hub disconnected " + f"({event.reason or 'no reason given'})." + ) + disconnected = True break - elif not event.connected and event.state == "disconnected": - err.print( - f"The hub disconnected ({event.reason or 'no reason given'})." - ) - disconnected = True - break + + # The program is over, so whatever is still being piped in has + # nowhere to go. + tg.cancel_scope.cancel() finally: # However this ends -- the program finishing, Ctrl-C, a broken pipe # -- a program this command started must not be left running on a @@ -478,6 +505,127 @@ async def streamed( return _ending(disconnected, running) +async def _forward_piped( + service: pb_client.Service, + hub: str | None, + source: piped.Piped, + arrived: anyio.Event, + err: Console, +) -> None: + """Pass piped standard input to the program until the input ends. + + Each write waits until the hub has taken it, so a hub that reads slowly + slows the reading here rather than piling input up in between. + + Args: + service: The connected service. + hub: Which hub. + source: Standard input. + arrived: Set once the hub says the program is running. Nothing is sent + before then, because the hub empties its input buffer as a program + starts and would throw away whatever had already come. + err: Where to say that the input could not be delivered. + """ + await arrived.wait() + after_cr = False + + # An error reading stdin is not caught. Each one there is means something + # is broken rather than finished, and carrying on would leave a program + # waiting in input() for what can no longer come. Raised, it ends the + # session, which stops the program on the way out. + while data := await source.read(): + data, after_cr = _line_endings(data, after_cr) + + while data: + try: + await service.write_stdin(data, hub_id=hub) + except pb_client.JsonRpcError as exc: + detail = _detail(exc) + + if exc.code != ErrorCode.HUB_BUSY or "firmware_limit" in detail: + # Refused for good, not for now: firmware 4.0 has no room + # for a write the size it reports, and waiting will not + # make any. Its message says to update the firmware. + _not_sent(err, exc) + return + + # The service gave up waiting for the program to read. That is + # the right answer for a keystroke, which somebody is waiting + # to see echoed, and the wrong one for a pipe: a program may + # do a minute's work before its first input(). So carry on + # from wherever the hub stopped taking it, for as long as the + # program runs. + written = detail.get("written") + data = data[written if isinstance(written, int) else 0 :] + except pb_client.ServiceTooOld as exc: + _not_sent(err, exc) + return + else: + break + + # The end of the input is not the end of the program. Nothing is sent to + # say so: the hub has no end-of-input, and Ctrl-D would mean something to + # the program that the person piping a file in did not ask for. + + +def _detail(exc: pb_client.JsonRpcError) -> dict[str, object]: + """Read the structured detail the service attached to an error. + + Args: + exc: The error. + + Returns: + Its data, or empty if it carries none. For ``HUB_BUSY`` that is + ``written``, how much was taken before the service gave up, and on + firmware 4.0 ``firmware_limit``, the most the hub can ever take. + """ + detail: object = exc.data + + if isinstance(detail, dict): + return cast("dict[str, object]", detail) + + return {} + + +def _not_sent(err: Console, exc: Exception) -> None: + """Say once that piped input is not reaching the hub. + + The program goes on either way and its output is still worth having, so + this is a line on stderr rather than a failed command. + + Args: + err: Where to say it. + exc: Why. + """ + logger.info("the hub would not take input: %s", exc) + err.print(f"Input was not sent to the hub: {exc}", markup=False) + + +def _line_endings(data: bytes, after_cr: bool) -> tuple[bytes, bool]: + r"""Make line endings what the hub's input() is waiting for. + + The hub ends a line on a carriage return, which is what Enter sends from a + terminal in raw mode, and drops a line feed without a trace. So text piped + in from a file or another program, which ends its lines with ``\n`` or + ``\r\n``, would never finish a single line. Both become ``\r``. + + Args: + data: One read of standard input. + after_cr: Whether the read before this one ended in ``\r``, so that a + ``\r\n`` split between two reads is still one line ending. + + Returns: + The translated bytes, and whether this read ended in ``\r``. + """ + + if after_cr and data.startswith(b"\n"): + data = data[1:] + + ends_in_cr = data.endswith(b"\r") + + return data.replace(b"\r\n", b"\r").replace(b"\n", b"\r"), ends_in_cr + + async def _stop_quietly(service: pb_client.Service, hub: str | None, noun: str) -> None: """Stop what we started, saying nothing about it. diff --git a/packages/pb-cli/tests/test_piped.py b/packages/pb-cli/tests/test_piped.py new file mode 100644 index 0000000..7937749 --- /dev/null +++ b/packages/pb-cli/tests/test_piped.py @@ -0,0 +1,398 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 The Pybricks Authors + +"""Piped standard input: telling what stdin is, and translating line endings. + +The whole path, a pipe through ``pb run`` to a hub, is tested end to end in +``tests/e2e/test_repl.py``. These are the two pieces of it that are decisions +rather than plumbing. +""" + +from __future__ import annotations + +import contextlib +import io +import os +import sys +from collections.abc import Callable, Iterator +from pathlib import Path + +import anyio +import anyio.to_thread +import pytest + +from pb_cli import piped, session + +pytestmark = pytest.mark.anyio + + +@pytest.fixture(scope="session") +def anyio_backend() -> str: + return "asyncio" + + +@pytest.mark.parametrize( + ("reads", "expected"), + [ + ([b"a\nb\n"], b"a\rb\r"), + ([b"a\r\nb\r\n"], b"a\rb\r"), + ([b"a\rb\r"], b"a\rb\r"), + # A \r\n split between two reads is still one line ending, not two. + ([b"a\r", b"\nb"], b"a\rb"), + ([b"a\r", b"\n", b"b\n"], b"a\rb\r"), + # A blank line is still a line. + ([b"\n\n"], b"\r\r"), + ([b"\r", b"\r\n"], b"\r\r"), + ], +) +def test_line_endings_become_what_the_hub_ends_a_line_on( + reads: list[bytes], expected: bytes +) -> None: + after_cr = False + out = b"" + + for data in reads: + translated, after_cr = session._line_endings( # pyright: ignore[reportPrivateUsage] + data, after_cr + ) + out += translated + + assert out == expected + + +def test_stdin_that_pytest_has_replaced_is_not_read( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Something with no descriptor behind it, as under pytest or an embedding. + monkeypatch.setattr(sys, "stdin", io.StringIO("not for the hub")) + assert piped.piped_stdin() is None + + +@pytest.fixture +def stdin_from(monkeypatch: pytest.MonkeyPatch) -> Iterator[Callable[[str], None]]: + """Make standard input a file or device, the way ``pb run < path`` does. + + Yields: + A function that opens a path as stdin, closed again afterwards. + """ + with contextlib.ExitStack() as opened: + + def use(path: str) -> None: + monkeypatch.setattr( + sys, "stdin", opened.enter_context(Path(path).open("rb")) + ) + + yield use + + +@pytest.mark.skipif(sys.platform == "win32", reason="NUL counts as a terminal there") +async def test_dev_null_ends_at_once(stdin_from: Callable[[str], None]) -> None: + # What stdin is under most service managers and CI runners. epoll refuses + # it, so it is found to be always ready, and reads as the end straight + # away -- rather than being waited on for ever. + stdin_from(os.devnull) + source = piped.piped_stdin() + assert source is not None + + with anyio.fail_after(5): + assert await source.read() == b"" + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX devices") +async def test_a_device_that_cannot_be_waited_on_is_read_like_a_file( + stdin_from: Callable[[str], None], +) -> None: + # /dev/zero never ends, which is fine: each write to the hub waits for the + # program to read, so it goes no faster than the program takes it, exactly + # as cat /dev/zero | pb run would. + stdin_from("/dev/zero") + source = piped.piped_stdin() + assert source is not None + + with anyio.fail_after(5): + for _ in range(3): + assert await source.read() == bytes(piped.READ_LIMIT) + + +@pytest.mark.skipif(sys.platform != "win32", reason="overlapped handles are Windows") +def test_an_overlapped_pipe_is_not_read(monkeypatch: pytest.MonkeyPatch) -> None: + # A synchronous read on an overlapped handle can report completion at + # once, so the zero-byte wait would spin. Such a handle is left alone. + import ctypes + import ctypes.wintypes as wintypes + import msvcrt + import uuid + + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + create = kernel32.CreateNamedPipeW + create.argtypes = ( + wintypes.LPCWSTR, + wintypes.DWORD, + wintypes.DWORD, + wintypes.DWORD, + wintypes.DWORD, + wintypes.DWORD, + wintypes.DWORD, + wintypes.LPVOID, + ) + create.restype = wintypes.HANDLE + pipe_access_inbound = 0x00000001 + file_flag_overlapped = 0x40000000 + + handle = create( + rf"\\.\pipe\pb-piped-{uuid.uuid4().hex}", + pipe_access_inbound | file_flag_overlapped, + 0, + 1, + 0, + 0, + 0, + None, + ) + assert handle not in (None, ctypes.c_void_p(-1).value) + + with os.fdopen(msvcrt.open_osfhandle(handle, os.O_RDONLY), "rb") as stdin: + monkeypatch.setattr(sys, "stdin", stdin) + assert piped.piped_stdin() is None + + +class _Broken: + async def read(self) -> bytes: + raise ConnectionResetError("the other end went away") + + +async def test_a_stdin_that_fails_is_not_swallowed() -> None: + # Every error reading stdin means something is broken rather than + # finished. Carrying on would leave the program waiting in input() for + # what can no longer come, so the error ends the session -- which stops the + # program on the way out. + arrived = anyio.Event() + arrived.set() + + with pytest.raises(ConnectionResetError), anyio.fail_after(5): + # No service: nothing reaches the point of writing to one. + await session._forward_piped( # pyright: ignore[reportPrivateUsage] + None, # pyright: ignore[reportArgumentType] + None, + _Broken(), + arrived, + None, # pyright: ignore[reportArgumentType] + ) + + +@pytest.fixture +def pipe(monkeypatch: pytest.MonkeyPatch) -> Iterator[int]: + read_fd, write_fd = os.pipe() + + with os.fdopen(read_fd, "rb", buffering=0) as reader: + monkeypatch.setattr(sys, "stdin", reader) + yield write_fd + + +async def test_a_pipe_is_read_until_its_writer_closes(pipe: int) -> None: + source = piped.piped_stdin() + assert source is not None + + os.write(pipe, b"hello\n") + os.close(pipe) + + received = b"" + with anyio.fail_after(5): + while data := await source.read(): + received += data + + assert received == b"hello\n" + + +async def test_waiting_on_an_empty_pipe_can_be_cancelled(pipe: int) -> None: + source = piped.piped_stdin() + assert source is not None + + try: + with anyio.move_on_after(0.2) as scope: + await source.read() + + assert scope.cancelled_caught + + # And cancelling the wait took nothing and broke nothing: the next + # thing written is the next thing read. + os.write(pipe, b"after") + with anyio.fail_after(5): + assert await source.read() == b"after" + finally: + os.close(pipe) + + +async def test_a_wait_already_in_progress_wakes_for_what_arrives(pipe: int) -> None: + source = piped.piped_stdin() + assert source is not None + received: list[bytes] = [] + + try: + with anyio.fail_after(5): + async with anyio.create_task_group() as tg: + + async def take() -> None: + received.append(await source.read()) + + tg.start_soon(take) + # Long enough for the read to be waiting, not just about to. + await anyio.sleep(0.1) + assert not received + + os.write(pipe, b"late") + finally: + os.close(pipe) + + assert received == [b"late"] + + +async def test_cancelling_at_every_moment_never_hangs(pipe: int) -> None: + # Cancellation can land before the waiting thread starts, while it is + # about to read, or while it is in the read. Each needs handling, and a + # mistake in any of them is a hang, so try a spread of moments. + source = piped.piped_stdin() + assert source is not None + + try: + with anyio.fail_after(20): + for i in range(200): + with anyio.move_on_after((i % 20) / 10_000): + await source.read() + finally: + os.close(pipe) + + +@pytest.mark.skipif(sys.platform != "win32", reason="the Windows waiting thread") +async def test_a_windows_wait_does_not_spin( + pipe: int, monkeypatch: pytest.MonkeyPatch +) -> None: + # The wait is a read that blocks. If it ever stopped blocking -- returned + # at once on an empty pipe -- read() would loop on it at full speed, which + # is the poll this design exists to avoid. + from pb_cli import _piped_windows + + calls = 0 + block = _piped_windows._ZeroReadPipe._block # pyright: ignore[reportPrivateUsage] + + def counted(self: _piped_windows._ZeroReadPipe) -> None: # pyright: ignore[reportPrivateUsage] + nonlocal calls + calls += 1 + block(self) + + monkeypatch.setattr(_piped_windows._ZeroReadPipe, "_block", counted) # pyright: ignore[reportPrivateUsage] + source = piped.piped_stdin() + assert source is not None + + try: + with anyio.move_on_after(0.3): + await source.read() + finally: + os.close(pipe) + + assert calls == 1 + + +async def test_a_file_is_read_through( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + path = tmp_path / "answers.txt" + path.write_bytes(b"x" * (piped.READ_LIMIT + 10)) + + with path.open("rb") as file: + monkeypatch.setattr(sys, "stdin", file) + source = piped.piped_stdin() + assert source is not None + + received = b"" + while data := await source.read(): + received += data + + assert received == path.read_bytes() + + +@pytest.mark.skipif(sys.platform != "win32", reason="the Windows waiting thread") +async def test_a_cancel_that_hits_other_io_still_releases_the_wait( + pipe: int, monkeypatch: pytest.MonkeyPatch +) -> None: + # Between saying it is about to read and reading, the waiting thread may + # do some other synchronous I/O -- a finalizer writing to a full stderr + # pipe, say. A cancel landing then cancels that instead and reports + # success, and the read starts afterwards with nothing to cancel it. The + # release has to keep going until the thread is past the read. + import threading + import time + + from pb_cli import _piped_windows + + side_read, side_write = os.pipe() + real_read_file = _piped_windows._ReadFile # pyright: ignore[reportPrivateUsage] + real_cancel = _piped_windows._CancelSynchronousIo # pyright: ignore[reportPrivateUsage] + detoured = threading.Event() + first_cancel_done = threading.Event() + + def cancel(handle: int) -> int: + result = real_cancel(handle) + first_cancel_done.set() + return result + + def read_file_after_other_io(*args: object) -> object: + if not detoured.is_set(): + detoured.set() + # Blocks, and is what the first cancel finds. + with contextlib.suppress(OSError): + os.read(side_read, 1) + + # Not straight on into the read: Windows itself can make the + # cancel call wait for a read started the instant the cancelled + # one ends -- measured, with plain threads and none of this code + # -- which is a different race from the one under test. Waiting + # for that call to return gives the old logic exactly one cancel, + # spent on the detour, and nothing to stop the read that follows. + first_cancel_done.wait(5) + + return real_read_file(*args) + + monkeypatch.setattr(_piped_windows, "_ReadFile", read_file_after_other_io) + monkeypatch.setattr(_piped_windows, "_CancelSynchronousIo", cancel) + source = piped.piped_stdin() + assert source is not None + + def rescue() -> None: + # A regression is a hang inside a shielded thread wait, which no + # timeout can interrupt, so it is ended from outside instead. + if not finished.wait(3): + os.write(pipe, b"rescued") + + finished = threading.Event() + threading.Thread(target=rescue, daemon=True).start() + + try: + started = time.monotonic() + async with anyio.create_task_group() as tg: + tg.start_soon(source.read) + # Bounded, because this wait is shielded: if the detour is never + # reached, an unbounded one would hang the whole suite. + assert await anyio.to_thread.run_sync(detoured.wait, 5) + await anyio.sleep(0.1) + tg.cancel_scope.cancel() + + finished.set() + assert time.monotonic() - started < 2 + finally: + finished.set() + os.close(pipe) + os.close(side_read) + os.close(side_write) + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows pipe handles") +def test_the_write_end_of_a_pipe_is_not_read(monkeypatch: pytest.MonkeyPatch) -> None: + # pb run x.py 0<&1 | more: stdin is a pipe, but not one that can be read. + read_fd, write_fd = os.pipe() + + with os.fdopen(write_fd, "wb", buffering=0) as wrong_end: + monkeypatch.setattr(sys, "stdin", wrong_end) + assert piped.piped_stdin() is None + + os.close(read_fd) diff --git a/tests/e2e/test_repl.py b/tests/e2e/test_repl.py index be12ac8..c163500 100644 --- a/tests/e2e/test_repl.py +++ b/tests/e2e/test_repl.py @@ -25,6 +25,7 @@ from __future__ import annotations import contextlib +import os import sys import uuid from collections.abc import AsyncGenerator, Callable, Coroutine, Generator, Iterator @@ -774,3 +775,231 @@ async def command() -> int: assert await _run(screen, terminal, talk, command) == errors.EXIT_OK # Nothing was drawn on the terminal at all: no status line, no margin. assert not screen.written + + +# ------------------------------------------------------ piped standard input + + +@pytest.fixture +def piped(monkeypatch: pytest.MonkeyPatch) -> Iterator[Callable[[bytes, bool], int]]: + """Make standard input a real pipe, the way a shell does for ``a | pb``. + + A real one rather than a stand-in, because how a pipe is waited on is the + thing under test, and it differs by platform. + + Yields: + A function that writes to the pipe, closing it afterwards if asked, + and returns the write end. + """ + read_fd, write_fd = os.pipe() + reader = os.fdopen(read_fd, "rb", buffering=0) + monkeypatch.setattr(sys, "stdin", reader) + open_ends = [write_fd] + + def feed(data: bytes, close: bool) -> int: + os.write(write_fd, data) + if close: + os.close(write_fd) + open_ends.remove(write_fd) + return write_fd + + yield feed + + for fd in open_ends: + os.close(fd) + reader.close() + + +def _run_waiting(tmp_path: Path) -> Command: + """``pb run demo.py --wait``, which always takes the path with no terminal. + + Args: + tmp_path: Where to put the script. + + Returns: + The command. + """ + + async def command() -> int: + return await program_commands.run_cmd( + _script(tmp_path, "print(input())\n"), hub=HUB_NAME, wait=True + ) + + return command + + +async def test_piped_input_reaches_the_program( + service: FakeHub, + terminal: list[_Screen], + piped: Callable[[bytes, bool], int], + tmp_path: Path, +) -> None: + hub = service + # Both kinds of line ending a file or another program might use. The hub + # ends a line on a carriage return and drops a line feed, so either has to + # arrive as the one it understands or input() never returns. + piped(b"a\nb\r\nc\n", True) + + async def talk(screen: _Screen) -> None: + del screen + await _when(lambda: bytes(hub.stdin) == b"a\rb\rc\r") + # The end of the input is not the end of the program. + await anyio.sleep(0.2) + assert hub.status & p.StatusFlag.USER_PROGRAM_RUNNING + hub.set_program_running(False) + + assert await _run(_Screen(), terminal, talk, _run_waiting(tmp_path)) == ( + errors.EXIT_OK + ) + assert bytes(hub.stdin) == b"a\rb\rc\r" + + +async def test_no_input_leaves_stdin_alone( + service: FakeHub, + terminal: list[_Screen], + piped: Callable[[bytes, bool], int], + tmp_path: Path, +) -> None: + hub = service + # while read hub; do pb run -n x.py; done < hubs.txt -- the rest of the + # file belongs to the loop, not to the first program it runs. + piped(b"second-hub\nthird-hub\n", True) + + async def talk(screen: _Screen) -> None: + del screen + await _when(lambda: bool(hub.status & p.StatusFlag.USER_PROGRAM_RUNNING)) + await anyio.sleep(0.2) + hub.set_program_running(False) + + async def command() -> int: + return await program_commands.run_cmd( + _script(tmp_path, "print(input())\n"), + hub=HUB_NAME, + wait=True, + no_input=True, + ) + + assert await _run(_Screen(), terminal, talk, command) == errors.EXIT_OK + assert bytes(hub.stdin) == b"" + # And it is all still there for whoever reads stdin next. + assert sys.stdin.read() == b"second-hub\nthird-hub\n" + + +async def test_firmware_4_0_says_so_once_and_lets_the_program_run( + service: FakeHub, + terminal: list[_Screen], + piped: Callable[[bytes, bool], int], + capsys: pytest.CaptureFixture[str], + tmp_path: Path, +) -> None: + hub = service + # Pybricks 4.0 reported a write size it had no room for: a Prime hub's + # buffer held 64 bytes, so a bigger write is refused for good. The service + # says so at once. Retrying that as though the program had not read yet + # would go on for as long as the program ran, so the forwarder stops and + # says why, and the program carries on. + hub.firmware = "4.0.1" + hub.stdin_capacity = 64 + piped(b"x" * 200 + b"\n", True) + + async def talk(screen: _Screen) -> None: + del screen + await _when(lambda: bool(hub.status & p.StatusFlag.USER_PROGRAM_RUNNING)) + await anyio.sleep(0.3) + assert hub.status & p.StatusFlag.USER_PROGRAM_RUNNING + hub.set_program_running(False) + + assert await _run(_Screen(), terminal, talk, _run_waiting(tmp_path)) == ( + errors.EXIT_OK + ) + + said = capsys.readouterr().err + assert said.count("Input was not sent to the hub") == 1 + assert "update the hub's firmware" in said + assert bytes(hub.stdin) == b"" + + +async def test_a_pipe_that_stays_open_does_not_hold_the_command( + service: FakeHub, + terminal: list[_Screen], + piped: Callable[[bytes, bool], int], + tmp_path: Path, +) -> None: + hub = service + # The writer has said nothing and has not closed its end -- a producer + # still thinking. The program ending has to end the command regardless, + # which only works if the wait for input can be cancelled. + piped(b"", False) + + async def talk(screen: _Screen) -> None: + del screen + await _when(lambda: bool(hub.status & p.StatusFlag.USER_PROGRAM_RUNNING)) + await anyio.sleep(0.1) + hub.set_program_running(False) + + assert await _run(_Screen(), terminal, talk, _run_waiting(tmp_path)) == ( + errors.EXIT_OK + ) + assert bytes(hub.stdin) == b"" + + +async def test_input_from_a_file_reaches_the_program( + service: FakeHub, + terminal: list[_Screen], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + hub = service + answers = tmp_path / "answers.txt" + answers.write_bytes(b"yes\nno\n") + + with answers.open("rb") as file: + # pb run demo.py < answers.txt + monkeypatch.setattr(sys, "stdin", file) + + async def talk(screen: _Screen) -> None: + del screen + await _when(lambda: bytes(hub.stdin) == b"yes\rno\r") + hub.set_program_running(False) + + assert await _run(_Screen(), terminal, talk, _run_waiting(tmp_path)) == ( + errors.EXIT_OK + ) + + +async def test_piped_input_waits_for_a_program_that_reads_slowly( + service: FakeHub, + terminal: list[_Screen], + piped: Callable[[bytes, bool], int], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + hub = service + # A small buffer, small writes, and a program that reads only now and + # then -- more slowly than the service is prepared to wait for a keystroke. + # A pipe has to wait as long as it takes, carrying on from wherever the hub + # stopped taking it, with nothing lost and nothing sent twice. + hub.stdin_capacity = 128 + hub.max_write_size = 64 + monkeypatch.setattr("pb_service.methods.stdio.STDIN_PATIENCE_SECONDS", 0.05) + sent = bytes(range(32, 127)) * 10 + piped(sent, True) + + def delivered() -> bytes: + return b"".join(hub.stdin_writes) + + async def talk(screen: _Screen) -> None: + del screen + + with anyio.fail_after(10): + while delivered() != sent: + # Stands for the program reading what has arrived. + await anyio.sleep(0.15) + hub.stdin.clear() + + hub.set_program_running(False) + + assert await _run(_Screen(), terminal, talk, _run_waiting(tmp_path)) == ( + errors.EXIT_OK + ) + assert delivered() == sent