11from asyncio import Future
22from datetime import timedelta
3+ from types import TracebackType
34from typing import final
45
56from natsrpy ._natsrpy_rs .js import JetStreamMessage
@@ -12,8 +13,11 @@ __all__ = [
1213 "PriorityPolicy" ,
1314 "PullConsumer" ,
1415 "PullConsumerConfig" ,
16+ "PullConsumerContextManager" ,
17+ "PullConsumerFetcher" ,
1518 "PushConsumer" ,
1619 "PushConsumerConfig" ,
20+ "PushConsumerContextManager" ,
1721 "ReplayPolicy" ,
1822]
1923
@@ -283,6 +287,28 @@ class MessagesIterator:
283287 def __aiter__ (self ) -> Self : ...
284288 def __anext__ (self ) -> Future [JetStreamMessage ]: ...
285289
290+ @final
291+ class PushConsumerContextManager :
292+ """
293+ Context manager for consuming messages from push-based consumer.
294+
295+ This class is used to scope the message consumption.
296+ Mostly used for opentelemetry support.
297+ """
298+
299+ def __aenter__ (self ) -> Future [MessagesIterator ]:
300+ """Get an async iterator for consuming messages.
301+
302+ :return: an async iterator over JetStream messages.
303+ """
304+
305+ def __aexit__ (
306+ self ,
307+ _exc_type : type [BaseException ] | None = None ,
308+ _exc_val : BaseException | None = None ,
309+ _exc_tb : TracebackType | None = None ,
310+ ) -> Future [None ]: ...
311+
286312@final
287313class PushConsumer :
288314 """A push-based JetStream consumer.
@@ -298,11 +324,26 @@ class PushConsumer:
298324 def stream_name (self ) -> str :
299325 """Get stream name that this consumer attached to."""
300326
301- def messages (self ) -> Future [ MessagesIterator ] :
302- """Get an async iterator for consuming messages.
327+ def consume (self ) -> PushConsumerContextManager :
328+ """Start consuming messages."""
303329
304- :return: an async iterator over JetStream messages.
305- """
330+ @final
331+ class PullConsumerFetcher :
332+ def __aiter__ (self ) -> Self :
333+ """Returns this very object."""
334+
335+ def __anext__ (self ) -> Future [JetStreamMessage ]:
336+ """Get a next message from the stream."""
337+
338+ @final
339+ class PullConsumerContextManager :
340+ def __aenter__ (self ) -> Future [PullConsumerFetcher ]: ...
341+ def __aexit__ (
342+ self ,
343+ _exc_type : type [BaseException ] | None = None ,
344+ _exc_val : BaseException | None = None ,
345+ _exc_tb : TracebackType | None = None ,
346+ ) -> Future [None ]: ...
306347
307348@final
308349class PullConsumer :
@@ -319,6 +360,9 @@ class PullConsumer:
319360 def stream_name (self ) -> str :
320361 """Get stream name that this consumer attached to."""
321362
363+ def consume (self ) -> PullConsumerContextManager :
364+ """Start consuming messages."""
365+
322366 def fetch (
323367 self ,
324368 max_messages : int | None = None ,
0 commit comments