fix(core): preserve data integrity and bound shared UI and response work
Module Package Release / publish-packages (push) Successful in 13s

Release v0.1.46. Coordinated integrity review: GovOPlaN/govoplan-core#298.
This commit is contained in:
2026-09-08 12:30:38 +02:00
parent dc1f244f17
commit 6591aaa3fd
33 changed files with 1889 additions and 114 deletions
@@ -1,12 +1,15 @@
from __future__ import annotations
import hashlib
from collections.abc import Awaitable, Callable
from collections.abc import AsyncIterator, Awaitable, Callable
from fastapi import Request
from starlette.responses import Response
JSON_CACHE_CONTROL = "private, no-cache"
# This bounds middleware-owned buffering, not the size of a route response.
# Larger responses retain their streaming iterator and are never truncated.
MAX_CONDITIONAL_JSON_BYTES = 1_048_576
JSON_ETAG_VARY_HEADERS = (
"Authorization",
"Cookie",
@@ -26,15 +29,34 @@ async def conditional_json_get_middleware(
The middleware deliberately works after route handling. That keeps the
contract platform-wide without requiring every module router to learn about
conditional requests, while still limiting buffering to successful JSON GET
responses.
conditional requests. Only small successful JSON responses are buffered;
larger responses stream unchanged. Authorization still runs on every GET.
"""
response = await call_next(request)
if not _eligible_for_conditional_json_get(request, response):
return response
body = b"".join([chunk async for chunk in response.body_iterator])
response.headers["cache-control"] = _conditional_cache_control(response.headers.get("cache-control"))
response.headers["vary"] = _merge_vary(response.headers.get("vary"), JSON_ETAG_VARY_HEADERS)
content_length = response.headers.get("content-length", "")
if content_length.isascii() and content_length.isdecimal() and int(content_length) > MAX_CONDITIONAL_JSON_BYTES:
return response
chunks: list[bytes] = []
size = 0
iterator = response.body_iterator
async for chunk in iterator:
if not chunk:
continue
chunks.append(chunk)
size += len(chunk)
if size > MAX_CONDITIONAL_JSON_BYTES:
# Include the crossing chunk exactly once, without draining the
# rest of the producer or copying a potentially large chunk.
response.body_iterator = _replay_prefix(chunks, iterator)
return response
body = b"".join(chunks)
etag = response.headers.get("etag") or json_response_etag(body)
headers = dict(response.headers)
headers["etag"] = etag
@@ -48,6 +70,14 @@ async def conditional_json_get_middleware(
return Response(content=body, status_code=response.status_code, headers=headers, background=response.background)
async def _replay_prefix(chunks: list[bytes], iterator: AsyncIterator[bytes]) -> AsyncIterator[bytes]:
for chunk in chunks:
yield chunk
chunks.clear()
async for chunk in iterator:
yield chunk
def json_response_etag(body: bytes) -> str:
digest = hashlib.sha256(body).hexdigest()
return f'W/"sha256-{digest}"'