6.2 KiB
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, kept for compatibility)
├── log.go LogHandler (v1.0.0 API, kept for compatibility)
├── 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)
- Create a
<Thing>Configstruct withMetrics *Metrics,Logger *slog.Logger,TracerProvider,Propagatorand adefaults()method (globals when nil) - Create metrics through
cfg.Metrics.base()so names have no namespace; follow<area>_<role>_requests_total/_request_duration_secondsnaming - Record latency with
observe(ctx, ...)to attach exemplars - Add an
Observerwrapper method, a metric to the README/doc.go reference tables, and panels/alerts indeploy/
Add a new metric type (e.g., Summary)
- Add a method to
Metricsinmetrics.gousingm.cfg.Namespace/m.cfg.Subsystem - Register via
register(m.registry, ...)(idempotent), notMustRegister
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:
Newsetsslog.Default, the global tracer provider, propagator and OTel error handler — only after everything that can fail succeeded.SetupTracersets provider + propagator. Tests must restore globals (newTestObserverdoes). - Built-in metric names ignore Namespace by design (
Metrics.base()); user metrics viao.Metrics()keep it. - Batching:
New/SetupTraceruse a batch span processor; tests callForceFlush(flushSpans) before reading an in-memory exporter. - No endpoint = no export: with an empty
Tracing.Endpointand noOTEL_EXPORTER_OTLP_*ENDPOINT, the provider has no exporter but still creates spans (log correlation, propagation). - Sampler:
<= 0means 1.0; sampling isParentBased(TraceIDRatioBased). UseDisabledto turn tracing off. - TLS by default: the OTLP connection is plaintext only with
TracerConfig.Insecure: true(orOBSX_TRACING_INSECURE=true);TLSsupplies a customtls.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
RouteFuncreadsr.Pattern; when the middleware wraps an*http.ServeMuxdirectly it falls back tomux.Handler(r). Other routers needRouteFunc. - 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;
Observerwires them - Isolated Prometheus registry per
Metrics - stdlib only testing — no testify, no gomock; gRPC tests use
bufconnwith the health service - Bounded cardinality — route templates, normalized methods, never raw paths or IDs as labels