sugarcraft / sugar-metrics
Telemetry primitives for SugarCraft / SugarSshServer — six instrument kinds (counter, gauge, histogram, up/down counter, async counter, async gauge) with pluggable backends (in-memory, StatsD UDP, Prometheus textfile, JSON stream, multi fan-out). Drop-in middleware for SSH session metrics.
Requires
- php: ^8.3
- sugarcraft/sugar-core: dev-master
- sugarcraft/sugar-ssh-server: dev-master
Requires (Dev)
- phpunit/phpunit: ^10.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-20 01:04:09 UTC
README
SugarMetrics
Lightweight telemetry primitives for SugarCraft / SugarSshServer servers. Six instrument kinds — counters, gauges, histograms, up/down counters, async counters and async gauges — with pluggable backends and drop-in middleware for SSH session metrics.
Formerly published as
sugarcraft/candy-metrics(renamed 2026-10).
composer require sugarcraft/sugar-metrics
Requirements
PHP >= 8.3. Three native extensions are enforced transitively — this manifest names none of them:
ext-intl and ext-mbstring arrive via sugarcraft/sugar-core, and ext-ffi arrives via
sugarcraft/sugar-ssh-server → sugarcraft/sugar-pty (whose own manifest hard-requires it). Check
them before wiring metrics into a minimal container.
The sugarcraft/sugar-ssh-server hard requirement is by design and serves only the optional drop-in SessionMetrics middleware — the Registry, the instruments and every backend never touch it, so a consumer that skips the middleware autoloads none of its code (nor its transitive crypto/pty stack). That promise is AUTOLOAD-only: Composer's platform checks still install and enforce the extensions above (and sugar-ssh-server's own deps) whether or not the middleware is ever used (sugar-metrics-059).
Concepts
| Primitive | Behaviour |
|---|---|
| Counter | Monotonic value that accumulates (connect counts, errors). Negative samples are refused. |
| Gauge | Instantaneous value that replaces on set (queue depth, RSS). |
| Histogram | Distribution of samples (latency, payload size). Negative samples are refused; the Prometheus backend emits 14 cumulative le buckets — the 11 classic client_golang boundaries extended with 25/50/100 — plus +Inf. |
| UpDownCounter | Synchronous counter that supports positive and negative increments — used for values that go up and down (active connections). |
| AsyncCounter | Counter backed by a callback; call observe() (optionally with per-call tags) whenever you want the current external reading emitted. |
| AsyncGauge | Gauge backed by a callback; call observe($tags) to emit an instantaneous external reading (memory, queue depth, pool size). |
A Registry is the application-facing facade; it forwards every emit to the configured Backend. Backends decide how to persist or forward. In this library a tag is a key/value pair attached to an emit; the Prometheus text format calls the same thing a label (PrometheusFileBackend translates).
Instrument factory helpers
The registry exposes dedicated factory methods that return instrument objects — useful when an instrument is held for repeated inc() / set() / add() / observe() calls. All six kinds are holdable (sugar-metrics-021): the sync trio newCounter / newGauge / newHistogram mirror the newUpDownCounter shape, and the async pair takes a callback:
$reg = Registry::new($backend); $hits = $reg->newCounter('http.requests', 'Requests served', ['route' => '/api']); $hits->inc(); // default step 1.0, static route tag rides // ... later, from anywhere holding $hits ... $hits->inc(1, ['status' => '500']); // per-call tags merge on top $connCounter = $reg->newUpDownCounter('server.active_connections', 'Active server connections', ['host' => $host]); $connCounter->add(1); // connection opened // ... later ... $connCounter->add(-1); // connection closed
Factory tags are static instrument tags: the $tags you pass to a factory ride on every add() / observe() from that instrument, and per-call tags merge on top (per-call wins on conflicts). observe() on the async instruments accepts an optional tag array for exactly that merge. The $help string is metadata carried by the instrument (name() / help()); the # HELP lines in the Prometheus textfile come from Descriptor registration below, not from factory calls.
Async instruments accept a callback that reads the external value each time you sample it:
$gcCount = $reg->newAsyncCounter('jvm.gc.count', 'JVM garbage collection count', fn() => $jvm->gcCount()); $gcCount->observe(); // invokes the callback and emits the reading now — nothing sweeps automatically $pool = $reg->newAsyncGauge('db.pool.size', 'Open database connections', fn() => $pdo->poolSize()); $pool->observe(['shard' => 'eu']); // static + per-call tags merge on this one sample
Direct emits for every kind exist too — $reg->upDownCounter(), $reg->asyncCounter(), $reg->asyncGauge() take the value (and tags) inline without an instrument object. On the direct-emitting side, counter()'s value parameter defaults to 1.0 (calling it bare is a +1), and upDownCounter() names its numeric parameter amount where counter() names the same shape value.
Names on the wire
Metric names and tag keys are not free text on every wire, and the folds differ per backend. The folds run on the emit path only — a registered Descriptor name must already be in the exposition charset (its constructor refuses dots, see Descriptor registration):
- StatsD (
StatsdBackend): the metric name may keep dots (http.requestsis idiomatic) but colons are flattened to_because:separates value from type on the wire, and braces{}fold in names too so a DogStatsD line-prefix dispatch (_sc{...}service checks,_e{...}events) can never be forged by an attacker-influenced name. Tag keys keep letters/digits/dots/underscores and all other punctuation the sweep below does not name — the sweep is a denylist of exactly:|,space, control/DEL, the C1 range and the Unicode line/paragraph separators U+2028/U+2029 (plus{}at the metric-name position), so-,/,@,=,#survive raw. - Prometheus textfile (
PrometheusFileBackend): metric names keep:(a legal Prometheus name character) and fold every other illegal rune (including.) to_; label names never keep:— illegal runes become_. - JSON stream: names are emitted verbatim inside a JSON string — the encoding itself is the framing.
Because the name/label folds are many-to-one, PrometheusFileBackend refuses silent collisions: two distinct raw series that fold onto the same metric name or the same label key throw a RuntimeException — at the second write, and at a remove() whose own raw never owned that folded key (see Cardinality management) — instead of merging or silently wiping the innocent twin behind your back.
Kind mapping to wire tokens:
| Registry kind | StatsD | Textfile # TYPE |
JSON kind |
|---|---|---|---|
| counter | |c |
counter |
counter |
| gauge | |g |
gauge |
gauge |
| histogram | |h (DogStatsD histogram token; etsy-style timers use |ms) |
histogram |
histogram |
| upDownCounter | signed |g |
gauge |
up_down_counter |
| asyncCounter | absolute |g |
counter |
async_counter |
| asyncGauge | |g |
gauge |
async_gauge |
Cardinality management
Every unique label-value combination is a distinct time series. High-cardinality labels (e.g. user_id, request_id) can exhaust memory if left unchecked.
The registry tracks per-metric cardinality and, when the limit (default: 10 000, must be ≥ 1 — anything else throws at construction) is exceeded, evicts the oldest combination (FIFO) — dropping it from the tracker and reclaiming that series from the backend, so a tag flood cannot grow backend memory without bound. Precisely: eviction delegates to the backend's remove() — storing backends (InMemoryBackend, PrometheusFileBackend) genuinely release the series, while StatsdBackend and JsonStreamBackend have nothing to retract once emitted and their remove() is a deliberate no-op, so against a push-only arm eviction bounds only the tracker. MultiBackend fans the call out to each child. The cardinality key is built from sorted, backslash-escaped k=v pairs (see Util::tagKey()), so lookalike tag sets such as ['x' => 'a|y=b'] and ['x' => 'a', 'y' => 'b'] stay distinct series. The tracker bounds series per metric name; the set of metric names itself is unbounded — treat untrusted strings as label values, never as metric names. A registry cloned with withTags() tracks its own budget independently of its parent.
// Default limit of 10 000 label combinations per metric $reg = Registry::new($backend); // Custom limit $reg = Registry::new($backend, [], 500); // Inspect current cardinality, and the configured ceiling $reg->cardinality('http.requests'); // → int $reg->cardinalityLimit(); // → int (500) // Drop one tracker entry only (default tags are merged in first, so you // pass just the per-emit tags): $reg->deleteLabelValues('http.requests', ['route' => '/logout']); // Reclaim tracker entry AND (on storing backends) the backend series: $reg->remove('http.requests', ['route' => '/logout']); // Push the current state to the backend (textfile durability — see below) $reg->flush();
Backends bound their own storage too. InMemoryBackend caps histogram samples per series (maxSamplesPerKey, default 4 096, reservoir-sampled) and — since this release — total series (maxSeries, default 0 = uncapped, oldest dropped FIFO when set). PrometheusFileBackend caps series per family (maxSeriesPerFamily, default 10 000, oldest dropped FIFO) and refuses a limit below 1. Backend::clear() resets a backend's accumulated state; the registry exposes it via $reg->backend()->clear().
Descriptor registration
The Descriptor DTO carries a metric's name, help text, type, and label keys. Register it with the registry so PrometheusFileBackend emits the family's # TYPE and # HELP lines even before the first sample arrives — informational metadata (the textfile format itself accepts sample-only families), handy for spotting declared-but-idle metrics:
use SugarCraft\Metrics\Registry; use SugarCraft\Metrics\Descriptor; use SugarCraft\Metrics\Backend\PrometheusFileBackend; $reg = Registry::new(PrometheusFileBackend::new('/var/lib/app/metrics.prom')); $reg->register(Descriptor::new( name: 'http_request_duration_seconds', help: 'HTTP request duration in seconds', type: 'histogram', labelKeys: ['route', 'status'], )); $stop = $reg->time('http_request_duration_seconds', ['route' => '/api/foo']); // … do the work … $elapsed = $stop(); // emits the duration and returns it (float seconds)
The constructor validates its input: a non-empty name matching [a-zA-Z_:][a-zA-Z0-9_:]*, non-empty help free of C0 control bytes and DEL, a type in counter|gauge|histogram|summary, and non-empty string label keys — violations throw. Because the name is checked RAW, dotted names like http.request.duration are refused here even though they are idiomatic on StatsD and legal to emit (the backend folds them at write time): register descriptors under the folded name they will occupy in the exposition. register() is idempotent only for identical re-registration: same type and same help is a no-op; anything else throws rather than silently picking a winner (per withTags() child registries: see the withTags() section — children inherit the ledger, so this door guards the whole family). A summary descriptor emits only the family's TYPE/HELP lines; the quantile/_sum/_count samples remain your responsibility. The descriptor universe is the four Prometheus wire types, while the registry offers six instrument kinds; the exposition mapping is counter and asyncCounter → TYPE counter, gauge, upDownCounter and asyncGauge → TYPE gauge, histogram → TYPE histogram, and summary is descriptor-only — no registry kind backs it.
time() records the sample exactly once — a second call to the stop-fn re-reads the clock and returns the then-current elapsed seconds, but records nothing further. Elapsed is measured on the monotonic clock (hrtime()), so a system-clock step (NTP correction, manual set) can never drive a negative duration into the histogram — and out of your finally arm; the reading is a duration, never a wall-clock timestamp.
Usage
The two happy paths are one-liners (sugar-metrics-045): Registry::inMemory()
for a registry that just accumulates (tests, boot probes), and Registry::to($target)
for one that streams newline JSON to a path, a resource, or php://stderr
when $target is null. Both forward every argument to the explicit
Registry::new(new InMemoryBackend()) / Registry::new(new JsonStreamBackend($target))
shape — use that whenever a non-default backend belongs in the picture:
use SugarCraft\Metrics\Registry; $reg = Registry::inMemory(); $audit = Registry::to('/var/log/metrics.json');
Full wiring:
use SugarCraft\Metrics\Registry; use SugarCraft\Metrics\Backend\StatsdBackend; $reg = Registry::new(StatsdBackend::new('127.0.0.1', 8125)); $reg->counter('http.requests', 1, ['route' => '/api/foo', 'status' => '200']); $reg->gauge ('queue.depth', 42); $stop = $reg->time('http.duration', ['route' => '/api/foo']); // … do the work … $stop();
withTags() returns a registry that pre-tags every emit:
$req = $reg->withTags(['request_id' => $rid, 'user' => $userId]); $req->counter('events'); // tagged with request_id + user automatically
A child cloned by withTags() inherits a snapshot of the parent's descriptor ledger, so a clashing re-registration on the child throws like one on the parent would (it no longer silently overwrites the shared family metadata). TYPE/HELP is backend-global regardless: a descriptor registered on any instance takes effect for every instance sharing the backend, so re-registering through a child to make emissions 'see' the metadata is unnecessary — and cross-registry conflicts (two registries over one backend, neither descended from the other) are caught only by the backend fold map, never by the per-instance ledgers.
If $rid / $userId come from untrusted callers, treat them like any other tag value: the backends sweep them for wire framing, but cardinality-wise every distinct value is a new series — hash or bucket before tagging.
Backends
InMemoryBackend
Useful for tests and as one arm of a fan-out. Counters add up, gauges hold the last value, histograms keep a bounded reservoir of samples per series (default 4 096). Until the reservoir fills it keeps every sample in arrival order; after that a new sample is accepted with probability cap/n — it replaces slot j = mt_rand(0, n-1) only when j falls inside the reservoir, so most later samples are discarded outright and the retained set stays a uniform random sample of the whole stream (Algorithm R). Set maxSeries to bound the total number of series (FIFO eviction; 0 leaves it uncapped).
Reading it in tests. The structured read surface is snapshot(): every accumulated series as its own row — {name, kind, tags, value} — with the internal storage key decoded back to the faithful name and tags you emitted (byte-exact, even for names carrying | or =; a histogram row's value is the reservoir sum). histogramSummary(name, tags) aggregates one series into {name, tags, count, observed, sum, mean} or returns null when absent. Both examples print through this surface. The raw maps are still exposed for zero-copy access: counters(), gauges(), histograms(), upDownCounters(), asyncCounters(), and asyncGauges() return the tracked maps keyed by the internal series key — the bare escaped name for untagged series, name| plus the canonicalized tag key otherwise; splitting those keys by hand re-implements the escaper, which is exactly what snapshot() exists to avoid. The per-series accessors take the parts instead: counterValue(name, tags), upDownCounterValue(name, tags), and asyncCounterValue(name, tags) report 0.0 for a series that was never recorded, while gaugeValue(name, tags) and asyncGaugeValue(name, tags) return null — a gauge has no meaningful zero, so absent and zero are distinguishable. histogramValues(name, tags) returns the retained samples ([] for an unseen series), and seriesCount() / clear() do what they say. Two traps (unchanged on the raw route, honestly split by histogramSummary): the histogram store is the reservoir, not the stream — once a series has seen more than maxSamplesPerKey samples, array_sum(histogramValues(...)) sums the retained subset, not the true total (count is the reservoir size, observed the full stream; assert on sample count and shape, or raise the cap); and the counter-zero vs gauge-null asymmetry means an unset gauge reads null, never 0.0.
JsonStreamBackend
Newline-delimited JSON, one event per line. The simplest, most diagnostic-friendly target. Default writes to stderr. Non-finite values render as the strings "NaN", "+Inf", "-Inf" (JSON has no number literal for them).
{"ts":"2026-05-02T16:30:00+00:00","kind":"counter","name":"hits","value":1,"tags":{"route":"/x"}}
A string file target's parent directory must exist and be writable — construction throws a RuntimeException naming the path otherwise. When throwOnError is set (the default), an unencodable emit or a failed flush throws instead of vanishing; with throwOnError: false the same conditions drop the event silently. A newly created string file's mode follows the process umask — PrometheusFileBackend no longer shares that consequence (its publish mode is chmod'd, 0600 by default), so for the ndjson stream choose a umask your reader can open. And the stream records tag values as captured: values that pass through SessionMetrics can carry personal data (usernames, term strings), so choose the sink path accordingly.
StatsdBackend
UDP datagrams in the etsy / DogStatsD wire format. The constructor takes six knobs: host (127.0.0.1) and port (8125) for the sink, dogstatsd (true) for the tag segment, failSilently (true), timeout (1.0 seconds bounding the socket CONNECT only — PHP applies it to connect(), not to the blocking gethostbyname() beneath a named host, so a blackholed resolver can stall construction past the bound; pass an IP literal or a pre-resolved existingSocket when you need a hard wall), and existingSocket (pass a ready stream resource when you manage the socket yourself). Opening the UDP socket happens at construction and throws a RuntimeException naming the endpoint if it fails; from then on failSilently: true means telemetry never breaks the program it instruments — failed or short writes are dropped. UDP is fire-and-forget, so even a write the socket accepts is no proof the stats agent received the datagram: packets can still vanish silently on the way. With failSilently: false write-side failures raise instead (that cannot resurrect a packet the network already dropped). For first runs, point the registry at JsonStreamBackend on stderr or at InMemoryBackend — you see exactly what would be emitted before wiring a collector.
Tags emit as |#k:v,...; with dogstatsd: false tags are dropped entirely (legacy StatsD has no tag channel). Every wire token is flattened at the send chokepoint so untrusted label values can never forge a second field, pair or line — the sweep is argued complete against all four grammars a Datadog-tagged agent dispatches on the port: metric lines, #k:v tag segments, _e{...} events and _sc{...} service checks. In metric names, control bytes, DEL, the C1 range, the Unicode LINE/PARAGRAPH SEPARATORS U+2028/U+2029 (a UTF-8-decoding line splitter sees them as newlines — they now fold like the byte-level ones), |, ,, space, : — and the prefix-dispatch enablers { } — become _; in tag keys the identical sweep applies (the same set, : included — measured: a=b rides raw, a:b folds to a_b; braces stay raw inside the tag grammar); in tag values |, ,, space and control/C1 bytes become _ while : is kept (safe, since a pair token can no longer contain a separator). Colons inside a tag value therefore survive; colons in the name or in a key do not. The sweep is a denylist: other punctuation (-, /, @, =, #) survives everywhere except braces at the name position.
hits:1|c|#route:/x,env:prod
Type tokens follow the table in Names on the wire; notably async counters emit an absolute |g (StatsD \|c is itself a monotonic counter, so re-publishing a cumulative external reading as |c would double-count it). Histograms ride \|h in both tag modes; with dogstatsd: false the lib still ships \|h — the current Prometheus statsd mapping drops \|h series entirely, so collector-side tolerance for the legacy shape is a deployment decision, not something the wire grammar here can fix (sugar-metrics-060). And the integrity note: UDP carries no authentication and no integrity protection — anything that can reach the sink port can emit as your service, untraceably (sugar-metrics-050). Keep host at 127.0.0.1 or inside a trusted network boundary; no fold or clamp in StatsdBackend defends against a forged datagram, only against smuggled wire bytes.
PrometheusFileBackend
HELP text and label values ride a byte-oriented control sweep (C0/DEL and the canonical UTF-8 spellings of C1 fold to _), and the result is then REPAIRED to valid UTF-8 rather than rejected: malformed bytes (a latin-1 username, a truncated sequence) become U+FFFD, because the exposition format mandates UTF-8 and one invalid byte is enough for a strict collector to reject the whole file. Well-formed UTF-8 passes byte-identical.
Atomically rewrites a .prom textfile-collector file with the current state of every metric. Pairs with node_exporter --collector.textfile.directory=…. Each flush() stages a fresh body into a uniquely named per-writer file (<path>.<pid>-<entropy>.tmp) created with x+ — a taken name fails closed and the writer retries with a fresh entropy draw, so planted or crash-residual bytes can never be published — fsyncs it, and publishes with an atomic rename(); rename(2) alone carries the atomicity (a reader sees the old file or the new one, never a half-written body), and a best-effort directory fsync after it makes the published link survive power loss. Simultaneous flushes resolve last-writer-wins; a crashed flush leaves at most one stale staging file behind. The .tmp suffix is node_exporter's version-independent ignore rule for textfile directories (this repo ships no live-collector CI; the rule predates the 1.6 filter flag and is what node_exporter's own atomic-write recipe prescribes), and every successful publish sweeps residue of its own staging pattern older than one hour — names are per-writer-unique and this class is the only writer, so a swept stale cannot be a flush in flight. The published file is mode 0600 by default (chmod on the exclusive staging path before the rename — umask-independent); pass fileMode: 0644 when the exporter reads as a different user. The parent directory of the target must exist and be writable; flush() throws a RuntimeException naming the staging path if it is not.
Counter values accumulate across flush()s; histograms emit the 14 cumulative bucket boundaries (le="0.005" … le="100" — the classic client_golang set extended with 25/50/100) plus le="+Inf", alongside _count and _sum. Bucket boundaries passed to the constructor must be finite and strictly increasing. A caller-supplied le tag is refused on histograms — it would forge a second bucket label. Series per family are capped (maxSeriesPerFamily, default 10 000, oldest dropped FIFO), and remove() / clear() reclaim accumulated series from memory so a tag flood cannot grow the backend without bound. Exposition integrity is guarded at flush time: a histogram sharing its base name with any other kind of metric throws a loud RuntimeException even under different label sets (a histogram emits only derived _bucket/_count/_sum lines, so such a pair would otherwise publish them under the other kind's # TYPE), and two series with identical emitted name+labels (possible only through a sanitizing fold the registry could not see, or a counter colliding with a histogram's derived _count/_sum) likewise throw, naming the offender instead of publishing a file Prometheus will reject wholesale.
Always call flush() explicitly — e.g. on every scrape-adjacent tick or session close — to guarantee delivery and surface errors; the library arms no timers of its own. The destructor invokes flush() automatically, but everything it throws is silently swallowed in __destruct — a failed open, a short write, a failed fflush or fsync, a failed rename, or even an exposition-integrity refusal all vanish at shutdown (destructors must not throw, so nothing surfaces there). Explicit calls throw a RuntimeException on failure — a failed open of the staging path, a short write, a failed fflush or fsync, or a failed rename. clear() resets accumulated state but does not delete the already-written .prom file — the next flush() rewrites whatever remains.
MultiBackend
Fan out to multiple backends — e.g. live StatsD plus a JSON audit trail. Constructing it with zero children throws.
$reg = Registry::new(MultiBackend::new( StatsdBackend::new(), JsonStreamBackend::new('./metrics.jsonl'), ));
Error isolation: with the plain constructor the fan-out stops at the first failing child and that failure propagates unchanged. Build with MultiBackend::withContinueOnError(...) instead and every child gets a turn: all failures are collected and rethrown as one MultiBackendException, whose errors() method returns the collected Throwables. The rule holds for every operation — emits, remove() and clear() alike: remove() / clear() propagate the first child failure by default and aggregate under withContinueOnError.
Writing a backend
SugarCraft\Metrics\Backend is ten void methods and nothing else (sugar-metrics-011):
| Method | Contract |
|---|---|
counter($name, $value, $tags) |
monotonic add ($value >= 0; the registry refuses negatives at the verb) |
gauge($name, $value, $tags) |
set the current level — last write wins, negatives allowed |
histogram($name, $value, $tags) |
observe one sample into the named family's distribution |
upDownCounter($name, $amount, $tags) |
apply a signed delta |
asyncCounter($name, $value, $tags) / asyncGauge($name, $value, $tags) |
publish an ABSOLUTE reading of externally-owned state |
describe(Descriptor $descriptor) |
record a family's TYPE/HELP metadata; called once per new registration, so a backend with no metadata channel may no-op |
flush() |
make buffered state observable (rewrite the file, drain the buffer); the shipping sinks throw a RuntimeException here on write failure |
remove($name, $tags) |
reclaim one series — the eviction hook the cardinality caps call during churn, so it must tolerate being called at any time |
clear() |
reclaim everything |
Conventions the shipped backends keep to: emit verbs may throw on structurally invalid input (a name or label key that folds to empty refuses at the exposition chokepoint; a cross-kind name collision refuses loudly) — never accept-and-corrupt; the tag array merges with registry default tags already applied by the caller, raw, before dispatch; nothing arms timers — flush() happens only when the application calls it (or a destructor attempts its one swallowed pass); and the whole surface is value-typed (string/float/array) so a backend can be exercised without touching a wire.
SugarSshServer session middleware
Wires session telemetry into a SugarSshServer stack:
use SugarCraft\SshServer\Server; use SugarCraft\Metrics\Registry; use SugarCraft\Metrics\Backend\PrometheusFileBackend; use SugarCraft\Metrics\Middleware\SessionMetrics; $reg = Registry::new(PrometheusFileBackend::new('/var/lib/ssh/metrics.prom')); Server::new() ->use(SessionMetrics::new($reg)) ->use(/* ... your stack ... */) ->serve();
Per session this emits:
| Metric | Type | Tags |
|---|---|---|
ssh.session.connect |
counter | user, term |
ssh.session.duration |
histogram | user, term |
ssh.session.error |
counter | user, term, exception |
user and term are attacker-controllable, so they are normalised to [A-Za-z0-9._:@/-] (everything else collapses to _) and clamped to 64 bytes. The same clamp is applied to every value your extraTags closure returns — the closure contributes tag keys freely, but its values cannot smuggle unbounded or control bytes into the scraped label space. Base user/term stay authoritative: an extraTags entry returning a user key can never rewrite the normalised session identity. The exception tag carries the throwable class basename normalised the same way — a public scrape should not fingerprint your dependency layout through full FQCNs — and it is assigned after the merge, so a closure can never shadow it either; operators on a private sink can restore full names with new($registry, extraTags: …, fullExceptionClass: true) (backslashes fold to _).
Pass extraTags (a callable receiving the Session) to add things like client subnet, geo, build version.
The middleware only emits — it registers no Descriptors, so a textfile sink shows nothing for a family until its first session (sugar-metrics-010). To publish # TYPE/# HELP up front, pre-register the names the backend will see: the dotted emit names above arrive at the exposition folded, dots to underscores (see Descriptor registration — the descriptor door refuses raw dots):
$reg->register(Descriptor::new('ssh_session_connect', 'SSH connect attempts', 'counter', ['user', 'term'])); $reg->register(Descriptor::new('ssh_session_duration', 'Seconds each session stayed open', 'histogram', ['user', 'term'])); $reg->register(Descriptor::new('ssh_session_error', 'Sessions ended by an exception', 'counter', ['user', 'term', 'exception']));
The bundled examples/ssh-server-with-metrics.php honours SSH_METRICS_TEXTFILE=<path> and publishes textfile exposition there alongside its StatsD packets; the library itself never reads the environment (sugar-metrics-061).
Localization
Every exception message in this library is looked up through SugarCraft\Core\I18n\Lang (the metrics namespace facade), so failures render in the operator's locale. The lookup flows through Lang; the selection lives on T, and the library never sets the locale itself — out of the box every message renders from lang/en.php. Select one at startup:
\SugarCraft\Core\I18n\T::setLocale('de'); // messages arrive in German
T::detect() (reads LC_ALL, LC_MESSAGES, LANG) is the opt-in alternative; prefer pinning the locale per service over detecting it.
Sixteen locales ship: ar, cs, de, en, es, fr, it, ja, ko, nl, pl, pt, pt-br, ru, tr, zh-cn. Locale parity is pinned by the test suite.
Status
Feature-complete and in production use: all six instrument kinds holdable (newCounter/newGauge/newHistogram join the async trio), Registry cardinality tracking with FIFO eviction and backend reclaim, exposition-integrity guards, fsync-before-rename durability, a structured read surface (snapshot()/histogramSummary()), and five backends — InMemory, JsonStream, Statsd, PrometheusFile and Multi. 291 tests (1,584 assertions; ≈37 s full run measured at this commit on the lane host — the two-process staging and append pins cost real wall time; pure unit legs stay a few seconds): Registry, each backend, SessionMetrics middleware, wire-format and tag-key collision pins, hex-level forgery pins, i18n locale parity across all 16 shipped locales, and example smoke checks.
Breaking changes
MultiBackendException::getErrors() → errors(). The accessor now follows
the library's bare-accessor convention (no get prefix). A repo-wide grep
found no call sites outside sugar-metrics itself, so the rename landed complete
in one pass; external code still calling getErrors() must switch to
errors().
Wire-integrity hardening (2026-11). These were silent-corruption or silent-loss behaviours; they are now loud:
- StatsD lines: colons in metric names are flattened to
_(they forged the value/type separator), and,, space, pipe, control bytes and the C1 range are swept out of every wire token — attacker-influenced tag values can no longer forge pairs, fields or datagram lines. PrometheusFileBackendrefuses, at write time, two distinct raw names/tag keys whose sanitising fold would collide (previously one silently overwrote the other, or the fold produced a duplicate label that made the entire exposition scrapable-nothing); one metric name used as two kinds — a histogram and any other kind sharing the base name, even under different label sets — and duplicate emitted series (a metric name clashing with a histogram's derived_count/_sum, or the old silentnewUpDownCountertag-drop replaying as a re-type) now throw at flush instead of poisoning the file.- Histograms reject a caller-supplied
letag; bucket-boundary lists must be finite and strictly increasing (validated in the constructor). Registrycardinality limits below 1 throw at construction; negative values on monotonic counters and histograms throw (gauges, up/down counters and async instruments still accept negatives); re-register()with a different type or help throws instead of first-write-wins.Descriptorconstructor validates name charset, help text, type and label keys (previously six literalthrows with unvalidated input landing in the exposition).MultiBackendwith zero children throws;remove()/clear()now honour the error mode (they previously swallowed child failures even in default mode).JsonStreamBackend: theupdowncounterkind string is nowup_down_counter, and an unencodable payload throws in loud mode instead of dropping the record.Registry::flush()is public — long-lived textfile deployments should drive it (the library still never arms timers of its own).observe()onAsyncCounter/AsyncGaugetakes optional per-call tags merged over the instrument's static tags.- SessionMetrics metrics renamed
wish.session.*→ssh.session.*(the wish lineage name predated the 2026-10 rename);InMemoryBackendgained amaxSeriescap knob;StatsdBackendasync counters emit absolute|ginstead of signed|cdeltas (StatsD counters are monotonic — publishing a cumulative external reading as|cdouble-counted it).
