tracing

package
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 2, 2026 License: Apache-2.0 Imports: 19 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	SpanSendRelay                    = "smartrouter.SendRelay"
	SpanParsedRelay                  = "smartrouter.SendParsedRelay"
	SpanParseRelay                   = "smartrouter.ParseRelay"
	SpanProcessRelaySend             = "smartrouter.ProcessRelaySend"
	SpanProcessingResult             = "smartrouter.ProcessingResult"
	SpanCacheLookup                  = "smartrouter.CacheLookup"
	SpanGetSessions                  = "smartrouter.GetSessions"
	SpanFilterEndpointsByConsistency = "smartrouter.filterEndpointsByConsistency"
	SpanRelayInnerDirect             = "smartrouter.relayInnerDirect"
	SpanSendJSONRPCRelay             = "smartrouter.sendJSONRPCRelay"
	SpanSendRESTRelay                = "smartrouter.sendRESTRelay"
	SpanSendGRPCRelay                = "smartrouter.sendGRPCRelay"
)

Span names — each matches the function or operation it instruments.

View Source
const (
	// Body recording attributes (gated by --otel-trace-body, set from
	// rpcsmartrouter via tracing.RecordBody).
	AttrRelayRequestBody  = "relay.request_body"
	AttrRelayResponseBody = "relay.response_body"
)

Span attribute keys.

View Source
const SmartRouterTracerName = "smartrouter"

SmartRouterTracerName is the OTel instrumentation scope name used for all SmartRouter spans. Centralised here so call sites don't drift.

View Source
const TraceBodyFlag = "otel-trace-body"

TraceBodyFlag is the only Lava-specific tracing CLI flag. Everything else comes from the standard OTel SDK environment variables, which are auto-read by the OTel exporter packages and the autoexport contrib package.

Tracing is enabled when:

  • OTEL_SDK_DISABLED is not "true" (per OTel spec), AND
  • OTEL_TRACES_EXPORTER is not "none"

When no OTLP endpoint is explicitly configured, the SDK uses the spec defaults: http://localhost:4317 (gRPC) or http://localhost:4318 (HTTP). Operators who do NOT run a local collector should explicitly disable tracing via OTEL_SDK_DISABLED=true or OTEL_TRACES_EXPORTER=none, otherwise the exporter will log connection errors against the default endpoint.

Standard OTel env vars honoured by the SDK / autoexport / exporter packages:

General SDK:
  OTEL_SDK_DISABLED                       — disable the SDK entirely
  OTEL_SERVICE_NAME                       — service.name resource attribute
  OTEL_RESOURCE_ATTRIBUTES                — additional resource attributes
  OTEL_TRACES_SAMPLER                     — sampler strategy (default: parentbased_always_on)
  OTEL_TRACES_SAMPLER_ARG                 — sampler argument (e.g. ratio)

Exporter selection (autoexport):
  OTEL_TRACES_EXPORTER                    — otlp (default) | none | console
  OTEL_EXPORTER_OTLP_PROTOCOL             — grpc | http/protobuf (default per spec)

OTLP exporter (auto-read by otlptracegrpc / otlptracehttp packages):
  OTEL_EXPORTER_OTLP_ENDPOINT             — collector URL (general)
  OTEL_EXPORTER_OTLP_TRACES_ENDPOINT      — traces-specific endpoint override
  OTEL_EXPORTER_OTLP_INSECURE             — disable TLS
  OTEL_EXPORTER_OTLP_HEADERS              — auth headers (k=v,k=v)
  OTEL_EXPORTER_OTLP_COMPRESSION          — gzip | none
  OTEL_EXPORTER_OTLP_TIMEOUT              — export timeout (ms)
  OTEL_EXPORTER_OTLP_CERTIFICATE          — TLS server cert
  OTEL_EXPORTER_OTLP_CLIENT_KEY           — mTLS client key
  OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE   — mTLS client cert
  (each has a TRACES_-prefixed per-signal variant)

Variables

This section is empty.

Functions

func ExtractHTTP

func ExtractHTTP(ctx context.Context, metadata []pairingtypes.Metadata) context.Context

ExtractHTTP reads W3C trace context from a Metadata slice into ctx, returning a new context that carries the remote span as parent. Keys are lowercased because HTTP/1.1 headers may arrive in Title-Case while the W3C propagator expects lowercase keys.

func InjectGRPC

func InjectGRPC(ctx context.Context, headers map[string]string)

InjectGRPC sets W3C trace context headers (traceparent/tracestate) in a string map used for gRPC-style metadata.

func InjectHTTP

func InjectHTTP(ctx context.Context, headers []pairingtypes.Metadata) []pairingtypes.Metadata

InjectHTTP injects W3C trace context headers (traceparent/tracestate) into a Metadata slice. Existing entries with matching (case-insensitive) names are replaced in place; remaining propagator keys are appended. Replacing rather than blindly appending avoids producing two `traceparent` headers downstream when an inbound traceparent has been passed through by the chain spec — receivers cannot reliably pick the correct one in that case.

func IsTraceBodyEnabled

func IsTraceBodyEnabled() bool

IsTraceBodyEnabled returns true when --otel-trace-body is active. Instrumentation sites call this to decide whether to record request/response bodies.

func RecordBody

func RecordBody(span trace.Span, attrKey string, body []byte)

RecordBody records a body attribute on the span. Callers MUST gate the call with IsTraceBodyEnabled() — this function does not check the flag itself, so that the caller can also avoid the []byte conversion (and any other prep work) when --otel-trace-body is off. We pre-truncate to the SDK's configured OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT so a large body with a small cap doesn't pay a full string allocation before the SDK truncates.

func RecordCacheResult

func RecordCacheResult(ctx context.Context, span trace.Span, hit bool, latencyMs float64)

RecordCacheResult records a cache lookup outcome (hit/miss) and its latency on the cache lookup child span, AND bubbles `cache.hit` up to the inbound relay span (if one is on the context) so TraceQL filters on the top-level trace (`{name="smartrouter.SendRelay" && cache.hit=true}`) work as operators expect.

func RecordConsistencyStats

func RecordConsistencyStats(span trace.Span, total, passed, rejected int)

RecordConsistencyStats records consistency filter counts on the span.

func RecordError

func RecordError(span trace.Span, err error)

RecordError records the error on the span and sets its status to Error.

func RecordGRPCRequest

func RecordGRPCRequest(span trace.Span, methodPath, urlStr string)

RecordGRPCRequest sets `rpc.system`="grpc", `rpc.service`, `rpc.method`, and (best-effort) `net.peer.name`/`net.peer.port` on a client-kind gRPC span. methodPath is split into service+method by the last "/" if present (e.g. "cosmos.bank.v1beta1.Query/Balance" → service="cosmos.bank.v1beta1.Query", method="Balance"). Paths without a slash are recorded as method only.

func RecordGRPCResponse

func RecordGRPCResponse(span trace.Span, response *lavasession.DirectRPCResponse)

RecordGRPCResponse records the gRPC response status and payload size on a client gRPC span. Skipped when response is nil. We reuse the http.status_code attribute because the SmartRouter's DirectRPCResponse surfaces a unified status field across protocols.

func RecordHTTPRequest

func RecordHTTPRequest(span trace.Span, method, urlStr string)

RecordHTTPRequest sets `http.method`, `http.url`, and (best-effort) `net.peer.name`/`net.peer.port` on a client-kind HTTP span. Call once when the span is started, before the request is dispatched, so the attributes are present even if the request later errors out.

func RecordHTTPResponse

func RecordHTTPResponse(span trace.Span, response *lavasession.HTTPDirectRPCResponse)

RecordHTTPResponse records `http.status_code` and `http.response_content_length` on a client HTTP span. Skipped when response is nil (transport error before a response was received).

func RecordProviderAttributes

func RecordProviderAttributes(span trace.Span, guid uint64, providerAddress string)

RecordProviderAttributes records per-provider identification attributes (GUID and provider address) on a provider-scoped span.

func RecordRelayAttempt

func RecordRelayAttempt(span trace.Span, attempt int)

RecordRelayAttempt records the 1-indexed batch number this provider call belongs to. All parallel calls in the same batch (cross-validation) share the same value.

func RecordRelayAttributes

func RecordRelayAttributes(span trace.Span, guid uint64, chainID, apiInterface string)

RecordRelayAttributes records the standard relay identification attributes (GUID, chain ID, API interface) at the entry of a relay span.

func RecordRelayMethod

func RecordRelayMethod(span trace.Span, methodName string)

RecordRelayMethod records the parsed API method name on the span.

func RecordRetryCount

func RecordRetryCount(span trace.Span, retries int)

RecordRetryCount records the total number of retry batches dispatched for a relay. Negative values are clamped to 0 (e.g. cache hit, no batches dispatched).

func RecordSessionStats

func RecordSessionStats(span trace.Span, requested, acquired int)

RecordSessionStats records session manager requested/acquired counts.

func RelaySpanFromContext

func RelaySpanFromContext(ctx context.Context) trace.Span

RelaySpanFromContext returns the inbound relay span previously stored via WithRelaySpan. When none was set it falls back to the current span in context (which may itself be a non-recording noop span).

func StartClientSpan

func StartClientSpan(ctx context.Context, name string) (context.Context, trace.Span)

StartClientSpan starts a CLIENT-kind child span only when the context already carries a recording parent. When called from a code path that has no parent span (e.g. internal init/crafted relays from sendCraftedRelays → sendRelayWithRetries), it returns the existing non-recording span so call sites can unconditionally defer span.End() without producing orphan root spans.

func StartInternalSpan

func StartInternalSpan(ctx context.Context, name string) (context.Context, trace.Span)

StartInternalSpan starts an INTERNAL-kind child span only when the context already carries a recording parent. Same orphan-root protection as StartClientSpan.

func StartServerSpan

func StartServerSpan(ctx context.Context, name string) (context.Context, trace.Span)

StartServerSpan starts a SERVER-kind span. Use this for inbound request handling — e.g. the top-level relay span at the entry of SendRelay. There is no parent-recording guard here because a server span is by definition the start of a server-side trace; if no parent context is propagated the configured sampler decides whether to start a new root.

func WithRelaySpan

func WithRelaySpan(ctx context.Context, span trace.Span) context.Context

WithRelaySpan stores the inbound relay span on the context so deeply nested helpers (e.g. cache lookup) can decorate it directly without having to plumb the span through every function signature.

Types

type TraceConfig

type TraceConfig struct {
	// TraceBody enables recording of request/response bodies as span attributes.
	// Body size truncation is delegated to the SDK via SpanLimits, which
	// reads OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT (default: unlimited).
	TraceBody bool
}

TraceConfig holds Lava-specific tracing configuration. Standard OTel knobs are read from environment variables — see TraceBodyFlag doc.

type TraceManager

type TraceManager struct {
	// contains filtered or unexported fields
}

TraceManager owns the OTel SDK lifecycle.

func New

func New(ctx context.Context, cfg TraceConfig) (*TraceManager, error)

New initialises the OTel SDK based on standard environment variables. See TraceBodyFlag for the full env var contract.

func (*TraceManager) Shutdown

func (tm *TraceManager) Shutdown()

Shutdown flushes all pending spans. Blocks up to 5 seconds.

func (*TraceManager) Tracer

func (tm *TraceManager) Tracer(name string) trace.Tracer

Tracer returns a named tracer from the managed provider.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL