Documentation
¶
Overview ¶
Package pulse records production telemetry for a Go web app: request latency, slow SQL, Quiver jobs, cache hit ratios, outbound HTTP calls, grouped exceptions, and runtime health.
A Recorder takes events on the hot path without blocking: they go into a bounded channel, and when it is full they are dropped and counted (Recorder.Dropped). A background flusher folds them into one-minute, one-hour, and one-day rollups and writes those to a Store:
rec := pulse.New(pulse.NewMemoryStore(), pulse.WithSampleRate(0.25)) rec.Start(ctx) defer rec.Close(context.Background()) rec.StartRuntimeSampler(ctx, 15*time.Second) handler = pulse.HTTPMiddleware(rec)(handler)
Sampling scales counts back up, so totals and rates stay estimates of the real traffic. Slow requests, slow queries, slow jobs, slow outbound calls, and exceptions are always kept, whatever the sample rate.
The package depends on the standard library only. github.com/fletchhq/pulse/nock persists rollups in SQLite or Postgres, github.com/fletchhq/pulse/quiver records Quiver jobs, and github.com/fletchhq/pulse/pulsesight shows them in a Sight admin panel.
Index ¶
- Constants
- Variables
- func DefaultRoute(r *http.Request) string
- func Fingerprint(sql string) string
- func HTTPMiddleware(rec *Recorder, opts ...HTTPOption) func(http.Handler) http.Handler
- func NewTransport(rec *Recorder, base http.RoundTripper) http.RoundTripper
- func NormalizePath(p string) string
- func Series(buckets []Bucket, w Window, now time.Time, value func(Stats) int64) []int64
- func TrackCache[V any](r *Recorder, keyPrefix string, get func() (V, bool)) (V, bool)
- func WrapHTTPClient(rec *Recorder, c *http.Client) *http.Client
- type Batch
- type Bucket
- type Entry
- type ExceptionGroup
- type ExceptionSample
- type Frame
- type HTTPOption
- type Histogram
- type MemoryOption
- type MemoryStore
- func (s *MemoryStore) Exceptions(_ context.Context, q Query) ([]ExceptionGroup, error)
- func (s *MemoryStore) PruneBefore(_ context.Context, t time.Time) error
- func (s *MemoryStore) QueryRollups(_ context.Context, q Query) ([]Bucket, error)
- func (s *MemoryStore) TopSlow(_ context.Context, q Query) ([]SlowGroup, error)
- func (s *MemoryStore) WriteBuckets(_ context.Context, b *Batch) error
- type Metric
- type Option
- func WithBufferSize(n int) Option
- func WithClock(now func() time.Time) Option
- func WithFlushInterval(d time.Duration) Option
- func WithFrameworkPackages(prefixes ...string) Option
- func WithLogger(l *slog.Logger) Option
- func WithMaxEntries(n int) Option
- func WithMaxKeys(n int) Option
- func WithSampleRate(r float64) Option
- func WithSlowThreshold(m Metric, d time.Duration) Option
- type Overview
- type PanicError
- type Query
- type Recorder
- func (r *Recorder) Close(ctx context.Context) error
- func (r *Recorder) Dropped() uint64
- func (r *Recorder) FailedFlushes() uint64
- func (r *Recorder) Flush(ctx context.Context) error
- func (r *Recorder) RecordCache(op, keyPrefix string, hit bool)
- func (r *Recorder) RecordException(_ context.Context, err error, stack []byte)
- func (r *Recorder) RecordJob(queue, kind string, d time.Duration, err error)
- func (r *Recorder) RecordOutbound(method, host string, status int, d time.Duration, err error)
- func (r *Recorder) RecordQuery(_ context.Context, sql string, d time.Duration, err error)
- func (r *Recorder) RecordQueueDepth(queue string, depth int64)
- func (r *Recorder) RecordRequest(route string, status int, d time.Duration, detail string)
- func (r *Recorder) SampleRate() float64
- func (r *Recorder) SampleRuntime()
- func (r *Recorder) SlowThreshold(m Metric) time.Duration
- func (r *Recorder) Start(ctx context.Context)
- func (r *Recorder) StartRuntimeSampler(ctx context.Context, interval time.Duration)
- func (r *Recorder) Store() Store
- type SlowGroup
- type Stats
- type Store
- type Window
Constants ¶
The rollup periods a Recorder writes every event into.
const ( HeapAlloc = "heap_alloc" HeapInuse = "heap_inuse" Sys = "sys" Goroutines = "goroutines" GCPause = "gc_pause" NumGC = "num_gc" )
The Runtime gauge keys StartRuntimeSampler records.
const HistogramBins = 16
HistogramBins is the number of bins of a Histogram.
const OtherKey = "(other)"
OtherKey is the key that events past WithMaxKeys are folded into.
Variables ¶
var ( Window1h = Window{Key: "1h", Label: "1h", Span: time.Hour, Period: Minute} Window6h = Window{Key: "6h", Label: "6h", Span: 6 * time.Hour, Period: Minute} Window24h = Window{Key: "24h", Label: "24h", Span: Day, Period: Hour} Window7d = Window{Key: "7d", Label: "7d", Span: 7 * Day, Period: Hour} )
The windows a dashboard offers.
var HistogramBounds = [HistogramBins - 1]time.Duration{ time.Millisecond, 2 * time.Millisecond, 5 * time.Millisecond, 10 * time.Millisecond, 25 * time.Millisecond, 50 * time.Millisecond, 100 * time.Millisecond, 250 * time.Millisecond, 500 * time.Millisecond, time.Second, 2500 * time.Millisecond, 5 * time.Second, 10 * time.Second, 30 * time.Second, time.Minute, }
HistogramBounds are the upper bounds of a Histogram's bins; the last bin has no upper bound.
Periods lists the rollup periods, shortest first.
Windows lists the windows, shortest first.
Functions ¶
func DefaultRoute ¶
DefaultRoute is the default route of a request; see WithRoute.
func Fingerprint ¶
Fingerprint normalizes a SQL statement so executions that differ only in their values group together: literals and placeholders become ?, runs of whitespace one space, and IN lists of placeholders "(?...)". It keeps identifiers and keywords as written.
func HTTPMiddleware ¶
HTTPMiddleware records every request next serves: its route, status, and latency. A panic is recorded as an exception and a 500, then re-raised.
func NewTransport ¶
func NewTransport(rec *Recorder, base http.RoundTripper) http.RoundTripper
NewTransport returns a RoundTripper that records every call base makes: its host, method, status, and duration. A nil base is http.DefaultTransport.
func NormalizePath ¶
NormalizePath replaces path segments that look like IDs (numbers, UUIDs, long hex or mixed alphanumeric tokens) with {id}.
func Series ¶
Series returns one value per period of w ending at now, oldest first: value applied to the buckets that start in that period.
func TrackCache ¶
TrackCache calls get, records whether it found the value under keyPrefix as a "get", and returns what it returned.
Types ¶
type Batch ¶
type Batch struct {
Buckets []Bucket
Entries []Entry
Exceptions []ExceptionSample
}
Batch is what one flush writes.
type Bucket ¶
type Bucket struct {
Metric Metric
Key string
Period time.Duration
Start time.Time
Count int64
Failed int64
ClientErrors int64
Slow int64
Sum int64
Max int64
Last int64
Hist Histogram
}
Bucket is the rollup of one metric and key over one period starting at Start.
Key is the route ("GET /users/{id}") for Requests, the SQL fingerprint for Queries, "queue/kind" for Jobs, the queue for QueueDepth, the key prefix for Cache, the host for Outbound, the fingerprint for Exceptions, and a gauge name such as HeapInuse for Runtime.
Count is the number of events, scaled up for sampling. Failed counts server errors (5xx) for Requests and Outbound, errors for Queries and Jobs, and misses for Cache. ClientErrors counts 4xx Requests. Slow counts events over the slow threshold. Sum, Max, and Hist are durations in nanoseconds, except for the gauges QueueDepth and Runtime, where Sum and Max are of the sampled values and Last is the latest one.
type Entry ¶
type Entry struct {
Metric Metric
Key string
At time.Time
Duration time.Duration
// Detail is what is worth showing besides the key, such as the request
// path or the status of an outbound call.
Detail string
}
Entry is one slow event: a request, query, job, or outbound call over its threshold.
type ExceptionGroup ¶
type ExceptionGroup struct {
ExceptionSample
// Total is the occurrences over the query's range; Count is over all
// time.
Total int64
}
ExceptionGroup is an exception and its occurrences over a query's range.
type ExceptionSample ¶
type ExceptionSample struct {
Fingerprint string
Type string
Message string
// Location is the first application frame, as "func (file:line)".
Location string
// Stack is the latest stack, with application frames marked.
Stack []Frame
Count int64
FirstSeen time.Time
LastSeen time.Time
}
ExceptionSample is one occurrence group of an exception as the flusher writes it: how many times it happened since the last flush.
type Frame ¶
Frame is one stack frame of an exception. App marks the application's own code, as opposed to the standard library and framework packages.
type HTTPOption ¶
type HTTPOption func(*httpConfig)
HTTPOption configures HTTPMiddleware.
func WithIgnorePaths ¶
func WithIgnorePaths(prefixes ...string) HTTPOption
WithIgnorePaths skips requests whose path starts with one of prefixes, such as the admin panel that shows the dashboard.
type Histogram ¶
type Histogram [HistogramBins]int64
Histogram counts durations in fixed bins, so histograms of different buckets and nodes merge by adding.
type MemoryOption ¶
type MemoryOption func(*MemoryStore)
MemoryOption configures a MemoryStore.
func WithEntryLimit ¶
func WithEntryLimit(n int) MemoryOption
WithEntryLimit caps the slow entries kept per metric; the oldest go first. Default 1000.
func WithExceptionLimit ¶
func WithExceptionLimit(n int) MemoryOption
WithExceptionLimit caps the exception groups kept; the least recently seen go first. Default 500.
func WithRetention ¶
func WithRetention(d time.Duration) MemoryOption
WithRetention keeps rollups, entries, and exceptions this long. Default seven days. Minute rollups are kept at most a day.
func WithStoreClock ¶
func WithStoreClock(now func() time.Time) MemoryOption
WithStoreClock sets the clock retention is measured against. Default time.Now.
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore keeps rollups in memory, for a single node or tests. It forgets everything on restart.
func NewMemoryStore ¶
func NewMemoryStore(opts ...MemoryOption) *MemoryStore
NewMemoryStore returns an empty MemoryStore.
func (*MemoryStore) Exceptions ¶
func (s *MemoryStore) Exceptions(_ context.Context, q Query) ([]ExceptionGroup, error)
Exceptions implements Store.
func (*MemoryStore) PruneBefore ¶
PruneBefore implements Store.
func (*MemoryStore) QueryRollups ¶
QueryRollups implements Store.
func (*MemoryStore) WriteBuckets ¶
func (s *MemoryStore) WriteBuckets(_ context.Context, b *Batch) error
WriteBuckets implements Store.
type Metric ¶
type Metric string
Metric names a kind of recorded event.
const ( Requests Metric = "request" Queries Metric = "query" Jobs Metric = "job" QueueDepth Metric = "queue_depth" Cache Metric = "cache" Outbound Metric = "outbound" Exceptions Metric = "exception" Runtime Metric = "runtime" )
The metrics a Recorder writes. Bucket.Key means something different for each; see Bucket.
type Option ¶
type Option func(*config)
Option configures a Recorder.
func WithBufferSize ¶
WithBufferSize sets how many events wait for the flusher before new ones are dropped. Default 8192.
func WithFlushInterval ¶
WithFlushInterval sets how often rollups are written to the store. Default 5s.
func WithFrameworkPackages ¶
WithFrameworkPackages adds import-path prefixes whose stack frames are framework frames rather than application frames, besides the standard library and github.com/fletchhq.
func WithLogger ¶
WithLogger sets where failed flushes are logged. Default slog.Default().
func WithMaxEntries ¶
WithMaxEntries caps the slow entries one flush writes. Default 1000.
func WithMaxKeys ¶
WithMaxKeys caps the distinct keys of one metric in one flush; the rest are folded into the key "(other)". It bounds the cost of unnormalized routes or ad-hoc SQL. Default 500.
func WithSampleRate ¶
WithSampleRate keeps this share (0 to 1) of ordinary events and scales their counts up to match. Slow events and exceptions are always kept. Default 1.
type Overview ¶
type Overview struct {
Window Window
Requests Stats
// PerMinute is the mean requests per minute over the window.
PerMinute float64
Queries Stats
Jobs Stats
Cache Stats
Outbound Stats
Exceptions int64
QueueDepth int64
HeapInuse int64
Goroutines int64
RequestTrend []int64
}
Overview is the headline figures of a window.
type PanicError ¶
type PanicError struct{ Value any }
PanicError is the error a recovered panic value becomes.
func (*PanicError) Error ¶
func (e *PanicError) Error() string
func (*PanicError) Unwrap ¶
func (e *PanicError) Unwrap() error
Unwrap returns the panic value when it is an error.
type Query ¶
type Query struct {
Metric Metric
// Key limits the query to one key; "" is every key.
Key string
Period time.Duration
From time.Time
To time.Time
// Limit caps the rows of TopSlow and Exceptions; 0 is 10.
Limit int
}
Query selects rollups, entries, or exceptions over [From, To).
type Recorder ¶
type Recorder struct {
// contains filtered or unexported fields
}
Recorder takes telemetry events and writes their rollups to a Store. Its Record methods never block and are safe for concurrent use.
func New ¶
New returns a Recorder that writes to store. Call Start to flush in the background, or Flush to write what was recorded so far.
func (*Recorder) Close ¶
Close stops the flusher and writes what is left. It waits for the final write until ctx is done.
func (*Recorder) FailedFlushes ¶
FailedFlushes is how many flushes the store refused; their rollups are lost.
func (*Recorder) Flush ¶
Flush writes every event recorded so far to the store and returns the store's error.
func (*Recorder) RecordCache ¶
RecordCache records one cache lookup of a key starting with keyPrefix, such as "user:". op names the operation, such as "get"; lookups are grouped by op and prefix.
func (*Recorder) RecordException ¶
RecordException records an error or a recovered panic. stack is a goroutine trace in the format of debug.Stack; nil captures the caller's. Occurrences are grouped by the error's type and its first application frame, or by its type and message without digits when no frame is the application's.
func (*Recorder) RecordOutbound ¶
RecordOutbound records one outbound HTTP call to host. A transport error counts as failed with status 0. NewTransport calls it.
func (*Recorder) RecordQuery ¶
RecordQuery records one SQL statement, grouped by its Fingerprint.
func (*Recorder) RecordQueueDepth ¶
RecordQueueDepth records how many jobs wait on queue now.
func (*Recorder) RecordRequest ¶
RecordRequest records one handled request. route groups requests, such as "GET /users/{id}"; detail is shown with a slow request, such as its path. HTTPMiddleware calls it.
func (*Recorder) SampleRate ¶
SampleRate returns the share of ordinary events kept.
func (*Recorder) SampleRuntime ¶
func (r *Recorder) SampleRuntime()
SampleRuntime records the Runtime gauges once.
func (*Recorder) SlowThreshold ¶
SlowThreshold returns when an event of m counts as slow, or 0.
func (*Recorder) Start ¶
Start runs the flusher until ctx is done or Close is called. Calling it again while it runs does nothing.
func (*Recorder) StartRuntimeSampler ¶
StartRuntimeSampler records the Runtime gauges every interval (default 15s) until ctx is done: HeapAlloc, HeapInuse, Sys, Goroutines, the latest GC pause in nanoseconds (GCPause), and the GC count (NumGC). It samples once right away.
type Stats ¶
type Stats struct {
Key string
Count int64
Failed int64
ClientErrors int64
Slow int64
Sum int64
Max int64
Samples int64
// Last is the newest value of a gauge, and LastAt the start of its
// bucket.
Last int64
LastAt time.Time
Hist Histogram
}
Stats is the rollups of one key, or of every key, over a window.
func (Stats) MaxDuration ¶
MaxDuration is Max as a duration.
type Store ¶
type Store interface {
// WriteBuckets merges b's buckets into those stored (adding counts,
// keeping the larger Max and the newer Last), appends its entries, and
// merges its exceptions by fingerprint.
WriteBuckets(ctx context.Context, b *Batch) error
// QueryRollups returns the buckets of q.Metric and q.Period that start
// in q's range, oldest first.
QueryRollups(ctx context.Context, q Query) ([]Bucket, error)
// TopSlow groups the slow entries of q.Metric in q's range by key,
// slowest first.
TopSlow(ctx context.Context, q Query) ([]SlowGroup, error)
// Exceptions returns the exception groups seen in q's range, the most
// frequent first, with Total counted from the q.Period rollups.
Exceptions(ctx context.Context, q Query) ([]ExceptionGroup, error)
// PruneBefore deletes everything older than t.
PruneBefore(ctx context.Context, t time.Time) error
}
Store keeps rollups, slow entries, and exception groups. Methods are called from many goroutines.
type Window ¶
Window is a period a dashboard shows, read from rollups of Period.
func ParseWindow ¶
ParseWindow returns the window keyed key, or Window1h.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
demo
command
Command demo serves a Sight panel with the Pulse plugin at http://127.0.0.1:8090/admin/pages/pulse, fed by a small shop API and a generator that calls it.
|
Command demo serves a Sight panel with the Pulse plugin at http://127.0.0.1:8090/admin/pages/pulse, fed by a small shop API and a generator that calls it. |
|
Package nock keeps Pulse rollups in SQLite or Postgres through a Nock database, and records the statements a Nock database runs.
|
Package nock keeps Pulse rollups in SQLite or Postgres through a Nock database, and records the statements a Nock database runs. |
|
Package pulsesight shows Pulse telemetry in a Sight admin panel: an overview page, pages for requests, queries, jobs, and exceptions, and widgets on the panel's dashboard.
|
Package pulsesight shows Pulse telemetry in a Sight admin panel: an overview page, pages for requests, queries, jobs, and exceptions, and widgets on the panel's dashboard. |
|
Package pulsetest checks that a pulse.Store behaves as the interface says.
|
Package pulsetest checks that a pulse.Store behaves as the interface says. |
|
Package quiver records Quiver jobs with a Pulse recorder.
|
Package quiver records Quiver jobs with a Pulse recorder. |