Skip to content

BasePrometheusMiddleware

faststream.prometheus.middleware.BasePrometheusMiddleware #

BasePrometheusMiddleware(
    msg: AnyMsg | None,
    /,
    *,
    settings_provider_factory: Callable[
        [AnyMsg | None],
        MetricsSettingsProvider[AnyMsg, PublishCommandType]
        | None,
    ],
    metrics_manager: MetricsManager,
    context: ContextRepo,
    custom_labels: dict[str, str],
)

Bases: BaseMiddleware[PublishCommandType, AnyMsg | None], Generic[PublishCommandType, AnyMsg]

Source code in faststream/prometheus/middleware.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def __init__(
    self,
    msg: AnyMsg | None,
    /,
    *,
    settings_provider_factory: Callable[
        [AnyMsg | None],
        MetricsSettingsProvider[AnyMsg, PublishCommandType] | None,
    ],
    metrics_manager: MetricsManager,
    context: "ContextRepo",
    custom_labels: dict[str, str],
) -> None:
    self._metrics_manager = metrics_manager
    self._settings_provider = settings_provider_factory(msg)
    self._custom_labels = custom_labels
    super().__init__(msg, context=context)

msg instance-attribute #

msg = msg

context instance-attribute #

context = context

consume_scope async #

consume_scope(
    call_next: AsyncFuncAny, msg: StreamMessage[AnyMsg]
) -> Any
Source code in faststream/prometheus/middleware.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
async def consume_scope(
    self,
    call_next: "AsyncFuncAny",
    msg: "StreamMessage[AnyMsg]",
) -> Any:
    if self._settings_provider is None or msg.source_type is SourceType.RESPONSE:
        return await call_next(msg)

    messaging_system = self._settings_provider.messaging_system
    consume_attrs = self._settings_provider.get_consume_attrs_from_message(msg)
    destination_name = consume_attrs["destination_name"]

    self._metrics_manager.add_received_message(
        amount=consume_attrs["messages_count"],
        broker=messaging_system,
        handler=destination_name,
        **self._custom_labels,
    )

    self._metrics_manager.observe_received_messages_size(
        size=consume_attrs["message_size"],
        broker=messaging_system,
        handler=destination_name,
        **self._custom_labels,
    )

    self._metrics_manager.add_received_message_in_process(
        amount=consume_attrs["messages_count"],
        broker=messaging_system,
        handler=destination_name,
        **self._custom_labels,
    )

    err: Exception | None = None
    start_time = time.perf_counter()

    try:
        result = await call_next(msg)

    except Exception as e:
        err = e

        if not isinstance(err, IgnoredException):
            self._metrics_manager.add_received_processed_message_exception(
                exception_type=type(err).__name__,
                broker=messaging_system,
                handler=destination_name,
                **self._custom_labels,
            )
        raise

    finally:
        duration = time.perf_counter() - start_time
        self._metrics_manager.observe_received_processed_message_duration(
            duration=duration,
            broker=messaging_system,
            handler=destination_name,
            **self._custom_labels,
        )

        self._metrics_manager.remove_received_message_in_process(
            amount=consume_attrs["messages_count"],
            broker=messaging_system,
            handler=destination_name,
            **self._custom_labels,
        )

        status = ProcessingStatus.acked

        if msg.committed or err:
            status = (
                PROCESSING_STATUS_BY_ACK_STATUS.get(msg.committed)  # type: ignore[arg-type]
                or PROCESSING_STATUS_BY_HANDLER_EXCEPTION_MAP.get(type(err))
                or ProcessingStatus.error
            )

        self._metrics_manager.add_received_processed_message(
            amount=consume_attrs["messages_count"],
            status=status,
            broker=messaging_system,
            handler=destination_name,
            **self._custom_labels,
        )

    return result

publish_scope async #

publish_scope(
    call_next: Callable[
        [PublishCommandType], Awaitable[Any]
    ],
    cmd: PublishCommandType,
) -> Any
Source code in faststream/prometheus/middleware.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
async def publish_scope(
    self,
    call_next: Callable[[PublishCommandType], Awaitable[Any]],
    cmd: PublishCommandType,
) -> Any:
    if self._settings_provider is None or cmd.publish_type is PublishType.REPLY:
        return await call_next(cmd)

    destination_name = self._settings_provider.get_publish_destination_name_from_cmd(
        cmd
    )
    messaging_system = self._settings_provider.messaging_system

    err: Exception | None = None
    start_time = time.perf_counter()

    try:
        result = await call_next(cmd)

    except Exception as e:
        err = e
        self._metrics_manager.add_published_message_exception(
            exception_type=type(err).__name__,
            broker=messaging_system,
            destination=destination_name,
            **self._custom_labels,
        )
        raise

    finally:
        duration = time.perf_counter() - start_time

        self._metrics_manager.observe_published_message_duration(
            duration=duration,
            broker=messaging_system,
            destination=destination_name,
            **self._custom_labels,
        )

        status = PublishingStatus.error if err else PublishingStatus.success

        self._metrics_manager.add_published_message(
            amount=len(cmd.batch_bodies),
            status=status,
            broker=messaging_system,
            destination=destination_name,
            **self._custom_labels,
        )

    return result

on_receive async #

on_receive() -> None

Hook to call on message receive.

Source code in faststream/_internal/middlewares.py
31
32
async def on_receive(self) -> None:
    """Hook to call on message receive."""

after_processed async #

after_processed(
    exc_type: type[BaseException] | None = None,
    exc_val: BaseException | None = None,
    exc_tb: Optional[TracebackType] = None,
) -> bool | None

Asynchronously called after processing.

Source code in faststream/_internal/middlewares.py
34
35
36
37
38
39
40
41
async def after_processed(  # ruff: ignore[no-self-use]
    self,
    exc_type: type[BaseException] | None = None,
    exc_val: BaseException | None = None,
    exc_tb: Optional["TracebackType"] = None,
) -> bool | None:
    """Asynchronously called after processing."""
    return False