diff --git a/docs/docs/en/confluent/message.md b/docs/docs/en/confluent/message.md index 2020f359bb..cf0d69c0f5 100644 --- a/docs/docs/en/confluent/message.md +++ b/docs/docs/en/confluent/message.md @@ -113,3 +113,5 @@ In `#!python publish_batch()`, a plain `#!python None` goes through the configur Read `#!python msg.tombstone` for a single record or the booleans in `#!python msg.batch_tombstones` in batch order. With default deserialization, the body of a tombstone is `#!python b""`. An empty Kafka value and a JSON `null` payload have their tombstone flags set to `#!python False`. A FastAPI subscriber using the default decoder can declare an optional model with a default of `#!python None`. A single Kafka tombstone uses that default, including for embedded bodies and dependency bodies. + +With the default FastAPI decoder, a batch subscriber declaring `#!python list[Model | None]` receives `#!python None` at each tombstone position. A `#!python list[bytes]` handler receives `#!python b""` at those positions. diff --git a/docs/docs/en/kafka/message.md b/docs/docs/en/kafka/message.md index 9c65961203..5498a27810 100644 --- a/docs/docs/en/kafka/message.md +++ b/docs/docs/en/kafka/message.md @@ -104,3 +104,5 @@ Read `#!python msg.tombstone` for a single record or the booleans in `#!python m A FastAPI subscriber using the default decoder can declare an optional model with a default of `#!python None`. A single Kafka tombstone uses that default, including for embedded bodies and dependency bodies. With aiokafka, confirmation of a tombstone batch covers every record. The returned metadata describes the first input record. With `#!python acks=0`, the driver returns `#!python None` instead. + +With the default FastAPI decoder, a batch subscriber declaring `#!python list[Model | None]` receives `#!python None` at each tombstone position. A `#!python list[bytes]` handler receives `#!python b""` at those positions. diff --git a/faststream/_internal/fastapi/_compat.py b/faststream/_internal/fastapi/_compat.py index 3ddb7fb752..870bc5b3fd 100644 --- a/faststream/_internal/fastapi/_compat.py +++ b/faststream/_internal/fastapi/_compat.py @@ -1,5 +1,5 @@ import inspect -from collections.abc import Callable +from collections.abc import Callable, Sequence from dataclasses import dataclass, replace from functools import partial from types import UnionType @@ -17,6 +17,8 @@ from fastapi.dependencies.models import Dependant from fastapi.requests import Request + from faststream.message import StreamMessage + major, minor, patch, *_ = FASTAPI_VERSION.split(".") _FASTAPI_MAJOR, _FASTAPI_MINOR = int(major), int(minor) @@ -45,8 +47,10 @@ __all__ = ( "RequestValidationError", + "TombstoneBody", "bind_tombstone_body", "create_response_field", + "get_tombstone_body", "raise_fastapi_validation_error", "solve_faststream_dependency", ) @@ -153,9 +157,32 @@ async def solve_faststream_dependency( ) +@dataclass(slots=True) +class TombstoneBody: + batch: list[Any] | None = None + + +def get_tombstone_body( + message: "StreamMessage[Any]", decoded: Any +) -> TombstoneBody | None: + if not message.uses_default_decoder: + return None + if not message.has_body and _is_empty_body(decoded): + return TombstoneBody() + + missing = message.batch_body_missing + if isinstance(decoded, list) and len(decoded) == len(missing) and any(missing): + return TombstoneBody([ + None if absent and _is_empty_body(item) else item + for item, absent in zip(decoded, missing, strict=True) + ]) + return None + + def bind_tombstone_body( dependant: "Dependant", dependency_overrides_provider: Any, + tombstone: TombstoneBody, ) -> tuple["Dependant", "dict[tuple[Any, ...], Any] | None"]: """Apply the tombstone binding while retaining the original dependency keys.""" overrides = getattr(dependency_overrides_provider, "dependency_overrides", {}) @@ -164,7 +191,7 @@ def bind_tombstone_body( if overrides and not hasattr(dependant, "cache_key") else None ) - return _bind_tombstone_fields(dependant, overrides, cache), cache + return _bind_tombstone_fields(dependant, overrides, cache, tombstone.batch), cache _DEPENDANT_PARAMETERS = inspect.signature(get_dependant).parameters @@ -174,6 +201,7 @@ def _bind_tombstone_fields( dependant: "Dependant", overrides: dict[Any, Any], cache: "_OverrideDependencyCache | None", + batch: list[Any] | None, ) -> "Dependant": dependencies = [] for original in dependant.dependencies: @@ -181,7 +209,7 @@ def _bind_tombstone_fields( override = overrides.get(original.call) if override is not None: dependency = _get_overridden_dependant(original, override) - adapted = _bind_tombstone_fields(dependency, overrides, cache) + adapted = _bind_tombstone_fields(dependency, overrides, cache, batch) if cache is not None: assert adapted.call is not None adapted.call = cache.bind(adapted.call, original) @@ -190,9 +218,12 @@ def _bind_tombstone_fields( legacy_dependant.cache_key = cache_key dependencies.append(adapted) + accepts_tombstone = ( + _is_optional_model_body if batch is None else _accepts_nullable_model_items + ) body_params = [ - cast("ModelField", _TombstoneBodyField(field)) - if _is_optional_model_body(field) + cast("ModelField", _TombstoneBodyField(field, batch)) + if accepts_tombstone(field) else field for field in dependant.body_params ] @@ -296,10 +327,11 @@ def _is_generator(call: Any) -> bool: class _TombstoneBodyField: - __slots__ = ("_field",) + __slots__ = ("_batch", "_field") - def __init__(self, field: "ModelField") -> None: + def __init__(self, field: "ModelField", batch: list[Any] | None) -> None: self._field = field + self._batch = batch def __getattr__(self, name: str) -> Any: return getattr(self._field, name) @@ -307,6 +339,8 @@ def __getattr__(self, name: str) -> Any: def validate( self, value: Any, values: dict[str, Any], *, loc: tuple[int | str, ...] ) -> tuple[Any, Any]: + if self._batch is not None: + return self._field.validate(self._batch, values, loc=loc) if getattr(self._field.field_info, "validate_default", False): return self._field.validate(None, values, loc=loc) return None, [] @@ -328,10 +362,38 @@ def _is_optional_model_body(field: "ModelField") -> bool: ) +def _is_empty_body(value: Any) -> bool: + return value is None or (isinstance(value, (bytes, str)) and not value) + + +def _accepts_nullable_model_items(field: "ModelField") -> bool: + annotation = ( + field.field_info.annotation if FASTAPI_V2 else getattr(field, "outer_type_", None) + ) + annotation = _unwrap_annotated(annotation) + if get_origin(annotation) in {Union, UnionType}: + types = tuple(arg for arg in get_args(annotation) if arg is not type(None)) + if len(types) != 1: + return False + annotation = _unwrap_annotated(types[0]) + if get_origin(annotation) not in {list, Sequence}: + return False + items = get_args(annotation) + if not items: + return False + item = _unwrap_annotated(items[0]) + return type(None) in get_args(item) and _is_model_annotation(item) + + +def _unwrap_annotated(annotation: Any) -> Any: + if get_origin(annotation) is Annotated: + return get_args(annotation)[0] + return annotation + + def _is_model_annotation(annotation: Any) -> bool: + annotation = _unwrap_annotated(annotation) origin = get_origin(annotation) - if origin is Annotated: - return _is_model_annotation(get_args(annotation)[0]) if origin in {Union, UnionType}: return all( _is_model_annotation(arg) diff --git a/faststream/_internal/fastapi/route.py b/faststream/_internal/fastapi/route.py index be28868dda..bb117054d1 100644 --- a/faststream/_internal/fastapi/route.py +++ b/faststream/_internal/fastapi/route.py @@ -25,6 +25,7 @@ FASTAPI_V121, bind_tombstone_body, create_response_field, + get_tombstone_body, raise_fastapi_validation_error, solve_faststream_dependency, ) @@ -43,6 +44,7 @@ from faststream.message import StreamMessage as NativeMessage + from ._compat import TombstoneBody from .config import FastAPIConfig @@ -195,13 +197,7 @@ async def parsed_consumer(message: "NativeMessage[Any]") -> Any: path={}, ) - return await consume( - stream_message, - message, - not message.has_body - and message.uses_default_decoder - and (body is None or (isinstance(body, (bytes, str)) and not body)), - ) + return await consume(stream_message, message, get_tombstone_body(message, body)) return parsed_consumer @@ -218,7 +214,7 @@ def make_fastapi_execution( response_model_exclude_defaults: bool, response_model_exclude_none: bool, ) -> Callable[ - ["StreamMessage", "NativeMessage[Any]", bool], + ["StreamMessage", "NativeMessage[Any]", Optional["TombstoneBody"]], Awaitable[Response], ]: """Creates a FastAPI application.""" @@ -227,7 +223,7 @@ def make_fastapi_execution( async def app( request: "StreamMessage", raw_message: "NativeMessage[Any]", # to support BackgroundTasks by middleware - tombstone: bool, + tombstone: Optional["TombstoneBody"], ) -> Response: """Consume StreamMessage and return user function result.""" async with AsyncExitStack() as stack: @@ -248,9 +244,9 @@ async def app( solver_dependant = dependent overrides = fastapi_config.dependency_overrides_provider - if tombstone: + if tombstone is not None: solver_dependant, kwargs["dependency_cache"] = bind_tombstone_body( - dependent, overrides + dependent, overrides, tombstone ) overrides = None diff --git a/faststream/confluent/message.py b/faststream/confluent/message.py index bc2cfcd9fa..56d40cb69c 100644 --- a/faststream/confluent/message.py +++ b/faststream/confluent/message.py @@ -79,7 +79,7 @@ def tombstone(self) -> bool: @property def batch_tombstones(self) -> tuple[bool, ...]: """Whether each record has a null Kafka value, in raw message order.""" - return self._batch_body_missing + return self.batch_body_missing @property def raw_headers(self) -> dict[str, bytes | None]: diff --git a/faststream/kafka/message.py b/faststream/kafka/message.py index 0a0d980888..fa5e5ad849 100644 --- a/faststream/kafka/message.py +++ b/faststream/kafka/message.py @@ -69,7 +69,7 @@ def tombstone(self) -> bool: @property def batch_tombstones(self) -> tuple[bool, ...]: """Whether each record has a null Kafka value, in raw message order.""" - return self._batch_body_missing + return self.batch_body_missing @property def raw_headers(self) -> dict[str, bytes | None]: diff --git a/faststream/message/message.py b/faststream/message/message.py index 4817e5cf02..1659bc18db 100644 --- a/faststream/message/message.py +++ b/faststream/message/message.py @@ -49,7 +49,7 @@ def __init__( self.raw_message = raw_message self.body = body self.__no_body = _no_body - self._batch_body_missing = _batch_body_missing + self.__batch_body_missing = _batch_body_missing self.reply_to = reply_to self.content_type = content_type self.source_type = source_type @@ -76,6 +76,11 @@ def has_body(self) -> bool: """Whether this message has a body on the wire.""" return not self.__no_body + @property + def batch_body_missing(self) -> tuple[bool, ...]: + """Indicate which records in a batch have no body on the wire.""" + return self.__batch_body_missing + @property def uses_default_decoder(self) -> bool: """Whether the active decoder is the subscriber's default.""" diff --git a/tests/brokers/base/fastapi.py b/tests/brokers/base/fastapi.py index 5b5b44e94f..428059c375 100644 --- a/tests/brokers/base/fastapi.py +++ b/tests/brokers/base/fastapi.py @@ -1,5 +1,6 @@ import asyncio -from collections.abc import AsyncGenerator, Iterator +import typing +from collections.abc import AsyncGenerator, Iterator, Sequence from contextlib import asynccontextmanager from functools import partial from typing import Annotated, Any @@ -10,7 +11,7 @@ from fastapi.exceptions import RequestValidationError from fastapi.security import SecurityScopes from fastapi.testclient import TestClient -from pydantic import BaseModel +from pydantic import BaseModel, Field from faststream import ( Context as FSContext, @@ -275,6 +276,13 @@ async def subscriber(msg: StreamMessage) -> None: mock.assert_called_once_with(True) +_BareList = Annotated[typing.List, Body()] # ruff: ignore[non-pep585-annotation] + + +class _BatchModel(BaseModel): + x: int + + @pytest.mark.asyncio() class KafkaTombstoneFastAPILocalTestcase(BaseTestcaseConfig[Any]): router_class: Any @@ -449,6 +457,55 @@ async def handler( ordinary, tombstone = received assert tombstone == ordinary + @pytest.mark.parametrize( + ("annotation", "custom_decoder"), + ( + pytest.param(list[_BatchModel | None], False, id="list"), + pytest.param(list[_BatchModel | None], True, id="custom-decoder"), + pytest.param( + Sequence[Annotated[_BatchModel | None, Field(description="record")]] + | None, + False, + id="optional-sequence-with-annotated-item", + ), + pytest.param(_BareList, False, id="bare-typing-list"), + ), + ) + async def test_tombstone_batch_binds_each_body_field( + self, queue: str, mock: Mock, annotation: Any, custom_decoder: bool + ) -> None: + async def decoder(_: NativeMessage[Any]) -> list[dict[str, int]]: + return [{"x": 7}, {"x": 8}] + + async def parse_raw(values: list[Any]) -> list[Any]: + return values + + router = self.router_class() + args, kwargs = self.get_subscriber_params( + queue, batch=True, decoder=decoder if custom_decoder else None + ) + + async def handler( + msg: Any, raw: Annotated[list[Any], Depends(parse_raw)] + ) -> None: + mock(msg, raw) + + handler.__annotations__["msg"] = annotation + router.subscriber(*args, **kwargs)(handler) + + publisher = router.broker.publisher(queue, batch=True, key=b"key") + async with self.patch_broker(router.broker): + await publisher.publish(b'{"x": 5}', TOMBSTONE, b"null") + + expected: list[Any] + raw: list[Any] + if custom_decoder: + expected, raw = [_BatchModel(x=7), _BatchModel(x=8)], [{"x": 7}, {"x": 8}] + else: + raw = [{"x": 5}, b"", None] + expected = raw if annotation is _BareList else [_BatchModel(x=5), None, None] + mock.assert_called_once_with(expected, raw) + @pytest.mark.asyncio() class FastAPILocalTestcase(BaseTestcaseConfig[Any]):