Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit ae01a7e

Browse files
authored
Update type annotations for compatiblity with prometheus_client 0.14 (#12389)
Principally, `prometheus_client.REGISTRY.register` now requires its argument to extend `prometheus_client.Collector`. Additionally, `Gauge.set` is now annotated so that passing `Optional[int]` causes an error.
1 parent 793d03e commit ae01a7e

File tree

8 files changed

+67
-18
lines changed

8 files changed

+67
-18
lines changed

changelog.d/12389.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Update type annotations for compatiblity with prometheus_client 0.14.

synapse/metrics/__init__.py

+9-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Copyright 2015, 2016 OpenMarket Ltd
2+
# Copyright 2022 The Matrix.org Foundation C.I.C.
23
#
34
# Licensed under the Apache License, Version 2.0 (the "License");
45
# you may not use this file except in compliance with the License.
@@ -52,12 +53,13 @@
5253
start_http_server,
5354
)
5455
from synapse.metrics._gc import MIN_TIME_BETWEEN_GCS, install_gc_manager
56+
from synapse.metrics._types import Collector
5557

5658
logger = logging.getLogger(__name__)
5759

5860
METRICS_PREFIX = "/_synapse/metrics"
5961

60-
all_gauges: "Dict[str, Union[LaterGauge, InFlightGauge]]" = {}
62+
all_gauges: Dict[str, Collector] = {}
6163

6264
HAVE_PROC_SELF_STAT = os.path.exists("/proc/self/stat")
6365

@@ -78,11 +80,10 @@ def collect() -> Iterable[Metric]:
7880

7981

8082
@attr.s(slots=True, hash=True, auto_attribs=True)
81-
class LaterGauge:
82-
83+
class LaterGauge(Collector):
8384
name: str
8485
desc: str
85-
labels: Optional[Iterable[str]] = attr.ib(hash=False)
86+
labels: Optional[Sequence[str]] = attr.ib(hash=False)
8687
# callback: should either return a value (if there are no labels for this metric),
8788
# or dict mapping from a label tuple to a value
8889
caller: Callable[
@@ -125,7 +126,7 @@ def _register(self) -> None:
125126
MetricsEntry = TypeVar("MetricsEntry")
126127

127128

128-
class InFlightGauge(Generic[MetricsEntry]):
129+
class InFlightGauge(Generic[MetricsEntry], Collector):
129130
"""Tracks number of things (e.g. requests, Measure blocks, etc) in flight
130131
at any given time.
131132
@@ -246,7 +247,7 @@ def _register_with_collector(self) -> None:
246247
all_gauges[self.name] = self
247248

248249

249-
class GaugeBucketCollector:
250+
class GaugeBucketCollector(Collector):
250251
"""Like a Histogram, but the buckets are Gauges which are updated atomically.
251252
252253
The data is updated by calling `update_data` with an iterable of measurements.
@@ -340,7 +341,7 @@ def _values_to_metric(self, values: Iterable[float]) -> GaugeHistogramMetricFami
340341
#
341342

342343

343-
class CPUMetrics:
344+
class CPUMetrics(Collector):
344345
def __init__(self) -> None:
345346
ticks_per_sec = 100
346347
try:
@@ -470,6 +471,7 @@ def register_threadpool(name: str, threadpool: ThreadPool) -> None:
470471

471472

472473
__all__ = [
474+
"Collector",
473475
"MetricsResource",
474476
"generate_latest",
475477
"start_http_server",

synapse/metrics/_gc.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@
3030

3131
from twisted.internet import task
3232

33+
from synapse.metrics._types import Collector
34+
3335
"""Prometheus metrics for garbage collection"""
3436

3537

@@ -71,7 +73,7 @@
7173
)
7274

7375

74-
class GCCounts:
76+
class GCCounts(Collector):
7577
def collect(self) -> Iterable[Metric]:
7678
cm = GaugeMetricFamily("python_gc_counts", "GC object counts", labels=["gen"])
7779
for n, m in enumerate(gc.get_count()):
@@ -135,7 +137,7 @@ def _maybe_gc() -> None:
135137
#
136138

137139

138-
class PyPyGCStats:
140+
class PyPyGCStats(Collector):
139141
def collect(self) -> Iterable[Metric]:
140142

141143
# @stats is a pretty-printer object with __str__() returning a nice table,

synapse/metrics/_reactor_metrics.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121

2222
from twisted.internet import reactor
2323

24+
from synapse.metrics._types import Collector
25+
2426
#
2527
# Twisted reactor metrics
2628
#
@@ -54,7 +56,7 @@ def __getattr__(self, item: str) -> Any:
5456
return getattr(self._poller, item)
5557

5658

57-
class ReactorLastSeenMetric:
59+
class ReactorLastSeenMetric(Collector):
5860
def __init__(self, epoll_wrapper: EpollWrapper):
5961
self._epoll_wrapper = epoll_wrapper
6062

synapse/metrics/_types.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Copyright 2022 The Matrix.org Foundation C.I.C.
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+
# http://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+
16+
from abc import ABC, abstractmethod
17+
from typing import Iterable
18+
19+
from prometheus_client import Metric
20+
21+
try:
22+
from prometheus_client.registry import Collector
23+
except ImportError:
24+
# prometheus_client.Collector is new as of prometheus 0.14. We redefine it here
25+
# for compatibility with earlier versions.
26+
class _Collector(ABC):
27+
@abstractmethod
28+
def collect(self) -> Iterable[Metric]:
29+
pass
30+
31+
Collector = _Collector # type: ignore

synapse/metrics/background_process_metrics.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
noop_context_manager,
4747
start_active_span,
4848
)
49+
from synapse.metrics._types import Collector
4950

5051
if TYPE_CHECKING:
5152
import resource
@@ -127,7 +128,7 @@
127128
_bg_metrics_lock = threading.Lock()
128129

129130

130-
class _Collector:
131+
class _Collector(Collector):
131132
"""A custom metrics collector for the background process metrics.
132133
133134
Ensures that all of the metrics are up-to-date with any in-flight processes

synapse/metrics/jemalloc.py

+16-4
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,13 @@
1616
import logging
1717
import os
1818
import re
19-
from typing import Iterable, Optional
19+
from typing import Iterable, Optional, overload
2020

21-
from prometheus_client import Metric
21+
from prometheus_client import REGISTRY, Metric
22+
from typing_extensions import Literal
2223

23-
from synapse.metrics import REGISTRY, GaugeMetricFamily
24+
from synapse.metrics import GaugeMetricFamily
25+
from synapse.metrics._types import Collector
2426

2527
logger = logging.getLogger(__name__)
2628

@@ -59,6 +61,16 @@ def _setup_jemalloc_stats() -> None:
5961

6062
jemalloc = ctypes.CDLL(jemalloc_path)
6163

64+
@overload
65+
def _mallctl(
66+
name: str, read: Literal[True] = True, write: Optional[int] = None
67+
) -> int:
68+
...
69+
70+
@overload
71+
def _mallctl(name: str, read: Literal[False], write: Optional[int] = None) -> None:
72+
...
73+
6274
def _mallctl(
6375
name: str, read: bool = True, write: Optional[int] = None
6476
) -> Optional[int]:
@@ -134,7 +146,7 @@ def _jemalloc_refresh_stats() -> None:
134146
except Exception as e:
135147
logger.warning("Failed to reload jemalloc stats: %s", e)
136148

137-
class JemallocCollector:
149+
class JemallocCollector(Collector):
138150
"""Metrics for internal jemalloc stats."""
139151

140152
def collect(self) -> Iterable[Metric]:

synapse/storage/databases/main/events.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -200,9 +200,7 @@ async def _persist_events_and_state_updates(
200200
if stream < 0:
201201
# backfilled events have negative stream orderings, so we don't
202202
# want to set the event_persisted_position to that.
203-
synapse.metrics.event_persisted_position.set(
204-
events_and_contexts[-1][0].internal_metadata.stream_ordering
205-
)
203+
synapse.metrics.event_persisted_position.set(stream)
206204

207205
for event, context in events_and_contexts:
208206
if context.app_service:

0 commit comments

Comments
 (0)