Skip to content
Open
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
2 changes: 2 additions & 0 deletions docs/docs/en/confluent/message.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
2 changes: 2 additions & 0 deletions docs/docs/en/kafka/message.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
80 changes: 71 additions & 9 deletions faststream/_internal/fastapi/_compat.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -45,8 +47,10 @@

__all__ = (
"RequestValidationError",
"TombstoneBody",
"bind_tombstone_body",
"create_response_field",
"get_tombstone_body",
"raise_fastapi_validation_error",
"solve_faststream_dependency",
)
Expand Down Expand Up @@ -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
Comment on lines +165 to +179

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rearranging the decoded batch in middleware violates the list[Model | None] binding. If consume_scope expands the list from await msg.decode(), the tombstones mask remains in its original order. On both TestBroker got a validation error on b"" instead of [None, Model(...)]



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", {})
Expand All @@ -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
Expand All @@ -174,14 +201,15 @@ def _bind_tombstone_fields(
dependant: "Dependant",
overrides: dict[Any, Any],
cache: "_OverrideDependencyCache | None",
batch: list[Any] | None,
) -> "Dependant":
dependencies = []
for original in dependant.dependencies:
dependency = original
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)
Expand All @@ -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
]
Expand Down Expand Up @@ -296,17 +327,20 @@ 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)

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, []
Expand All @@ -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)
Comment on lines +369 to +385

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Batch with tombstone breaks list[bytes] with Pydantic v1. The same script gets [b""] at #3389 and crashes at #3390 when reading field_info.annotation.



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)
Expand Down
18 changes: 7 additions & 11 deletions faststream/_internal/fastapi/route.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
FASTAPI_V121,
bind_tombstone_body,
create_response_field,
get_tombstone_body,
raise_fastapi_validation_error,
solve_faststream_dependency,
)
Expand All @@ -43,6 +44,7 @@

from faststream.message import StreamMessage as NativeMessage

from ._compat import TombstoneBody
from .config import FastAPIConfig


Expand Down Expand Up @@ -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

Expand All @@ -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."""
Expand All @@ -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:
Expand All @@ -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

Expand Down
2 changes: 1 addition & 1 deletion faststream/confluent/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
2 changes: 1 addition & 1 deletion faststream/kafka/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
7 changes: 6 additions & 1 deletion faststream/message/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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."""
Expand Down
61 changes: 59 additions & 2 deletions tests/brokers/base/fastapi.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]):
Expand Down
Loading