feat(telemetry): local move-preview adoption metrics (Phase 4)
CI / changes (pull_request) Successful in 3s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 15s
CI / ui (pull_request) Successful in 57s
CI / conformance (pull_request) Successful in 9s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m17s

Measure uptake of the client-side local move-preview accelerator (§5) so
adoption can be watched before defaulting it on: app cold starts, dictionary
loads by result (fetched / cache_hit / miss) and move previews by path
(local / network — the backend load shed).

A small best-effort client beacon (POST /metrics/local-eval, session-gated)
batches counter deltas and posts them on a 60s timer and when the app is
backgrounded — never on the gameplay path: the in-app counters are plain
in-memory increments, only the periodic flush touches the network and it is
fire-and-forget. The gateway folds each batch into three OTel counters
(local_eval_cold_start_total, local_eval_dict_load_total,
local_eval_preview_total), clamped against a spoofed inflation.

- gateway: counters + recordLocalEval + session-gated /metrics/local-eval handler
- ui: localeval-metrics accumulator/beacon; hooks in the dict loader, in
  Game.recompute and in bootstrap (skipped under the mock harness)
- caddy: route /metrics/* to the gateway
- docs: ARCHITECTURE §11; Grafana "Scrabble — Users" dashboard panels
This commit is contained in:
Ilia Denisov
2026-07-01 23:31:49 +02:00
parent 5f87b3fa43
commit 2e8fa83814
12 changed files with 254 additions and 3 deletions
+47 -1
View File
@@ -28,6 +28,10 @@ type serverMetrics struct {
rateLimited metric.Int64Counter
banned metric.Int64Counter
active *activeUsers
// Client-reported local move-preview adoption (see localEvalMetricsHandler).
localColdStart metric.Int64Counter
localDictLoad metric.Int64Counter
localPreview metric.Int64Counter
}
// newServerMetrics builds the instruments on meter (nil selects a no-op meter),
@@ -54,7 +58,12 @@ func newServerMetrics(meter metric.Meter) *serverMetrics {
if err != nil {
b, _ = noop.NewMeterProvider().Meter(meterName).Int64Counter("gateway_abuse_banned_total")
}
m := &serverMetrics{edge: h, rateLimited: c, banned: b, active: newActiveUsers()}
m := &serverMetrics{
edge: h, rateLimited: c, banned: b, active: newActiveUsers(),
localColdStart: counterOf(meter, "local_eval_cold_start_total", "App cold starts reported by clients — the denominator for local-move-preview adoption."),
localDictLoad: counterOf(meter, "local_eval_dict_load_total", "Client dictionary loads for the local move preview, by result (fetched, cache_hit or miss)."),
localPreview: counterOf(meter, "local_eval_preview_total", "Client move previews, by path (local on-device, or network fallback)."),
}
gauge, err := meter.Int64ObservableGauge("active_users",
metric.WithDescription("Distinct accounts that performed an authenticated action within the window (in-memory, single gateway instance)."))
@@ -98,3 +107,40 @@ func (m *serverMetrics) recordRateLimited(ctx context.Context, class string) {
func (m *serverMetrics) recordBan(ctx context.Context, reason string) {
m.banned.Add(ctx, 1, metric.WithAttributes(attribute.String("reason", reason)))
}
// localEvalReport is the client-reported local move-preview telemetry batch — deltas since
// the client's previous report. It backs the adoption dashboard: app cold starts vs cached
// dictionaries vs on-device previews.
type localEvalReport struct {
ColdStart int `json:"cold_start"`
DictFetched int `json:"dict_fetched"`
DictCacheHit int `json:"dict_cache_hit"`
DictMiss int `json:"dict_miss"`
PreviewLocal int `json:"preview_local"`
PreviewNetwork int `json:"preview_network"`
}
// recordLocalEval folds one client report into the edge's local-eval counters.
func (m *serverMetrics) recordLocalEval(ctx context.Context, r localEvalReport) {
add := func(c metric.Int64Counter, n int, opts ...metric.AddOption) {
if n > 0 {
c.Add(ctx, int64(n), opts...)
}
}
add(m.localColdStart, r.ColdStart)
add(m.localDictLoad, r.DictFetched, metric.WithAttributes(attribute.String("result", "fetched")))
add(m.localDictLoad, r.DictCacheHit, metric.WithAttributes(attribute.String("result", "cache_hit")))
add(m.localDictLoad, r.DictMiss, metric.WithAttributes(attribute.String("result", "miss")))
add(m.localPreview, r.PreviewLocal, metric.WithAttributes(attribute.String("path", "local")))
add(m.localPreview, r.PreviewNetwork, metric.WithAttributes(attribute.String("path", "network")))
}
// counterOf builds an Int64Counter on meter, falling back to a no-op on the rare
// construction error so metrics never fail startup.
func counterOf(meter metric.Meter, name, desc string) metric.Int64Counter {
c, err := meter.Int64Counter(name, metric.WithDescription(desc))
if err != nil {
c, _ = noop.NewMeterProvider().Meter(meterName).Int64Counter(name)
}
return c
}
+49
View File
@@ -9,7 +9,9 @@ package connectsrv
import (
"context"
"crypto/subtle"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"strings"
@@ -191,6 +193,8 @@ func (s *Server) HTTPHandler() http.Handler {
// The client-side local move preview pulls each game's pinned dictionary blob
// through this session-gated route (not public); see dictBytesHandler.
mux.Handle("/dict/", s.dictBytesHandler())
// The client posts its local-move-preview adoption telemetry here (session-gated).
mux.Handle("/metrics/local-eval", s.localEvalMetricsHandler())
// The embedded UI: the game SPA under /app/ (web), /telegram/ (the Telegram Mini
// App) and /vk/ (the VK Mini App) — the single-origin model (docs/ARCHITECTURE.md
// §13). All sit below the h2c wrap so the Connect edge (a more specific prefix) keeps
@@ -474,6 +478,51 @@ func parseDictPath(p string) (variant, version string, ok bool) {
return variant, version, true
}
// localEvalMetricsHandler ingests a client's local move-preview telemetry batch into the
// edge's adoption counters (docs/ARCHITECTURE.md §11). Session-gated so only real clients
// report; the values are aggregate (no per-user attributes) and clamped against a spoofed
// inflation. Only POST; the body is a small JSON of per-metric deltas.
func (s *Server) localEvalMetricsHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
ip := peerIP(r.RemoteAddr, r.Header)
if _, _, err := s.resolve(r.Context(), r.Header, ip); err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
var rep localEvalReport
if err := json.NewDecoder(io.LimitReader(r.Body, 512)).Decode(&rep); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
clampReport(&rep)
s.metrics.recordLocalEval(r.Context(), rep)
w.WriteHeader(http.StatusNoContent)
})
}
// clampReport bounds each counter of a client report against a spoofed inflation — one batch
// reflects at most a few minutes of a single client's activity.
func clampReport(r *localEvalReport) {
const maxPerField = 1000
clamp := func(n *int) {
if *n < 0 {
*n = 0
} else if *n > maxPerField {
*n = maxPerField
}
}
clamp(&r.ColdStart)
clamp(&r.DictFetched)
clamp(&r.DictCacheHit)
clamp(&r.DictMiss)
clamp(&r.PreviewLocal)
clamp(&r.PreviewNetwork)
}
// resolve extracts and resolves the Authorization bearer token to an account id
// and its guest flag, returning a Connect Unauthenticated error when it is missing
// or unknown.