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
8 changes: 8 additions & 0 deletions docs/docs/en/confluent/message.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@ and its `raw_message` (the `confluent_kafka.Message`) exposes the rest through m
* `#!python topic(): str`
* `#!python value(): Optional[Union[str, bytes]]`

!!! note "Kafka tombstones"
A record with a null value is a Kafka tombstone, a delete marker on a compacted topic.
For a single tombstone, `#!python msg.tombstone` is `#!python True` and `#!python msg.body` is `#!python b""`.
With the default decoder, a FastAPI subscriber with an optional body parameter defaulting to `#!python None` receives `#!python None` for that record.

In a `#!python batch=True` subscriber, `#!python msg.tombstone` is always `#!python False`.
Publish a tombstone with `#!python await broker.publish(None, "topic", key=b"user-1")`.

For example, if you would like to access the headers of an incoming message, you would do so like this:

```python hl_lines="1 6"
Expand Down
9 changes: 9 additions & 0 deletions docs/docs/en/kafka/message.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ and its `raw_message` (the `aiokafka.ConsumerRecord`) contains the rest of the r
* `#!python topic: str`
* `#!python value: Optional[aiokafka.structs.VT]`

!!! note "Kafka tombstones"
A record with a null value is a Kafka tombstone, a delete marker on a compacted topic.
For a single tombstone, `#!python msg.tombstone` is `#!python True`.
With default value deserialization, `#!python msg.body` is `#!python b""`.
With the default decoder, a FastAPI subscriber with an optional body parameter defaulting to `#!python None` receives `#!python None` for that record.

In a `#!python batch=True` subscriber, `#!python msg.tombstone` is always `#!python False`.
Publish a tombstone with `#!python await broker.publish(None, "topic", key=b"user-1")`.

For example, if you would like to access the headers of an incoming message, you would do so like this:

```python hl_lines="1 6"
Expand Down
5 changes: 5 additions & 0 deletions faststream/_internal/endpoint/subscriber/call_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class HandlerItem(Generic[MsgType]):
"""A class representing handler overloaded item."""

__slots__ = (
"_uses_default_decoder",
"decoder",
"dependant",
"dependencies",
Expand Down Expand Up @@ -67,6 +68,7 @@ def __init__(
self.item_decoder = item_decoder
self.parser = None
self.decoder = None
self._uses_default_decoder = False
self.dependencies = dependencies
self.dependant = None

Expand All @@ -80,12 +82,14 @@ def _setup(
*,
parser: "AsyncCallable",
decoder: "AsyncCallable",
uses_default_decoder: bool,
config: "FastDependsConfig",
broker_dependencies: Sequence["Dependant"],
_call_decorators: Reversible["Decorator"],
) -> None:
self.parser = parser
self.decoder = decoder
self._uses_default_decoder = uses_default_decoder

self.dependant = self.handler.set_wrapped(
dependencies=(*broker_dependencies, *self.dependencies),
Expand Down Expand Up @@ -128,6 +132,7 @@ async def is_suitable(

# NOTE: final decoder will be set for success filter
message.set_decoder(decoder)
message._uses_default_decoder = self._uses_default_decoder

if await self.filter(message):
return message
Expand Down
1 change: 1 addition & 0 deletions faststream/_internal/endpoint/subscriber/usecase.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ def _build_fastdepends_model(self) -> None:
call._setup(
parser=async_parser,
decoder=async_decoder,
uses_default_decoder=async_decoder is self._decoder,
config=fd_config,
broker_dependencies=self._outer_config.broker_dependencies,
_call_decorators=self._call_decorators,
Expand Down
15 changes: 11 additions & 4 deletions faststream/_internal/fastapi/route.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@ class StreamMessage(Request):
scope: "dict[str, Any]"
_cookies: "dict[str, Any]"
_headers: "dict[str, Any]" # type: ignore[assignment]
_body: Union["dict[str, Any]", list[Any]] # type: ignore[assignment]
_body: Union["dict[str, Any]", list[Any], None] # type: ignore[assignment]
_query_params: "dict[str, Any]" # type: ignore[assignment]

def __init__(
self,
*,
body: Union["dict[str, Any]", list[Any]],
body: Union["dict[str, Any]", list[Any], None],
headers: "dict[str, Any]",
path: "dict[str, Any]",
) -> None:
Expand Down Expand Up @@ -172,6 +172,13 @@ async def parsed_consumer(message: "NativeMessage[Any]") -> Any:
"""Wrapper, that parser FastStream message to FastAPI compatible one."""
body = await message.decode()

# The query and path parameters still use the decoded value when the body is absent.
missing_body = (
message._no_body
and message._uses_default_decoder
and (body is None or (isinstance(body, (bytes, str)) and not body))
)

fastapi_body: dict[str, Any] | list[Any]
if first_arg is not None:
if isinstance(body, dict):
Expand All @@ -182,14 +189,14 @@ async def parsed_consumer(message: "NativeMessage[Any]") -> Any:
path = fastapi_body = {first_arg: body}

stream_message = StreamMessage(
body=fastapi_body,
body=None if missing_body else fastapi_body,
headers={"context__": context, **message.headers},
path={**path, **message.path},
)

else:
stream_message = StreamMessage(
body={},
body=None if missing_body else {},
headers={"context__": context},
path={},
)
Expand Down
5 changes: 5 additions & 0 deletions faststream/confluent/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ def __init__(
if not is_manual:
self.committed = AckStatus.ACKED

@property
def tombstone(self) -> bool:
"""Whether this single record has a null Kafka value."""
return self._no_body

@property
def raw_headers(self) -> dict[str, bytes | None]:
"""Original header bytes, or the first message's headers for a batch."""
Expand Down
5 changes: 3 additions & 2 deletions faststream/confluent/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,13 @@ async def parse_message(
"""Parses a Kafka message."""
headers = _parse_msg_headers(cast("_HeadersInput", message.headers() or ()))

body = message.value() or b""
value = message.value()
offset = message.offset()
_, timestamp = message.timestamp()

return KafkaMessage(
body=body,
body=value or b"",
_no_body=value is None,
headers=headers,
reply_to=headers.get("reply_to", ""),
content_type=headers.get("content-type"),
Expand Down
5 changes: 5 additions & 0 deletions faststream/kafka/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ def __init__(self, *args: Any, consumer: ConsumerProtocol, **kwargs: Any) -> Non
self.consumer = consumer
self.committed = AckStatus.ACKED

@property
def tombstone(self) -> bool:
"""Whether this single record has a null Kafka value."""
return self._no_body

@property
def raw_headers(self) -> dict[str, bytes | None]:
"""Original header bytes, or the first message's headers for a batch."""
Expand Down
3 changes: 3 additions & 0 deletions faststream/kafka/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,11 @@ async def parse_message(
if value is not None
}

# aiokafka computes the wire size before calling a user deserializer.
tombstone = message.serialized_value_size == -1
return self.msg_class(
body=message.value or b"",
_no_body=tombstone,
headers=headers,
reply_to=headers.get("reply_to", ""),
content_type=headers.get("content-type"),
Expand Down
2 changes: 1 addition & 1 deletion faststream/kafka/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ async def build_message(
partition=partition or 0,
key=k,
serialized_key_size=len(k),
serialized_value_size=0 if msg is None else len(msg),
serialized_value_size=-1 if msg is None else len(msg),
checksum=0 if msg is None else sum(msg),
offset=0,
headers=encode_headers(headers),
Expand Down
4 changes: 4 additions & 0 deletions faststream/message/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,11 @@ def __init__(
correlation_id: str | None = None,
message_id: str | None = None,
source_type: SourceType = SourceType.CONSUME,
_no_body: bool = False,
) -> None:
self.raw_message = raw_message
self.body = body
self._no_body = _no_body
self.reply_to = reply_to
self.content_type = content_type
self.source_type = source_type
Expand All @@ -61,13 +63,15 @@ def __init__(

# Setup later
self.__decoder: AsyncCallable | None = None
self._uses_default_decoder = False
self.__decoded_caches: dict[
Any,
Any,
] = {} # Cache values between filters and tests

def set_decoder(self, decoder: "AsyncCallable") -> None:
self.__decoder = decoder
self._uses_default_decoder = False

def clear_cache(self) -> None:
self.__decoded_caches.clear()
Expand Down
7 changes: 7 additions & 0 deletions faststream/message/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ def decode_message(message: "StreamMessage[Any]") -> "DecodedMessage":
isinstance(content_type, str)
and content_type.startswith(ContentTypes.JSON.value)
):
# A null record can still carry a JSON header (see issue #1967).
if (
getattr(message, "_no_body", False)
and isinstance(body, bytes)
and not body
):
return body
m = json_loads(body)

else:
Expand Down
116 changes: 115 additions & 1 deletion tests/brokers/base/fastapi.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import asyncio
from collections.abc import AsyncGenerator, Iterator
from contextlib import asynccontextmanager
from json import JSONDecodeError
from typing import Annotated, Any
from unittest.mock import Mock

import pytest
from fastapi import BackgroundTasks, Depends, FastAPI, Header
from fastapi import BackgroundTasks, Body, Depends, FastAPI, Header
from fastapi.exceptions import RequestValidationError
from fastapi.testclient import TestClient
from pydantic import BaseModel

from faststream import (
Context as FSContext,
Expand All @@ -17,6 +19,7 @@
from faststream._internal.fastapi.context import Context
from faststream._internal.fastapi.route import StreamMessage
from faststream.exceptions import SetupError
from faststream.message import StreamMessage as NativeMessage

from .basic import BaseTestcaseConfig

Expand Down Expand Up @@ -270,6 +273,117 @@ async def subscriber(msg: StreamMessage) -> None:
mock.assert_called_once_with(True)


@pytest.mark.asyncio()
class KafkaTombstoneFastAPILocalTestcase(BaseTestcaseConfig[Any]):
router_class: Any

async def test_optional_body_resolves_to_none_for_tombstone(self, queue: str) -> None:
"""Fixes https://github.com/ag2ai/faststream/issues/1967."""

class _BodyModel(BaseModel):
x: int

router = self.router_class()
received: list[_BodyModel | None] = []

args, kwargs = self.get_subscriber_params(queue)

@router.subscriber(*args, **kwargs)
async def handler(msg: _BodyModel | None = None) -> None:
received.append(msg)

app = FastAPI()
app.include_router(router)

async with self.patch_broker(router.broker) as br:
with TestClient(app):
await br.publish(b'{"x": 5}', queue, key=b"k1")
await br.publish(None, queue, key=b"k2")
headers = {"content-type": "application/json"}
await br.publish(None, queue, key=b"k3", headers=headers)
with pytest.raises(RequestValidationError):
await br.publish(b"", queue, key=b"k4")
with pytest.raises(JSONDecodeError):
await br.publish(b"", queue, key=b"k5", headers=headers)

assert received == [_BodyModel(x=5), None, None]

async def test_tombstone_preserves_bytes_parameter(
self, queue: str, mock: Mock
) -> None:
"""Fixes https://github.com/ag2ai/faststream/issues/1967."""
router = self.router_class()
args, kwargs = self.get_subscriber_params(queue)

@router.subscriber(*args, **kwargs)
async def handler(msg: bytes) -> None:
mock(msg)

async with self.patch_broker(router.broker) as br:
await br.publish(None, queue, key=b"key")

mock.assert_called_once_with(b"")

@pytest.mark.parametrize(
("decoded", "expected"),
(
pytest.param({"msg": b"decoded"}, b"decoded", id="mapping"),
pytest.param(b"", b"", id="empty-bytes"),
),
)
async def test_tombstone_preserves_custom_decoded_body(
self,
queue: str,
mock: Mock,
decoded: dict[str, bytes] | bytes,
expected: bytes,
) -> None:
"""Fixes https://github.com/ag2ai/faststream/issues/1967."""

class _BodyModel(BaseModel):
msg: bytes

async def decoder(_: NativeMessage[Any]) -> dict[str, bytes] | bytes:
return decoded

router = self.router_class()
args, kwargs = self.get_subscriber_params(queue, decoder=decoder)

@router.subscriber(*args, **kwargs)
async def handler(msg: _BodyModel | None = None) -> None:
mock(msg)

async with self.patch_broker(router.broker) as br:
await br.publish(None, queue, key=b"key")

mock.assert_called_once_with(_BodyModel(msg=expected))

async def test_tombstone_resolves_optional_body_in_dependency(
self, queue: str, mock: Mock
) -> None:
"""Fixes https://github.com/ag2ai/faststream/issues/1967."""

class _BodyModel(BaseModel):
x: int

async def parse_body(
msg: Annotated[_BodyModel | None, Body()] = None,
) -> _BodyModel | None:
return msg

router = self.router_class()
args, kwargs = self.get_subscriber_params(queue)

@router.subscriber(*args, **kwargs)
async def handler(msg: Annotated[_BodyModel | None, Depends(parse_body)]) -> None:
mock(msg)

async with self.patch_broker(router.broker) as br:
await br.publish(None, queue, key=b"key")

mock.assert_called_once_with(None)


@pytest.mark.asyncio()
class FastAPILocalTestcase(BaseTestcaseConfig[Any]):
router_class: Any
Expand Down
Loading
Loading