trace

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2026 License: MPL-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package trace provides a dependency-free tracing core for GOWDK Runtime and plain Go applications.

Index

Constants

View Source
const (
	AttrGOWDKSurface           = "gowdk.surface"
	AttrGOWDKLane              = "gowdk.lane"
	AttrGOWDKSourceFile        = "gowdk.source.file"
	AttrGOWDKSourceLine        = "gowdk.source.line"
	AttrGOWDKSourceCol         = "gowdk.source.column"
	AttrHTTPRoute              = "http.route"
	AttrHTTPRequestMethod      = "http.request.method"
	AttrHTTPResponseStatusCode = "http.response.status_code"
	AttrURLPath                = "url.path"
	AttrServerAddress          = "server.address"
)

Variables

This section is empty.

Functions

func ContextWithTraceContext

func ContextWithTraceContext(ctx context.Context, traceContext TraceContext) context.Context

ContextWithTraceContext returns a context carrying trace identity.

func ContextWithTracer

func ContextWithTracer(ctx context.Context, tracer *Tracer) context.Context

ContextWithTracer returns a context carrying tracer for child spans started by helper packages such as runtime/app and runtime/contracts.

func Extract

func Extract(ctx context.Context, carrier Carrier) context.Context

Extract reads a W3C traceparent header from carrier into ctx.

func Inject

func Inject(ctx context.Context, carrier Carrier)

Inject writes the active span or trace context from ctx into carrier.

func Traceparent

func Traceparent(traceContext TraceContext) string

Traceparent encodes traceContext as a W3C traceparent header.

Types

type Attribute

type Attribute struct {
	Key   string `json:"key"`
	Value any    `json:"value,omitempty"`
}

Attribute is an OpenTelemetry-compatible key/value attribute.

type Carrier

type Carrier interface {
	Get(string) string
	Set(string, string)
}

Carrier is the minimal interface implemented by http.Header and compatible request metadata maps.

type Collector

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

Collector combines an in-memory ring sink with a small HTTP JSON/SSE handler for local inspection.

func NewCollector

func NewCollector(limit int) *Collector

NewCollector creates a collector backed by a RingSink.

func (*Collector) Dropped

func (collector *Collector) Dropped() uint64

Dropped returns the ring overflow count.

func (*Collector) Handler

func (collector *Collector) Handler() http.Handler

Handler serves recent spans as JSON. Requests to /events or requests with an Accept header containing text/event-stream receive an SSE stream of existing and future spans. POST requests accept one Snapshot or a JSON array of Snapshots so generated browser runtimes can join frontend spans to backend traces without another collector dependency.

func (*Collector) RecordSpan

func (collector *Collector) RecordSpan(ctx context.Context, span Snapshot) error

RecordSpan implements Sink.

func (*Collector) Spans

func (collector *Collector) Spans() []Snapshot

Spans returns completed spans from oldest to newest.

func (*Collector) ViewerHandler

func (collector *Collector) ViewerHandler() http.Handler

ViewerHandler serves a self-contained local trace viewer plus JSON and SSE endpoints. It is intentionally unprotected; generated apps must mount it behind an access gate when enabling it outside dev.

type ConsoleSink

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

ConsoleSink writes one readable line per completed span.

func NewConsoleSink

func NewConsoleSink(writer io.Writer) *ConsoleSink

NewConsoleSink creates a console sink.

func (*ConsoleSink) RecordSpan

func (sink *ConsoleSink) RecordSpan(ctx context.Context, span Snapshot) error

RecordSpan implements Sink.

type CountedSampler

type CountedSampler struct {
	N uint64
	// contains filtered or unexported fields
}

CountedSampler is a deterministic test helper that samples every n-th span.

func (*CountedSampler) Sample

func (sampler *CountedSampler) Sample(SamplingContext) bool

Sample implements Sampler.

type Event

type Event struct {
	Time       time.Time   `json:"time"`
	Level      string      `json:"level,omitempty"`
	Message    string      `json:"message"`
	Attributes []Attribute `json:"attributes,omitempty"`
}

Event records a timestamped span event.

type Exporter

type Exporter interface {
	ExportSpans(context.Context, []OTLPSpan) error
}

Exporter receives completed spans in the dependency-free OTLP-like shape.

type JSONLSink

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

JSONLSink writes one JSON object per completed span.

func NewJSONLSink

func NewJSONLSink(writer io.Writer) *JSONLSink

NewJSONLSink creates a JSON Lines sink.

func (*JSONLSink) RecordSpan

func (sink *JSONLSink) RecordSpan(ctx context.Context, span Snapshot) error

RecordSpan implements Sink.

type Lane

type Lane string

Lane identifies the GOWDK execution lane represented by a span.

const (
	LaneRoute    Lane = "route"
	LaneGuard    Lane = "guard"
	LaneHandler  Lane = "handler"
	LaneSSR      Lane = "ssr"
	LaneAction   Lane = "action"
	LaneAPI      Lane = "api"
	LaneFragment Lane = "fragment"
	LaneContract Lane = "contract"
	LaneJob      Lane = "job"
	LaneIsland   Lane = "island"
	LaneNav      Lane = "nav"
	LaneUser     Lane = "user"
)

type OTLPSpan

type OTLPSpan struct {
	TraceID           TraceID     `json:"traceId"`
	SpanID            SpanID      `json:"spanId"`
	ParentSpanID      SpanID      `json:"parentSpanId,omitempty"`
	Name              string      `json:"name"`
	StartTimeUnixNano int64       `json:"startTimeUnixNano"`
	EndTimeUnixNano   int64       `json:"endTimeUnixNano"`
	Attributes        []Attribute `json:"attributes,omitempty"`
	Events            []Event     `json:"events,omitempty"`
	Status            Status      `json:"status,omitempty"`
}

OTLPSpan is intentionally shaped like the OTLP span model while remaining a dependency-free value type.

func OTLPSpanFromSnapshot

func OTLPSpanFromSnapshot(span Snapshot) OTLPSpan

OTLPSpanFromSnapshot converts a completed span to the OTLP-like model.

type RingSink

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

RingSink stores the most recent completed spans in memory. On overflow it drops the oldest span and increments Dropped.

func NewRingSink

func NewRingSink(limit int) *RingSink

NewRingSink creates a bounded in-memory sink.

func (*RingSink) Dropped

func (sink *RingSink) Dropped() uint64

Dropped returns the number of spans dropped because the ring was full.

func (*RingSink) RecordSpan

func (sink *RingSink) RecordSpan(ctx context.Context, span Snapshot) error

RecordSpan implements Sink. It never blocks on external I/O.

func (*RingSink) Spans

func (sink *RingSink) Spans() []Snapshot

Spans returns completed spans from oldest to newest.

type Sampler

type Sampler interface {
	Sample(SamplingContext) bool
}

Sampler decides whether a span should be recorded.

func AlwaysOff

func AlwaysOff() Sampler

AlwaysOff samples no spans.

func AlwaysOn

func AlwaysOn() Sampler

AlwaysOn samples every span.

func RatioSampler

func RatioSampler(ratio float64) Sampler

RatioSampler returns a deterministic trace-id based sampler. Ratios <= 0 are always off; ratios >= 1 are always on.

type SamplingContext

type SamplingContext struct {
	TraceID      TraceID
	ParentSpanID SpanID
	Name         string
	Surface      Surface
	Lane         Lane
	Attributes   []Attribute
}

SamplingContext is passed to samplers before a span is allocated.

type Sink

type Sink interface {
	RecordSpan(context.Context, Snapshot) error
}

Sink receives completed span snapshots.

func ExporterSink

func ExporterSink(exporter Exporter) Sink

ExporterSink adapts an Exporter into a Sink.

func MultiSink

func MultiSink(sinks ...Sink) Sink

MultiSink sends completed spans to each sink in order.

type Snapshot

type Snapshot struct {
	TraceID      TraceID     `json:"traceId"`
	SpanID       SpanID      `json:"spanId"`
	ParentSpanID SpanID      `json:"parentSpanId,omitempty"`
	Name         string      `json:"name"`
	Surface      Surface     `json:"surface,omitempty"`
	Lane         Lane        `json:"lane,omitempty"`
	Source       SourceRef   `json:"source,omitempty"`
	Attributes   []Attribute `json:"attributes,omitempty"`
	Events       []Event     `json:"events,omitempty"`
	Status       Status      `json:"status,omitempty"`
	StartTime    time.Time   `json:"startTime"`
	EndTime      time.Time   `json:"endTime"`
	DurationNS   int64       `json:"durationNs"`
}

Snapshot is the immutable JSON/export shape of a completed span.

type SourceRef

type SourceRef struct {
	File      string `json:"file,omitempty"`
	Line      int    `json:"line,omitempty"`
	Column    int    `json:"column,omitempty"`
	OwnerKind string `json:"ownerKind,omitempty"`
	OwnerID   string `json:"ownerId,omitempty"`
}

SourceRef points a span back to GOWDK source or generated runtime metadata.

type Span

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

Span records one sampled unit of work. Methods are nil-safe so callers can defer span.End() even when sampling is disabled.

func SpanFrom

func SpanFrom(ctx context.Context) *Span

SpanFrom returns the active sampled span from ctx.

func Start

func Start(ctx context.Context, name string, options ...StartOption) (context.Context, *Span)

Start starts a span using the default tracer unless WithTracer is supplied.

func (*Span) End

func (span *Span) End()

End completes the span and sends an immutable snapshot to the configured sink. Calling End more than once is safe.

func (*Span) EndTime

func (span *Span) EndTime(t time.Time)

EndTime completes the span at t. It is useful for deterministic tests.

func (*Span) Event

func (span *Span) Event(level string, message string, attrs map[string]any)

Event records a timestamped event on the span.

func (*Span) Set

func (span *Span) Set(key string, value any)

Set records or replaces one span attribute.

func (*Span) SetStatus

func (span *Span) SetStatus(code StatusCode, message string)

SetStatus records the final span status.

func (*Span) Snapshot

func (span *Span) Snapshot() Snapshot

Snapshot returns an immutable copy of the span's current state.

func (*Span) TraceContext

func (span *Span) TraceContext() TraceContext

TraceContext returns the span's W3C trace identity.

type SpanID

type SpanID string

SpanID is a W3C Trace Context parent-id/span-id: 8 bytes encoded as 16 lowercase hexadecimal characters.

func NewSpanID

func NewSpanID() SpanID

NewSpanID creates a non-zero W3C span ID.

func (SpanID) Valid

func (id SpanID) Valid() bool

Valid reports whether id is a valid non-zero W3C span ID.

type StartOption

type StartOption func(*startConfig)

StartOption configures one span.

func WithAttributes

func WithAttributes(attrs map[string]any) StartOption

WithAttributes records initial span attributes.

func WithLane

func WithLane(lane Lane) StartOption

WithLane records a span lane.

func WithSource

func WithSource(source SourceRef) StartOption

WithSource records a source reference.

func WithStartTime

func WithStartTime(start time.Time) StartOption

WithStartTime sets a deterministic start time.

func WithSurface

func WithSurface(surface Surface) StartOption

WithSurface records a span surface.

func WithTracer

func WithTracer(tracer *Tracer) StartOption

WithTracer starts a span with tracer instead of the default tracer.

type Status

type Status struct {
	Code    StatusCode `json:"code,omitempty"`
	Message string     `json:"message,omitempty"`
}

Status records the final span status.

type StatusCode

type StatusCode string

StatusCode follows the OpenTelemetry span status shape without importing the OpenTelemetry SDK.

const (
	StatusUnset StatusCode = "unset"
	StatusOK    StatusCode = "ok"
	StatusError StatusCode = "error"
)

type Surface

type Surface string

Surface identifies where a span was produced.

const (
	SurfaceBackend  Surface = "backend"
	SurfaceFrontend Surface = "frontend"
	SurfaceWorker   Surface = "worker"
)

type TraceContext

type TraceContext struct {
	TraceID TraceID
	SpanID  SpanID
	Sampled bool
	Remote  bool
}

TraceContext is the trace identity stored in context.Context and encoded in W3C traceparent headers.

func ParseTraceparent

func ParseTraceparent(value string) (TraceContext, error)

ParseTraceparent parses a W3C traceparent header.

func TraceContextFromContext

func TraceContextFromContext(ctx context.Context) (TraceContext, bool)

TraceContextFromContext returns trace identity from ctx when present.

type TraceID

type TraceID string

TraceID is a W3C Trace Context trace-id: 16 bytes encoded as 32 lowercase hexadecimal characters.

func NewTraceID

func NewTraceID() TraceID

NewTraceID creates a non-zero W3C trace ID.

func (TraceID) Valid

func (id TraceID) Valid() bool

Valid reports whether id is a valid non-zero W3C trace ID.

type Tracer

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

Tracer owns sampling and completed-span delivery.

func NewTracer

func NewTracer(options ...TracerOption) *Tracer

NewTracer creates a Tracer.

func TracerFromContext

func TracerFromContext(ctx context.Context) (*Tracer, bool)

TracerFromContext returns the tracer stored in ctx, or the tracer that owns the active sampled span.

func (*Tracer) Start

func (tracer *Tracer) Start(ctx context.Context, name string, options ...StartOption) (context.Context, *Span)

Start starts a span. If sampling rejects the span, the returned context is unchanged and the returned span is nil.

type TracerOption

type TracerOption func(*Tracer)

TracerOption configures a Tracer.

func WithSampler

func WithSampler(sampler Sampler) TracerOption

WithSampler sets the sampler. Nil means AlwaysOn.

func WithSink

func WithSink(sink Sink) TracerOption

WithSink sets the completed-span sink.

Jump to

Keyboard shortcuts

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