"""Kind 21802: the diagnostic telemetry a node may publish about itself.
Opt-in, and deliberately coarse. One event per sample window, aggregated
over the whole node: how many wraps came in, how many were duplicates a
relay replayed, how many were dropped before they reached a handler, and
how much strain the node recorded. Nothing names a peer, a shard or a
transport, which is why the counters are binned instead of exact: a
reader learns whether the node is busy, not who is making it so.
Alpha measurement only. The bins and tag names are the protocol; the
choice of what to count is this reference's and a second node may count
differently as long as it bins the same way.
"""
from __future__ import annotations
from typing import Mapping, Optional
from ..storage import store
from ..wire.interfaces import EventLike, UnsignedNostrEvent
KIND: int = 21802
BINS: tuple[int, ...] = (0, 1, 10, 100, 1000, 10000)
METRICS: tuple[str, ...] = ('wraps_in', 'wraps_seen_again', 'wraps_dropped', 'strain', 'peers')
[docs]def bin_of(n: int) -> str:
"""The coarse bin a counter lands in: the largest BINS entry at or
below it, written as a floor. 0, 1, 10, 100, 1000 or 10000; a reader
sees an order of magnitude and nothing finer."""
if n < 0:
raise ValueError('a counter cannot be negative')
out = BINS[0]
for b in BINS:
if n >= b:
out = b
return str(out)
[docs]def telemetry(
pubkey: str,
now: int,
sample_window: int,
counters: Mapping[str, int],
expiration: Optional[int] = None,
) -> UnsignedNostrEvent:
"""One kind 21802. `sample_window` is the seconds the counters cover;
`counters` is metric name -> raw count, binned here. Unknown metric
names are dropped rather than carried, so a node cannot leak a
per-peer counter under a name of its own. Tags: sample_window,
metric (name, bin) per metric in METRICS order, expiration if given."""
if sample_window <= 0:
raise ValueError('sample_window must be positive')
tags: list[list[str]] = [['sample_window', str(sample_window)]]
for m in METRICS:
if m in counters:
tags.append(['metric', m, bin_of(int(counters[m]))])
if expiration is not None:
tags.append(['expiration', str(expiration)])
return store.make_event(pubkey, now, KIND, tags, '')
[docs]def check_telemetry(ev: EventLike) -> list[str]:
"""Structural. Returns problems; empty means the event is well-formed."""
out: list[str] = []
if ev.get('kind') != KIND:
return ['not a kind %d' % KIND]
if ev.get('content'):
out.append('content must be empty')
w = store.first_tag(ev, 'sample_window')
if w is None or len(w) < 2 or not w[1].isdigit() or int(w[1]) <= 0:
out.append('sample_window missing or not a positive integer')
seen: set[str] = set()
for t in ev.get('tags', []):
if not t or t[0] != 'metric':
continue
if len(t) != 3 or t[1] not in METRICS or t[2] not in {str(b) for b in BINS}:
out.append('malformed metric tag %r' % (list(t),))
elif t[1] in seen:
out.append('metric %s given twice' % t[1])
seen.add(t[1] if len(t) > 1 else '')
return out
[docs]def read(ev: EventLike) -> dict[str, int]:
"""metric -> bin floor, for a well-formed event. Raises on a malformed one."""
problems = check_telemetry(ev)
if problems:
raise ValueError('; '.join(problems))
return {t[1]: int(t[2]) for t in ev.get('tags', []) if t and t[0] == 'metric'}