Documentation
¶
Overview ¶
Package flowhawk is the OpenTelemetry Go SDK plus business-flow tagging and remote-controlled collection; the Go twin of @flowhawk/sdk-node and flowhawk-sdk (Python). Usage, first thing in main:
shutdown, err := flowhawk.Init(flowhawk.Options{Service: "orders"})
if err != nil { log.Fatal(err) }
defer shutdown(context.Background())
http.ListenAndServe(":8080", flowhawk.Middleware(mux))
Naming the customer and recording a handled error on the request that is running.
Index ¶
- Constants
- Variables
- func Count(ctx context.Context, name string, value float64, labels Labels, ...)
- func GRPCClient(opts ...otelgrpc.Option) grpc.DialOption
- func GRPCServer(opts ...otelgrpc.Option) grpc.ServerOption
- func Gauge(name string, read func() float64, labels Labels, opts ...MetricOption) error
- func GaugePoints(name string, read func() []GaugePoint, labels Labels, opts ...MetricOption) error
- func Handler(next slog.Handler) slog.Handler
- func Histogram(ctx context.Context, name string, value float64, labels Labels, ...)
- func Init(o Options) (func(context.Context) error, error)
- func Logger() *slog.Logger
- func Middleware(h http.Handler) http.Handler
- func OpenDB(driverName, dsn string, opts ...otelsql.Option) (*sql.DB, error)
- func ParseSentryTrace(header string) (trace.TraceID, trace.SpanID, bool)
- func RecordError(ctx context.Context, err error) bool
- func SQLComment(ctx context.Context) string
- func SetCodeSkip(paths []string)
- func SetCustomer(ctx context.Context, id string) bool
- func SetRoute(ctx context.Context, route string)
- func SetSQLComments(on bool, service string)
- func Shutdown(ctx context.Context) error
- func TagSQL(ctx context.Context, sql string) string
- func TraceHash(id trace.TraceID) float64
- func Transport(rt http.RoundTripper) http.RoundTripper
- func UpDown(ctx context.Context, name string, delta float64, labels Labels, ...)
- func WithStep(ctx context.Context, flow, step string, fn func(ctx context.Context) error) error
- func WrapConnector(c driver.Connector, system string, opts ...otelsql.Option) *sql.DB
- type Boost
- type BusinessBaggage
- type BusinessMap
- type ConfigError
- type Decision
- type Flow
- type FlowStep
- type FlowTagger
- type GaugePoint
- type LLMCall
- type LLMRequest
- type LLMResult
- type Labels
- type MetricOption
- type MetricsConfig
- type Options
- type Policy
- type RemoteConfig
- type SentryTrace
- type ServiceMetrics
- type SpanFacts
- type Step
- type StepMatch
- type TailSampler
Constants ¶
const ( AttrFlow = "business.flow" AttrStep = "business.step" AttrEntry = "business.entry" )
const AttrCustomer = "user.id"
AttrCustomer is the attribute SetCustomer writes.
const AttrFlowStart = "business.flow.start"
AttrFlowStart is the baggage key for the time a flow started (epoch milliseconds), set at its first entry.
const SDKID = "flowhawk-go/0.2.0"
SDKID identifies this SDK to the control plane.
Variables ¶
var DefaultRedactAttributes = []string{"user.email", "card.number", "http.request.header.authorization", "http.request.header.cookie", "http.response.header.set-cookie", "http.request.header.x-api-key"}
DefaultRedactAttributes are the attributes redacted by default (DEFAULT_REDACT_ATTRIBUTES in packages/schema/src/index.ts). They apply when no policy is loaded (before the first config, or after the control plane has been unreachable), so redaction fails closed.
var StepBuckets = []float64{2, 5, 10, 15, 25, 40, 60, 80, 100, 150, 200, 300, 400, 500, 750, 1000, 1500, 2000, 3000, 4000, 5000, 7500, 10000, 20000, 30000, 60000, 120000, 300000, 600000, 1800000, 3600000, 7200000, 14400000, 43200000, 86400000}
StepBuckets are fine buckets so the platform's p95 from business.step.duration is close to the true one (same as the Node and Python SDKs).
Functions ¶
func Count ¶
Count adds to a counter (orders placed, emails sent). Inside a request it carries the request's flow and step.
func GRPCClient ¶ added in v0.2.0
func GRPCClient(opts ...otelgrpc.Option) grpc.DialOption
GRPCClient traces outgoing calls and carries the trace and flow.
func GRPCServer ¶ added in v0.2.0
func GRPCServer(opts ...otelgrpc.Option) grpc.ServerOption
GRPCServer traces incoming calls.
func Gauge ¶
func Gauge(name string, read func() float64, labels Labels, opts ...MetricOption) error
Gauge reports a value read on each export (queue depth, pool usage). It is read outside any request, so it reaches flows through the service unless the labels name a flow.
func GaugePoints ¶
func GaugePoints(name string, read func() []GaugePoint, labels Labels, opts ...MetricOption) error
GaugePoints is Gauge for several labelled values at once (depth per queue).
func Handler ¶
Handler returns a handler that passes every record to next unchanged and also sends it to Flowhawk, filtered by the flow's policy. next may be nil.
func Histogram ¶
func Histogram(ctx context.Context, name string, value float64, labels Labels, opts ...MetricOption)
Histogram records a distribution (render time, basket size).
func Init ¶
Init starts tracing, metrics, logs and remote control, and sets the global OpenTelemetry providers and propagator. Call it once, first thing in main; later calls do nothing. The returned function flushes and stops everything (Shutdown).
func Logger ¶
Logger is a slog.Logger that sends to Flowhawk (and to stderr when FLOWHAWK_LOG_CONSOLE=1). Pass the request's context (log.InfoContext(ctx, ...)) so records carry the trace and the flow.
func Middleware ¶
Middleware traces incoming HTTP requests (otelhttp), so they can be matched to business steps. Once the router has picked a handler, the span is named after the route ("GET /orders/{id}") and carries http.route: Go's ServeMux patterns are read automatically, other routers call SetRoute. A panic is recorded on the span as an exception with its stack, the span is marked as an error, and the panic carries on to the server as before.
func OpenDB ¶ added in v0.2.0
OpenDB opens a traced database/sql pool. Extra otelsql options are applied after the SDK's.
func ParseSentryTrace ¶
ParseSentryTrace returns the trace and span id of a sentry-trace header, ok false when it isn't one (pinned by packages/schema/sentry-trace-vectors.json in every SDK).
func RecordError ¶ added in v0.2.0
RecordError records an error your code handled (so nothing returned it to the server) on the running request: it becomes an issue with its stack trace, and the request counts as failed. It reports false when no request is running or err is nil.
func SQLComment ¶
SQLComment is the comment for ctx, e.g. /*flow='checkout',service='api',step='pay'*/, or "" outside a flow and trace.
func SetCodeSkip ¶
func SetCodeSkip(paths []string)
SetCodeSkip sets the path fragments of the app's own query helpers, skipped when picking a query's code location (FLOWHAWK_CODE_SKIP).
func SetCustomer ¶ added in v0.2.0
SetCustomer names the customer the running request is for (a user, an account, a tenant: whatever your app calls one), as user.id on the request's span. Their page then lists this request, and an issue counts them among the people it hit. Send an id, not an email address or a name. It reports false when no request is running or the id is empty.
func SetRoute ¶ added in v0.2.0
SetRoute names the request's server span after its route template, for routers other than ServeMux:
chi: flowhawk.SetRoute(r.Context(), chi.RouteContext(r.Context()).RoutePattern()) (in a middleware, after next) gin: flowhawk.SetRoute(c.Request.Context(), c.FullPath()) echo: flowhawk.SetRoute(c.Request().Context(), c.Path())
func SetSQLComments ¶
SetSQLComments turns the tags on or off and sets the service name they carry (Init does this).
func TagSQL ¶
TagSQL appends the comment tags to a query, before a trailing semicolon. A query that already has tags, or tags turned off (FLOWHAWK_SQL_COMMENTS=off), leaves the query as it is.
func TraceHash ¶
TraceHash is the deterministic position of a trace id in [0, 1): every service decides the same for a trace.
func Transport ¶
func Transport(rt http.RoundTripper) http.RoundTripper
Transport traces outgoing HTTP requests and carries the flow to the next service; nil wraps http.DefaultTransport.
func WithStep ¶
WithStep runs a background job (queue consumer, cron) as a business step entry: a new root span with business.* set. An error returned by fn marks the span as an error and is returned; a panic is recorded on the span and carries on.
func WrapConnector ¶ added in v0.2.0
WrapConnector traces a database/sql connector: sql.OpenDB(flowhawk.WrapConnector(c, "postgresql")). system is the db.system.name value (postgresql, mysql, sqlite, microsoft.sql_server, ...).
Types ¶
type BusinessBaggage ¶
type BusinessBaggage struct {
// contains filtered or unexported fields
}
BusinessBaggage is a W3C baggage propagator that also writes business.flow/business.step for the current span, so the next service inherits the flow. Use it instead of (not next to) propagation.Baggage.
func (BusinessBaggage) Extract ¶
func (p BusinessBaggage) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context
func (BusinessBaggage) Fields ¶
func (p BusinessBaggage) Fields() []string
func (BusinessBaggage) Inject ¶
func (p BusinessBaggage) Inject(ctx context.Context, carrier propagation.TextMapCarrier)
type BusinessMap ¶
type BusinessMap struct {
Flows []Flow `json:"flows"`
}
BusinessMap is the customer's flows and the rules that match spans to their steps.
type ConfigError ¶
type ConfigError struct {
// contains filtered or unexported fields
}
ConfigError is a remote config that failed validation.
func (*ConfigError) Error ¶
func (e *ConfigError) Error() string
type Decision ¶
type Decision struct {
Keep bool
Reason string // "error" | "slow" | "sampled" | "ai"
SampleRate int
}
Decision is the keep/drop decision for a trace (or one span of it).
type FlowStep ¶
type FlowStep struct{ Flow, Step string }
FlowStep is the business flow and step a span belongs to.
type FlowTagger ¶
type FlowTagger struct {
// contains filtered or unexported fields
}
FlowTagger tags spans with their business flow and step and records the step metrics of entry spans. Register it before the TailSampler so the tail decision sees business.flow.
func (*FlowTagger) ForceFlush ¶
func (t *FlowTagger) ForceFlush(context.Context) error
func (*FlowTagger) OnEnd ¶
func (t *FlowTagger) OnEnd(s sdktrace.ReadOnlySpan)
func (*FlowTagger) OnStart ¶
func (t *FlowTagger) OnStart(parent context.Context, s sdktrace.ReadWriteSpan)
type GaugePoint ¶
GaugePoint is one value a gauge reports, with its own labels.
type LLMCall ¶
type LLMCall struct {
// contains filtered or unexported fields
}
LLMCall is an open gen_ai span.
func TraceLLM ¶
TraceLLM starts a gen_ai span named "<operation> <model>" and returns a context that carries it. End the call with End.
type LLMRequest ¶
type LLMRequest struct {
System string // gen_ai.system, e.g. "anthropic"
Model string
Operation string // default "chat"
Input string // recorded only with capturePrompts
MaxTokens int
Temperature *float64
}
LLMRequest describes a model call.
type LLMResult ¶
type LLMResult struct {
Output string // recorded only with capturePrompts
ResponseModel string
InputTokens int
OutputTokens int
FinishReason string
}
LLMResult is what a model call returned.
type MetricOption ¶
type MetricOption func(*metricOpts)
MetricOption sets a metric's unit or description (used when the instrument is first created).
func Description ¶
func Description(d string) MetricOption
func Unit ¶
func Unit(u string) MetricOption
type MetricsConfig ¶
type MetricsConfig struct {
Runtime string `json:"runtime"`
Services map[string]ServiceMetrics `json:"services"`
// Keep maps a metric name to the labels its points keep (the catalog's labels.keep).
Keep map[string][]string `json:"keep"`
// Drop are metrics turned off in the catalog.
Drop []string `json:"drop"`
}
MetricsConfig is the remote config's metrics block: runtime level, per-service overrides, label allowlists.
type Options ¶
type Options struct {
Service string
Version string // default FLOWHAWK_SERVICE_VERSION or 0.0.0
Environment string // default FLOWHAWK_ENVIRONMENT or development
// Endpoint is the OTLP HTTP base URL; default OTEL_EXPORTER_OTLP_ENDPOINT or http://localhost:4318.
Endpoint string
// ControlURL is the control plane base URL; default FLOWHAWK_CONTROL_URL or http://localhost:4000.
ControlURL string
// APIKey is the workspace ingest key, sent as the bearer token on OTLP exports and /v1/opamp; default
// FLOWHAWK_API_KEY. Not needed in local dev mode.
APIKey string
// CodeSkip are path fragments of your own query helpers, skipped when recording where a query is called;
// default FLOWHAWK_CODE_SKIP (comma separated).
CodeSkip []string
// NoSQLComments turns off the SQL comment tags TagSQL adds (also FLOWHAWK_SQL_COMMENTS=off).
NoSQLComments bool
// NoConsoleLogs stops sending what the standard log package writes (also FLOWHAWK_CONSOLE_LOGS=off).
NoConsoleLogs bool
// NoCrashReports stops sending a panic nothing recovered, in any goroutine, as a FATAL log (also
// FLOWHAWK_CRASH_REPORTS=off). See crash.go.
NoCrashReports bool
}
Options configure Init. Every field has an environment default.
type Policy ¶
type Policy struct {
Flow string `json:"flow"`
Traces struct {
Enabled bool `json:"enabled"`
SampleRate float64 `json:"sampleRate"`
KeepErrors bool `json:"keepErrors"`
KeepSlowerThanMs *float64 `json:"keepSlowerThanMs,omitempty"`
} `json:"traces"`
Logs struct {
Enabled bool `json:"enabled"`
Level string `json:"level"`
} `json:"logs"`
Metrics struct {
Enabled bool `json:"enabled"`
Custom bool `json:"custom"`
} `json:"metrics"`
Attributes struct {
Drop []string `json:"drop"`
Redact []string `json:"redact"`
} `json:"attributes"`
LLM struct {
CapturePrompts bool `json:"capturePrompts"`
} `json:"llm"`
}
Policy is a flow's collection policy (CollectionPolicy in packages/schema/src/config.ts).
type RemoteConfig ¶
type RemoteConfig struct {
Map BusinessMap `json:"map"`
Policies map[string]*Policy `json:"policies"`
DefaultPolicy *Policy `json:"defaultPolicy"`
Boosts map[string]Boost `json:"boosts"`
Metrics MetricsConfig `json:"metrics"`
}
RemoteConfig is the config applied in this process.
func CurrentConfig ¶
func CurrentConfig() (hash string, config *RemoteConfig)
CurrentConfig is the remote config currently applied and its hash, or nil before the first one arrives.
func ParseRemoteConfig ¶
func ParseRemoteConfig(raw []byte) (*RemoteConfig, error)
ParseRemoteConfig validates a received config and fills the schema's defaults.
func (*RemoteConfig) PolicyFor ¶
func (c *RemoteConfig) PolicyFor(flow string) *Policy
PolicyFor is the flow's policy, or the default policy for unmatched telemetry.
func (*RemoteConfig) RateFor ¶
func (c *RemoteConfig) RateFor(flow string, now time.Time) float64
RateFor is the flow's sample rate or an active boost, whichever is higher.
func (*RemoteConfig) RuntimeLevel ¶
func (c *RemoteConfig) RuntimeLevel(service string) string
RuntimeLevel is the runtime metrics level for a service: off, standard or full. Standard until a config arrives.
type SentryTrace ¶
type SentryTrace struct{}
SentryTrace extracts sentry-trace as the remote parent. List it before propagation.TraceContext so a traceparent sent too wins. The parent always counts as sampled: Flowhawk's sampling decides what is kept, not the app's tracesSampleRate. It injects nothing (outgoing calls carry traceparent).
func (SentryTrace) Extract ¶
func (SentryTrace) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context
func (SentryTrace) Fields ¶
func (SentryTrace) Fields() []string
func (SentryTrace) Inject ¶
func (SentryTrace) Inject(context.Context, propagation.TextMapCarrier)
type ServiceMetrics ¶
type ServiceMetrics struct {
Runtime string `json:"runtime,omitempty"`
}
type SpanFacts ¶
type SpanFacts struct {
Service string
Method string
Path string // without the query string
SpanName string
Queue string
// Attributes are the span's start-time attributes as strings, for Where matches.
Attributes map[string]string
}
SpanFacts are what a step match looks at.
type StepMatch ¶
type StepMatch struct {
Service string `json:"service,omitempty"`
Route string `json:"route,omitempty"`
SpanName string `json:"spanName,omitempty"`
Queue string `json:"queue,omitempty"`
// Where: span attributes that must all match; `*` is any characters.
Where map[string]string `json:"where,omitempty"`
}
StepMatch is one rule that ties a span to a step.
type TailSampler ¶
type TailSampler struct {
// contains filtered or unexported fields
}
TailSampler buffers spans per trace and forwards the kept ones, finalized, to the next processor.
func (*TailSampler) ForceFlush ¶
func (t *TailSampler) ForceFlush(ctx context.Context) error
func (*TailSampler) OnEnd ¶
func (t *TailSampler) OnEnd(s sdktrace.ReadOnlySpan)
func (*TailSampler) OnStart ¶
func (t *TailSampler) OnStart(ctx context.Context, s sdktrace.ReadWriteSpan)