acemq_amqp.telemetry
What the library is doing, and whether it is still working.
Two questions an operator asks about a service that consumes a queue, and the library is the only thing that can answer either. How much is going through, how much is failing and how long a handler takes are numbers nobody outside can see; whether the connection is really up — as opposed to a socket that is open and wedged — is a question only something holding the connection can ask.
The metric names are the same in Java, Go, Ruby, .NET and here, so a dashboard
built against one library reads against another. Java publishes them through
Micrometer and .NET through System.Diagnostics.Metrics; Python's standard
library has no metrics interface at all, which is why this module defines a
small one and calls it. Implement Observer against Prometheus,
OpenTelemetry, statsd or a log line — or use Metrics, which keeps the
numbers in memory and is enough for a health endpoint, a test, or a signal
handler that prints them.
Taking a dependency on a metrics library instead would put every user of this package on the one it chose. The transport already makes that argument and wins it: aio-pika is an extra, and so is anything here that needs more than the standard library.
Health is a HealthReport with three states rather than a boolean.
degraded exists because "working, but not as well as it should" is worth an
alert and is not worth taking an instance out of rotation — the replacement will
almost certainly be degraded too.
1# Copyright 2026 AceMQ. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# https://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""What the library is doing, and whether it is still working. 16 17Two questions an operator asks about a service that consumes a queue, and the 18library is the only thing that can answer either. How much is going through, how 19much is failing and how long a handler takes are numbers nobody outside can see; 20whether the connection is really up — as opposed to a socket that is open and 21wedged — is a question only something holding the connection can ask. 22 23The metric names are the same in Java, Go, Ruby, .NET and here, so a dashboard 24built against one library reads against another. Java publishes them through 25Micrometer and .NET through ``System.Diagnostics.Metrics``; Python's standard 26library has no metrics interface at all, which is why this module defines a 27small one and calls it. Implement :class:`Observer` against Prometheus, 28OpenTelemetry, statsd or a log line — or use :class:`Metrics`, which keeps the 29numbers in memory and is enough for a health endpoint, a test, or a signal 30handler that prints them. 31 32Taking a dependency on a metrics library instead would put every user of this 33package on the one it chose. The transport already makes that argument and wins 34it: aio-pika is an extra, and so is anything here that needs more than the 35standard library. 36 37Health is a :class:`HealthReport` with three states rather than a boolean. 38``degraded`` exists because "working, but not as well as it should" is worth an 39alert and is not worth taking an instance out of rotation — the replacement will 40almost certainly be degraded too. 41""" 42 43from __future__ import annotations 44 45import asyncio 46import threading 47from collections.abc import Mapping 48from dataclasses import dataclass, field 49from datetime import datetime, timezone 50from enum import Enum 51from typing import Any, Protocol, runtime_checkable 52 53#: Publishes, tagged with :data:`TAG_OUTCOME`. 54#: 55#: One counter with an outcome rather than one counter per outcome, because a 56#: dashboard that wants the failure rate wants a ratio of two series of the same 57#: metric and not a division between two differently-named ones. 58METRIC_PUBLISH_TOTAL = "acemq.publish.total" 59 60#: How long a publish took, in seconds, tagged with :data:`TAG_OUTCOME` and 61#: carrying the same labels as :data:`METRIC_PUBLISH_TOTAL`. 62#: 63#: From calling ``send`` to the broker answering, so it includes the encode, the 64#: interceptor chain and the confirm round trip — everything a caller waits for. 65#: Recorded whatever the outcome, including a publish that failed and one that 66#: reached no queue, because the slow publishes are the interesting ones and a 67#: timing that covered only the successes would drop them. 68#: 69#: The same labels as the total beside it, deliberately: a dashboard dividing one 70#: into the other needs both series cut the same way, and a duration with a label 71#: the total does not have cannot be divided into it. 72METRIC_PUBLISH_DURATION = "acemq.publish.duration" 73 74#: Deliveries that were settled, tagged with :data:`TAG_OUTCOME`. 75#: 76#: Counted once per delivery, from the settlement rather than from what the 77#: handler asked for: a handler asking for a retry it has no attempts left for 78#: is dead-lettered, and this says so. The sum across the outcomes is how many 79#: messages were handled. 80METRIC_CONSUME_TOTAL = "acemq.consume.total" 81 82#: How long a delivery took, in seconds, tagged with :data:`TAG_OUTCOME`. 83#: 84#: Timed around the interceptors as well as the handler, because what an 85#: operator wants to know is how long a message takes to deal with, and an 86#: interceptor that opens a transaction is part of dealing with it. 87METRIC_CONSUME_DURATION = "acemq.consume.duration" 88 89#: Which attempt a delivery was on when it was handled, as a distribution, 90#: labelled :data:`TAG_QUEUE`. 91#: 92#: Not a duration, and the only metric here that is not. A rising distribution is 93#: a dependency in trouble, and it says so earlier than anything else does: the 94#: dead letters only move once the attempts run out, so a queue whose messages 95#: have started needing three tries each looks entirely healthy on every other 96#: number until the first one gives up. 97#: 98#: Recorded through :meth:`Observer.observe` because that is the only 99#: distribution the interface has. Adding a method for it would break every 100#: observer an application has already written, for one metric — see the note on 101#: :meth:`Observer.observe` for what that means for an implementation. 102METRIC_CONSUME_ATTEMPTS = "acemq.consume.attempts" 103 104#: How many messages are in a handler right now, as a gauge. Bounded by prefetch 105#: times concurrency. 106METRIC_CONSUME_IN_FLIGHT = "acemq.consume.in.flight" 107 108#: Messages sent to a retry queue, or otherwise given another attempt. Labelled 109#: ``where``: ``broker``, ``consumer`` or ``requeued``. 110#: 111#: Kept beside :data:`METRIC_CONSUME_TOTAL` rather than folded into it, exactly 112#: as Java keeps it: the outcome on a delivery says what was decided, and this 113#: says how many messages are going round again, which is the number an alert is 114#: written against. 115METRIC_RETRIED_TOTAL = "acemq.messages.retried.total" 116 117#: Messages set aside, tagged with :data:`TAG_OUTCOME`: ``dead_lettered`` for one 118#: that ran out of attempts and went to ``{queue}.dlq``, ``parked`` for one that 119#: nothing could read and went to ``{queue}.parked``. 120#: 121#: One counter split by the outcome rather than two metrics, which is what Java 122#: settled on: both are a message this queue gave up on, and an operator asking 123#: how much a queue is giving up on wants one number that can then be split. The 124#: split still matters — a message that failed five times and a message nothing 125#: could read are different problems with different answers, and whoever drains 126#: the queue should not have to sort them by hand — which is what the tag is for. 127METRIC_DEAD_LETTERED_TOTAL = "acemq.messages.dead.lettered.total" 128 129#: Long retries that had to wait in the consumer because the rung queue they 130#: were meant to wait on is not on the broker. 131#: 132#: Worth an alert. Nothing breaks — the message is still retried and the wait 133#: still happens — but the reason the rung exists is gone: a consumer restart 134#: mid-wait now shortens a five-minute backoff to nothing, and the only other 135#: sign of it is one log line on a path nobody is watching. 136METRIC_RUNG_MISSING = "acemq.retry.rung.missing" 137 138#: Messages that could not be moved to a dead-letter or parking queue, usually 139#: because it was never declared. The message is rejected to the broker instead, 140#: which is the last thing between it and nothing. Labelled :data:`TAG_QUEUE` and 141#: :data:`TAG_TARGET`. 142METRIC_SET_ASIDE_FAILED = "acemq.messages.set.aside.failed" 143 144#: Request and reply round trips, tagged with :data:`TAG_ROUTING_KEY` and 145#: :data:`TAG_OUTCOME`: :data:`OUTCOME_ANSWERED`, :data:`OUTCOME_TIMED_OUT` or 146#: :data:`OUTCOME_FAILED`. 147#: 148#: The caller's number, and only the caller's. A responder's side is an ordinary 149#: queue and is counted on :data:`METRIC_CONSUME_TOTAL` like any other; what 150#: nothing else can see is how long *asking* took, because the publish and the 151#: reply's delivery are two unrelated hops and neither of them is the round trip. 152METRIC_REQUEST_TOTAL = "acemq.request.total" 153 154#: How long a round trip took, in seconds, carrying the same labels as 155#: :data:`METRIC_REQUEST_TOTAL`. 156#: 157#: Measured as the caller experienced it: from before the request is published to 158#: after the reply is in hand, so the publish, the responder's work and the reply 159#: coming back are all inside it. A request that times out is recorded too, at 160#: its deadline, because a p99 that quietly drops the slowest calls is a p99 that 161#: says a service is fast right up to the point where nothing answers at all. 162METRIC_REQUEST_DURATION = "acemq.request.duration" 163 164#: Outbox records the relay has handled, tagged with :data:`TAG_OUTCOME`: 165#: :data:`OUTCOME_PUBLISHED` or :data:`OUTCOME_FAILED`. Labelled 166#: :data:`TAG_EXCHANGE` and :data:`TAG_ROUTING_KEY` as well, because a relay 167#: drains one outbox into many destinations and "the relay is behind" is nearly 168#: always "the relay is behind *on one exchange*". 169METRIC_OUTBOX_TOTAL = "acemq.outbox.total" 170 171#: Routing-slip runs that reached the end of their itinerary, labelled 172#: :data:`TAG_PIPELINE`, :data:`TAG_STEP` and :data:`TAG_OUTCOME`. 173#: 174#: Java's ``acemq.pipeline.run.total``, written from the same place: the step 175#: that found no next stop is the step that finished the run, so the counter goes 176#: up exactly once per run however many services it passed through. 177#: 178#: The outcome is :data:`OUTCOME_COMPLETED`, or :data:`OUTCOME_ENDED_EARLY` for 179#: a step that returned :data:`~acemq_amqp.patterns.NOTHING` with stops still to 180#: go, as Java writes it. 181METRIC_PIPELINE_RUN_TOTAL = "acemq.pipeline.run.total" 182 183#: How old a message was when it left a pipeline, in seconds, carrying the same 184#: labels as :data:`METRIC_PIPELINE_RUN_TOTAL`. 185#: 186#: The *run's* duration and not the step's, which is why it is the envelope's age 187#: rather than a timer: the envelope was created when the message entered the 188#: pipeline and carried through every hop, so this is the only number that spans 189#: services. A per-step timing is :data:`METRIC_CONSUME_DURATION` on each step's 190#: own queue, and summing those misses every second a message spent waiting on a 191#: queue between two of them — which on a busy pipeline is most of the answer. 192METRIC_PIPELINE_RUN_DURATION = "acemq.pipeline.run.duration" 193 194#: How long an outbox record waited between being committed and being published, 195#: in seconds. Recorded only for a record that went out, and carrying the same 196#: labels as :data:`METRIC_OUTBOX_TOTAL`. 197#: 198#: **The one number that reveals a stopped relay.** A committed, unpublished row 199#: is a message that exists, is owed to somebody, and appears in no queue depth 200#: anywhere: publish rates, consume rates and queue depths all read as a system 201#: with nothing to send, which is exactly what a system that has stopped sending 202#: looks like from outside. 203#: 204#: Measured from the record's own ``created_at`` — when the transaction that 205#: decided the message committed — and not from the start of the sweep that 206#: picked it up. The question a lag answers is how long somebody has been owed 207#: this message, so the wait for a sweep is part of the answer rather than the 208#: start of it; timed from the sweep, a relay that has been down for an hour 209#: reports the same handful of milliseconds as one that is keeping up. 210METRIC_OUTBOX_LAG = "acemq.outbox.lag" 211 212# ---------- tag names ---------- 213# 214# Dotted, because Micrometer and OpenTelemetry are dotted and these have to be 215# the same words in five languages. ``routing.key`` and ``message.type`` are 216# both illegal Prometheus label names; :mod:`acemq_amqp.prometheus` and 217# :func:`prometheus_text` rewrite the dots to underscores at the point of 218# export, which is the only place the restriction applies. 219 220#: The exchange a message was published to, empty for the default exchange. 221TAG_EXCHANGE = "exchange" 222 223#: The routing key used, or the queue name when publishing without an exchange. 224TAG_ROUTING_KEY = "routing.key" 225 226#: The queue a delivery came from. 227TAG_QUEUE = "queue" 228 229#: Where a message was being set aside to when that failed: the dead-letter 230#: queue or the parking lot. Bounded by the topology, so it is safe as a tag. 231TAG_TARGET = "target" 232 233#: The pipeline a routing-slip run belongs to, which is its exchange. Empty when 234#: the run carried a JSON slip that names no pipeline. 235TAG_PIPELINE = "pipeline" 236 237#: The step a pipeline run was at when it finished. Bounded by the route, which 238#: names a fixed handful of steps, so it is safe as a tag. 239TAG_STEP = "step" 240 241#: What happened. The publish outcomes are below; the delivery outcomes are 242#: :data:`~acemq_amqp.ack.OUTCOME_ACKED` and its neighbours in 243#: :mod:`acemq_amqp.ack`, which are the same words the settlement and the span 244#: already use. 245TAG_OUTCOME = "outcome" 246 247#: A publish the broker took responsibility for. 248OUTCOME_CONFIRMED = "confirmed" 249 250#: A publish that went out with nothing promising anything about it. Publisher 251#: confirms were not on. 252OUTCOME_PUBLISHED = "published" 253 254#: A mandatory publish the broker had no queue for. The quietest failure AMQP 255#: has, and the reason ``mandatory`` is worth setting. 256OUTCOME_UNROUTABLE = "unroutable" 257 258#: A publish that may have been lost: the broker nacked it, the confirm never 259#: came, or the connection failed partway. The message may or may not be on the 260#: broker, which is what makes this the outcome worth alerting on. 261OUTCOME_FAILED = "failed" 262 263#: A publish this library declined before writing anything to the wire — today 264#: a :class:`~acemq_amqp.PublishingPausedError`, raised while the broker has 265#: blocked the connection. Nothing was sent, so nothing was lost and retrying 266#: cannot duplicate it. Kept apart from :data:`OUTCOME_FAILED` so a broker 267#: alarm does not read as message loss; the same word in all five libraries. 268OUTCOME_REFUSED = "refused" 269 270#: A request that got its reply. 271OUTCOME_ANSWERED = "answered" 272 273#: A request that reached its deadline with no reply. 274OUTCOME_TIMED_OUT = "timed_out" 275 276#: A pipeline run that reached the end of its itinerary. 277OUTCOME_COMPLETED = "completed" 278 279#: A pipeline run that stopped before the end of its route because a step chose 280#: to stop it: a :data:`~acemq_amqp.patterns.Stage` that returned 281#: :data:`~acemq_amqp.patterns.NOTHING` with stops still to go. A ``then`` chain 282#: returning ``NOTHING`` does not write it — it has no pipeline and no run. 283OUTCOME_ENDED_EARLY = "ended_early" 284 285 286@runtime_checkable 287class Observer(Protocol): 288 """Told what the library is doing. 289 290 Every method is called on the path a message takes, so none of them may 291 block and all of them have to be safe to call from several tasks at once. 292 An observer that talks to the network on each call is an observer that makes 293 every publish as slow as the network it talks to; buffer, and flush 294 somewhere else. 295 296 Nothing here is awaitable, deliberately. A metrics call that could suspend 297 would reorder the code around it and turn "count this" into a scheduling 298 decision, and no metrics library needs it. 299 """ 300 301 def count(self, metric: str, delta: int, labels: Mapping[str, str]) -> None: 302 """Adds to a counter.""" 303 304 def observe(self, metric: str, seconds: float, labels: Mapping[str, str]) -> None: 305 """Records one sample of a distribution. 306 307 A duration in seconds for every metric but one. The exception is 308 :data:`METRIC_CONSUME_ATTEMPTS`, which is a count of attempts and is 309 recorded here because this is the only distribution the interface has — 310 Java uses a Micrometer ``DistributionSummary`` for it and a ``Timer`` for 311 the rest, and this interface has one method where Java has two. 312 313 The argument keeps its name because renaming it would break every 314 observer that passes it by keyword, and because it is a duration in every 315 case but that one. An implementation that puts durations into histogram 316 buckets should give that metric its own: seconds-shaped buckets over a 317 value of 1, 2 or 3 report an attempt count as a handful of very fast 318 handlers. :class:`~acemq_amqp.prometheus.PrometheusObserver` does exactly 319 that, with :data:`~acemq_amqp.prometheus.DEFAULT_ATTEMPT_BUCKETS`. 320 """ 321 322 def gauge(self, metric: str, value: int, labels: Mapping[str, str]) -> None: 323 """Sets a current value.""" 324 325 326class NullObserver: 327 """An observer that does nothing, which is what a connection has by default. 328 329 A real object rather than ``None`` checked for at each call site, because 330 the alternative is a branch on every publish and every delivery, and one of 331 them is eventually written the wrong way round. 332 """ 333 334 def count(self, metric: str, delta: int, labels: Mapping[str, str]) -> None: 335 return None 336 337 def observe(self, metric: str, seconds: float, labels: Mapping[str, str]) -> None: 338 return None 339 340 def gauge(self, metric: str, value: int, labels: Mapping[str, str]) -> None: 341 return None 342 343 344@dataclass(frozen=True, slots=True) 345class DurationSummary: 346 """What a :class:`Metrics` knows about a timing. 347 348 Deliberately not percentiles. Computing those needs either every sample kept 349 or a sketch, and a library that quietly did either would be making a 350 decision about memory that belongs to the application. 351 """ 352 353 count: int = 0 354 total: float = 0.0 355 fastest: float = 0.0 356 slowest: float = 0.0 357 358 @property 359 def mean(self) -> float: 360 """The average, or zero when nothing has been recorded.""" 361 return self.total / self.count if self.count else 0.0 362 363 364class Metrics: 365 """An :class:`Observer` that keeps the numbers in memory. 366 367 Enough to serve from a health endpoint, assert on in a test, or print on a 368 signal. It is not a substitute for a real metrics system: no histograms, no 369 percentiles, and nothing is exported anywhere. :func:`prometheus_text` 370 renders what it has for a scraper, which needs no dependency at all. 371 372 Locked rather than relying on the event loop, because the blocking API in 373 :mod:`acemq_amqp.sync` runs handlers on a thread pool and a counter read 374 from two threads at once is a counter that loses increments. 375 """ 376 377 def __init__(self) -> None: 378 self._lock = threading.Lock() 379 self._counts: dict[str, int] = {} 380 self._gauges: dict[str, int] = {} 381 self._durations: dict[str, DurationSummary] = {} 382 383 def count(self, metric: str, delta: int, labels: Mapping[str, str]) -> None: 384 key = metric_key(metric, labels) 385 with self._lock: 386 self._counts[key] = self._counts.get(key, 0) + delta 387 388 def gauge(self, metric: str, value: int, labels: Mapping[str, str]) -> None: 389 key = metric_key(metric, labels) 390 with self._lock: 391 self._gauges[key] = value 392 393 def observe(self, metric: str, seconds: float, labels: Mapping[str, str]) -> None: 394 key = metric_key(metric, labels) 395 with self._lock: 396 existing = self._durations.get(key) 397 if existing is None: 398 self._durations[key] = DurationSummary(1, seconds, seconds, seconds) 399 return 400 self._durations[key] = DurationSummary( 401 count=existing.count + 1, 402 total=existing.total + seconds, 403 fastest=min(existing.fastest, seconds), 404 slowest=max(existing.slowest, seconds), 405 ) 406 407 @property 408 def counts(self) -> dict[str, int]: 409 """Every counter, keyed by metric and labels.""" 410 with self._lock: 411 return dict(self._counts) 412 413 @property 414 def gauges(self) -> dict[str, int]: 415 """Every gauge.""" 416 with self._lock: 417 return dict(self._gauges) 418 419 @property 420 def durations(self) -> dict[str, DurationSummary]: 421 """A summary per timing: how many, the total, the fastest, the slowest.""" 422 with self._lock: 423 return dict(self._durations) 424 425 def __str__(self) -> str: 426 lines = [f"{name} {value}" for name, value in sorted(self.counts.items())] 427 lines += [f"{name} {value}" for name, value in sorted(self.gauges.items())] 428 lines += [ 429 f"{name} count={summary.count} mean={summary.mean:.4f}s" 430 for name, summary in sorted(self.durations.items()) 431 ] 432 return "\n".join(lines) or "nothing recorded yet" 433 434 435def metric_key(metric: str, labels: Mapping[str, str]) -> str: 436 """A metric and its labels as one string. 437 438 Sorted, so the same labels always give the same key however the mapping was 439 built. Unsorted, one counter quietly becomes several that each hold part of 440 the answer. 441 """ 442 if not labels: 443 return metric 444 rendered = ",".join(f'{name}="{labels[name]}"' for name in sorted(labels)) 445 return f"{metric}{{{rendered}}}" 446 447 448def prometheus_text(metrics: Metrics) -> str: 449 """Renders a :class:`Metrics` in the Prometheus text format. 450 451 Written out rather than through a client library, so a service that only 452 wants a scrape endpoint needs nothing installed. The format is small and 453 stable: a TYPE line, then samples, with dots in the metric name — and in the 454 label names, where ``routing.key`` and ``message.type`` have the same 455 problem — replaced by underscores, because Prometheus allows them in 456 neither. 457 458 A real registry — exemplars, native histograms, a shared process collector — 459 is what :mod:`acemq_amqp.prometheus` is for, and it needs the extra. 460 461 :param metrics: what to render 462 :returns: the body of a ``/acemq-metrics`` response 463 """ 464 lines: list[str] = [] 465 for name, value in sorted(metrics.counts.items()): 466 metric, labels = _split_key(name) 467 base = _prometheus_name(metric) 468 lines += [f"# TYPE {base} counter", f"{base}{labels} {value}"] 469 for name, value in sorted(metrics.gauges.items()): 470 metric, labels = _split_key(name) 471 base = _prometheus_name(metric) 472 lines += [f"# TYPE {base} gauge", f"{base}{labels} {value}"] 473 for name, summary in sorted(metrics.durations.items()): 474 metric, labels = _split_key(name) 475 base = _prometheus_name(metric) 476 lines += [ 477 f"# TYPE {base} summary", 478 f"{base}_count{labels} {summary.count}", 479 f"{base}_sum{labels} {summary.total}", 480 ] 481 return "\n".join(lines) + ("\n" if lines else "") 482 483 484def _split_key(key: str) -> tuple[str, str]: 485 """A key back into its metric and its labels, both ready for a scraper. 486 487 The label names are rewritten here as well as the metric name, because 488 ``routing.key`` and ``message.type`` are no more legal as Prometheus label 489 names than a dotted metric name is, and a scrape carrying one is a scrape 490 the server rejects in full — the sample it could not parse is not the only 491 one lost. 492 """ 493 if "{" not in key: 494 return key, "" 495 metric, _, labels = key.partition("{") 496 return metric, "{" + _prometheus_labels(labels[:-1]) + "}" 497 498 499def _prometheus_labels(rendered: str) -> str: 500 """``routing.key="a.b"`` becomes ``routing_key="a.b"``. 501 502 Names only. A label *value* is where a queue name lives, and queue names 503 have dots in them that mean something — rewriting those would report a 504 different queue than the one the message came from. 505 506 The parse leans on :func:`metric_key` having written this string: a name, an 507 equals sign, then a value between the next two quotes. Anything that does 508 not read that way is handed back untouched, because a mangled scrape line is 509 worse than an odd one. 510 """ 511 pairs: list[str] = [] 512 rest = rendered 513 while rest: 514 name, equals, rest = rest.partition('=') 515 if not equals or not rest.startswith('"'): 516 return rendered 517 value, quote, rest = rest[1:].partition('"') 518 if not quote: 519 return rendered 520 pairs.append(f'{name.replace(".", "_")}="{value}"') 521 if rest.startswith(","): 522 rest = rest[1:] 523 elif rest: 524 return rendered 525 return ",".join(pairs) 526 527 528def _prometheus_name(metric: str) -> str: 529 return metric.replace(".", "_") 530 531 532class HealthStatus(str, Enum): 533 """How a check turned out.""" 534 535 #: Working. 536 UP = "up" 537 538 #: Not working. A readiness probe should fail on this. 539 DOWN = "down" 540 541 #: Working, but not as well as it should. Worth an alert; not worth taking 542 #: the instance out of rotation, because the replacement will almost 543 #: certainly be degraded too. 544 DEGRADED = "degraded" 545 546 547@dataclass(frozen=True, slots=True) 548class HealthReport: 549 """What a check found. 550 551 :param status: up, down or degraded 552 :param detail: why, when it is not simply up 553 :param checked: when this was worked out, in UTC 554 :param parts: whatever the check wants to show — a consumer count, a 555 round-trip time, the reports of the checks that were combined 556 """ 557 558 status: HealthStatus 559 detail: str = "" 560 checked: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) 561 parts: Mapping[str, Any] = field(default_factory=dict) 562 563 @property 564 def healthy(self) -> bool: 565 """Whether a readiness probe should pass. 566 567 Degraded passes. An instance that is slow is still an instance that 568 works, and taking it out of rotation moves the traffic to one that will 569 be just as slow with more of it. 570 """ 571 return self.status is not HealthStatus.DOWN 572 573 def __str__(self) -> str: 574 return self.status.value if not self.detail else f"{self.status.value}: {self.detail}" 575 576 577@runtime_checkable 578class HealthCheck(Protocol): 579 """Anything that can report on itself. 580 581 The library provides one for the connection; an application adds its own — a 582 database, a downstream service — and :func:`aggregate_health` combines them. 583 """ 584 585 @property 586 def name(self) -> str: 587 """What this check is called in a combined report.""" 588 589 async def check(self) -> HealthReport: 590 """The current state. 591 592 It must return quickly and must not raise: a check that hangs makes a 593 readiness probe hang with it, and a probe that hangs is a pod that never 594 comes back. 595 """ 596 597 598async def aggregate_health(*checks: HealthCheck, timeout: float = 5.0) -> HealthReport: 599 """Runs every check at once and combines the answers. 600 601 The combined status is the worst of them: one thing being down makes the 602 whole report down, because a service that cannot reach its broker is not 603 ready however healthy the rest of it is. 604 605 At once rather than in turn, so a slow check does not add its latency to the 606 others, and under a deadline, so one that ignores the instruction above 607 still cannot hang the probe. A check that times out is reported as down with 608 the reason, which is the honest reading: something that will not answer in 609 five seconds is not something a request can depend on. 610 611 :param checks: what to ask 612 :param timeout: how long to give all of them together 613 :returns: the combined report 614 """ 615 if not checks: 616 return HealthReport(HealthStatus.UP) 617 618 async def run(check: HealthCheck) -> tuple[str, HealthReport]: 619 try: 620 return check.name, await check.check() 621 except Exception as failure: 622 return check.name, HealthReport( 623 HealthStatus.DOWN, f"the check itself failed: {failure}" 624 ) 625 626 tasks = [asyncio.ensure_future(run(check)) for check in checks] 627 try: 628 done, pending = await asyncio.wait(tasks, timeout=timeout) 629 except asyncio.CancelledError: 630 for task in tasks: 631 task.cancel() 632 raise 633 634 parts: dict[str, Any] = {} 635 worst = HealthStatus.UP 636 reasons: list[str] = [] 637 638 for task in pending: 639 task.cancel() 640 for index, task in enumerate(tasks): 641 if task in done: 642 name, report = task.result() 643 else: 644 name = checks[index].name 645 report = HealthReport(HealthStatus.DOWN, f"did not answer within {timeout}s") 646 parts[name] = report 647 if report.status is HealthStatus.DOWN: 648 worst = HealthStatus.DOWN 649 reasons.append(name) 650 elif report.status is HealthStatus.DEGRADED: 651 if worst is not HealthStatus.DOWN: 652 worst = HealthStatus.DEGRADED 653 reasons.append(name) 654 655 return HealthReport(worst, ", ".join(reasons), parts=parts)
287@runtime_checkable 288class Observer(Protocol): 289 """Told what the library is doing. 290 291 Every method is called on the path a message takes, so none of them may 292 block and all of them have to be safe to call from several tasks at once. 293 An observer that talks to the network on each call is an observer that makes 294 every publish as slow as the network it talks to; buffer, and flush 295 somewhere else. 296 297 Nothing here is awaitable, deliberately. A metrics call that could suspend 298 would reorder the code around it and turn "count this" into a scheduling 299 decision, and no metrics library needs it. 300 """ 301 302 def count(self, metric: str, delta: int, labels: Mapping[str, str]) -> None: 303 """Adds to a counter.""" 304 305 def observe(self, metric: str, seconds: float, labels: Mapping[str, str]) -> None: 306 """Records one sample of a distribution. 307 308 A duration in seconds for every metric but one. The exception is 309 :data:`METRIC_CONSUME_ATTEMPTS`, which is a count of attempts and is 310 recorded here because this is the only distribution the interface has — 311 Java uses a Micrometer ``DistributionSummary`` for it and a ``Timer`` for 312 the rest, and this interface has one method where Java has two. 313 314 The argument keeps its name because renaming it would break every 315 observer that passes it by keyword, and because it is a duration in every 316 case but that one. An implementation that puts durations into histogram 317 buckets should give that metric its own: seconds-shaped buckets over a 318 value of 1, 2 or 3 report an attempt count as a handful of very fast 319 handlers. :class:`~acemq_amqp.prometheus.PrometheusObserver` does exactly 320 that, with :data:`~acemq_amqp.prometheus.DEFAULT_ATTEMPT_BUCKETS`. 321 """ 322 323 def gauge(self, metric: str, value: int, labels: Mapping[str, str]) -> None: 324 """Sets a current value."""
Told what the library is doing.
Every method is called on the path a message takes, so none of them may block and all of them have to be safe to call from several tasks at once. An observer that talks to the network on each call is an observer that makes every publish as slow as the network it talks to; buffer, and flush somewhere else.
Nothing here is awaitable, deliberately. A metrics call that could suspend would reorder the code around it and turn "count this" into a scheduling decision, and no metrics library needs it.
1771def _no_init_or_replace_init(self, *args, **kwargs): 1772 cls = type(self) 1773 1774 if cls._is_protocol: 1775 raise TypeError('Protocols cannot be instantiated') 1776 1777 # Already using a custom `__init__`. No need to calculate correct 1778 # `__init__` to call. This can lead to RecursionError. See bpo-45121. 1779 if cls.__init__ is not _no_init_or_replace_init: 1780 return 1781 1782 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. 1783 # The first instantiation of the subclass will call `_no_init_or_replace_init` which 1784 # searches for a proper new `__init__` in the MRO. The new `__init__` 1785 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent 1786 # instantiation of the protocol subclass will thus use the new 1787 # `__init__` and no longer call `_no_init_or_replace_init`. 1788 for base in cls.__mro__: 1789 init = base.__dict__.get('__init__', _no_init_or_replace_init) 1790 if init is not _no_init_or_replace_init: 1791 cls.__init__ = init 1792 break 1793 else: 1794 # should not happen 1795 cls.__init__ = object.__init__ 1796 1797 cls.__init__(self, *args, **kwargs)
302 def count(self, metric: str, delta: int, labels: Mapping[str, str]) -> None: 303 """Adds to a counter."""
Adds to a counter.
305 def observe(self, metric: str, seconds: float, labels: Mapping[str, str]) -> None: 306 """Records one sample of a distribution. 307 308 A duration in seconds for every metric but one. The exception is 309 :data:`METRIC_CONSUME_ATTEMPTS`, which is a count of attempts and is 310 recorded here because this is the only distribution the interface has — 311 Java uses a Micrometer ``DistributionSummary`` for it and a ``Timer`` for 312 the rest, and this interface has one method where Java has two. 313 314 The argument keeps its name because renaming it would break every 315 observer that passes it by keyword, and because it is a duration in every 316 case but that one. An implementation that puts durations into histogram 317 buckets should give that metric its own: seconds-shaped buckets over a 318 value of 1, 2 or 3 report an attempt count as a handful of very fast 319 handlers. :class:`~acemq_amqp.prometheus.PrometheusObserver` does exactly 320 that, with :data:`~acemq_amqp.prometheus.DEFAULT_ATTEMPT_BUCKETS`. 321 """
Records one sample of a distribution.
A duration in seconds for every metric but one. The exception is
METRIC_CONSUME_ATTEMPTS, which is a count of attempts and is
recorded here because this is the only distribution the interface has —
Java uses a Micrometer DistributionSummary for it and a Timer for
the rest, and this interface has one method where Java has two.
The argument keeps its name because renaming it would break every
observer that passes it by keyword, and because it is a duration in every
case but that one. An implementation that puts durations into histogram
buckets should give that metric its own: seconds-shaped buckets over a
value of 1, 2 or 3 report an attempt count as a handful of very fast
handlers. ~acemq_amqp.prometheus.PrometheusObserver does exactly
that, with ~acemq_amqp.prometheus.DEFAULT_ATTEMPT_BUCKETS.
327class NullObserver: 328 """An observer that does nothing, which is what a connection has by default. 329 330 A real object rather than ``None`` checked for at each call site, because 331 the alternative is a branch on every publish and every delivery, and one of 332 them is eventually written the wrong way round. 333 """ 334 335 def count(self, metric: str, delta: int, labels: Mapping[str, str]) -> None: 336 return None 337 338 def observe(self, metric: str, seconds: float, labels: Mapping[str, str]) -> None: 339 return None 340 341 def gauge(self, metric: str, value: int, labels: Mapping[str, str]) -> None: 342 return None
An observer that does nothing, which is what a connection has by default.
A real object rather than None checked for at each call site, because
the alternative is a branch on every publish and every delivery, and one of
them is eventually written the wrong way round.
345@dataclass(frozen=True, slots=True) 346class DurationSummary: 347 """What a :class:`Metrics` knows about a timing. 348 349 Deliberately not percentiles. Computing those needs either every sample kept 350 or a sketch, and a library that quietly did either would be making a 351 decision about memory that belongs to the application. 352 """ 353 354 count: int = 0 355 total: float = 0.0 356 fastest: float = 0.0 357 slowest: float = 0.0 358 359 @property 360 def mean(self) -> float: 361 """The average, or zero when nothing has been recorded.""" 362 return self.total / self.count if self.count else 0.0
What a Metrics knows about a timing.
Deliberately not percentiles. Computing those needs either every sample kept or a sketch, and a library that quietly did either would be making a decision about memory that belongs to the application.
365class Metrics: 366 """An :class:`Observer` that keeps the numbers in memory. 367 368 Enough to serve from a health endpoint, assert on in a test, or print on a 369 signal. It is not a substitute for a real metrics system: no histograms, no 370 percentiles, and nothing is exported anywhere. :func:`prometheus_text` 371 renders what it has for a scraper, which needs no dependency at all. 372 373 Locked rather than relying on the event loop, because the blocking API in 374 :mod:`acemq_amqp.sync` runs handlers on a thread pool and a counter read 375 from two threads at once is a counter that loses increments. 376 """ 377 378 def __init__(self) -> None: 379 self._lock = threading.Lock() 380 self._counts: dict[str, int] = {} 381 self._gauges: dict[str, int] = {} 382 self._durations: dict[str, DurationSummary] = {} 383 384 def count(self, metric: str, delta: int, labels: Mapping[str, str]) -> None: 385 key = metric_key(metric, labels) 386 with self._lock: 387 self._counts[key] = self._counts.get(key, 0) + delta 388 389 def gauge(self, metric: str, value: int, labels: Mapping[str, str]) -> None: 390 key = metric_key(metric, labels) 391 with self._lock: 392 self._gauges[key] = value 393 394 def observe(self, metric: str, seconds: float, labels: Mapping[str, str]) -> None: 395 key = metric_key(metric, labels) 396 with self._lock: 397 existing = self._durations.get(key) 398 if existing is None: 399 self._durations[key] = DurationSummary(1, seconds, seconds, seconds) 400 return 401 self._durations[key] = DurationSummary( 402 count=existing.count + 1, 403 total=existing.total + seconds, 404 fastest=min(existing.fastest, seconds), 405 slowest=max(existing.slowest, seconds), 406 ) 407 408 @property 409 def counts(self) -> dict[str, int]: 410 """Every counter, keyed by metric and labels.""" 411 with self._lock: 412 return dict(self._counts) 413 414 @property 415 def gauges(self) -> dict[str, int]: 416 """Every gauge.""" 417 with self._lock: 418 return dict(self._gauges) 419 420 @property 421 def durations(self) -> dict[str, DurationSummary]: 422 """A summary per timing: how many, the total, the fastest, the slowest.""" 423 with self._lock: 424 return dict(self._durations) 425 426 def __str__(self) -> str: 427 lines = [f"{name} {value}" for name, value in sorted(self.counts.items())] 428 lines += [f"{name} {value}" for name, value in sorted(self.gauges.items())] 429 lines += [ 430 f"{name} count={summary.count} mean={summary.mean:.4f}s" 431 for name, summary in sorted(self.durations.items()) 432 ] 433 return "\n".join(lines) or "nothing recorded yet"
An Observer that keeps the numbers in memory.
Enough to serve from a health endpoint, assert on in a test, or print on a
signal. It is not a substitute for a real metrics system: no histograms, no
percentiles, and nothing is exported anywhere. prometheus_text()
renders what it has for a scraper, which needs no dependency at all.
Locked rather than relying on the event loop, because the blocking API in
acemq_amqp.sync runs handlers on a thread pool and a counter read
from two threads at once is a counter that loses increments.
394 def observe(self, metric: str, seconds: float, labels: Mapping[str, str]) -> None: 395 key = metric_key(metric, labels) 396 with self._lock: 397 existing = self._durations.get(key) 398 if existing is None: 399 self._durations[key] = DurationSummary(1, seconds, seconds, seconds) 400 return 401 self._durations[key] = DurationSummary( 402 count=existing.count + 1, 403 total=existing.total + seconds, 404 fastest=min(existing.fastest, seconds), 405 slowest=max(existing.slowest, seconds), 406 )
408 @property 409 def counts(self) -> dict[str, int]: 410 """Every counter, keyed by metric and labels.""" 411 with self._lock: 412 return dict(self._counts)
Every counter, keyed by metric and labels.
414 @property 415 def gauges(self) -> dict[str, int]: 416 """Every gauge.""" 417 with self._lock: 418 return dict(self._gauges)
Every gauge.
420 @property 421 def durations(self) -> dict[str, DurationSummary]: 422 """A summary per timing: how many, the total, the fastest, the slowest.""" 423 with self._lock: 424 return dict(self._durations)
A summary per timing: how many, the total, the fastest, the slowest.
436def metric_key(metric: str, labels: Mapping[str, str]) -> str: 437 """A metric and its labels as one string. 438 439 Sorted, so the same labels always give the same key however the mapping was 440 built. Unsorted, one counter quietly becomes several that each hold part of 441 the answer. 442 """ 443 if not labels: 444 return metric 445 rendered = ",".join(f'{name}="{labels[name]}"' for name in sorted(labels)) 446 return f"{metric}{{{rendered}}}"
A metric and its labels as one string.
Sorted, so the same labels always give the same key however the mapping was built. Unsorted, one counter quietly becomes several that each hold part of the answer.
449def prometheus_text(metrics: Metrics) -> str: 450 """Renders a :class:`Metrics` in the Prometheus text format. 451 452 Written out rather than through a client library, so a service that only 453 wants a scrape endpoint needs nothing installed. The format is small and 454 stable: a TYPE line, then samples, with dots in the metric name — and in the 455 label names, where ``routing.key`` and ``message.type`` have the same 456 problem — replaced by underscores, because Prometheus allows them in 457 neither. 458 459 A real registry — exemplars, native histograms, a shared process collector — 460 is what :mod:`acemq_amqp.prometheus` is for, and it needs the extra. 461 462 :param metrics: what to render 463 :returns: the body of a ``/acemq-metrics`` response 464 """ 465 lines: list[str] = [] 466 for name, value in sorted(metrics.counts.items()): 467 metric, labels = _split_key(name) 468 base = _prometheus_name(metric) 469 lines += [f"# TYPE {base} counter", f"{base}{labels} {value}"] 470 for name, value in sorted(metrics.gauges.items()): 471 metric, labels = _split_key(name) 472 base = _prometheus_name(metric) 473 lines += [f"# TYPE {base} gauge", f"{base}{labels} {value}"] 474 for name, summary in sorted(metrics.durations.items()): 475 metric, labels = _split_key(name) 476 base = _prometheus_name(metric) 477 lines += [ 478 f"# TYPE {base} summary", 479 f"{base}_count{labels} {summary.count}", 480 f"{base}_sum{labels} {summary.total}", 481 ] 482 return "\n".join(lines) + ("\n" if lines else "")
Renders a Metrics in the Prometheus text format.
Written out rather than through a client library, so a service that only
wants a scrape endpoint needs nothing installed. The format is small and
stable: a TYPE line, then samples, with dots in the metric name — and in the
label names, where routing.key and message.type have the same
problem — replaced by underscores, because Prometheus allows them in
neither.
A real registry — exemplars, native histograms, a shared process collector —
is what acemq_amqp.prometheus is for, and it needs the extra.
Parameters
- metrics: what to render
:returns: the body of a
/acemq-metricsresponse
533class HealthStatus(str, Enum): 534 """How a check turned out.""" 535 536 #: Working. 537 UP = "up" 538 539 #: Not working. A readiness probe should fail on this. 540 DOWN = "down" 541 542 #: Working, but not as well as it should. Worth an alert; not worth taking 543 #: the instance out of rotation, because the replacement will almost 544 #: certainly be degraded too. 545 DEGRADED = "degraded"
How a check turned out.
548@dataclass(frozen=True, slots=True) 549class HealthReport: 550 """What a check found. 551 552 :param status: up, down or degraded 553 :param detail: why, when it is not simply up 554 :param checked: when this was worked out, in UTC 555 :param parts: whatever the check wants to show — a consumer count, a 556 round-trip time, the reports of the checks that were combined 557 """ 558 559 status: HealthStatus 560 detail: str = "" 561 checked: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) 562 parts: Mapping[str, Any] = field(default_factory=dict) 563 564 @property 565 def healthy(self) -> bool: 566 """Whether a readiness probe should pass. 567 568 Degraded passes. An instance that is slow is still an instance that 569 works, and taking it out of rotation moves the traffic to one that will 570 be just as slow with more of it. 571 """ 572 return self.status is not HealthStatus.DOWN 573 574 def __str__(self) -> str: 575 return self.status.value if not self.detail else f"{self.status.value}: {self.detail}"
What a check found.
Parameters
- status: up, down or degraded
- detail: why, when it is not simply up
- checked: when this was worked out, in UTC
- parts: whatever the check wants to show — a consumer count, a round-trip time, the reports of the checks that were combined
564 @property 565 def healthy(self) -> bool: 566 """Whether a readiness probe should pass. 567 568 Degraded passes. An instance that is slow is still an instance that 569 works, and taking it out of rotation moves the traffic to one that will 570 be just as slow with more of it. 571 """ 572 return self.status is not HealthStatus.DOWN
Whether a readiness probe should pass.
Degraded passes. An instance that is slow is still an instance that works, and taking it out of rotation moves the traffic to one that will be just as slow with more of it.
578@runtime_checkable 579class HealthCheck(Protocol): 580 """Anything that can report on itself. 581 582 The library provides one for the connection; an application adds its own — a 583 database, a downstream service — and :func:`aggregate_health` combines them. 584 """ 585 586 @property 587 def name(self) -> str: 588 """What this check is called in a combined report.""" 589 590 async def check(self) -> HealthReport: 591 """The current state. 592 593 It must return quickly and must not raise: a check that hangs makes a 594 readiness probe hang with it, and a probe that hangs is a pod that never 595 comes back. 596 """
Anything that can report on itself.
The library provides one for the connection; an application adds its own — a
database, a downstream service — and aggregate_health() combines them.
1771def _no_init_or_replace_init(self, *args, **kwargs): 1772 cls = type(self) 1773 1774 if cls._is_protocol: 1775 raise TypeError('Protocols cannot be instantiated') 1776 1777 # Already using a custom `__init__`. No need to calculate correct 1778 # `__init__` to call. This can lead to RecursionError. See bpo-45121. 1779 if cls.__init__ is not _no_init_or_replace_init: 1780 return 1781 1782 # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`. 1783 # The first instantiation of the subclass will call `_no_init_or_replace_init` which 1784 # searches for a proper new `__init__` in the MRO. The new `__init__` 1785 # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent 1786 # instantiation of the protocol subclass will thus use the new 1787 # `__init__` and no longer call `_no_init_or_replace_init`. 1788 for base in cls.__mro__: 1789 init = base.__dict__.get('__init__', _no_init_or_replace_init) 1790 if init is not _no_init_or_replace_init: 1791 cls.__init__ = init 1792 break 1793 else: 1794 # should not happen 1795 cls.__init__ = object.__init__ 1796 1797 cls.__init__(self, *args, **kwargs)
590 async def check(self) -> HealthReport: 591 """The current state. 592 593 It must return quickly and must not raise: a check that hangs makes a 594 readiness probe hang with it, and a probe that hangs is a pod that never 595 comes back. 596 """
The current state.
It must return quickly and must not raise: a check that hangs makes a readiness probe hang with it, and a probe that hangs is a pod that never comes back.
599async def aggregate_health(*checks: HealthCheck, timeout: float = 5.0) -> HealthReport: 600 """Runs every check at once and combines the answers. 601 602 The combined status is the worst of them: one thing being down makes the 603 whole report down, because a service that cannot reach its broker is not 604 ready however healthy the rest of it is. 605 606 At once rather than in turn, so a slow check does not add its latency to the 607 others, and under a deadline, so one that ignores the instruction above 608 still cannot hang the probe. A check that times out is reported as down with 609 the reason, which is the honest reading: something that will not answer in 610 five seconds is not something a request can depend on. 611 612 :param checks: what to ask 613 :param timeout: how long to give all of them together 614 :returns: the combined report 615 """ 616 if not checks: 617 return HealthReport(HealthStatus.UP) 618 619 async def run(check: HealthCheck) -> tuple[str, HealthReport]: 620 try: 621 return check.name, await check.check() 622 except Exception as failure: 623 return check.name, HealthReport( 624 HealthStatus.DOWN, f"the check itself failed: {failure}" 625 ) 626 627 tasks = [asyncio.ensure_future(run(check)) for check in checks] 628 try: 629 done, pending = await asyncio.wait(tasks, timeout=timeout) 630 except asyncio.CancelledError: 631 for task in tasks: 632 task.cancel() 633 raise 634 635 parts: dict[str, Any] = {} 636 worst = HealthStatus.UP 637 reasons: list[str] = [] 638 639 for task in pending: 640 task.cancel() 641 for index, task in enumerate(tasks): 642 if task in done: 643 name, report = task.result() 644 else: 645 name = checks[index].name 646 report = HealthReport(HealthStatus.DOWN, f"did not answer within {timeout}s") 647 parts[name] = report 648 if report.status is HealthStatus.DOWN: 649 worst = HealthStatus.DOWN 650 reasons.append(name) 651 elif report.status is HealthStatus.DEGRADED: 652 if worst is not HealthStatus.DOWN: 653 worst = HealthStatus.DEGRADED 654 reasons.append(name) 655 656 return HealthReport(worst, ", ".join(reasons), parts=parts)
Runs every check at once and combines the answers.
The combined status is the worst of them: one thing being down makes the whole report down, because a service that cannot reach its broker is not ready however healthy the rest of it is.
At once rather than in turn, so a slow check does not add its latency to the others, and under a deadline, so one that ignores the instruction above still cannot hang the probe. A check that times out is reported as down with the reason, which is the honest reading: something that will not answer in five seconds is not something a request can depend on.
Parameters
- checks: what to ask
- timeout: how long to give all of them together :returns: the combined report