action0-req 0.1.1__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. {action0_req-0.1.1 → action0_req-0.2.0}/.github/workflows/ci.yml +9 -9
  2. {action0_req-0.1.1 → action0_req-0.2.0}/.github/workflows/release.yml +4 -4
  3. action0_req-0.2.0/CHANGELOG.md +70 -0
  4. {action0_req-0.1.1 → action0_req-0.2.0}/CLAUDE.md +2 -2
  5. {action0_req-0.1.1 → action0_req-0.2.0}/PKG-INFO +23 -5
  6. {action0_req-0.1.1 → action0_req-0.2.0}/README.md +21 -3
  7. {action0_req-0.1.1 → action0_req-0.2.0}/docs/api.md +2 -1
  8. action0_req-0.2.0/docs/changelog.md +2 -0
  9. {action0_req-0.1.1 → action0_req-0.2.0}/docs/index.md +5 -0
  10. {action0_req-0.1.1 → action0_req-0.2.0}/docs/usage.md +260 -2
  11. {action0_req-0.1.1 → action0_req-0.2.0}/pyproject.toml +1 -0
  12. {action0_req-0.1.1 → action0_req-0.2.0}/src/action0/req/__init__.py +7 -1
  13. action0_req-0.2.0/src/action0/req/body.py +1628 -0
  14. action0_req-0.2.0/src/action0/req/response.py +518 -0
  15. action0_req-0.2.0/tests/action0/req/test_body.py +2022 -0
  16. action0_req-0.2.0/tests/action0/req/test_response.py +1051 -0
  17. {action0_req-0.1.1 → action0_req-0.2.0}/uv.lock +106 -1
  18. action0_req-0.1.1/src/action0/req/body.py +0 -396
  19. action0_req-0.1.1/src/action0/req/response.py +0 -248
  20. action0_req-0.1.1/tests/action0/req/test_body.py +0 -234
  21. action0_req-0.1.1/tests/action0/req/test_response.py +0 -269
  22. {action0_req-0.1.1 → action0_req-0.2.0}/.gitignore +0 -0
  23. {action0_req-0.1.1 → action0_req-0.2.0}/.python-version +0 -0
  24. {action0_req-0.1.1 → action0_req-0.2.0}/LICENSE +0 -0
  25. {action0_req-0.1.1 → action0_req-0.2.0}/docs/conf.py +0 -0
  26. {action0_req-0.1.1 → action0_req-0.2.0}/src/action0/req/headers.py +0 -0
  27. {action0_req-0.1.1 → action0_req-0.2.0}/src/action0/req/py.typed +0 -0
  28. {action0_req-0.1.1 → action0_req-0.2.0}/src/action0/req/request.py +0 -0
  29. {action0_req-0.1.1 → action0_req-0.2.0}/src/action0/req/status.py +0 -0
  30. {action0_req-0.1.1 → action0_req-0.2.0}/tests/action0/req/test_headers.py +0 -0
  31. {action0_req-0.1.1 → action0_req-0.2.0}/tests/action0/req/test_init.py +0 -0
  32. {action0_req-0.1.1 → action0_req-0.2.0}/tests/action0/req/test_request.py +0 -0
  33. {action0_req-0.1.1 → action0_req-0.2.0}/tests/action0/req/test_status.py +0 -0
@@ -19,19 +19,19 @@ jobs:
19
19
  strategy:
20
20
  fail-fast: false
21
21
  matrix:
22
- python-version: ["3.11", "3.12", "3.13", "3.14"]
22
+ python-version: ["3.11", "3.12", "3.13", "3.14", "3.15"]
23
23
  experimental: [false]
24
24
  include:
25
- # 3.15 is still a pre-release: run it, but don't fail the whole
25
+ # 3.16 is still a pre-release: run it, but don't fail the whole
26
26
  # workflow while parts of the toolchain don't support it yet
27
- - python-version: "3.15"
27
+ - python-version: "3.16"
28
28
  experimental: true
29
29
 
30
30
  steps:
31
- - uses: actions/checkout@v4
31
+ - uses: actions/checkout@v7
32
32
 
33
33
  - name: Install uv
34
- uses: astral-sh/setup-uv@v6
34
+ uses: astral-sh/setup-uv@v10.0.1
35
35
  with:
36
36
  python-version: ${{ matrix.python-version }}
37
37
 
@@ -60,10 +60,10 @@ jobs:
60
60
  name: docs build
61
61
  runs-on: ubuntu-latest
62
62
  steps:
63
- - uses: actions/checkout@v4
63
+ - uses: actions/checkout@v7
64
64
 
65
65
  - name: Install uv
66
- uses: astral-sh/setup-uv@v6
66
+ uses: astral-sh/setup-uv@v10.0.1
67
67
 
68
68
  - name: Install dependencies
69
69
  run: uv sync --locked --group docs
@@ -72,7 +72,7 @@ jobs:
72
72
  run: uv run --group docs sphinx-build -W --keep-going -b html docs docs/_build/html
73
73
 
74
74
  - name: Upload pages artifact
75
- uses: actions/upload-pages-artifact@v3
75
+ uses: actions/upload-pages-artifact@v5
76
76
  with:
77
77
  path: docs/_build/html
78
78
 
@@ -96,4 +96,4 @@ jobs:
96
96
  steps:
97
97
  - name: Deploy to GitHub Pages
98
98
  id: deployment
99
- uses: actions/deploy-pages@v4
99
+ uses: actions/deploy-pages@v5
@@ -9,10 +9,10 @@ jobs:
9
9
  name: check and build
10
10
  runs-on: ubuntu-latest
11
11
  steps:
12
- - uses: actions/checkout@v4
12
+ - uses: actions/checkout@v7
13
13
 
14
14
  - name: Install uv
15
- uses: astral-sh/setup-uv@v6
15
+ uses: astral-sh/setup-uv@v10.0.1
16
16
 
17
17
  - name: Install dependencies
18
18
  run: uv sync --locked
@@ -37,7 +37,7 @@ jobs:
37
37
  - name: Build sdist and wheel
38
38
  run: uv build
39
39
 
40
- - uses: actions/upload-artifact@v4
40
+ - uses: actions/upload-artifact@v7
41
41
  with:
42
42
  name: dist
43
43
  path: dist/
@@ -53,7 +53,7 @@ jobs:
53
53
  # OIDC token for PyPI trusted publishing
54
54
  id-token: write
55
55
  steps:
56
- - uses: actions/download-artifact@v4
56
+ - uses: actions/download-artifact@v8
57
57
  with:
58
58
  name: dist
59
59
  path: dist/
@@ -0,0 +1,70 @@
1
+ # Changelog
2
+
3
+ All notable changes to action0-req are listed here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the version
5
+ numbers follow [Semantic Versioning](https://semver.org/).
6
+
7
+ ## 0.2.0 — 2026-11-26
8
+
9
+ ### Added
10
+
11
+ - `SpooledBody`: a body producer that is written first and read
12
+ afterwards. It keeps the data in memory up to `max_memory` bytes and
13
+ moves it to an anonymous temporary file beyond that. It is re-readable,
14
+ also by several consumers at once, offers read-only, seekable file
15
+ views via `file()`, and is removed deterministically by `close()` or a
16
+ `with` block. `awrite()`, `achunks()` and `aclose()` do their file I/O
17
+ in a worker thread.
18
+ - `Response.body_file()`: the response body as a seekable binary file
19
+ object, whatever form the body has. A streamed body is spooled, and
20
+ the stream closed; a `FileBody` hands out its file without a copy
21
+ (`FileBody.close()` closes a file opened for that).
22
+ - `Response.save_body()` and `Response.asave_body()`, plus the functions
23
+ `save_body()` and `asave_body()`: copy a body into a path or an open
24
+ file object chunk by chunk, with `append=True` for resumed downloads.
25
+ A path is opened only once the body has delivered its first chunk, so
26
+ a body that cannot be read leaves an existing file untouched. A write
27
+ that fails closes the stream.
28
+ - `Response.close()` and `Response.aclose()`; a response is now a sync
29
+ and async context manager. They release what the body holds and do
30
+ nothing for in-memory bodies. When a `with` block is left by an
31
+ exception, a failure to close is attached to that exception as a note
32
+ instead of replacing it.
33
+ - `IterableBody(..., close=...)` and `AsyncIterableBody(..., aclose=...)`:
34
+ a callback releasing the resource behind the stream. It runs exactly
35
+ once: after the body has been consumed, when a consumer stops early,
36
+ or on `close()` / `aclose()`. Both classes are context managers.
37
+ Closing also closes a generator behind the body, so one that was read
38
+ in part runs its `finally` blocks right away.
39
+ `AsyncIterableBody.close()` is the synchronous counterpart for a body
40
+ with nothing left to release; it raises while the callback is pending.
41
+ - trio support for asynchronous file I/O: `FileBody.achunks()` and the
42
+ new asynchronous file operations use trio's thread pool when running
43
+ below trio. Before, `FileBody.achunks()` worked on asyncio only.
44
+ Cleanup — closing a file, writing out what has arrived — also runs
45
+ when the task has been cancelled.
46
+
47
+ ### Fixed
48
+
49
+ - `FileBody.achunks()` no longer leaves the file it opened unclosed when
50
+ the consuming task is cancelled: the close also runs when the task is
51
+ cancelled repeatedly, as anyio does on a timeout.
52
+ - `FileBody.achunks()` on asyncio: a cancelled read of a regular file or
53
+ a seekable file object is finished before the cancellation is passed
54
+ on, so it no longer moves the file position under the next reader. A
55
+ source that may block for good (a named pipe, a device, a non-seekable
56
+ file object) is still left behind at once — now in a daemon thread of
57
+ its own, which neither occupies the loop's thread pool nor delays its
58
+ shutdown, and which closes the file it opened.
59
+
60
+ ## 0.1.1 — 2026-08-08
61
+
62
+ ### Changed
63
+
64
+ - Installation instructions: the package is published on PyPI.
65
+
66
+ ## 0.1.0 — 2026-08-08
67
+
68
+ First release: the `Header`, `Status` and `Method` constants, `Headers`,
69
+ `Request`, `Response` and the `BodyProducer` protocol with `BytesBody`,
70
+ `FileBody`, `IterableBody` and `AsyncIterableBody`.
@@ -44,8 +44,8 @@ The package is being built up module by module under `src/action0/req/`. Planned
44
44
  - `headers.py` — `Headers`: ordered, case-insensitive, multi-value aware mapping of header fields, internally a `list[tuple[str, str]]` of lines preserving the representation (order and casing) exactly. The `MutableMapping` view is single-value (last line per field, like `Params`); `get_all()`/`get_values()` (RFC 9110 comma-splitting)/`add()`/`set()`/`remove()`/`update()`/`as_lines()`/`as_dict()`/`as_str()` handle multiple lines. No underscore→dash normalization (header smuggling footgun). `__eq__` ignores field order and name casing but respects per-field line order; `repr()`/`str()` redact the values of `Headers.secret_names` with `***` — only the wire rendering `as_str()` keeps them. Also `Header`: `StrEnum` of the IANA HTTP field name registry (permanent + deprecated + provisional registrations, generated from the registry CSV on 2026-08-07) plus a block of unregistered de-facto `X-…` names.
45
45
  - `status.py` — `Status`: custom `IntEnum` of the IANA status code registry with `phrase` and `is_informational`/`is_success`/`is_redirection`/`is_client_error`/`is_server_error` properties. Deliberately not `http.HTTPStatus`: the stdlib's code list and category properties vary across 3.11–3.15. Two pre-RFC-9110 aliases (`PAYLOAD_TOO_LARGE`, `UNPROCESSABLE_ENTITY`).
46
46
  - `request.py` — `Method`: `StrEnum` of the RFC 9110 verbs + `PATCH` + `QUERY`. `Request`: method (uppercased str), `url` (`action0.url.Url` — copied on ingestion, `query=` kwarg replaces the URL's query like the `Url` constructor), `headers` (`Headers`), `body` (`bytes | str | BodyProducer | None`, stored as set), `http_version` and a `meta` dict (application metadata: never on the wire, excluded from `__eq__`, shallow-copied by `copy()`; the constructor copies the given mapping) as plain attributes. Typed body accessors `body_bytes()`/`body_str()`/`body_producer()` convert between the three forms using the Content-Type charset (default utf-8). `copy(**overrides)` (own `Url`/`Headers`; a `BodyProducer` body is shared), part-wise `__eq__` (body compared as set), `repr()` redacts via `Url.__repr__` and omits headers/body, `as_str(include_body=False, separator="\r\n")` renders the wire format with origin-form target and derived `Host` (secrets included; a `BodyProducer` is never consumed — placeholder).
47
- - `body.py` — `BodyProducer`: runtime-checkable `Protocol` for streaming bodies: `content_length()` (`None` = unknown), sync `chunks()`, async `achunks()`, `as_bytes()`. Implementations: `BytesBody` (in-memory, single chunk), `FileBody` (path or open binary file object + `chunk_size`; paths open freshly per iteration → re-iterable, seekable file objects are rewound per iteration and never closed, non-seekable ones are single-use with unknown length; `achunks()` does all file ops via `asyncio.to_thread`), `IterableBody` (wraps `Iterable[bytes]`, unknown length, generator sources single-use), `AsyncIterableBody` (wraps `AsyncIterable[bytes]`, async-only: sync `chunks()`/`as_bytes()` raise `RuntimeError`). Also the `BodyTypes` alias and the private conversion helpers (`_charset`, `_body_bytes`/`_body_str`/`_body_producer`, `_rendered_body`) shared by `Request` and `Response` — the classes keep their own thin, documented accessor methods.
48
- - `response.py` — `Response`: `status` (any int; `Status` members welcome), `headers`, `body`, `reason` (server-sent phrase; the `phrase` property falls back to the `Status` registry, `""` for unknown codes), `http_version`, an optional `request` back-reference (metadata: shared, not copied, excluded from `__eq__`) and a `meta` dict like `Request`'s. Category properties (`is_success`, …) computed from the numeric range so unregistered codes work. Same body accessors as `Request`; `copy(**overrides)`, `as_str(include_body, separator)` with status line, redacting-by-omission `repr()` (`Response(404 Not Found)`).
47
+ - `body.py` — `BodyProducer`: runtime-checkable `Protocol` for streaming bodies: `content_length()` (`None` = unknown), sync `chunks()`, async `achunks()`, `as_bytes()`. Implementations: `BytesBody` (in-memory, single chunk), `FileBody` (path or open binary file object + `chunk_size`; paths open freshly per iteration → re-iterable, seekable file objects are rewound per iteration and never closed, non-seekable ones are single-use with unknown length; `achunks()` does all file ops in a worker thread via the private `_in_thread` helper: `asyncio.to_thread`, or — when there is no running asyncio loop but `trio` is in `sys.modules` — `trio.to_thread.run_sync`; trio is never imported — it is a dev dependency for the tests only. Three dispatch variants: `_in_thread` never abandons a started call — on asyncio it waits for it through cancellations and re-raises afterwards (the result is lost then, so code opening a file in a thread records the handle itself); `_in_thread_shielded`, for cleanup (closing a file, the final flush), on trio also starts in a scope that is cancelled already; `_in_thread_abandonable` leaves the thread behind on cancellation — on asyncio a daemon thread of its own (`_in_daemon_thread`) instead of the loop's pool, on trio `abandon_on_cancel` (`cancellable` before 0.23). `FileBody.achunks()` uses it only for what may block for good: a path that is not a regular file (open and reads; the private `_OwnedFile` lets the abandoned call close the file) and a non-seekable file object. Regular files and seekable file objects are read with `_in_thread`, so a cancelled read never moves the position under the next reader. For `Response.body_file()` a `FileBody` hands out its seekable file via the private `_file_view()`: the given file object, or for the path of a regular file a newly opened file per call, tracked and closed by its public `close()`; `None` (→ spooled) for non-seekable/non-regular sources and for subclasses overriding `chunks()`/`achunks()`/`as_bytes()`), `IterableBody` (wraps `Iterable[bytes]`, unknown length, generator sources single-use; optional `close=` callback run exactly once — after consumption, on abandoned iteration or on `close()` — because a never-started generator's `finally` does not run; `close()` also closes a generator source — generators only, other iterables with a `close()` are left alone, and not a generator that is running right now: then the callback is what releases, and without one `close()` raises `RuntimeError`), `AsyncIterableBody` (wraps `AsyncIterable[bytes]`, async-only: sync `chunks()`/`as_bytes()` raise `RuntimeError`; `aclose=` callback/`aclose()` as the async twin; `aclose()` also closes an async generator source unless another task is running in it (then as in `IterableBody`: callback, or `RuntimeError` without one); the sync `close()` is a no-op unless the callback is still pending or a started async generator is still open — then it raises `RuntimeError`), `SpooledBody` (written first, read afterwards: a `SpooledTemporaryFile` with its automatic rollover turned off — the class rolls over itself once `max_memory` is exceeded, so `awrite()` can stay inline while in memory and move the rollover and all later writes into a worker thread; the private `_Spool` subclass tracks the rollover and refuses one on a closed spool; every reader has a position of its own — `chunks()`/`achunks()` track an offset, `file()` returns a new read-only `io.BufferedReader` over the private `_SpoolView` per call (closing it leaves the body alone, no `fileno()`) — and a lock makes each seek+read/write on the one file object a single step, so overlapping readers are safe (`achunks()` reads inline only via the non-waiting `_read_inline`, never blocking the loop on the lock; a reader ends where the data ends, so a body is to be read once complete); `close()`/`aclose()`/context managers remove the temp file). `close()`/`aclose()` are deliberately NOT part of the `BodyProducer` protocol (duck-typed by `Response.close()`), so third-party producers stay valid. `save_body()`/`asave_body()` copy a body into a path (`append=` for Range-resumed downloads) or file object — a path is opened only after the body's first chunk, so an unreadable body leaves the file untouched, and `_write_all` completes the short writes of a raw target (`None` from an `io.RawIOBase` is non-blocking "nothing written" → `BlockingIOError`; from any other file-like it counts as written); a generator of chunks is closed on the way out, so a failed write does not leave the stream half-read; the async one opens the file and writes the first chunk in one thread call, batches small chunks to 64 KiB per thread hop (the batch is taken over inside the thread, so a flush trio refuses to start loses nothing) and flushes what has arrived when the stream breaks off. Also the `BodyTypes` alias and the private conversion helpers (`_charset`, `_body_bytes`/`_body_str`/`_body_producer`, `_rendered_body`) shared by `Request` and `Response` — the classes keep their own thin, documented accessor methods.
48
+ - `response.py` — `Response`: `status` (any int; `Status` members welcome), `headers`, `body`, `reason` (server-sent phrase; the `phrase` property falls back to the `Status` registry, `""` for unknown codes), `http_version`, an optional `request` back-reference (metadata: shared, not copied, excluded from `__eq__`) and a `meta` dict like `Request`'s. Category properties (`is_success`, …) computed from the numeric range so unregistered codes work. Same body accessors as `Request`, plus the response-only `body_file()` (seekable file view; a streamed body is spooled and the `SpooledBody` REPLACES `body` so the response stays readable and closable; the replaced producer is closed. A producer with only `aclose()` is replaced by the private `_SpooledStream`, which carries that `aclose()` along. A `FileBody` is not copied and not replaced where it can hand out a seekable file itself (see `_file_view()`); otherwise it is spooled. A `SpooledBody` hands out a new read-only view per call), `save_body()`/`asave_body()` and `close()`/`aclose()` + sync/async context manager (release the body's connection or temp file; no-ops for in-memory bodies; `close()` raises `RuntimeError` for a body that only an awaited `aclose()` can release — the body's own `close()` raises it, or it has none; `__exit__`/`__aexit__` with an exception in flight attach any `Exception` from closing to it as a note instead of replacing it). Picklable with an in-memory body (pinned by a test — out-of-process caches rely on it). `copy(**overrides)`, `as_str(include_body, separator)` with status line, redacting-by-omission `repr()` (`Response(404 Not Found)`).
49
49
 
50
50
  Conventions:
51
51
 
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: action0-req
3
- Version: 0.1.1
3
+ Version: 0.2.0
4
4
  Summary: Library for representing, creating and manipulating HTTP requests and responses
5
5
  Project-URL: Homepage, https://github.com/LaughInJar/action0-req
6
6
  Project-URL: Documentation, https://laughinjar.github.io/action0-req/
@@ -44,7 +44,8 @@ Full documentation including the API reference:
44
44
  **Status:** the core API is complete — the header name, status code and
45
45
  method constants, the `Headers` mapping, `Request` and `Response`, and
46
46
  sync/async body streaming via `BodyProducer` (`BytesBody`, `FileBody`,
47
- `IterableBody`, `AsyncIterableBody`).
47
+ `IterableBody`, `AsyncIterableBody`, `SpooledBody`). Changes per release
48
+ are listed in the [changelog](https://laughinjar.github.io/action0-req/changelog.html).
48
49
 
49
50
 
50
51
  ## Installation
@@ -122,6 +123,23 @@ print(resp.as_str(separator="\n")) # "\r\n" by default
122
123
  # Content-Type: text/plain
123
124
  ```
124
125
 
126
+ A response body can also be read as a seekable file object and copied
127
+ into a file, and a response releases what its body holds (a connection,
128
+ a temporary file) when closed:
129
+
130
+ ```python
131
+ import gzip
132
+
133
+ from action0.req import IterableBody, Response
134
+
135
+ compressed = gzip.compress(b"a large report")
136
+ with Response(200, body=IterableBody([compressed[:8], compressed[8:]])) as resp:
137
+ # a streamed body is spooled: in memory up to 1 MiB, in a temporary file beyond
138
+ print(gzip.GzipFile(fileobj=resp.body_file()).read()) # b'a large report'
139
+ written = resp.save_body("report.gz") # a path or an open binary file
140
+ print(written == len(compressed)) # True
141
+ ```
142
+
125
143
  ## Development
126
144
 
127
145
  The project is managed with [uv](https://docs.astral.sh/uv/); `uv run`
@@ -146,8 +164,8 @@ matches `__version__`, builds sdist + wheel and publishes to PyPI via
146
164
  trusted publishing:
147
165
 
148
166
  ```shell
149
- git tag v0.1.0
150
- git push origin v0.1.0
167
+ git tag vX.Y.Z
168
+ git push origin vX.Y.Z
151
169
  ```
152
170
 
153
171
  ## AI-assisted development
@@ -16,7 +16,8 @@ Full documentation including the API reference:
16
16
  **Status:** the core API is complete — the header name, status code and
17
17
  method constants, the `Headers` mapping, `Request` and `Response`, and
18
18
  sync/async body streaming via `BodyProducer` (`BytesBody`, `FileBody`,
19
- `IterableBody`, `AsyncIterableBody`).
19
+ `IterableBody`, `AsyncIterableBody`, `SpooledBody`). Changes per release
20
+ are listed in the [changelog](https://laughinjar.github.io/action0-req/changelog.html).
20
21
 
21
22
 
22
23
  ## Installation
@@ -94,6 +95,23 @@ print(resp.as_str(separator="\n")) # "\r\n" by default
94
95
  # Content-Type: text/plain
95
96
  ```
96
97
 
98
+ A response body can also be read as a seekable file object and copied
99
+ into a file, and a response releases what its body holds (a connection,
100
+ a temporary file) when closed:
101
+
102
+ ```python
103
+ import gzip
104
+
105
+ from action0.req import IterableBody, Response
106
+
107
+ compressed = gzip.compress(b"a large report")
108
+ with Response(200, body=IterableBody([compressed[:8], compressed[8:]])) as resp:
109
+ # a streamed body is spooled: in memory up to 1 MiB, in a temporary file beyond
110
+ print(gzip.GzipFile(fileobj=resp.body_file()).read()) # b'a large report'
111
+ written = resp.save_body("report.gz") # a path or an open binary file
112
+ print(written == len(compressed)) # True
113
+ ```
114
+
97
115
  ## Development
98
116
 
99
117
  The project is managed with [uv](https://docs.astral.sh/uv/); `uv run`
@@ -118,8 +136,8 @@ matches `__version__`, builds sdist + wheel and publishes to PyPI via
118
136
  trusted publishing:
119
137
 
120
138
  ```shell
121
- git tag v0.1.0
122
- git push origin v0.1.0
139
+ git tag vX.Y.Z
140
+ git push origin vX.Y.Z
123
141
  ```
124
142
 
125
143
  ## AI-assisted development
@@ -4,7 +4,8 @@ The public constants and classes are importable from the package root:
4
4
 
5
5
  ```python
6
6
  from action0.req import Header, Headers, Method, Request, Response, Status
7
- from action0.req import BodyProducer, BytesBody
7
+ from action0.req import BodyProducer, BytesBody, FileBody, IterableBody, AsyncIterableBody
8
+ from action0.req import SpooledBody, save_body, asave_body
8
9
  ```
9
10
 
10
11
  ## Headers and Header
@@ -0,0 +1,2 @@
1
+ ```{include} ../CHANGELOG.md
2
+ ```
@@ -31,6 +31,10 @@ uv add action0-req # not on PyPI yet — install from GitHub for now
31
31
  {py:class}`~action0.req.body.BodyProducer` protocol — sync and async
32
32
  (without blocking the event loop), with in-memory, file-backed and
33
33
  (async-)iterable-backed producers.
34
+ - Response bodies as files: spooled to a temporary file while they
35
+ arrive ({py:class}`~action0.req.body.SpooledBody`), read through a
36
+ seekable file object, saved to a path — and released
37
+ deterministically with `close()` or a `with` block.
34
38
  - Fully typed (checked with mypy strict, pyright and ty), Python 3.11+,
35
39
  no runtime dependencies beyond `action0-url`.
36
40
 
@@ -42,4 +46,5 @@ personal projects.
42
46
 
43
47
  usage
44
48
  api
49
+ changelog
45
50
  ```
@@ -277,8 +277,10 @@ print(req.body_bytes()) # reads the stream — consumes a generator source
277
277
  iterable — e.g. an async generator proxying another stream. It is
278
278
  async-only: the synchronous `chunks()`/`as_bytes()` raise a
279
279
  `RuntimeError`. Every producer supports `achunks()` for asynchronous
280
- consumption (`FileBody` runs its file operations in the default thread
281
- pool, so the event loop is never blocked):
280
+ consumption (`FileBody` runs its file operations in a worker thread —
281
+ `asyncio.to_thread`, or trio's thread pool below trio — so the event
282
+ loop is never blocked; a source that may block for good, like a named
283
+ pipe nobody writes to, does not stand in the way of a timeout):
282
284
 
283
285
  ```python
284
286
  import asyncio
@@ -299,6 +301,115 @@ print(asyncio.run(main()))
299
301
  # [b'async', b'chunks']
300
302
  ```
301
303
 
304
+ ### Releasing a streamed body
305
+
306
+ A body streaming from a resource — an open connection, say — takes a
307
+ callback that releases it: `close=` for `IterableBody`, an awaitable
308
+ `aclose=` for `AsyncIterableBody`. The callback runs exactly once: when
309
+ the body has been read to its end, when a consumer gives up midway, or
310
+ when the body is closed explicitly. The last case also covers a body
311
+ that is never read at all, where a generator's own `finally` block
312
+ would not run:
313
+
314
+ ```python
315
+ from action0.req import IterableBody
316
+
317
+
318
+ def generate():
319
+ yield b"chunk1"
320
+ yield b"chunk2"
321
+
322
+
323
+ body = IterableBody(generate(), close=lambda: print("connection released"))
324
+ with body:
325
+ pass # decided not to read it
326
+ # connection released
327
+ body.close() # no effect: the callback has run
328
+ ```
329
+
330
+ Closing the body also closes a generator behind it, ahead of the
331
+ callback: a generator that was read only in part gets to run its own
332
+ `finally` blocks right away instead of at garbage collection. A body
333
+ over a generator cannot be read after it has been closed; one over a
334
+ list is not affected. A generator that is running at that moment —
335
+ another task is waiting in it for the next chunk — is left alone: the
336
+ callback releases what it reads from, which is how a stalled read is
337
+ aborted from outside. Without a callback there is nothing that could
338
+ stop the read, and closing raises a `RuntimeError` instead of pretending
339
+ — cancel the reading task.
340
+
341
+ ### Spooled bodies
342
+
343
+ {py:class}`~action0.req.body.SpooledBody` is the producer for a body
344
+ that is stored first and read afterwards: it is written to while the
345
+ data arrives, so the connection is free again before anyone looks at
346
+ the data. Up to `max_memory` bytes (1 MiB by default) are kept in
347
+ memory; the write exceeding that moves everything to an anonymous
348
+ temporary file, so memory use stays bounded however large the body is.
349
+ It can be read any number of times, and
350
+ {py:meth}`~action0.req.body.SpooledBody.file` offers it as a seekable
351
+ binary file object:
352
+
353
+ ```python
354
+ from action0.req import SpooledBody
355
+
356
+ with SpooledBody(max_memory=8) as body:
357
+ body.write(b"chunk1")
358
+ print(body.rolled)
359
+ # False
360
+ body.write(b"chunk2") # exceeds max_memory: moved to a temporary file
361
+ print(body.rolled, body.content_length())
362
+ # True 12
363
+ print(list(body.chunks()) == list(body.chunks())) # re-readable
364
+ # True
365
+ file = body.file() # a seekable view, a new one per call
366
+ file.seek(5)
367
+ print(file.read())
368
+ # b'1chunk2'
369
+ print(body.closed) # leaving the block removed the temporary file
370
+ # True
371
+ ```
372
+
373
+ The temporary file is removed by `close()` or by leaving the `with`
374
+ block — garbage collection is only the last resort.
375
+
376
+ The file object from `file()` is a read-only view with a position of its
377
+ own, and so is every iteration of the body. Several consumers can
378
+ therefore read the same body at once — two tasks serving one cached
379
+ response, say — and closing a view, or handing it to a wrapper that
380
+ closes what it wraps (`io.TextIOWrapper`), leaves the body alone. A view
381
+ has no file descriptor; `save_body()` puts the data into a real file.
382
+
383
+ Read a spooled body once it is complete: a reader ends where the data
384
+ ends at that moment, and cannot tell a body that is still being written
385
+ from a finished one.
386
+
387
+ In asynchronous code use `awrite()`, `achunks()` and `aclose()` (or
388
+ `async with`). While the data is in memory they run inline; once it is
389
+ in the temporary file every file operation runs in a worker thread
390
+ (`asyncio.to_thread`, or trio's thread pool when running below trio), so
391
+ the event loop is never blocked. That is one thread hop per `awrite()`
392
+ call — write chunks of tens of kilobytes rather than single bytes.
393
+ `aclose()` removes the temporary file also when the task has been
394
+ cancelled, e.g. by a timeout:
395
+
396
+ ```python
397
+ import asyncio
398
+
399
+ from action0.req import SpooledBody
400
+
401
+
402
+ async def main():
403
+ async with SpooledBody(max_memory=0) as body: # 0: on disk from the first byte
404
+ await body.awrite(b"chunk1")
405
+ await body.awrite(b"chunk2")
406
+ return [chunk async for chunk in body.achunks()]
407
+
408
+
409
+ print(asyncio.run(main()))
410
+ # [b'chunk1chunk2']
411
+ ```
412
+
302
413
  ## Responses
303
414
 
304
415
  {py:class}`~action0.req.response.Response` mirrors `Request` for the
@@ -350,3 +461,150 @@ print(resp.request)
350
461
  print(resp == Response(200))
351
462
  # True
352
463
  ```
464
+
465
+ ### Response bodies as files
466
+
467
+ {py:meth}`~action0.req.response.Response.body_file` returns the body as
468
+ a seekable binary file object — for consumers that read from a file,
469
+ like streaming parsers or decompressors. For an in-memory body that is
470
+ an in-memory file; a {py:class}`~action0.req.body.SpooledBody` hands out
471
+ a read-only view of itself; a {py:class}`~action0.req.body.FileBody` hands out the
472
+ file it wraps, or opens its path anew for every call — nothing is
473
+ copied, and what you have not closed yourself is closed with the
474
+ response; and a streamed body is read to its end into a new
475
+ `SpooledBody`, which then replaces `resp.body`, so the response stays
476
+ readable. The stream it replaces has delivered everything and is closed,
477
+ which releases its connection:
478
+
479
+ ```python
480
+ import gzip
481
+ import json
482
+
483
+ from action0.req import IterableBody, Response
484
+
485
+ compressed = gzip.compress(json.dumps({"rows": [1, 2, 3]}).encode())
486
+ resp = Response(200, body=IterableBody([compressed[:10], compressed[10:]])) # a streamed body
487
+
488
+ with resp: # closing the response discards the spooled data
489
+ with gzip.GzipFile(fileobj=resp.body_file()) as report:
490
+ print(json.load(report))
491
+ # {'rows': [1, 2, 3]}
492
+ print(type(resp.body).__name__)
493
+ # SpooledBody
494
+ ```
495
+
496
+ The replacement happens in this response only. A `copy()` made before
497
+ shares the original stream, which is used up afterwards — as it is after
498
+ any other read of a streamed body.
499
+
500
+ ### Saving a response body
501
+
502
+ {py:meth}`~action0.req.response.Response.save_body` copies the body into
503
+ a path or an open binary file object, chunk by chunk — a streamed body
504
+ never has to fit in memory. A path is created or truncated, or appended
505
+ to with `append=True`; a file object is written at its current position
506
+ and left open. The return value is the number of bytes written.
507
+
508
+ Because the response is in your hands before anything is written, you
509
+ decide whether its body belongs in the file. Resuming a download with an
510
+ HTTP `Range` request, for example, appends only if the server really
511
+ answered with the requested part — an error page never ends up in the
512
+ file:
513
+
514
+ ```python
515
+ from pathlib import Path
516
+ from tempfile import TemporaryDirectory
517
+
518
+ from action0.req import IterableBody, Response
519
+
520
+ with TemporaryDirectory() as tmp:
521
+ path = Path(tmp) / "feed.json"
522
+ path.write_bytes(b'{"items": [1, 2') # an earlier download that broke off
523
+ offset = path.stat().st_size
524
+
525
+ # the answer to a request sent with "Range: bytes=15-"
526
+ resp = Response(
527
+ 206,
528
+ headers={"Content-Range": f"bytes {offset}-19/20"},
529
+ body=IterableBody([b", 3", b"]}"]),
530
+ )
531
+ with resp:
532
+ if resp.status == 206 and resp.headers["Content-Range"].startswith(f"bytes {offset}-"):
533
+ print(resp.save_body(path, append=True))
534
+ # 5
535
+ print(path.read_bytes())
536
+ # b'{"items": [1, 2, 3]}'
537
+ ```
538
+
539
+ If the body breaks off midway, the exception passes through and what
540
+ has arrived is in the file — its size is the offset to resume from. A
541
+ path is opened only once the body has delivered its first chunk: a body
542
+ that cannot be read at all (already closed, failing right away) raises
543
+ without creating or truncating the file. If it is the write that fails
544
+ (a full disk), the stream is closed, which releases its connection.
545
+
546
+ {py:meth}`~action0.req.response.Response.asave_body` is the asynchronous
547
+ twin: it reads the body via `achunks()` and does every file operation in
548
+ a worker thread, writing small chunks 64 KiB at a time. A cancellation
549
+ (a timeout) does not tear anything apart: a write that is under way is
550
+ finished, and once the file is open, what has arrived is written and the
551
+ file closed before the cancellation is passed on. Both exist as
552
+ functions too ({py:func}`~action0.req.body.save_body`,
553
+ {py:func}`~action0.req.body.asave_body`), for a body that is not part of
554
+ a response.
555
+
556
+ ### Closing a response
557
+
558
+ A response whose body holds a resource should be closed: a streamed
559
+ body that was not read to its end still occupies its connection, a
560
+ spooled body its temporary file. Use the response as a context manager
561
+ (`with` or `async with`), or call
562
+ {py:meth}`~action0.req.response.Response.close` /
563
+ {py:meth}`~action0.req.response.Response.aclose`. For a body that holds
564
+ nothing (bytes, str, none) both do nothing, so closing every response
565
+ is always safe:
566
+
567
+ ```python
568
+ from action0.req import IterableBody, Response
569
+
570
+ body = IterableBody(iter([b"never", b"read"]), close=lambda: print("connection released"))
571
+ with Response(200, body=body) as resp:
572
+ print(resp.status)
573
+ # 200
574
+ # connection released
575
+
576
+ with Response(200, body=b"plain") as resp: # nothing to release
577
+ print(resp.body_bytes())
578
+ # b'plain'
579
+ ```
580
+
581
+ `copy()` shares the body, so closing one copy closes it for all of
582
+ them. A body that can only be closed asynchronously (an
583
+ `AsyncIterableBody` with an `aclose` callback, or over an async
584
+ generator that was read in part) makes `close()` raise a `RuntimeError`
585
+ instead of silently leaving the resource open.
586
+
587
+ When a `with` or `async with` block is left by an exception, that
588
+ exception is the one you see: a failure to close does not replace it,
589
+ but is attached to it as a note.
590
+
591
+ ### Pickling
592
+
593
+ A response with an in-memory body (bytes or str) can be pickled, with
594
+ its headers, `meta` and request reference — which is what storing
595
+ responses outside the process (a cache server, a queue) needs:
596
+
597
+ ```python
598
+ import pickle
599
+
600
+ from action0.req import Response
601
+
602
+ resp = Response(200, headers={"Content-Type": "application/json"}, body=b'{"a": 1}')
603
+ restored = pickle.loads(pickle.dumps(resp))
604
+ print(restored == resp, restored.body_bytes())
605
+ # True b'{"a": 1}'
606
+ ```
607
+
608
+ The request reference is pickled along. Drop it first
609
+ (`resp.copy(request=None)`) if the request carries credentials that
610
+ should not end up in the store.
@@ -41,6 +41,7 @@ dev = [
41
41
  "pyright>=1.1.411",
42
42
  "pytest>=9.0.3",
43
43
  "ruff>=0.15.6",
44
+ "trio>=0.35.0",
44
45
  "ty>=0.0.23",
45
46
  ]
46
47
  docs = [
@@ -3,6 +3,9 @@ from .body import BodyProducer
3
3
  from .body import BytesBody
4
4
  from .body import FileBody
5
5
  from .body import IterableBody
6
+ from .body import SpooledBody
7
+ from .body import asave_body
8
+ from .body import save_body
6
9
  from .headers import Header
7
10
  from .headers import Headers
8
11
  from .request import Method
@@ -10,7 +13,7 @@ from .request import Request
10
13
  from .response import Response
11
14
  from .status import Status
12
15
 
13
- __version__: str = "0.1.1"
16
+ __version__: str = "0.2.0"
14
17
 
15
18
  __all__ = [
16
19
  "AsyncIterableBody",
@@ -23,5 +26,8 @@ __all__ = [
23
26
  "Method",
24
27
  "Request",
25
28
  "Response",
29
+ "SpooledBody",
26
30
  "Status",
31
+ "asave_body",
32
+ "save_body",
27
33
  ]