# `Mobius.Charts`
[🔗](https://github.com/mobius-home/mobius/blob/v0.8.0/lib/mobius/charts.ex#L1)

Query-ready data structures for graphing Mobius metrics.

`Mobius.Data` returns the raw building blocks — a reconstructed
`Mobius.DDSketch`, a flat list of metric points, a per-quantile map. Turning
those into the shapes a chart actually wants (sorted histogram bars, a line
per quantile over time, the latest value per metric) is the same handful of
transforms re-written at every call site. This module does those transforms
once and hands back plain, well-typed maps.

Nothing here is tied to a particular renderer. Every function returns plain
maps and lists with absolute second-resolution timestamps and raw numeric
values; mapping those onto VegaLite, an ASCII chart, JSON, or anything else
is the caller's job and is a trivial `Enum.map/2`.

Four shapes, one per common query:

  * `distribution/3` — a histogram's bins as sorted `{value, count}` bars
    (`t:distribution/0`).
  * `quantiles_over_time/4` — one line of `{timestamp, value}` points per
    requested quantile (`t:quantiles_over_time/0`).
  * `series/4` — a single metric's values over time as `{timestamp, value}`
    points (`t:series/0`). Works for any metric type, including
    `{:summary, :average}` for an average-over-time line.
  * `latest/2` — the most recent value for a set of metrics
    (`t:latest_value/0`).

All four accept the same window options (`:last`, `:from`/`:to`,
`:mobius_instance`; see `t:opt/0`) and report the resolved absolute window
back in the result so a caller can label axes without re-deriving it.

# `bin`

```elixir
@type bin() :: %{value: float(), count: pos_integer()}
```

One histogram bar: the bin's representative value and its observation count.

`value` is the DDSketch bin estimator — the same value `Mobius.DDSketch.quantile/2`
reports for a value that lands in the bin. Bins are spaced geometrically, so
treat `value` as an ordered category rather than a linear coordinate when
plotting.

# `distribution`

```elixir
@type distribution() :: %{
  metric: Mobius.metric_name(),
  tags: map(),
  window: window(),
  total_count: non_neg_integer(),
  bins: [bin()]
}
```

A metric's distribution over a window: the histogram bars plus context.

  * `:metric` / `:tags` - what was queried
  * `:window` - the resolved time window
  * `:total_count` - total observations across all bins
  * `:bins` - bars sorted ascending by `value`; empty when nothing was observed

# `latest_value`

```elixir
@type latest_value() :: %{
  metric: Mobius.metric_name(),
  type: metric_type(),
  tags: map(),
  value: number() | map(),
  timestamp: integer()
}
```

The most recent stored value for one metric.

`value` is a number for plain types and summary fields; for the plain
`:summary` type it is the calculated `%{average:, std_dev:, reports:}` map.

# `metric_listing`

```elixir
@type metric_listing() :: %{
  metric: Mobius.metric_name(),
  type: metric_type(),
  tags: [atom()],
  histogram?: boolean()
}
```

One entry in the list of metrics available to chart.

  * `:metric` / `:type` / `:tags` - identity, ready to pass to the other
    queries (`tags` is the list of configured tag keys)
  * `:histogram?` - whether a `t:distribution/0` is available for this metric
    (true only for summary metrics registered with histograms enabled)

# `metric_ref`

```elixir
@type metric_ref() ::
  {Mobius.metric_name(), metric_type()}
  | {Mobius.metric_name(), metric_type(), map()}
```

A metric to request a latest value for: `{name, type, tags}`.

# `metric_type`

```elixir
@type metric_type() :: Mobius.metric_type() | {:summary, atom()}
```

A metric type to query: a plain `t:Mobius.metric_type/0` (`:counter`,
`:last_value`, `:sum`, `:summary`), or a summary field such as
`{:summary, :average}`.

# `opt`

```elixir
@type opt() ::
  {:mobius_instance, Mobius.instance()}
  | {:from, integer()}
  | {:to, integer()}
  | {:last, integer() | {integer(), Mobius.time_unit()}}
```

Options shared by every query.

  * `:mobius_instance` - the instance to query (default `:mobius`)
  * `:last` - window covering the last `x`, where `x` is an integer number of
    seconds or `{integer(), Mobius.time_unit()}`
  * `:from` / `:to` - explicit unix-second window bounds; each may be given
    alone — `:from` defaults to 0 (the beginning of stored history) and
    `:to` defaults to now

With no window option the last 180 seconds are used.

# `point`

```elixir
@type point() :: %{timestamp: integer(), value: number()}
```

One point on a time line: a value at an absolute second-resolution timestamp.

# `quantile_line`

```elixir
@type quantile_line() :: %{quantile: float(), points: [point()]}
```

One quantile's line over time.

`quantile` is the requested fraction in `[0.0, 1.0]`; `points` are sorted
ascending by timestamp. Windows with no observations contribute no point, so
a sparse metric yields a shorter line rather than gaps of `nil`.

# `quantiles_over_time`

```elixir
@type quantiles_over_time() :: %{
  metric: Mobius.metric_name(),
  tags: map(),
  window: window(),
  lines: [quantile_line()]
}
```

Quantiles of a histogram metric tracked over a window.

Each requested quantile becomes its own `t:quantile_line/0`, in the order the
quantiles were requested — ready to draw as one line per series. The window is
divided at the resolution Mobius actually stored (one point per stored
snapshot interval).

# `series`

```elixir
@type series() :: %{
  metric: Mobius.metric_name(),
  type: metric_type(),
  tags: map(),
  window: window(),
  points: [point()]
}
```

A single metric's values over time.

# `window`

```elixir
@type window() :: %{from: integer(), to: integer()}
```

The absolute window a result covers, as resolved unix-second bounds.

# `distribution`

```elixir
@spec distribution(Mobius.metric_name(), map(), [opt()]) ::
  {:ok, distribution()} | {:error, term()}
```

Project a histogram metric's distribution over a window into sorted bars.

The metric must have been registered with histograms enabled
(`reporter_options: [histogram: ...]`). Returns `{:error, reason}` from
`Mobius.Data.histogram/3` when it is not.

    {:ok, dist} = Mobius.Charts.distribution("http.request.duration", %{}, last: {1, :hour})
    # dist.bins => [%{value: 9.8, count: 412}, %{value: 11.0, count: 380}, ...]

Plotting then needs no math — map `:value`/`:count` straight onto x/y.

# `latest`

```elixir
@spec latest([metric_ref()], [opt()]) :: [latest_value()]
```

The most recent stored value for each of several metrics.

Each entry is `{name, type}` or `{name, type, tags}`. Metrics with no data in
the window are omitted, so the result is ready to render directly. Order
follows the input.

    Mobius.Charts.latest(
      [
        {"vm.memory.total", :last_value},
        {"vm.memory.processes", :last_value}
      ],
      last: {5, :minute}
    )
    # => [%{metric: "vm.memory.total", value: 51_200_000, timestamp: ...}, ...]

# `list_metrics`

```elixir
@spec list_metrics(Mobius.instance()) :: [metric_listing()]
```

List the metrics an instance is configured to track.

Each entry carries the `metric`/`type`/`tags` needed to call the other
queries, plus `histogram?` so a caller knows whether `distribution/3` is
available. Sourced from the configured `Telemetry.Metrics` definitions, so
metrics that have not reported a value yet are still listed.

    Mobius.Charts.list_metrics()
    # => [%{metric: "vm.memory.total", type: :last_value, tags: [], histogram?: false}, ...]

# `quantiles_over_time`

```elixir
@spec quantiles_over_time(Mobius.metric_name(), [float()], map(), [opt()]) ::
  {:ok, quantiles_over_time()} | {:error, term()}
```

Track quantiles of a histogram metric across a window, one line per quantile.

`quantiles` is a list of fractions in `[0.0, 1.0]`. The window is split at the
resolution Mobius stored — each stored snapshot interval becomes one point,
carrying only the observations attributable to that interval. Windows with no
observations are skipped, so a quiet stretch shortens the line rather than
drawing a zero.

    {:ok, qot} =
      Mobius.Charts.quantiles_over_time("http.request.duration", [0.5, 0.95, 0.99], %{},
        last: {1, :hour}
      )

    for line <- qot.lines do
      # line.quantile => 0.95, line.points => [%{timestamp: ..., value: ...}, ...]
    end

# `series`

```elixir
@spec series(Mobius.metric_name(), metric_type(), map(), [opt()]) ::
  {:ok, series()} | {:error, term()}
```

A single metric's values over time as `{timestamp, value}` points.

Accepts any `t:metric_type/0`. Use a plain type
(`:last_value`, `:counter`, `:sum`) for a gauge or counter line, or
`{:summary, :average}` / `{:summary, :std_dev}` / `{:summary, :reports}`
for a summary metric (plain `:summary` gives the full per-interval
`%{average:, std_dev:, reports:}` map, where `reports` is the subgroup
size n for that interval).

Summary statistics are **per interval**: the stored summary is a cumulative
accumulator (sum / sum-of-squares / count since the metric started), so each
point is computed from the *delta* between consecutive stored snapshots —
the same idea `DDSketch.delta/2` applies to histograms. A snapshot interval
with no new reports contributes no point.

Returns `{:error, :unavailable}` when the instance is down or too busy to
answer (see `Mobius.Data`), and `{:error, {:invalid_summary_field, field}}`
for a summary field other than `:average`, `:std_dev`, or `:reports`.

    {:ok, avg} = Mobius.Charts.series("http.request.duration", {:summary, :average}, %{}, last: {1, :hour})
    # avg.points => [%{timestamp: ..., value: 12.4}, ...]

---

*Consult [api-reference.md](api-reference.md) for complete listing*
