diff --git a/docs/runner-payloads.md b/docs/runner-payloads.md index 347f831..7f0aa9a 100644 --- a/docs/runner-payloads.md +++ b/docs/runner-payloads.md @@ -16,7 +16,7 @@ All parameters except `runner_url` must be passed by keyword. | `payload` | `None` | Request body; see [body types](#body-types). | | `content_type` | `None` | Override the request's `Content-Type` header without changing its encoding. | | `method` | `"POST"` | HTTP request method. | -| `signer_url` | `None` | Remote signer URL for automatic payment. Required for paid calls. | +| `signer_url` | `None` | Remote signer URL for automatic payment. Required for on-chain calls. | | `signer_headers` | `None` | Dictionary of additional HTTP headers for signer requests. | | `payment_unit` | `None` | `"hour"`, `"seconds"`, or `"fixed"`. Defaults to the runner's pricing unit; an explicit value must agree with it. With neither, payment uses ongoing funding. | | `timeout` | `5.0` | Seconds per request attempt; see [timeouts](#timeouts) for streaming behavior. | @@ -46,7 +46,6 @@ payload. Bare files and async iterables use the same defaults. | Field | Default | Meaning | |---|---|---| | `source` | Required | A binary file with a synchronous `read()` method, or an async iterable yielding `bytes`. | -| `expect100` | `True` | Send headers first and wait for a continuation response before reading or sending input; see [when input is read](#when-input-is-read). Set to `False` for endpoints without this support. | | `retry_buffer` | `True` | Retain input from non-seekable files and async iterables so it can be sent again on a retry. | | `retry_buffer_memory_limit` | `25_000_000` | Bytes of retained input allowed in memory before using temporary disk storage (25 MB). | | `retry_buffer_limit` | `250_000_000` | Total bytes of input retained for retries (250 MB). | @@ -60,40 +59,24 @@ Seekable files rewind for retries and do not use these limits. ### When input is read Creating a `StreamPayload` or discovering runners does not read the input. -Reading begins during `call_runner()` or `cursor.next()`: with `expect100=True`, -headers are sent first so the runner can request payment or reject the call -before consuming input. The SDK uses aiohttp's native handling: `100 Continue` -normally starts the upload, but other informational `1xx` responses except -`101 Switching Protocols`, such as `102 Processing` or `103 Early Hints`, can -also start it (unexpected informational responses like these are rare in -practice). If waiting for this response times out, the request fails before -reading or sending the body. - -With `expect100=False`, reading starts after the headers are sent. In either -case, input is read as it uploads, starting at the file's current position. -An early response or failure can leave it partly consumed. + +For streaming requests to on-chain single-shot runners, `call_runner(runner=discovered_runner, ...)` +or `cursor.next()` first sends an empty request to the app URL to receive a +`402 Payment Required` challenge. After obtaining payment from the signer, +the SDK sends a second request with payment headers and the streamed body. +Challenge acquisition and signing leave the body unread. + +A failed or rejected upload may leave the source partly consumed. Retrying +requires either rewinding a seekable file or resending the consumed input +from the retry buffer; resending may not be appropriate for all content types +(eg, live video that should stay close to the edge). If resending is not +possible, the SDK raises `LivepeerGatewayError`. You are responsible for closing files and managing generator resources. Keep inputs usable until the call finishes or the response/selector context closes, and do not read them elsewhere during the operation. The examples nest contexts to ensure this. -For an endpoint without `100 Continue` support: - -```python -from livepeer_gateway import StreamPayload, call_runner - - -async def upload(runner_url, path): - with open(path, "rb") as audio: - return await call_runner( - runner_url, - payload=StreamPayload(source=audio, expect100=False), - content_type="audio/wav", - timeout=60, - ) -``` - ## Retries A retry sends the same body in a new request: @@ -116,11 +99,7 @@ must still be usable: - Non-seekable files and async iterables can resend the full body, including after a partial upload, if retry buffering remains available. - With `retry_buffer=False`, non-seekable input can only be retried before reading - starts—for example, after a payment challenge received before upload permission. - -Retry eligibility follows actual input consumption. If an informational response -starts an unbuffered upload before a payment challenge, the consumed input can -prevent an automatic retry. + starts. A required retry raises `LivepeerGatewayError` if the body cannot be sent again. This retry support lasts for one call or selector cursor. For a separate call, @@ -139,10 +118,11 @@ For an app that accepts audio and returns text incrementally: from livepeer_gateway import call_runner -async def transcribe(runner_url, path): +async def transcribe(runner, signer_url, path): with open(path, "rb") as audio: async with await call_runner( - runner_url, + runner=runner, + signer_url=signer_url, payload=audio, content_type="audio/wav", stream=True, @@ -160,7 +140,9 @@ payment funding. Errors while reading a returned response are not retried. | Response mode | What `timeout` bounds per attempt | |---|---| | `stream=False` | The whole HTTP request, including upload and response reading. Increase it for longer uploads or jobs. | -| `stream=True` | Connection establishment and, with `expect100=True`, [waiting for a continuation response](#when-input-is-read). Uploads and response reading have no deadline after that response; with `expect100=False`, only connection establishment is bounded. | +| `stream=True` | Connection establishment only. Uploads and response reading have no deadline. | + +Payment challenge requests use `timeout` for the complete request. Retries can make the overall operation take longer. Use `asyncio.timeout()` around the operation if you need an overall deadline. diff --git a/src/livepeer_gateway/_http_continue.py b/src/livepeer_gateway/_http_continue.py deleted file mode 100644 index d07fc31..0000000 --- a/src/livepeer_gateway/_http_continue.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Bound aiohttp's native continue handshake without replacing response parsing.""" - -from __future__ import annotations - -import asyncio -import contextlib -from typing import Any - -import aiohttp - - -class _ContinueResponse(aiohttp.ClientResponse): - def __init__(self, *args: Any, continue_timeout: float, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self._continue_timeout = continue_timeout - - async def start(self, connection: Any) -> aiohttp.ClientResponse: - continued = self._continue - if continued is None: - return await super().start(connection) - - # aiohttp releases this waiter on any informational response except 101. - # Only the wait is bounded; uploads/final headers can take longer once - # permission arrives. Final headers also end the wait through start(). - waiting = True - async with asyncio.timeout(self._continue_timeout) as handshake: - def allow_upload(future: asyncio.Future[bool]) -> None: - if waiting and not future.cancelled() and not handshake.expired(): - handshake.reschedule(None) - - continued.add_done_callback(allow_upload) - try: - return await super().start(connection) - finally: - waiting = False - continued.remove_done_callback(allow_upload) - - -async def _close_response(response: aiohttp.ClientResponse) -> None: - """Stop and join an attempt's writer before another attempt borrows its state.""" - writer = response._writer - response.close() - await _cancel_writer(writer) - - -async def _cancel_writer(writer: asyncio.Task[None] | None) -> None: - if writer is not None: - writer.cancel() - # aiohttp 3.9 tries write_eof() on cancellation. Its failure after the - # peer closes must not mask a final response that was already received. - with contextlib.suppress( - asyncio.CancelledError, ConnectionError, aiohttp.ClientError - ): - await writer diff --git a/src/livepeer_gateway/http.py b/src/livepeer_gateway/http.py index 9bfec69..9c15c74 100644 --- a/src/livepeer_gateway/http.py +++ b/src/livepeer_gateway/http.py @@ -1,14 +1,12 @@ from __future__ import annotations import json -from functools import partial from typing import Any from urllib.parse import ParseResult, urlparse import aiohttp -from ._http_continue import _ContinueResponse, _close_response -from .runner_payload import RunnerPayload, _StreamState, _UploadBody +from .runner_payload import RunnerPayload, _StreamState, _UploadBody, _cancel_writer from .errors import ( LivepeerHTTPError, LivepeerGatewayError, @@ -84,27 +82,9 @@ def _request_parts( return resolved_method, req_headers, body -def _request_session( - payload: RunnerPayload | _StreamState, - timeout: aiohttp.ClientTimeout, - handshake_timeout: float, -) -> tuple[aiohttp.ClientSession, dict[str, Any]]: - if not isinstance(payload, _StreamState): - return aiohttp.ClientSession(timeout=timeout), {} - session = aiohttp.ClientSession( - timeout=timeout, - response_class=partial(_ContinueResponse, continue_timeout=handshake_timeout), - ) - # aiohttp >= 3.10 may silently retry idempotent requests after disconnect. - # Stream resends are controlled by the SDK's replay state instead. - if hasattr(session, "_retry_connection"): - session._retry_connection = False - return session, {"expect100": payload.config.expect100, "allow_redirects": False} - - -def _request_failed(status: int, payload: RunnerPayload | _StreamState) -> bool: +def _request_failed(status: int, *, allow_redirects: bool) -> bool: return status >= 400 or ( - isinstance(payload, _StreamState) and status in (301, 302, 303, 307, 308) + not allow_redirects and status in (301, 302, 303, 307, 308) ) @@ -139,6 +119,13 @@ def _ensure_json_object(data: Any, *, url: str) -> dict[str, Any]: return data +async def _close_response(response: aiohttp.ClientResponse) -> None: + """Stop and join an attempt's writer before another attempt borrows its state.""" + writer = response._writer + response.close() + await _cancel_writer(writer) + + async def _request_body( url: str, *, @@ -146,6 +133,8 @@ async def _request_body( payload: RunnerPayload | _StreamState = None, headers: dict[str, str] | None = None, timeout: float = 5.0, + allow_redirects: bool = True, + read_response_body: bool = True, ) -> tuple[bytes, str]: """ Make an HTTP request and return the raw response body. @@ -160,11 +149,13 @@ async def _request_body( try: session, resp = await _open_request( url, method=method, payload=payload, headers=headers, - timeout=aiohttp.ClientTimeout(total=timeout), handshake_timeout=timeout, + timeout=aiohttp.ClientTimeout(total=timeout), allow_redirects=allow_redirects, ) async with session: try: - raw = await resp.content.read() if isinstance(payload, _StreamState) else await resp.read() + raw = b"" + if read_response_body: + raw = await resp.content.read() if isinstance(payload, _StreamState) else await resp.read() content_type = resp.content_type or "" finally: await _close_response(resp) @@ -241,14 +232,13 @@ async def open_stream( body, for streaming responses (SSE, chunked). The caller owns both and must close them. - No total/read timeout; bounds connection and optional 100-continue handshake. + No total/read timeout; bounds connection establishment only. Raises LivepeerHTTPError on >= 400 (e.g. the 402 payment retry). """ try: return await _open_request( url, method=method, payload=payload, headers=headers, timeout=aiohttp.ClientTimeout(total=None, sock_connect=connect_timeout, sock_read=None), - handshake_timeout=connect_timeout, ) except (TimeoutError, aiohttp.ClientError) as e: raise LivepeerGatewayError( @@ -263,17 +253,24 @@ async def _open_request( payload: RunnerPayload | _StreamState, headers: dict[str, str] | None, timeout: aiohttp.ClientTimeout, - handshake_timeout: float, + allow_redirects: bool = True, ) -> tuple[aiohttp.ClientSession, aiohttp.ClientResponse]: method, headers, body = _request_parts(url, method=method, payload=payload, headers=headers) - session, options = _request_session(payload, timeout, handshake_timeout) - if payload is None: - # aiohttp otherwise adds application/octet-stream even for an empty POST. - options["skip_auto_headers"] = {"Content-Type"} + session = aiohttp.ClientSession(timeout=timeout) + if isinstance(payload, _StreamState): + allow_redirects = False + # aiohttp >= 3.10 may silently retry idempotent requests after disconnect. + # Stream resends are controlled by the SDK's replay state instead. + if hasattr(session, "_retry_connection"): + session._retry_connection = False resp = None try: - resp = await session.request(method, url, data=body, headers=headers, **options) - if _request_failed(resp.status, payload): + resp = await session.request( + method, url, data=body, headers=headers, allow_redirects=allow_redirects, + # aiohttp otherwise adds application/octet-stream even for an empty POST. + skip_auto_headers={"Content-Type"} if payload is None else None, + ) + if _request_failed(resp.status, allow_redirects=allow_redirects): # Read before cancelling the writer: aiohttp 3.13 closes the socket # on cancellation, which can discard a fragmented payment challenge. raw = (await resp.content.read()).decode(errors="replace") diff --git a/src/livepeer_gateway/live_runner.py b/src/livepeer_gateway/live_runner.py index 48e77ed..6e2afd0 100644 --- a/src/livepeer_gateway/live_runner.py +++ b/src/livepeer_gateway/live_runner.py @@ -10,7 +10,7 @@ import shutil import subprocess from dataclasses import dataclass, field, replace -from decimal import Decimal +from decimal import Decimal, InvalidOperation from typing import ( Any, Literal, @@ -26,10 +26,9 @@ import aiohttp from aiohttp.helpers import parse_mimetype -from ._http_continue import _close_response from .channel_reader import ChannelReader from .errors import LivepeerGatewayError, LivepeerHTTPError, SignerRefreshRequired -from .http import _post_empty, _request_body, open_stream, post_json, request_json +from .http import _close_response, _post_empty, _request_body, open_stream, post_json, request_json from .remote_signer import ( LivePaymentChallenge, LivePaymentSession, @@ -843,7 +842,10 @@ async def call_runner( send raw data. ``content_type`` overrides the default ``application/json`` for dictionaries or ``application/octet-stream`` for other bodies. Omitted/None payloads send an empty body. Bare files and async byte iterables - use StreamPayload defaults (100-continue and bounded replay buffering). + use StreamPayload defaults (bounded replay buffering). For single-shot, + on-chain runners, an empty request acquires the payment challenge before + the source is read. A rejected on-chain upload may still consume input, so + retries require replayability. """ state = _stream_state(payload) owned = state is not None and not isinstance(payload, _StreamState) @@ -853,6 +855,7 @@ async def call_runner( if not runner_url: raise LivepeerGatewayError("Live runner call requires runner_url") payment_type = _runner_payment_type(runner, payment_unit) if signer_url else "" + probe_for_payment = state is not None and _is_onchain_single_shot(runner) max_price: LiveRunnerPriceInfo | None = None if signer_url and runner is not None and runner.price_info is not None: max_price = _pad_runner_price(runner.price_info) @@ -907,6 +910,21 @@ async def call_runner( needs_ongoing_funding = payment_type == "live" try: + if probe_for_payment and challenge is None: + state.require_replayable() + # A complete empty request can traverse tunnels without an + # early continuation response releasing the upload source. + await _request_body( + runner_url, + method=method, + headers=request_headers, + timeout=timeout, + allow_redirects=False, + read_response_body=False, + ) + raise LivepeerGatewayError( + f"Live runner payment challenge request expected HTTP 402 (url={runner_url})" + ) if stream: # Payment challenges are handled before returning a live response. session, resp = await open_stream( @@ -980,7 +998,7 @@ async def call_runner( if e.status_code != 402: raise if not signer_url: - raise LivepeerGatewayError("Live runner paid call requires signer_url") from e + raise LivepeerGatewayError("Live runner on-chain call requires signer_url") from e if state is not None: state.require_replayable(e) challenge = _parse_runner_payment_challenge(e) @@ -1040,6 +1058,16 @@ async def _stop_funding(task: asyncio.Task[None] | None) -> None: await task +def _is_onchain_single_shot(runner: LiveRunnerInstance | None) -> bool: + if runner is None or runner.mode != "single-shot" or runner.price_info is None: + return False + try: + price = Decimal(str(runner.price_info.price).strip()) + except InvalidOperation: + return False + return price.is_finite() and price > 0 + + def _runner_payment_type( runner: LiveRunnerInstance | None, payment_unit: str | None = None, diff --git a/src/livepeer_gateway/runner_payload.py b/src/livepeer_gateway/runner_payload.py index f127cd4..66ddb3d 100644 --- a/src/livepeer_gateway/runner_payload.py +++ b/src/livepeer_gateway/runner_payload.py @@ -12,9 +12,9 @@ from dataclasses import dataclass from typing import Any, BinaryIO +import aiohttp from aiohttp.payload import Payload -from ._http_continue import _cancel_writer from .errors import LivepeerGatewayError _LOG = logging.getLogger(__name__) @@ -23,7 +23,7 @@ @dataclass(frozen=True, kw_only=True) class StreamPayload: - """A caller-owned source with 100-continue and bounded replay buffering. + """A caller-owned source with bounded replay buffering. Limits are decimal bytes. Overflow or storage failure disables later retries without interrupting the upload. Seekable files rewind instead of buffering, @@ -31,7 +31,6 @@ class StreamPayload: """ source: AsyncIterable[bytes] | BinaryIO - expect100: bool = True retry_buffer: bool = True retry_buffer_memory_limit: int = 25_000_000 retry_buffer_limit: int = 250_000_000 @@ -70,6 +69,17 @@ async def _file_io[T](operation: Callable[[], T], *, threaded: bool = True) -> T raise +async def _cancel_writer(writer: asyncio.Task[None] | None) -> None: + if writer is not None: + writer.cancel() + # aiohttp 3.9 tries write_eof() on cancellation. Its failure after the + # peer closes must not mask a final response that was already received. + with contextlib.suppress( + asyncio.CancelledError, ConnectionError, aiohttp.ClientError + ): + await writer + + class _StreamState: def __init__(self, config: StreamPayload) -> None: self.config = config diff --git a/tests/test_call_runner_uploads.py b/tests/test_call_runner_uploads.py index 21a6c75..b256aac 100644 --- a/tests/test_call_runner_uploads.py +++ b/tests/test_call_runner_uploads.py @@ -11,6 +11,7 @@ from livepeer_gateway import ( LiveRunnerInstance, + LiveRunnerPriceInfo, RunnerSelectionCursor, StreamPayload, call_runner, @@ -20,6 +21,7 @@ LivepeerGatewayError, LivepeerHTTPError, NoRunnerAvailableError, + SignerRefreshRequired, ) @@ -89,10 +91,14 @@ async def connected(reader, writer): raise errors[0] -async def headers(reader): +async def headers(reader, *, expected_request=None): raw = await reader.readuntil(b"\r\n\r\n") lines = raw.decode().split("\r\n") - return dict(line.split(": ", 1) for line in lines[1:] if line) + if expected_request is not None: + assert lines[0] == expected_request + result = dict(line.split(": ", 1) for line in lines[1:] if line) + assert "Expect" not in result + return result async def body(reader, request_headers): @@ -132,11 +138,6 @@ async def respond(writer, status=200, data=None, *, fragment=False, location=Non await writer.drain() -async def allow_upload(writer): - writer.write(b"HTTP/1.1 100 Continue\r\n\r\n") - await writer.drain() - - class Source: def __init__(self, *chunks): self.chunks = iter(chunks) @@ -159,8 +160,11 @@ async def aclose(self): self.closed = True -def candidate(url): - return LiveRunnerInstance(url, "test", "runner", "single-shot", url, {}) +def candidate(url, *, price=None, mode="single-shot"): + return LiveRunnerInstance( + url, "test", "runner", mode, url, {}, + price_info=LiveRunnerPriceInfo(price, "wei", "fixed") if price is not None else None, + ) CUSTOM_TYPE = "application/vnd.test+json; charset=utf-8" @@ -186,14 +190,13 @@ def candidate(url): async def test_request_bodies(kwargs, expected, content_type, stream): async def handler(reader, writer): request_headers = await headers(reader) - assert "Expect" not in request_headers assert request_headers["Accept"] == "*/*" assert request_headers.get("Content-Type") == content_type assert await body(reader, request_headers) == expected await respond(writer) async with serve(handler) as url: - result = await call_runner(url, stream=stream, **kwargs) + result = await call_runner(url, runner=candidate(url, price=10), stream=stream, **kwargs) if stream: async with result: assert json.loads(b"".join([chunk async for chunk in result.aiter_bytes()])) == {"ok": True} @@ -202,40 +205,47 @@ async def handler(reader, writer): @pytest.mark.parametrize("stream", [False, True]) -async def test_early_payment_challenge_does_not_touch_source( - stream, signer, no_loop_errors -): +@pytest.mark.parametrize("refresh", [False, True]) +async def test_payment_challenge_does_not_touch_source(stream, refresh, signer, no_loop_errors): source = Source(b"one", b"two") attempts = 0 sessions = [] + async def sign(*args, **kwargs): + assert source.iterations == source.reads == 0 + if refresh and signer.await_count == 1: + raise SignerRefreshRequired("refresh") + return signer.return_value + + signer.side_effect = sign + async def handler(reader, writer): nonlocal attempts - request_headers = await headers(reader) + request_headers = await headers(reader, expected_request="PATCH /upload?model=test HTTP/1.1") attempts += 1 - assert request_headers["Expect"] == "100-continue" - if attempts == 1: + assert request_headers["Livepeer-Payer-Address"] == "payer" + if "Livepeer-Payment" not in request_headers: assert source.iterations == source.reads == 0 + assert request_headers["Content-Length"] == "0" + assert "Transfer-Encoding" not in request_headers + assert await body(reader, request_headers) == b"" + writer.write(b"HTTP/1.1 100 Continue\r\n\r\n") + await writer.drain() await respond(writer, 402, CHALLENGE, fragment=True) assert await reader.read() == b"" return assert request_headers["Livepeer-Payment"] == "paid" + assert request_headers["Livepeer-Segment"] == "segment" assert [session.manifest_id for session in sessions] == [CHALLENGE["manifest_id"]] - assert source.iterations == source.reads == 0 - await allow_upload(writer) assert await body(reader, request_headers) == b"onetwo" await respond(writer) async with serve(handler) as url: - # Cancelling the upload writer as soon as final headers arrive can - # discard a fragmented 402 body on newer aiohttp. Bound the whole test - # so a regression fails rather than waiting forever for payment JSON. result = await asyncio.wait_for( call_runner( - url, - payload=StreamPayload(source=source, retry_buffer=False), + url + "/upload?model=test", runner=candidate("http://unused", price="10"), + payload=StreamPayload(source=source, retry_buffer=False), method="PATCH", signer_url="http://signer.example", - payment_unit="fixed", on_payment_session=sessions.append, stream=stream, ), @@ -243,16 +253,17 @@ async def handler(reader, writer): ) if stream: await result.aclose() - assert attempts == 2 + assert attempts == (3 if refresh else 2) assert source.reads == 3 assert not source.closed - signer.assert_awaited_once() + assert signer.await_count == (2 if refresh else 1) payment_request = signer.call_args.args[1] assert payment_request["orchestrator"] == CHALLENGE["payment_params"] assert payment_request["ManifestID"] == CHALLENGE["manifest_id"] + assert payment_request["maxPrice"] == {"price": 10.12, "currency": "wei", "unit": "fixed"} -@pytest.mark.parametrize("status,kind", [(402, "nonseekable"), (503, "iterator"), (307, "file")]) +@pytest.mark.parametrize("status,kind", [(402, "nonseekable"), (503, "iterator"), (307, "file"), (200, "iterator")]) async def test_early_rejection_preserves_source_for_next_candidate(tmp_path, status, kind): class NonSeekable(io.BytesIO): def seekable(self): @@ -277,21 +288,20 @@ def assert_unread(): assert source.tell() == (5 if kind == "file" else 0) async def reject(reader, writer): - await headers(reader) + request_headers = await headers(reader) + assert await body(reader, request_headers) == b"" assert_unread() await respond(writer, status, location=second if status == 307 else None) assert await reader.read() == b"" async def accept(reader, writer): request_headers = await headers(reader) - assert_unread() - await allow_upload(writer) assert await body(reader, request_headers) == b"body" await respond(writer) async with serve(reject) as first, serve(accept) as second: payload = source if kind == "file" else StreamPayload(source=source, retry_buffer=False) - async with RunnerSelectionCursor([candidate(first), candidate(second)], body=payload) as cursor: + async with RunnerSelectionCursor([candidate(first, price=10), candidate(second)], body=payload) as cursor: result = await cursor.next() assert result.data == {"ok": True} and result.runner_url == second assert len(cursor.rejections) == 1 @@ -299,35 +309,62 @@ async def accept(reader, writer): @pytest.mark.parametrize("stream", [False, True]) -async def test_expect_timeout_aborts_without_consumption(stream, no_loop_errors): +@pytest.mark.parametrize("status,match", [(None, "failed to reach endpoint"), (200, "expected HTTP 402")]) +async def test_incomplete_challenge_leaves_source_unread(stream, status, match, no_loop_errors): source = Source(b"never") async def handler(reader, writer): - await headers(reader) + assert await body(reader, await headers(reader)) == b"" + if status == 200: + writer.write(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n") + await writer.drain() assert await reader.read() == b"" async with serve(handler) as url: - with pytest.raises(LivepeerGatewayError): + with pytest.raises(LivepeerGatewayError, match=match): await asyncio.wait_for( - call_runner(url, payload=source, stream=stream, timeout=0.05), 1 + call_runner( + runner=candidate(url, price=10), payload=source, stream=stream, + timeout=0.05 if status is None else 10, + ), + 1, ) assert source.iterations == source.reads == 0 assert not source.closed @pytest.mark.parametrize("stream", [False, True]) -async def test_expect_can_be_disabled(stream): +async def test_closed_source_is_rejected_before_challenge(stream, signer): + source = io.BytesIO(b"data") + source.close() + with mock.patch.object(live_runner, "_request_body", new_callable=mock.AsyncMock) as request: + with pytest.raises(LivepeerGatewayError, match="no longer replayable"): + await call_runner( + runner=candidate("http://unused", price=10), payload=source, + signer_url="http://signer.example", stream=stream, + ) + request.assert_not_called() + signer.assert_not_called() + + +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("price,mode", [ + (None, "single-shot"), (0, "single-shot"), ("0.0", "single-shot"), + (-1, "single-shot"), ("unknown", "single-shot"), ("NaN", "single-shot"), + ("Infinity", "single-shot"), (10, "persistent"), (10, ""), (10, "unknown"), +]) +async def test_ordinary_upload_starts_immediately(stream, price, mode): source = Source(b"direct") async def handler(reader, writer): request_headers = await headers(reader) - assert "Expect" not in request_headers assert await body(reader, request_headers) == b"direct" await respond(writer) async with serve(handler) as url: result = await call_runner( - url, payload=StreamPayload(source=source, expect100=False), stream=stream + runner=candidate(url, price=price, mode=mode), + payload=StreamPayload(source=source), stream=stream, ) if stream: await result.aclose() @@ -341,7 +378,6 @@ async def test_buffered_upload_can_be_reused_by_cursor_until_close(): async def handler(reader, writer): request_headers = await headers(reader) assert request_headers["Content-Type"] == "video/test" - await allow_upload(writer) received.append(await body(reader, request_headers)) await respond(writer) @@ -368,7 +404,6 @@ async def test_seekable_file_replays_from_initial_position_without_buffering(): async def handler(reader, writer): request_headers = await headers(reader) - await allow_upload(writer) received.append(await body(reader, request_headers)) await respond(writer, 503 if len(received) == 1 else 200) @@ -395,7 +430,6 @@ async def handler(reader, writer): nonlocal attempts attempts += 1 request_headers = await headers(reader) - await allow_upload(writer) assert await body(reader, request_headers) == b"prefixover-limittail" await respond(writer, 503) @@ -416,7 +450,6 @@ async def test_exhausted_cursor_releases_cache(success): async def handler(reader, writer): request_headers = await headers(reader) - await allow_upload(writer) await body(reader, request_headers) await respond(writer, 200 if success else 503) @@ -457,14 +490,12 @@ async def reject(reader, writer): nonlocal rejections rejections += 1 await headers(reader) - await allow_upload(writer) assert await read_chunk(reader) == b"prefix" await read_started.wait() async def accept(reader, writer): request_headers = await headers(reader) assert not source_cancelled - await allow_upload(writer) assert await read_chunk(reader) == b"prefix" finish_read.set() assert await body(reader, request_headers) == b"middletail" @@ -481,7 +512,8 @@ async def accept(reader, writer): @pytest.mark.parametrize("stream", [False, True]) -async def test_partial_upload_payment_retry_replays_prefix(stream, signer): +@pytest.mark.parametrize("known_onchain", [False, True]) +async def test_partial_upload_payment_retry_replays_prefix(stream, known_onchain, signer): read_started = asyncio.Event() finish_read = asyncio.Event() attempts = 0 @@ -496,9 +528,12 @@ async def handler(reader, writer): nonlocal attempts request_headers = await headers(reader) attempts += 1 - await allow_upload(writer) + if known_onchain and attempts == 1: + assert await body(reader, request_headers) == b"" + await respond(writer, 402, CHALLENGE, fragment=True) + return assert await read_chunk(reader) == b"prefix" - if attempts == 1: + if attempts == (2 if known_onchain else 1): await read_started.wait() await respond(writer, 402, CHALLENGE, fragment=True) else: @@ -510,7 +545,7 @@ async def handler(reader, writer): async with serve(handler) as url: result = await asyncio.wait_for( call_runner( - url, + runner=candidate(url, price=10 if known_onchain else None), payload=source(), signer_url="http://signer.example", payment_unit="fixed", @@ -520,17 +555,21 @@ async def handler(reader, writer): ) if stream: await result.aclose() - signer.assert_awaited_once() - assert attempts == 2 + assert signer.await_count == (2 if known_onchain else 1) + assert attempts == (3 if known_onchain else 2) @pytest.mark.parametrize("mode", ["buffered", "stream", "cursor"]) -async def test_unbuffered_consumed_body_is_not_paid_or_retried(mode, signer): +@pytest.mark.parametrize("known_onchain", [False, True]) +async def test_unbuffered_consumed_body_is_not_paid_again_or_retried(mode, known_onchain, signer): source = Source(b"data") async def handler(reader, writer): request_headers = await headers(reader) - await allow_upload(writer) + if known_onchain and "Livepeer-Payment" not in request_headers: + assert await body(reader, request_headers) == b"" + await respond(writer, 402, CHALLENGE) + return assert await body(reader, request_headers) == b"data" await respond(writer, 402, CHALLENGE) @@ -539,12 +578,13 @@ async def handler(reader, writer): LivepeerGatewayError, match="no longer replayable" ) as error: payload = StreamPayload(source=source, retry_buffer=False) + runner = candidate(url, price=10 if known_onchain else None) if mode == "cursor": - await RunnerSelectionCursor([candidate(url)], body=payload, signer_url="http://signer.example").next() + await RunnerSelectionCursor([runner], body=payload, signer_url="http://signer.example").next() else: - await call_runner(url, payload=payload, signer_url="http://signer.example", payment_unit="fixed", stream=mode == "stream") + await call_runner(runner=runner, payload=payload, signer_url="http://signer.example", payment_unit="fixed", stream=mode == "stream") assert isinstance(error.value.__cause__, LivepeerHTTPError) - signer.assert_not_called() + assert signer.await_count == (1 if known_onchain else 0) @pytest.mark.parametrize("stream", [False, True]) @@ -558,7 +598,6 @@ async def source(): async def handler(reader, writer): await headers(reader) - await allow_upload(writer) assert await read_chunk(reader) == b"prefix" await reader.read() @@ -596,7 +635,6 @@ async def source(): async def handler(reader, writer): await headers(reader) - await allow_upload(writer) assert await read_chunk(reader) == b"prefix" await read_started.wait() # Send response headers while the request source is still live. @@ -616,17 +654,13 @@ async def handler(reader, writer): @pytest.mark.parametrize("stream", [False, True]) -async def test_response_mode_controls_timeout_after_continue(stream): +async def test_response_mode_controls_upload_timeout(stream): async def source(): await asyncio.sleep(0.1) yield b"delayed" async def handler(reader, writer): request_headers = await headers(reader) - # Native aiohttp also accepts 103 as permission; exercise that here - # while checking that permission ends only the continue-wait deadline. - writer.write(b"HTTP/1.1 103 Early Hints\r\n\r\n") - await writer.drain() assert await body(reader, request_headers) == b"delayed" await respond(writer)