diff --git a/pyhap/media/recording.py b/pyhap/media/recording.py index afe6727b..78369e41 100644 --- a/pyhap/media/recording.py +++ b/pyhap/media/recording.py @@ -406,7 +406,7 @@ def mux(item: BufferedMedia) -> None: mux(item) self.ring.listener = mux try: - self._process = await asyncio.create_subprocess_exec( + process = await asyncio.create_subprocess_exec( *command, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, @@ -416,8 +416,15 @@ def mux(item: BufferedMedia) -> None: self.ring.listener = None self._queue = None raise - logger.info("Recording transcoder started, pid %d", self._process.pid) - process = self._process + if self._queue is not queue or self._closed: + # stop() ran, or the source ended, while the transcoder started + # and found none to end. + with contextlib.suppress(ProcessLookupError): + process.kill() + await process.wait() + raise RuntimeError("The recording was stopped while it started") + self._process = process + logger.info("Recording transcoder started, pid %d", process.pid) loop = asyncio.get_running_loop() self._stderr_tail.clear() self._stderr_done = loop.create_task(_log_stderr(process, self._stderr_tail)) diff --git a/pyhap/media/worker.py b/pyhap/media/worker.py index b65f874e..c1532db9 100644 --- a/pyhap/media/worker.py +++ b/pyhap/media/worker.py @@ -476,7 +476,9 @@ async def start(self, command: list[str], prebuffer: float) -> None: prebuffer=prebuffer, ) except BaseException: - self._recording = False + # The worker may run the transcoder all the same, e.g. when the + # request was cancelled before its answer. + await asyncio.shield(self.stop()) raise async def stop(self) -> None: diff --git a/tests/test_media_recording.py b/tests/test_media_recording.py index b123f850..7c4fd851 100644 --- a/tests/test_media_recording.py +++ b/tests/test_media_recording.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +from collections.abc import Awaitable, Callable import os import shutil import sys @@ -452,6 +453,35 @@ async def test_one_recording_at_a_time() -> None: source.close() +async def _stop(recorder: Recorder, _source: MediaSource) -> None: + await recorder.stop() + + +async def _close_source(_recorder: Recorder, source: MediaSource) -> None: + source.close("gone") + + +@pytest.mark.parametrize("end", [_stop, _close_source], ids=["stop", "source-closed"]) +async def test_end_while_the_transcoder_starts( + end: Callable[[Recorder, MediaSource], Awaitable[None]], +) -> None: + """Verify a stop or source end while the transcoder starts leaves none.""" + source = MediaSource() + await source.start() + recorder = Recorder(source, prebuffer=4.0) + try: + starting = asyncio.ensure_future(recorder.start(CAT, 4.0)) + await asyncio.sleep(0) + await end(recorder, source) + with pytest.raises(RuntimeError, match="stopped while it started"): + await starting + assert not recorder.recording + assert recorder._process is None + finally: + await recorder.close() + source.close() + + def has_ffmpeg() -> bool: """Whether real ffmpeg tests are wanted and possible.""" return FFMPEG is not None and os.environ.get("HAP_PYTHON_FFMPEG_TESTS") == "1" diff --git a/tests/test_media_worker.py b/tests/test_media_worker.py index 6ef80ee3..3bb7f885 100644 --- a/tests/test_media_worker.py +++ b/tests/test_media_worker.py @@ -9,6 +9,7 @@ import os import pathlib import signal +import sys import time from typing import Any @@ -466,6 +467,49 @@ async def test_worker_crash_ends_its_sources(worker: MediaWorker) -> None: assert not again.closed +# Stands in for the recording transcoder: names a file in the directory it is +# given after its process ID, then runs until it is stopped. +TRANSCODER = """ +import os, sys, time +open(os.path.join(sys.argv[1], f"{os.getpid()}.pid"), "w").close() +time.sleep(60) +""" + + +def transcoders(directory: pathlib.Path) -> list[int]: + """The process IDs of the transcoders started in ``directory`` that still run.""" + running = [] + for path in directory.glob("*.pid"): + with contextlib.suppress(ProcessLookupError): + os.kill(int(path.stem), 0) + running.append(int(path.stem)) + return running + + +@pytest.mark.parametrize("separate_process", [False, True], ids=["thread", "process"]) +async def test_cancelled_recording_start_leaves_no_transcoder( + monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path, separate_process: bool +) -> None: + """Verify a recording whose start is cancelled mid-request ends in the worker.""" + worker = MediaWorker(separate_process=separate_process, log_dir=tmp_path / "log") + recorder = await worker.open_recorder(await worker.open_source(), prebuffer=0) + command = [sys.executable, "-c", TRANSCODER, str(tmp_path)] + # The worker starts the transcoder, its answer does not arrive in time. + monkeypatch.setattr(worker, "_dispatch", ignore_message) + starting = asyncio.ensure_future(recorder.start(command, 0)) + await wait_until(lambda: len(transcoders(tmp_path)) == 1) + monkeypatch.undo() + starting.cancel() + with pytest.raises(asyncio.CancelledError): + await starting + assert not recorder.recording + await recorder.start(command, 0) + assert recorder.recording + await recorder.stop() + assert transcoders(tmp_path) == [] + await worker.close() + + async def wait_for_line(path: pathlib.Path, text: str) -> str: """Wait until the file at ``path`` contains ``text``; return the file.""" for _ in range(300):