flowhawk

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 54 Imported by: ? 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.

README

Flowhawk Go SDK

The OpenTelemetry Go SDK plus business-flow tagging, policy-driven tail sampling, redaction, LLM spans and remote control. It behaves like @flowhawk/sdk-node and flowhawk-sdk (Python). Go 1.26 or later.

go get github.com/flowhawk-dev/flowhawk-go

Docs: flowhawk.dev/docs/sending-data.

Where it sends

On the hosted service, set these where the service runs. The key is a Services key from Settings > API keys.

FLOWHAWK_API_KEY=<ingest key>
FLOWHAWK_CONTROL_URL=https://api.flowhawk.dev
OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.flowhawk.dev
FLOWHAWK_ENVIRONMENT=production

Without the two addresses the SDK sends to a Flowhawk on this machine (http://localhost:4000 and http://localhost:4318). Set FLOWHAWK_ENVIRONMENT where the service runs in production: flow health, flow alerts and the watcher count production and prod only, and an SDK with no environment reports development.

import flowhawk "github.com/flowhawk-dev/flowhawk-go"

func main() {
	shutdown, err := flowhawk.Init(flowhawk.Options{Service: "payments"}) // APIKey defaults to FLOWHAWK_API_KEY
	if err != nil {
		log.Fatal(err)
	}
	defer shutdown(context.Background())

	client := &http.Client{Transport: flowhawk.Transport(nil)} // carries the flow to the next service
	log := flowhawk.Logger()                                     // log/slog, filtered by the flow's policy

	mux := http.NewServeMux()
	mux.HandleFunc("POST /checkout", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		flowhawk.Count(ctx, "orders.placed", 1, flowhawk.Labels{"plan": "team"})
		log.InfoContext(ctx, "order placed")

		ctx, call := flowhawk.TraceLLM(ctx, flowhawk.LLMRequest{System: "anthropic", Model: "claude-haiku-5-5", Input: prompt})
		// ... call the model ...
		call.Record(flowhawk.LLMResult{Output: text, InputTokens: in, OutputTokens: out})
		call.End(err)
	})
	http.ListenAndServe(":8080", flowhawk.Middleware(mux))
}

Background jobs that no route matches: flowhawk.WithStep(ctx, "payouts", "run-batch", func(ctx context.Context) error { ... }).

Who a request is for: flowhawk.SetCustomer(ctx, account.ID) (an id, not an email). Their page then lists the request, and issues count them. An error you handled yourself: flowhawk.RecordError(ctx, err) makes it an issue and counts the request as failed.

What is traced

  • HTTP servers. flowhawk.Middleware(h) names each request's span after its route (GET /orders/{id}, with http.route), read from Go's ServeMux patterns. With chi, gin or echo, call flowhawk.SetRoute(ctx, route) from a middleware (chi.RouteContext(r.Context()).RoutePattern(), c.FullPath(), c.Path()). A panic in a handler is recorded on the span with its stack, so it shows in Issues, and then carries on as it would without the SDK; WithStep does the same.
  • Crashes. A panic nothing recovers, in any goroutine, or a fatal runtime error (concurrent map writes, out of memory) is sent as a FATAL log with its stack, so it shows in Issues. Go runs no code in a crashing program, so Init starts a small monitor (your binary run again with FLOWHAWK_CRASH_MONITOR set; keep Init first in main) that receives the runtime's crash report and sends it. As process 1 in a container the report is written to FLOWHAWK_CRASH_DIR (default the temp dir) and sent at the next start. The crash still goes to stderr with the same exit code. Options{NoCrashReports: true} or FLOWHAWK_CRASH_REPORTS=off turns it off; it is off in tests.
  • HTTP clients. flowhawk.Transport(nil).
  • Databases. flowhawk.OpenDB("pgx", dsn) instead of sql.Open (any database/sql driver: pgx, lib/pq, MySQL, SQLite, SQL Server, ClickHouse): a span per query with db.system.name, db.query.text and the line that sent it, and the SQL comment tags added to the query, so TagSQL isn't needed. flowhawk.WrapConnector(c, "postgresql") for sql.OpenDB. For pgx's own pool use github.com/exaring/otelpgx, for Redis go-redis's redisotel, for MongoDB otelmongo: they report into the SDK.
  • gRPC. grpc.NewServer(flowhawk.GRPCServer()) and grpc.NewClient(addr, flowhawk.GRPCClient(), ...): spans named by method, with rpc.method, and the flow carried to the next service.
  • Queues. Any OpenTelemetry instrumentation (Kafka through otelsarama or franz-go's kotel, NATS, SQS through otelaws) works unchanged; a consumer span starts a step like a request does.
  • Logs. flowhawk.Logger() or flowhawk.Handler(next) for log/slog. Lines written through the standard log package (and slog while its default handler is in place) still go where they went and are also sent, at the level slog's format names; Options.NoConsoleLogs or FLOWHAWK_CONSOLE_LOGS=off stops that. A warn or error that carries an error value (log.ErrorContext(ctx, "charge failed", "err", err)) gets the exception type, message and the stack of the call that logged it, so it shows in Issues.

Init sets the global OpenTelemetry tracer, meter and logger providers and the propagator, so any OpenTelemetry instrumentation library (database drivers, gRPC, messaging) works unchanged and its spans are tagged and sampled too.

Tests: go test ./... (Go 1.26).

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

View Source
const (
	AttrFlow  = "business.flow"
	AttrStep  = "business.step"
	AttrEntry = "business.entry"
)
View Source
const AttrCustomer = "user.id"

AttrCustomer is the attribute SetCustomer writes.

View Source
const AttrFlowStart = "business.flow.start"

AttrFlowStart is the baggage key for the time a flow started (epoch milliseconds), set at its first entry.

View Source
const SDKID = "flowhawk-go/0.2.0"

SDKID identifies this SDK to the control plane.

Variables

View Source
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.

View Source
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

func Count(ctx context.Context, name string, value float64, labels Labels, opts ...MetricOption)

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

func Handler(next slog.Handler) slog.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

func Init(o Options) (func(context.Context) error, error)

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

func Logger() *slog.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

func Middleware(h http.Handler) http.Handler

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

func OpenDB(driverName, dsn string, opts ...otelsql.Option) (*sql.DB, error)

OpenDB opens a traced database/sql pool. Extra otelsql options are applied after the SDK's.

func ParseSentryTrace

func ParseSentryTrace(header string) (trace.TraceID, trace.SpanID, bool)

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

func RecordError(ctx context.Context, err error) bool

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

func SQLComment(ctx context.Context) string

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

func SetCustomer(ctx context.Context, id string) bool

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

func SetRoute(ctx context.Context, route string)

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

func SetSQLComments(on bool, service string)

SetSQLComments turns the tags on or off and sets the service name they carry (Init does this).

func Shutdown

func Shutdown(ctx context.Context) error

Shutdown flushes and stops telemetry. Safe to call more than once.

func TagSQL

func TagSQL(ctx context.Context, sql string) string

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

func TraceHash(id trace.TraceID) float64

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 UpDown

func UpDown(ctx context.Context, name string, delta float64, labels Labels, opts ...MetricOption)

UpDown moves a value up or down (items in a queue, open connections).

func WithStep

func WithStep(ctx context.Context, flow, step string, fn func(ctx context.Context) error) error

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

func WrapConnector(c driver.Connector, system string, opts ...otelsql.Option) *sql.DB

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 Boost

type Boost struct {
	Rate  float64 `json:"rate"`
	Until string  `json:"until"`
}

Boost raises a flow's sample rate until a time.

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 (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).

func Decide

func Decide(id trace.TraceID, spans []sdktrace.ReadOnlySpan, root sdktrace.ReadOnlySpan, p *Policy, rate float64) Decision

Decide is the keep/drop decision for one trace. A nil policy means no config yet: keep everything.

type Flow

type Flow struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Criticality string `json:"criticality"`
	Steps       []Step `json:"steps"`
}

type FlowStep

type FlowStep struct{ Flow, Step string }

FlowStep is the business flow and step a span belongs to.

func FlowOf

func FlowOf(ctx context.Context) (FlowStep, bool)

FlowOf is the business flow and step of the active span in ctx.

func MatchStep

func MatchStep(m BusinessMap, f SpanFacts) (FlowStep, bool)

MatchStep is the first step in the map whose rules match the span, in map order.

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)

func (*FlowTagger) Shutdown

func (t *FlowTagger) Shutdown(context.Context) error

type GaugePoint

type GaugePoint struct {
	Value  float64
	Labels Labels
}

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

func TraceLLM(ctx context.Context, r LLMRequest) (context.Context, *LLMCall)

TraceLLM starts a gen_ai span named "<operation> <model>" and returns a context that carries it. End the call with End.

func (*LLMCall) End

func (c *LLMCall) End(err error)

End ends the span; a non-nil err marks it as an error.

func (*LLMCall) Record

func (c *LLMCall) Record(r LLMResult)

Record records the response on the span (the completion only with capturePrompts).

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 Labels

type Labels map[string]any

Labels are a metric point's labels: string, bool, int or float64 values.

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) Fields

func (SentryTrace) Fields() []string

func (SentryTrace) Inject

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 Step

type Step struct {
	ID    string      `json:"id"`
	Name  string      `json:"name"`
	Match []StepMatch `json:"match"`
	// FailWhen: rules on an entry span's attributes that fail the run without an error status (stepFailed).
	FailWhen []map[string]string `json:"failWhen,omitempty"`
}

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)

func (*TailSampler) Shutdown

func (t *TailSampler) Shutdown(ctx context.Context) error

Jump to

Keyboard shortcuts

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