Reference / Metrics API for Python
Metrics API for Python
Every public class, function and type of the Metrics engine in tinystore, generated from its source. The Metrics guide explains how to use them, and the Bun and Node, Go and Rust pages list the same API.
SeriesQuery
class SeriesQuery(TypedDict, total=False):
name: str # the series of this name; a timer's name, the series it writes
where: Mapping[str, Condition]
since: Duration # the span before now the range covers; or from_ and to
from_: datetime # the range's start, included
to: datetime # the range's end, excluded; now, a sample taken now in the range, unless given
limit: int # a page of read or aggregate, this many samples or buckets at most, 100,000 at most; without it, the whole
after: str # the page after the one whose next this is, read with the same query and limitThe series a call finds and its range; a condition given as None is InvalidError, never left out.
AggregateQuery
class AggregateQuery(SeriesQuery, total=False):
every: Duration # the buckets' span, counted from 1970 in UTC; the range is one bucket without it
calendar: Calendar # buckets of a calendar in time_zone, in place of every: "day" begins each at a local midnight
time_zone: str # the IANA zone a calendar's buckets are in, such as Europe/Moscow or UTC
op: Op | str
by: Sequence[str] # the labels a group keeps; without by and without, every series of a name is one group
without: Sequence[str] # the labels a group leaves out, keeping every other; [] keeps every series apart
estimate: bool # a timer's percentile also gives a point between its bounds, interpolated: an estimate
skip_nan: bool # a NaN sample counts in no bucket, which says how many it passed over in skipped; an infinity is still refused
fill: bool # every bucket of the range retention keeps, an empty one with samples 0 and no value; with since or from_, and a page's limit counts the empty ones tooAn aggregate: a query cut into buckets of every, each one exact value of op, by groups.
Series
@dataclass(slots=True)
class Series:
name: str
kind: SeriesKind
labels: Mapping[str, LabelValue] = field(default_factory=dict[str, LabelValue])
samples: Sequence[tuple[Time, float]] | None = None
times: Sequence[Time] | None = None
values: Sequence[float] | None = None
keep: Duration | None = None # how long the name's samples stay: its own, kept in the file; unless given, what it keeps already
more: bool = False # a page cut the series here: the page its next reads begins with the rest of itA series: what ingest writes, and what a read gives back.
Ingest takes its samples as (time, value) pairs, or as times and values
columns, a time an aware datetime or unix milliseconds. A read gives
times, unix milliseconds in an array('q'), and values, an
array('d') whose bytes keep every value's bits: -0 and a NaN's
payload survive.
AggregateBucket
@dataclass(frozen=True, slots=True)
class AggregateBucket:
at: datetime # where it begins
samples: int # how many samples it comes from; a timer's, how many durations
resets: int
partial: bool # its value comes from less than its span: the range, the clock or retention cut it
gap: bool # its first step began before the bucket before it: a whole bucket between had no samples
value: float | None = None
lower: float | None = None
upper: float | None = None # infinity past the last bound
estimate: float | None = None
skipped: int = 0 # the NaN samples it passed over, with skip_nan
date: _date | None = None # a calendar's bucket's local date: a week's Monday, a month's first; none for everyA bucket of an aggregate.
A bucket of count … last has its value; a percentile's is a gauge's sample at the rank, or a timer's bucket of its spread that holds it, from lower to upper, and with estimate asked a point between them.
Aggregate
@dataclass(frozen=True, slots=True)
class Aggregate:
name: str
labels: dict[str, str] # the labels by kept or without left
buckets: list[AggregateBucket] # a bucket without samples is left out, and so is one of NaN alone, unless the query gave fill
more: bool = False # a page cut the group here: the page its next reads begins with the rest of its bucketsPoint
@dataclass(frozen=True, slots=True)
class Point:
name: str
labels: dict[str, str]
at: datetime
value: floatA series' newest sample in the range.
Compared
@dataclass(frozen=True, slots=True)
class Compared:
value: float | None # op over the newest window; None when it holds no sample
usual: float | None # the median over the windows before that hold samples; None when none does
ratio: float | None # value / usual; None when either is None or usual is 0
samples: int # the samples of the newest window
windows: int # the windows the usual stands onWhat compare found; a value it could not give is None, never zero.
ComparedGroup
@dataclass(frozen=True, slots=True)
class ComparedGroup:
name: str
labels: dict[str, str] # the labels by kept or without left
value: float | None
usual: float | None
ratio: float | None
samples: int
windows: intWhat compare_groups found of one group: its name and labels, and what compare finds.
Plan
@dataclass(frozen=True, slots=True)
class Plan:
series: int
bytes: int
decoded: int
exceeds: Exceeds | NoneWhat a read or an aggregate would spend of each bound, and the bound it would stop at.
NameInfo
@dataclass(frozen=True, slots=True)
class NameInfo:
name: str
kind: SeriesKind
series_count: int
unit: str
help: str
keep: str
retained_from: datetime # its oldest sample, or where its keep begins while it holds samples from before
newest: datetimeA name the store holds samples of.
NamePage
@dataclass(frozen=True, slots=True)
class NamePage:
names: list[NameInfo]
next: str | None # where the next page starts; none on the lastMetricsDamage
@dataclass(frozen=True, slots=True)
class MetricsDamage:
name: str
labels: dict[str, str]
error: strA series whose bytes no longer read, which delete removes.
Metrics
class Metrics:
...A store's metrics: series by name and labels, their reads and aggregates, and the program's instruments.
Metrics.ingest
async def ingest(series: Series | Sequence[Series]) -> None: ...Writes series and their samples in one write, every one or none: a refused series names itself.
One call takes 100,000 samples, as one exporter's text does; one past a message goes up in pieces.
Metrics.replace
async def replace(series: Series, *, from_: datetime, to: datetime) -> None: ...Replaces a gauge's samples from from_ to to, to excluded, with the series' own.
Whether the store had packed them or not: a time given takes its value, a time not there before is added, and a time the series does not give goes. One write: a read sees the range as it was or as it is now, never half, and the same samples sent again write nothing. A counter's or a histogram's is an InvalidError:
# the last three days read again from the shop's database, a refund taken off yesterday
samples = [(day(3), 1000), (day(2), 1000), (day(1), 900)]
corrected = Series(name="revenue", kind="gauge", labels={"shop": "msk"}, samples=samples)
await store.metrics.replace(corrected, from_=day(3), to=day(0))Metrics.ingest_prometheus
async def ingest_prometheus(
text: str | bytes,
*,
labels: Mapping[str, LabelValue] | None = None,
at: Time | None = None,
keep: Duration | None = None,
) -> None: ...Reads the text an exporter serves, in Prometheus' format or OpenMetrics', and writes its series.
Every one or none: a counter as a counter, a histogram's _bucket series as histogram. labels
go beside every series' own, at is the time of a sample the text gives none, the store's
clock unless given, and keep how long every name of the text keeps its samples. A line it
cannot read is an InvalidError naming the line:
text = httpx.get("http://web-1:9100/metrics").text
await store.metrics.ingest_prometheus(text, labels={"instance": "web-1"})Metrics.read
async def read(**query: Unpack[SeriesQuery]) -> SeriesPage: ...The samples of each series the query finds, in its range: whole, or a LimitError naming its bound.
With limit, a page, which may hold fewer samples than limit and still have next.
Metrics.latest
async def latest(**query: Unpack[SeriesQuery]) -> list[Point]: ...The newest sample of each series the query finds, when it has one in the range.
Metrics.aggregate
async def aggregate(**query: Unpack[AggregateQuery]) -> AggregatePage: ...The buckets of each group of the series the query finds, each one exact value of op, rounded once.
With limit, a page, which ends between two whole buckets of a group.
Metrics.explain
async def explain(**query: Unpack[AggregateQuery]) -> Plan: ...What a read, or an aggregate when given its op, would spend of each bound; it decodes no sample.
Metrics.compare
async def compare(
name: str,
*,
op: Op | str,
window: Duration,
against: Duration,
where: Mapping[str, Condition] | None = None,
same_hour: bool = False,
estimate: bool = False,
skip_nan: bool = False,
) -> Compared: ...op over the newest window, [now - window, now], against the median of the windows before it.
The windows before reach back over against: the same hours of each earlier day with same_hour, a day 24 hours in no time zone, or every window before otherwise, 1000 at most. A window without a sample counts in no median, and a timer's percentile compares only with estimate.
Metrics.compare_groupsNew in 0.13.1
async def compare_groups(
name: str,
*,
op: Op | str,
window: Duration,
against: Duration,
where: Mapping[str, Condition] | None = None,
by: Sequence[str] | None = None,
without: Sequence[str] | None = None,
same_hour: bool = False,
estimate: bool = False,
skip_nan: bool = False,
limit: int | None = None,
after: str | None = None,
) -> ComparePage: ...What compare finds, for each group of the series apart, as an aggregate groups them by labels.
Without limit every group, or a LimitError naming its bound; with limit a page of that many groups at most and next while there is more. A group past the series one query finds is read in parts, for every op but a percentile.
Metrics.names
async def names(
*,
prefix: str | None = None,
limit: int | None = None,
after: str | None = None,
) -> NamePage: ...A page of the names the store holds samples of, in the byte order of their text.
Metrics.label_names
async def label_names(
name: str,
*,
prefix: str | None = None,
limit: int | None = None,
after: str | None = None,
) -> LabelPage: ...A page of a name's label names, but the store's own.
Metrics.label_values
async def label_values(
name: str,
label: str,
*,
prefix: str | None = None,
limit: int | None = None,
after: str | None = None,
) -> ValuePage: ...A page of the values a label of a name's series holds.
Metrics.describe
async def describe(name: str, *, unit: str = '', help: str = '') -> None: ...Sets a name's unit and help in place of what it had: what is not given is removed.
They belong to the name, so a delete of its series leaves them.
Metrics.description
async def description(name: str) -> Description: ...A name's unit and help; both empty when nothing described it.
Metrics.delete
async def delete(*, name: str, labels: Mapping[str, LabelValue]) -> bool: ...Removes the one series of exactly this name and these labels, whether its samples still read or not.
True when the store held it; labels={} is the series without labels.
Metrics.damaged
async def damaged() -> list[MetricsDamage]: ...The series whose bytes no longer read, 1000 at most, each with what broke; deleting them shows the next.
Metrics.flush
async def flush() -> None: ...Sends what every instrument changed and has the store write its totals now, as it does every 15 seconds.
Metrics.counter
def counter(
name: str,
*,
unit: str | None = None,
help: str | None = None,
keep: Duration | None = None,
max_series: int | None = None,
) -> Counter: ...A total that only goes up, which the store keeps: processes counting into one series count into one total.
max_series is the sets of labels it holds at once, 1 to 2000, 2000 unless given: a new one past them
counts into its series of __overflow, said once in TinyStore's lines.
Metrics.gauge
def gauge(
name: str,
*,
unit: str | None = None,
help: str | None = None,
keep: Duration | None = None,
max_series: int | None = None,
) -> Gauge: ...A value that goes up and down: a queue's length, a temperature.
Metrics.gauge_func
def gauge_func(
name: str,
read: Callable[[], float | Awaitable[float]],
*,
labels: Mapping[str, LabelValue] | None = None,
unit: str | None = None,
help: str | None = None,
keep: Duration | None = None,
) -> None: ...A gauge whose value read gives every 15 seconds, of the set of labels given.
Another set of the name takes a function of its own. It may be async, is never called again while a call of it runs, and an error or an answer that is not a number writes nothing that time, said once while it repeats:
store.metrics.gauge_func("queue_depth", emails.depth, labels={"queue": "emails"})Metrics.timer
def timer(
name: str,
*,
buckets: Sequence[float] | Literal['exponential'] | None = None,
help: str | None = None,
keep: Duration | None = None,
max_series: int | None = None,
) -> Timer: ...How many things took how long: their count, sum and longest in milliseconds, and their spread.
Metrics.histogram
def histogram(
name: str,
*,
buckets: Sequence[float] | Literal['exponential'] | None = None,
unit: str | None = None,
help: str | None = None,
keep: Duration | None = None,
max_series: int | None = None,
) -> Histogram: ...A timer of numbers that are not durations: a response's size in bytes.
exponential_buckets
def exponential_buckets(start: float, factor: float, count: int) -> list[float]: ...Upper bounds from start, each factor times the one before: exponential_buckets(1, 2, 14) is 1, 2, 4 … 8192.
Instruments
class Instruments:
...The instruments of a store's handle, and what sends their changes; store.metrics makes them.
Instruments.declare
def declare(
name: str,
form: Form,
*,
unit: str | None = None,
help_: str | None = None,
keep: Duration | None = None,
buckets: Sequence[float] | Literal['exponential'] | None = None,
max_series: int | None = None,
read: bool = False,
) -> _Declared: ...An instrument of name, made the first time; another form or other options than it has are refused.
Instruments.reader
def reader(
name: str,
labels: dict[str, str],
read: Callable[[], float | Awaitable[float]],
**told: Any,
) -> None: ...A gauge of name whose set of labels read gives every 15 seconds; each set has a function of its own.
Instruments.set_of
def set_of(instrument: _Declared, labels: dict[str, str]) -> _Set: ...The set of labels of an instrument, made the first time; past the sets it holds, its __overflow.
Instruments.pending
def pending(set_: _Set) -> _Change | None: ...Instruments.change
def change(set_: _Set) -> _Change: ...What a call changes of a set, kept for the next batch.
Instruments.flush
async def flush() -> bool: ...Sends what changed now and has the store write its totals; says whether there was anything to send.
One the store cannot be reached for fails as a call does, and what it carried goes once the store can be. What the store refused since the flush before, and what a store that started again may have lost, fail it, each once.
Instruments.sent
async def sent() -> None: ...Sends what changed and waits for the store to apply it, without asking it to write.
The store writes its totals before a read that finds an instrument that changed, so a read after this sees what the calls counted. It waits for nothing when nothing is on its way, and raises never, since the read meets what kept the batch from the store.
Instruments.stop
async def stop() -> None: ...Stops the timers, sends what is left, and ends the stream; the store's close calls it.
Counter
class Counter:
...A total that only goes up, which the store keeps: processes counting into one series count into one total.
Counter.labels
def labels(**labels: LabelValue) -> Counter: ...The same counter with more labels, a series of its own; the same labels in any order are one.
Counter.inc
def inc() -> None: ...Counter.add
def add(n: float) -> None: ...Adds n, a finite number of 0 or more; add(0) makes the set of labels known with a total of zero.
Gauge
class Gauge:
...A value that goes up and down, written while this program is connected.
Gauge.labels
def labels(**labels: LabelValue) -> Gauge: ...Gauge.set
def set(value: float) -> None: ...Gauge.add
def add(n: float) -> None: ...Moves it by n, from zero when it was never set.
Gauge.inc
def inc() -> None: ...Gauge.dec
def dec() -> None: ...Timer
class Timer:
...How many things took how long: their count, sum and longest in milliseconds, and their spread.
Timer.labels
def labels(**labels: LabelValue) -> Timer: ...Timer.record
def record(duration: timedelta | Duration) -> None: ...Records a duration measured elsewhere: a timedelta, or text such as "250ms".
Timer.measure
def measure() -> Timing: ...Measures the block it runs: async with latency.measure():, recorded whether it returns or raises.
Timer.start
def start() -> Timing: ...A timing that records when it stops, for a span that is no one block.
Timing
class Timing:
...A span a timer measures from its start; stop records it, once.
Timing.stop
def stop() -> timedelta: ...Records how long since the timing started, the first time it is called, and gives it.
Histogram
class Histogram:
...A timer of numbers that are not durations: a response's size in bytes.
Histogram.labels
def labels(**labels: LabelValue) -> Histogram: ...Histogram.record
def record(value: float) -> None: ...Records a value of 0 or more.