telemetry

package
v0.168.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 27 Imported by: 0 modules, 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

Overview

Package telemetry is muster's tracing: OpenTelemetry spans for the server (muster-server) and the host agent (muster-mirror), exported over OTLP/HTTP, and the W3C trace context that joins them into one trace across the browser, the server and the mirror tunnel.

🔴 OFF UNLESS AN OTLP ENDPOINT IS SET, AND OFF MEANS NOTHING CHANGES. With neither OTEL_EXPORTER_OTLP_ENDPOINT nor OTEL_EXPORTER_OTLP_TRACES_ENDPOINT in the environment (or with OTEL_SDK_DISABLED=true), Setup installs nothing: the global tracer provider stays OpenTelemetry's no-op, Middleware returns its handler unwrapped, the database gets no query tracer, no frame on the tunnel carries a trace context and no response carries a Server-Timing header. The browser suite and a local run see exactly the bytes they saw before this package existed (TestOffIsANoOp pins that).

🔴 A SPAN CARRIES IDS, SIZES, COUNTS, DURATIONS AND STATUS — NEVER CONTENT. muster's spans describe operators' private sessions, and the repository is public: no attribute, event or status may carry a message, a transcript line, pane contents, a window title or label, a prompt, a token, a cookie or an error's prose (an error string can quote a path or a value). Errors are recorded as a closed reason code (Reason) and nothing else. What otelhttp adds on its own is cut at export (scrubExporter): no caller address, port or user agent, and url.path is the route PATTERN, never the raw path. The mirrored view's and terminal's opens and a hub send are guarded by a test that fills every fixture with a sentinel string and asserts it reaches no exported span (internal/api's TestNoExportedSpanCarriesPrivateContent); an agent's page is not in that test.

Index

Constants

View Source
const (
	EnvEndpoint       = "OTEL_EXPORTER_OTLP_ENDPOINT"
	EnvTracesEndpoint = "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"
	EnvSDKDisabled    = "OTEL_SDK_DISABLED"
)

The variables Setup reads by name. Everything else the OTLP exporter and the SDK read for themselves (OTEL_SERVICE_NAME, OTEL_RESOURCE_ATTRIBUTES, OTEL_EXPORTER_OTLP_HEADERS, …): see docs/telemetry.md.

View Source
const (
	ReasonOK         = "ok"
	ReasonClientLeft = "client_left"
	// ReasonShutdown: muster itself ended the stream because it is shutting
	// down (a deploy): ErrShuttingDown is the cause. An error status, unlike
	// client_left — a deploy that cuts every view is a disconnect the person
	// sees, not one they chose.
	ReasonShutdown = "shutdown"
	ReasonTimeout  = "timeout"
	ReasonError    = "error"
)

The reasons every span and metric in muster speaks of: a CLOSED vocabulary, so a reason can be a metric label (cardinality) and a span status without ever carrying an error's prose.

View Source
const DefaultSampleRatio = 0.05

DefaultSampleRatio is EnvSampleRatio's default: one trace in twenty for everything that is not an open. The sidebar's re-fetches, the event stream and the badge poll are most of a busy page's requests, and at 1.0 they would bury the opens this exists for.

View Source
const EnvSampleRatio = "MUSTER_TRACE_SAMPLE_RATIO"

EnvSampleRatio is the share of traces kept for requests that are not part of opening a session (MUSTER_TRACE_SAMPLE_RATIO, 0–1).

View Source
const TraceparentQuery = "tp"

TraceparentQuery is the query parameter a browser socket carries its trace context in. A browser cannot set a header on a WebSocket's upgrade request, so the page puts its open span's traceparent here, and Middleware moves it into the header otelhttp reads — the socket's server span is then a child of the browser's open, in the same trace.

View Source
const TracerName = "github.com/ZacxDev/muster"

TracerName is the instrumentation scope of every span muster starts.

Variables

View Source
var ErrShuttingDown = errors.New("muster is shutting down")

ErrShuttingDown is the cause muster cancels a live stream with when it shuts down. A stream whose context ends with it is reported as ReasonShutdown — never as the browser leaving.

Functions

func Annotate

func Annotate(r *http.Request, attrs ...attribute.KeyValue)

Annotate adds attrs to the request's server span (a no-op while off, or for an untraced path).

func Configured

func Configured(getenv func(string) string) bool

Configured reports whether getenv names an OTLP endpoint and does not disable the SDK: Setup's whole on/off decision.

func Detached

func Detached(ctx context.Context) context.Context

Detached is ctx with no span: work a long-lived socket does after its open (each turn, each batch) starts no span in the open's trace. Its values and cancellation are ctx's.

func Enabled

func Enabled() bool

Enabled reports whether tracing is on in this process. Everything that would cost something when it is off (a wrapped handler, a query tracer, a header) asks this first.

func End

func End(span trace.Span, reason string)

End ends span with reason: "" or ReasonOK is OK, anything else an error status whose description is the reason CODE — never an error's text.

⚠ Off, Start handed back the CALLER'S span (a no-op one), so End must not end it: it does nothing then.

func EndedBy

func EndedBy(ctx context.Context) string

EndedBy is the reason a stream whose context ended (and whose own error is nil or the context's) ended: ReasonShutdown when ctx was cancelled with ErrShuttingDown, else ReasonClientLeft.

func Middleware

func Middleware(next http.Handler) http.Handler

Middleware wraps next in a server span per request (otelhttp), named for the ROUTE PATTERN the mux matched ("GET /mirror/view"), never the raw path, which carries ids. Off (Enabled false), it returns next itself.

The response carries `Server-Timing: traceparent;desc="00-…"`: the browser reads it off the navigation entry (performance.getEntriesByType), so the page's own spans join the trace of the request that served it.

🔴 A WEBSOCKET'S SPAN IS ITS OPEN, NOT ITS LIFE. otelhttp's span lasts as long as the handler, which for a socket is minutes to hours, and everything done under it would grow one trace for as long. A socket upgrade instead gets a server span of muster's own that the handler ends when the open is over (OpenDone: a rendered view's first batch, a terminal's first output, a chat socket's accept) — or when it returns, if it never got there. Work after that runs Detached; the socket's end is a span of its own, a ROOT linked to the open (StreamClosed), so a deploy's disconnects can be found without a trace that never ends.

⚠ next MUST BE (OR END IN) THE ServeMux, CALLED WITH THE REQUEST IT IS HANDED: the mux writes the matched pattern onto that request (r.Pattern), which is read after it returns. accessLog relies on the same thing.

func NewProvider

func NewProvider(exp sdktrace.SpanExporter, ratio float64, sync bool, opts ...sdktrace.TracerProviderOption) *sdktrace.TracerProvider

NewProvider is the tracer provider Setup builds around exp: muster's sampler at ratio, and every span scrubbed (scrubExporter) before exp sees it, exported synchronously when sync (a test's) or batched. Tests build theirs with it, so what they read is what a deployment exports.

func NormalizeSQL

func NormalizeSQL(sql string) string

NormalizeSQL is sql as a span records it: literals replaced with `?`, whitespace collapsed, cut to at most maxQueryText bytes on a rune boundary (a cut through a multi-byte character would export invalid UTF-8).

func OpenDone

func OpenDone(r *http.Request, reason string)

OpenDone ends r's socket span — the socket's open is over — with reason ("" or ReasonOK for a good one). A no-op for a request that is not a traced socket, and after the first call.

func OpenRoute

func OpenRoute(path string) bool

OpenRoute reports whether path is one of the routes that open a session: /mirror/view, /mirror/terminal, /agents/{name}, and their sockets (/mirror/view/ws, /mirror/terminal/ws, /agents/{name}/ws, /agents/{name}/terminal and /agents/{name}/terminal/ws).

func QueryTracer

func QueryTracer() pgx.QueryTracer

QueryTracer is the pgx tracer that gives every query, and every wait for a pooled connection, a span — nil while tracing is off, so the pool is built exactly as before (internal/db.Connect).

🔴 A QUERY IS TRACED ONLY INSIDE A TRACE. A query whose context carries no span (a background loop's sweep, the boot ping) starts none: a root span per query would bury the opens this exists for under the reconcilers' noise.

🔴 THE STATEMENT IS NORMALISED BEFORE IT IS RECORDED: every quoted string and every number is replaced with `?`. muster's queries take their values as parameters, which pgx never shows here — but a statement that inlined one would otherwise put it into a span.

func Sampler

func Sampler(ratio float64) sdktrace.Sampler

Sampler is muster's sampler. In order:

  1. a request that OPENS a session — the GET of a mirrored view, a mirrored terminal or an agent's page, and each of their sockets (OpenRoute) — is ALWAYS sampled, whatever its parent says (a socket's ?tp= parent is still its parent: sampling never changes the trace a span is in);
  2. any OTHER server span whose parent is REMOTE — a page's fetch, XHR or poll carrying the browser's traceparent — is kept at ratio, NOT because the browser sampled it: Faro samples every page at 1, so following it would trace every ask poll, list refresh and badge poll in full;
  3. anything else with a parent follows it (parent-based): an in-process child of a sampled span is sampled, so a hub request, a query or a host span (whose remote parent is muster's own span, never a server span of the host's) is kept exactly when its open is;
  4. a root with a sampled LINK follows it: a socket's close (StreamClosed) is kept exactly when its open was;
  5. any other root is kept at ratio (trace-id based, so the decision is the same on every process that sees the trace).

The route is read off the server span's START attributes (otelhttp and serveSocket set the method and url.path there), since the span's name is only the method until the mux has matched.

func SetReason

func SetReason(span trace.Span, reason string)

SetReason records reason on span (End's status rule) without ending it.

func Setup

func Setup(ctx context.Context, getenv func(string) string, o Options) (func(context.Context) error, error)

Setup turns tracing on when getenv names an OTLP endpoint (Configured), and returns the flush to run at exit. Off, it installs nothing and returns a shutdown that does nothing.

The exporter is OTLP over HTTP/protobuf; it reads the standard OTEL_EXPORTER_OTLP_* endpoint and headers variables itself. Its client refuses redirects (exporterClient), which reads the timeout variables and refuses the certificate ones. The sampler is muster's own (Sampler): every open always, a sampled parent's children always, any other root at MUSTER_TRACE_SAMPLE_RATIO. It replaces OTEL_TRACES_SAMPLER, which is not read. A ratio that is not a number in [0, 1] keeps tracing off and says why, rather than guessing.

func SpanTraceparent

func SpanTraceparent(sc trace.SpanContext) string

SpanTraceparent is sc as a W3C traceparent value, "" for an invalid one.

func Start

func Start(ctx context.Context, name string, attrs ...attribute.KeyValue) (context.Context, trace.Span)

Start starts a span named name under ctx's span. Off, it returns ctx and a no-op span without asking the provider at all.

func StartAt

func StartAt(ctx context.Context, name string, at time.Time, attrs ...attribute.KeyValue) (context.Context, trace.Span)

StartAt is Start with an explicit start time (a phase measured before its span could be opened).

func StreamClosed

func StreamClosed(r *http.Request, reason string, lived time.Duration)

StreamClosed records a socket's END as a span of its own: a root, LINKED to the socket's open span, carrying the reason (an error status for anything but ok, client_left and ended) and how long the socket lived. It is kept exactly when its open was (Sampler follows a sampled link of a root).

func TraceID

func TraceID(ctx context.Context) string

TraceID is ctx's trace id as hex, "" for none: what a log line carries so a trace can be found from `kubectl logs` and the other way round.

func TracedPath

func TracedPath(path string) bool

TracedPath reports whether a request for path gets a server span.

func Traceparent

func Traceparent(ctx context.Context) string

Traceparent is ctx's span context as a W3C traceparent value, "" when ctx has no valid span (always, while tracing is off).

func Tracer

func Tracer() trace.Tracer

Tracer is muster's tracer from the current provider: a no-op one while tracing is off.

func Use

func Use(tp trace.TracerProvider) (restore func())

Use installs tp for a TEST and returns the function that puts back what was there (tests in this module run a package's tests one at a time unless they say otherwise, and none that traces says otherwise).

func ValidTraceparent

func ValidTraceparent(tp string) bool

ValidTraceparent reports whether tp is a well-formed W3C traceparent naming a valid trace and span.

func WithTraceparent

func WithTraceparent(ctx context.Context, tp string) context.Context

WithTraceparent is ctx with tp (a W3C traceparent) as its REMOTE parent; ctx unchanged when tp is empty or malformed, or tracing is off.

Types

type Options

type Options struct {
	// Service is the default service.name; OTEL_SERVICE_NAME and
	// OTEL_RESOURCE_ATTRIBUTES override it.
	Service string
	// Version is service.version.
	Version string
	// Attributes are added to the resource (muster-mirror adds its host).
	Attributes []attribute.KeyValue
	Logger     *log.Logger
}

Options names the process for its resource.

Jump to

Keyboard shortcuts

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