Files
upstream-mirror c60cc7ca75
Some checks failed
CI / Run tests and lints (push) Failing after 29s
CI / Build CLI docs (push) Has been skipped
CI / Run Playwright end-to-end tests (mysql) (push) Failing after 3s
CI / Run Playwright end-to-end tests (postgres) (push) Failing after 2s
CI / Run Playwright end-to-end tests (sqlite) (push) Failing after 3s
CodeQL / Analyze (go) (push) Failing after 4s
CodeQL / Analyze (javascript) (push) Failing after 3s
Docker Image Scanners / scanners (push) Failing after 4s
Synchronize Issue Labels / Synchronize Issue Labels (push) Has been skipped
CI / Run end-to-end tests (postgres) (push) Failing after 19s
CI / Run end-to-end tests (sqlite) (push) Failing after 2s
CI / Run Playwright end-to-end tests (cockroach) (push) Failing after 2s
CI / Draft newsletter (push) Has been skipped
CI / Generate release (push) Has been skipped
CI / Pending approval Slack notification (push) Has been skipped
CI / Send newsletter (push) Has been skipped
snapshot of https://github.com/ory/kratos.git (master, 2026-09-15; blobs > 131072B omitted)
2026-09-15 21:19:12 +05:00

62 lines
1.9 KiB
Go

// Copyright © 2026 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package prometheusx
import (
"context"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel/trace"
)
// ExemplarFromContext returns exemplar labels (trace_id, span_id) for the
// sampled trace span in ctx, or nil when there is none. The nil return makes
// it directly usable with promhttp.WithExemplarFromContext.
func ExemplarFromContext(ctx context.Context) prometheus.Labels {
sc := trace.SpanContextFromContext(ctx)
if !sc.IsValid() || !sc.IsSampled() {
return nil
}
return prometheus.Labels{
"trace_id": sc.TraceID().String(),
"span_id": sc.SpanID().String(),
}
}
// AddWithExemplar adds v to counter. When ctx carries a sampled trace span,
// the addition carries a trace exemplar so dashboards can link the counter
// to the trace. Any panic from exemplar validation is swallowed: a lost
// exemplar must never break the recording path, and client_golang applies
// the addition before validating the exemplar, so the count is recorded
// either way.
func AddWithExemplar(ctx context.Context, counter prometheus.Counter, v float64) {
exemplar := ExemplarFromContext(ctx)
adder, ok := counter.(prometheus.ExemplarAdder)
if exemplar == nil || !ok {
counter.Add(v)
return
}
defer func() {
_ = recover()
}()
adder.AddWithExemplar(v, exemplar)
}
// ObserveWithExemplar records v on obs. When ctx carries a sampled trace
// span, the observation carries a trace exemplar on the histogram bucket it
// falls into. The same panic-swallowing rationale as AddWithExemplar
// applies.
func ObserveWithExemplar(ctx context.Context, obs prometheus.Observer, v float64) {
exemplar := ExemplarFromContext(ctx)
observer, ok := obs.(prometheus.ExemplarObserver)
if exemplar == nil || !ok {
obs.Observe(v)
return
}
defer func() {
_ = recover()
}()
observer.ObserveWithExemplar(v, exemplar)
}