Files
obsx/AGENTS.md
T
M.ShakhmatovandClaude Fable 5.2 8837e8d316
CI / test (push) Successful in 1m12s
Deprecate v1.0.0 HTTP and log helpers in favour of the toolkit API
LogHandler and HTTPTransport now delegate to NewTraceHandler and
NewHTTPTransport. HTTPMiddleware keeps its v1.0.0 metric names but
shares responseWriter and normalizeMethod with NewHTTPMiddleware.
The package example shows obsx.New.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 16:43:33 +03:00

6.2 KiB

AGENTS.md — obsx

Universal guide for AI coding agents working with this codebase.

Overview

git.codelab.vc/pkg/obsx is an observability toolkit for Go microservices: slog logging with trace correlation, OpenTelemetry tracing, Prometheus metrics, health checks, an admin HTTP server, and ready-made instrumentation for HTTP/gRPC servers and clients. The main design goal is uniformity: every service exposes the same metric names, log fields and endpoints.

Package map

obsx/                     Root package (single package)
├── doc.go                Package documentation
├── observer.go           Observer, New, Track, HTTP/gRPC helpers, Shutdown
├── config.go             Config, AdminConfig, defaults, WithEnv, BuildInfo
├── logger.go             LogConfig, NewLogger, ParseLevel, TraceHandler
├── tracer.go             TracerConfig, SetupTracer, StartSpan, Trace, RecordError, TraceID
├── metrics.go            Metrics factory, register (idempotent), observe (exemplars)
├── http.go               HTTPMiddleware, HTTPTransport (v1.0.0 API, deprecated wrappers)
├── log.go                LogHandler (v1.0.0 API, deprecated alias of NewTraceHandler)
├── httpserver.go         NewHTTPMiddleware, responseWriter, route detection
├── httpclient.go         NewHTTPTransport
├── grpc.go               NewGRPCInterceptors (server/client, unary/stream)
├── health.go             Health, checks, HTTP handlers, grpc.health.v1 server
├── admin.go              Observer.AdminHandler, LogLevelHandler
├── examples/service/     Runnable example service
└── deploy/               Grafana dashboard + Prometheus alerts for built-in metrics

Architecture

                          obsx.New(ctx, Config)
                                   │
   ┌──────────────┬────────────────┼───────────────┬──────────────┐
   ▼              ▼                ▼               ▼              ▼
NewLogger   newTracerProvider  NewMetrics      NewHealth     admin server
(slog JSON  (OTLP grpc/http,   (isolated reg,  (liveness,    (/metrics, /healthz,
 + Trace-    ParentBased       go+process,     readiness,    /readyz, /buildinfo,
 Handler)    sampler)          build_info)     gRPC health)  /loglevel, pprof)
   │              │                │
   └──────────────┴───────┬────────┘
                          ▼
     Observer.HTTPMiddleware / HTTPClient / GRPC*Options / Track
     (thin wrappers over NewHTTPMiddleware, NewHTTPTransport,
      NewGRPCInterceptors with the Observer's components)

Common tasks

Add new built-in instrumentation (e.g., message queue consumer)

  1. Create a <Thing>Config struct with Metrics *Metrics, Logger *slog.Logger, TracerProvider, Propagator and a defaults() method (globals when nil)
  2. Create metrics through cfg.Metrics.base() so names have no namespace; follow <area>_<role>_requests_total / _request_duration_seconds naming
  3. Record latency with observe(ctx, ...) to attach exemplars
  4. Add an Observer wrapper method, a metric to the README/doc.go reference tables, and panels/alerts in deploy/

Add a new metric type (e.g., Summary)

  1. Add a method to Metrics in metrics.go using m.cfg.Namespace / m.cfg.Subsystem
  2. Register via register(m.registry, ...) (idempotent), not MustRegister

Add an environment variable

Add an env* call in Config.WithEnv (config.go), document it in the doc comment and the README table, extend TestConfig_WithEnv.

Regenerate the Grafana dashboard

The dashboard JSON is hand-maintainable; keep the job variable and $__rate_interval usage consistent across panels.

Gotchas

  • Globals: New sets slog.Default, the global tracer provider, propagator and OTel error handler — only after everything that can fail succeeded. SetupTracer sets provider + propagator. Tests must restore globals (newTestObserver does).
  • Built-in metric names ignore Namespace by design (Metrics.base()); user metrics via o.Metrics() keep it.
  • Batching: New/SetupTracer use a batch span processor; tests call ForceFlush (flushSpans) before reading an in-memory exporter.
  • No endpoint = no export: with an empty Tracing.Endpoint and no OTEL_EXPORTER_OTLP_*ENDPOINT, the provider has no exporter but still creates spans (log correlation, propagation).
  • Sampler: <= 0 means 1.0; sampling is ParentBased(TraceIDRatioBased). Use Disabled to turn tracing off.
  • TLS by default: the OTLP connection is plaintext only with TracerConfig.Insecure: true (or OBSX_TRACING_INSECURE=true); TLS supplies a custom tls.Config.
  • Stable API: v1 is stable — do not break it; record changes in CHANGELOG.md.
  • Tracer name: all instrumentation shares the scope git.codelab.vc/pkg/obsx.
  • Route detection: default RouteFunc reads r.Pattern; when the middleware wraps an *http.ServeMux directly it falls back to mux.Handler(r). Other routers need RouteFunc.
  • Panics are recorded and re-raised (HTTP middleware, gRPC server interceptors, Track).
  • Admin shutdown waits at most 1s, then closes connections; tracer flush happens first.
  • Idempotent registration: identical metric definitions return the existing collector; conflicting ones panic.

Commands

go build ./...                          # compile
go test ./...                           # all tests
go test -race ./...                     # tests with race detector
go test -v -run TestName ./...          # single test
go vet ./...                            # static analysis
go run ./examples/service               # example service on :8080, admin on :9090

Conventions

  • Struct-based configs with defaults() methods; no functional options
  • Explicit dependencies in standalone constructors; Observer wires them
  • Isolated Prometheus registry per Metrics
  • stdlib only testing — no testify, no gomock; gRPC tests use bufconn with the health service
  • Bounded cardinality — route templates, normalized methods, never raw paths or IDs as labels