Coverage for faststream/message/message.py: 96%
45 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
1from enum import Enum
2from typing import (
3 TYPE_CHECKING,
4 Any,
5 Generic,
6 Optional,
7 TypeVar,
8)
9from uuid import uuid4
11from typing_extensions import Self
13from .source_type import SourceType
15if TYPE_CHECKING:
16 from faststream._internal.types import AsyncCallable
18# prevent circular imports
19MsgType = TypeVar("MsgType")
21_NOT_CACHED = object()
24class AckStatus(str, Enum):
25 ACKED = "ACKED"
26 NACKED = "NACKED"
27 REJECTED = "REJECTED"
30class StreamMessage(Generic[MsgType]):
31 """Generic class to represent a stream message."""
33 def __init__(
34 self,
35 raw_message: "MsgType",
36 body: bytes | Any,
37 *,
38 headers: dict[str, Any] | None = None,
39 reply_to: str = "",
40 batch_headers: list[dict[str, Any]] | None = None,
41 path: dict[str, Any] | None = None,
42 content_type: str | None = None,
43 correlation_id: str | None = None,
44 message_id: str | None = None,
45 source_type: SourceType = SourceType.CONSUME,
46 ) -> None:
47 self.raw_message = raw_message
48 self.body = body
49 self.reply_to = reply_to
50 self.content_type = content_type
51 self.source_type = source_type
53 self.headers = headers or {}
54 self.batch_headers = batch_headers or []
55 self.path = path or {}
56 self.correlation_id = correlation_id or str(uuid4())
57 self.message_id = message_id or self.correlation_id
59 self.committed: AckStatus | None = None
60 self.processed = False
62 # Setup later
63 self.__decoder: AsyncCallable | None = None
64 self.__decoded_caches: dict[
65 Any,
66 Any,
67 ] = {} # Cache values between filters and tests
69 def set_decoder(self, decoder: "AsyncCallable") -> None:
70 self.__decoder = decoder
72 def clear_cache(self) -> None:
73 self.__decoded_caches.clear()
75 def __copy__(self) -> Self:
76 message = self.__class__.__new__(self.__class__)
77 message.__dict__.update(self.__dict__)
78 # A copy answers for its own body, so it must not share the decode cache
79 message.__decoded_caches = {}
80 return message
82 def __repr__(self) -> str:
83 inner = ", ".join(
84 filter(
85 bool,
86 (
87 f"body={self.body!r}",
88 f"content_type={self.content_type}",
89 f"message_id={self.message_id}",
90 f"correlation_id={self.correlation_id}",
91 f"reply_to={self.reply_to}" if self.reply_to else "",
92 f"headers={self.headers}",
93 f"path={self.path}",
94 f"committed={self.committed}",
95 f"raw_message={self.raw_message}",
96 ),
97 ),
98 )
100 return f"{self.__class__.__name__}({inner})"
102 async def decode(self) -> Optional["Any"]:
103 """Serialize the message by lazy decoder.
105 Returns a cache after first usage. To prevent such behavior, please call
106 `message.clear_cache()` after `message.body` changes.
107 """
108 assert self.__decoder, "You should call `set_decoder()` method first."
110 if (
111 result := self.__decoded_caches.get(self.__decoder, _NOT_CACHED)
112 ) is _NOT_CACHED:
113 result = self.__decoded_caches[self.__decoder] = await self.__decoder(self)
115 return result
117 async def ack(self) -> None:
118 if self.committed is None:
119 self.committed = AckStatus.ACKED
121 async def nack(self) -> None:
122 if self.committed is None: 122 ↛ exitline 122 didn't return from function 'nack' because the condition on line 122 was always true
123 self.committed = AckStatus.NACKED
125 async def reject(self) -> None:
126 if self.committed is None:
127 self.committed = AckStatus.REJECTED