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
58 changes: 20 additions & 38 deletions docs/runner-payloads.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down Expand Up @@ -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). |
Expand All @@ -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:
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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.
Expand Down
54 changes: 0 additions & 54 deletions src/livepeer_gateway/_http_continue.py

This file was deleted.

65 changes: 31 additions & 34 deletions src/livepeer_gateway/http.py
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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)
)


Expand Down Expand Up @@ -139,13 +119,22 @@ 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,
*,
method: str | None = None,
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.
Expand All @@ -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)
Expand Down Expand Up @@ -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(
Expand All @@ -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")
Expand Down
38 changes: 33 additions & 5 deletions src/livepeer_gateway/live_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading