Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,12 @@ A wait on {class}`~libvt.aio.AsyncTerminalStream` or
one read contains several synchronized updates. A transient prompt can
match before the next update replaces it.

#### Close the writer after input failure or cancellation (#160)

Closing an async stream now closes its writer even when the input pump
fails. Concurrent close calls share cleanup, and a cancelled caller receives
its cancellation after cleanup finishes.

### Documentation

#### Assert effective colors alongside screen goldens (#190)
Expand Down
10 changes: 5 additions & 5 deletions docs/topics/sync-and-asyncio.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,11 @@ Leaving `async with` or calling
master descriptor, closes it, and calls
{meth}`~libvt.terminal.Terminal.notify_process_exit`.

Concurrent stream close calls share delivery of frames already received.
Wait for close to finish before restarting the stream. Concurrent PTY
close calls share process cleanup and the final frame drain. A caller
cancelled during that drain receives {exc}`asyncio.CancelledError` when
the drain finishes.
Concurrent close calls on either transport wait for the same cleanup.
Wait for close to finish before restarting a stream. A failed stream
input pump closes its writer and reports the read error. A task
cancelled while waiting for close receives {exc}`asyncio.CancelledError`
after cleanup finishes.

## `tmux` control mode (`-C` / `-CC`)

Expand Down
76 changes: 38 additions & 38 deletions src/libvt/aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ def __init__(
self._read_task: asyncio.Task[bool] | None = None
self._read_waiters = 0
self._writer_task: asyncio.Task[None] | None = None
self._frame_drain_task: asyncio.Task[None] | None = None
self._close_task: asyncio.Task[None] | None = None
if self.terminal._on_reply_queued is None:
self.terminal._on_reply_queued = self._flush_terminal_replies

Expand Down Expand Up @@ -1181,71 +1181,71 @@ async def _pump_loop(self) -> None:
self._cancel_sync_timer()
self._frame_event.set()

async def _finish_received_frames(self) -> None:
"""Share delivery of the bytes received before stream close."""
task = self._frame_drain_task
if task is None:
if self._read_pending is None and not self._eof_pending:
return
task = self._frame_drain_task = asyncio.create_task(
self._finish_pending_read()
)
try:
await _join_close_task(task)
finally:
if self._frame_drain_task is task and task.done():
self._frame_drain_task = None
self._read_pending = None
self._eof_pending = False

def start(self) -> asyncio.Task[None]:
"""Start background stream pumping on the running event loop."""
if self._closed and (self._read_pending is not None or self._eof_pending):
msg = "Cannot start a stream while delivering frames from its last read"
if self._close_task is not None and not self._close_task.done():
msg = "Cannot start a stream while it is closing"
raise RuntimeError(msg)
if self._task is None or self._task.done():
self._close_task = None
self._closed = False
self._task = asyncio.create_task(self._pump_loop())
if self._write_queue or self._writer_draining:
self._ensure_writer_task()
return self._task

async def aclose(self) -> None:
"""Close the stream and deliver pending frames from its last read.
"""Join owned tasks, close the writer and expire any held frame.

Concurrent closes share the drain of frames already received.
Concurrent callers share cleanup. A cancelled caller receives
:exc:`asyncio.CancelledError` once cleanup finishes.
"""
self._closed = True
task = self._close_task
if task is None:
if self._closed:
return
self._closed = True
task = self._close_task = asyncio.create_task(self._close_stream())
try:
await _join_close_task(task)
finally:
if self._close_task is task and task.done():
self._close_task = None

async def _close_stream(self) -> None:
"""Close the writer after both owned tasks have stopped."""
self._write_wakeup.set()
self._drain_event.set()
self._cancel_sync_timer()
try:
if self._read_task is not None:
if not self._read_task.cancelling():
self._read_task.cancel()
await asyncio.gather(self._read_task, return_exceptions=True)
if self._task is not None:
self._task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await self._task
self._task = None
if self._writer_task is not None:
self._writer_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await self._writer_task
self._writer_task = None
tasks = [
task
for task in (self._task, self._writer_task, self._read_task)
if task is not None
]
for task in tasks:
if not task.cancelling():
task.cancel()
results = await asyncio.gather(*tasks, return_exceptions=True)
if self.writer is not None:
self.writer.close()
with contextlib.suppress(OSError):
await self.writer.wait_closed()
for result in results:
if isinstance(result, BaseException) and not isinstance(
result, asyncio.CancelledError
):
raise result
finally:
if self.terminal._on_reply_queued == self._flush_terminal_replies:
self.terminal._on_reply_queued = None
self._task = None
self._writer_task = None
try:
await self._finish_received_frames()
await self._finish_pending_read()
finally:
self._read_pending = None
self._eof_pending = False
self._write_queue.clear()
self._write_buffered_bytes = 0
self._writer_draining = False
Expand Down
133 changes: 133 additions & 0 deletions tests/test_aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -1270,3 +1270,136 @@ def on_event(event: libvt.Event) -> None:
await stream.aclose()
if closers:
await asyncio.gather(*closers, return_exceptions=True)


class _ClosingWriter(_MemoryWriter):
def __init__(self) -> None:
super().__init__()
self.close_calls = 0
self.wait_calls = 0

def close(self) -> None:
self.close_calls += 1
super().close()

async def wait_closed(self) -> None:
self.wait_calls += 1
await super().wait_closed()


async def test_failed_pump_closes_writer_and_preserves_read_error() -> None:
"""Return the original read error after closing the independent writer."""
reader = asyncio.StreamReader()
writer = _ClosingWriter()
stream = AsyncTerminalStream(reader, writer)
pumping = stream.start()
error = OSError("read failed")
reader.set_exception(error)
with pytest.raises(OSError, match="read failed") as pump_error:
await pumping
with pytest.raises(OSError, match="read failed") as close_error:
await stream.aclose()
assert pump_error.value is close_error.value is error
assert (writer.close_calls, writer.wait_calls) == (1, 1)
assert stream.terminal._on_reply_queued is None
await stream.aclose()
assert (writer.close_calls, writer.wait_calls) == (1, 1)


async def test_cancelled_closer_waits_for_the_pump_and_writer() -> None:
"""Deliver owner cancellation after the read and write endpoints unwind."""
reading = asyncio.Event()
unwinding = asyncio.Event()
release = asyncio.Event()

class Reader(asyncio.StreamReader):
async def read(self, n: int = -1) -> bytes:
reading.set()
try:
return await super().read(n)
finally:
unwinding.set()
await release.wait()

writer = _ClosingWriter()
stream = AsyncTerminalStream(Reader(), writer)
stream.start()
await reading.wait()
owner = asyncio.create_task(stream.aclose())
await unwinding.wait()
owner.cancel()
release.set()
with pytest.raises(asyncio.CancelledError):
await owner
assert (writer.close_calls, writer.wait_calls) == (1, 1)
assert stream.terminal._on_reply_queued is None


async def test_concurrent_close_waits_for_writer_and_releases_held_frame() -> None:
"""Concurrent closes wait for one writer and publish one final frame."""
closing = asyncio.Event()
finish = asyncio.Event()

class Writer(_ClosingWriter):
async def wait_closed(self) -> None:
await super().wait_closed()
closing.set()
await finish.wait()

writer = Writer()
stream = AsyncTerminalStream(asyncio.StreamReader(), writer, rows=2, cols=4)
stream.terminal.feed(b"base")
before = stream.terminal.committed
stream.terminal.feed(b"\x1b[?2026h\r\x1b[32m" + "界Z ".encode())
first = asyncio.create_task(stream.aclose())
await closing.wait()
second = asyncio.create_task(stream.aclose())
try:
await asyncio.sleep(0)
assert not second.done()
assert stream.terminal.synchronized
assert stream.terminal.committed.lines == before.lines == ("base", "")
finally:
finish.set()
await asyncio.gather(first, second)
snap = stream.terminal.committed
assert snap.lines == ("界Z ", "")
assert (snap.cursor.row, snap.cursor.col, snap[0].wrapped) == (0, 3, False)
assert [cell.style.fg for cell in snap[0]] == [2, 2, 2, 2]
assert before.lines == ("base", "")
assert (writer.close_calls, writer.wait_calls) == (1, 1)


async def test_close_joins_a_pump_cancelled_by_its_caller() -> None:
"""Finish a publicly cancelled pump before closing the writer."""
reading = asyncio.Event()
unwinding = asyncio.Event()
release = asyncio.Event()
released = asyncio.Event()

class Reader(asyncio.StreamReader):
async def read(self, n: int = -1) -> bytes:
reading.set()
try:
return await super().read(n)
finally:
unwinding.set()
await release.wait()
released.set()

writer = _ClosingWriter()
stream = AsyncTerminalStream(Reader(), writer)
pump = stream.start()
await reading.wait()
pump.cancel()
await unwinding.wait()
closing = asyncio.create_task(stream.aclose())
try:
await asyncio.sleep(0)
await asyncio.sleep(0)
assert not writer.closed
finally:
release.set()
await closing
assert released.is_set()
assert (writer.close_calls, writer.wait_calls) == (1, 1)
Loading