package telemetry import ( "context" "strconv" "sync" "time" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/metric" ) var ( metricsOnce sync.Once httpDuration metric.Float64Histogram jobsProcessed metric.Int64Counter jobDuration metric.Float64Histogram jobsAccepted metric.Int64Counter timeToReady metric.Float64Histogram jobsReadyInBudget metric.Int64Counter ttrMissed metric.Int64Counter workerBusy metric.Int64ObservableGauge workerCapacity metric.Int64ObservableGauge dbUsed metric.Int64ObservableGauge dbIdle metric.Int64ObservableGauge dbMax metric.Int64ObservableGauge dbEmptyAcquire metric.Int64ObservableCounter dbEmptyWait metric.Float64ObservableCounter processCPU metric.Float64ObservableCounter processMemory metric.Int64ObservableGauge processMemLimit metric.Int64ObservableGauge oldestJobAge metric.Float64ObservableGauge oldestOutboxAge metric.Float64ObservableGauge jobsOverdue metric.Int64ObservableGauge ) func initMetrics() { metricsOnce.Do(func() { meter := otel.Meter("messenger") httpDuration, _ = meter.Float64Histogram("http.server.request.duration", metric.WithDescription("HTTP server request duration"), metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10)) jobsProcessed, _ = meter.Int64Counter("messenger.jobs.processed", metric.WithDescription("Attachment job attempts by outcome")) jobDuration, _ = meter.Float64Histogram("messenger.job.duration", metric.WithDescription("Attachment job processing duration"), metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120)) jobsAccepted, _ = meter.Int64Counter("messenger.jobs.accepted", metric.WithDescription("Durable attachment jobs accepted with 202")) timeToReady, _ = meter.Float64Histogram("messenger.job.time_to_ready", metric.WithDescription("Time from durable acceptance to ready"), metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(1, 2.5, 5, 10, 20, 30, 60, 120, 300)) jobsReadyInBudget, _ = meter.Int64Counter("messenger.jobs.ready_within_budget", metric.WithDescription("Jobs ready within the 30s TTR objective")) ttrMissed, _ = meter.Int64Counter("messenger.jobs.ttr_missed", metric.WithDescription("Jobs that missed or failed the 30s TTR objective")) workerBusy, _ = meter.Int64ObservableGauge("messenger.worker.busy", metric.WithDescription("Worker slots currently processing a job")) workerCapacity, _ = meter.Int64ObservableGauge("messenger.worker.capacity", metric.WithDescription("Configured worker concurrency")) dbUsed, _ = meter.Int64ObservableGauge("messenger.db.pool.used") dbIdle, _ = meter.Int64ObservableGauge("messenger.db.pool.idle") dbMax, _ = meter.Int64ObservableGauge("messenger.db.pool.max") dbEmptyAcquire, _ = meter.Int64ObservableCounter("messenger.db.pool.empty_acquire", metric.WithDescription("Acquisitions that had to wait for a free connection")) dbEmptyWait, _ = meter.Float64ObservableCounter("messenger.db.pool.empty_acquire_wait_seconds", metric.WithDescription("Cumulative wait time for empty pool acquisitions"), metric.WithUnit("s")) processCPU, _ = meter.Float64ObservableCounter("messenger.process.cpu_seconds", metric.WithDescription("Cumulative process CPU time from cgroup or /proc"), metric.WithUnit("s")) processMemory, _ = meter.Int64ObservableGauge("messenger.process.memory_usage_bytes", metric.WithDescription("Resident/current memory of this container"), metric.WithUnit("By")) processMemLimit, _ = meter.Int64ObservableGauge("messenger.process.memory_limit_bytes", metric.WithDescription("Container memory limit, 0 when unknown"), metric.WithUnit("By")) oldestJobAge, _ = meter.Float64ObservableGauge("messenger.queue.oldest_job_age", metric.WithDescription("Age of the oldest queued or processing job"), metric.WithUnit("s")) oldestOutboxAge, _ = meter.Float64ObservableGauge("messenger.outbox.oldest_unpublished_age", metric.WithDescription("Age of the oldest unpublished outbox intent"), metric.WithUnit("s")) jobsOverdue, _ = meter.Int64ObservableGauge("messenger.jobs.overdue", metric.WithDescription("Queued/processing jobs older than the 30s TTR objective")) }) } // RecordHTTP records one completed server request. route must be an OpenAPI // template, never a raw path. func RecordHTTP(ctx context.Context, method, route string, status int, duration time.Duration) { initMetrics() class := statusClass(status) attrs := metric.WithAttributes( attribute.String("http.request.method", method), attribute.String("http.route", route), attribute.Int("http.response.status_code", status), attribute.String("http.response.status_class", class), ) httpDuration.Record(ctx, duration.Seconds(), attrs) } // RecordJobAccepted counts a durable 202 acceptance. func RecordJobAccepted(ctx context.Context, pipelineVersion int) { initMetrics() jobsAccepted.Add(ctx, 1, metric.WithAttributes(attribute.Int("pipeline.version", pipelineVersion))) } // RecordJobAttempt records one processing attempt. func RecordJobAttempt(ctx context.Context, jobType, outcome string, duration time.Duration) { initMetrics() attrs := metric.WithAttributes( attribute.String("job.type", jobType), attribute.String("outcome", outcome), ) jobsProcessed.Add(ctx, 1, attrs) jobDuration.Record(ctx, duration.Seconds(), attrs) } // RecordJobReady records a terminal ready result and its time-to-ready. func RecordJobReady(ctx context.Context, pipelineVersion int, duration time.Duration) { initMetrics() attrs := metric.WithAttributes(attribute.Int("pipeline.version", pipelineVersion)) timeToReady.Record(ctx, duration.Seconds(), attrs) if duration <= 30*time.Second { jobsReadyInBudget.Add(ctx, 1, attrs) } } // RegisterWorkerMetrics exposes the worker's in-flight slots and capacity. // RegisterRelayMetrics exposes durable backlog age gauges computed in the relay. func RegisterRelayMetrics(oldestJob func(context.Context) (float64, error), oldestOutbox func(context.Context) (time.Duration, error), overdue func(context.Context) (int64, error)) error { initMetrics() _, err := otel.Meter("messenger").RegisterCallback(func(ctx context.Context, o metric.Observer) error { if oldestJob != nil { if seconds, err := oldestJob(ctx); err == nil { o.ObserveFloat64(oldestJobAge, seconds) } } if oldestOutbox != nil { if age, err := oldestOutbox(ctx); err == nil { o.ObserveFloat64(oldestOutboxAge, age.Seconds()) } } if overdue != nil { if count, err := overdue(ctx); err == nil { o.ObserveInt64(jobsOverdue, count) } } return nil }, oldestJobAge, oldestOutboxAge, jobsOverdue) return err } // RecordTTRMissed records jobs marked as TTR misses by the relay sweeper. func RecordTTRMissed(ctx context.Context, count int64) { initMetrics() // Add zero at relay startup so the counter exists before the first miss; // otherwise the first rate() window loses the initial increment. ttrMissed.Add(ctx, count) } func RegisterWorkerMetrics(busy func() int64, capacity int64) error { initMetrics() _, err := otel.Meter("messenger").RegisterCallback(func(_ context.Context, o metric.Observer) error { o.ObserveInt64(workerBusy, busy()) o.ObserveInt64(workerCapacity, capacity) return nil }, workerBusy, workerCapacity) return err } func statusClass(status int) string { if status < 100 || status > 599 { return "unknown" } return strconv.Itoa(status/100) + "xx" }