pulse

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: Apache-2.0, MIT Imports: 22 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

pulse

Opt-in production telemetry and health dashboard for Go and Fletch applications, shipped as a sight.Plugin in a single CGO_ENABLED=0 module.

Install

go get github.com/fletchhq/pulse

Adding github.com/fletchhq/pulse to a Fletch app's go.mod lets fletch ax sync and fletch docs auto-discover docs/pulse.md and skills/pulse/SKILL.md.

Packages

Package Purpose
github.com/fletchhq/pulse Stdlib-only Recorder, collectors, Store, MemoryStore, 16-bin Histogram, time windows, and LoadOverview.
github.com/fletchhq/pulse/nock SQLite and Postgres rollup store on fletch/nock (no direct DB driver imports), query observer, and Quiver pruning job.
github.com/fletchhq/pulse/quiver fletch/quiver job execution middleware and queue-depth sampler.
github.com/fletchhq/pulse/pulsesight sight.Plugin and Crest dashboard UI (ProGrade light/dark theme, strict @alpinejs/csp).
github.com/fletchhq/pulse/pulsetest Stdlib-only StoreContract suite for verifying custom pulse.Store implementations.
examples/demo Runnable Sight + Pulse demo server with a synthetic traffic generator.

Quickstart

package main

import (
	"context"
	"net/http"
	"time"

	"github.com/fletchhq/pulse"
	"github.com/fletchhq/pulse/pulsesight"
)

func setupPulse(ctx context.Context, mux *http.ServeMux) (*pulse.Recorder, func() error) {
	store := pulse.NewMemoryStore()
	rec := pulse.New(store)
	rec.Start(ctx)
	rec.StartRuntimeSampler(ctx, 10*time.Second)

	// Serve the dashboard stylesheet at "/_pulse/pulse.css".
	mux.Handle(pulsesight.StylesheetPath, pulsesight.StylesheetHandler())

	// Register the plugin with Sight:
	//   sight.WithPlugins(pulsesight.Plugin(store, pulsesight.WithRecorder(rec)))
	_ = pulsesight.Plugin(store, pulsesight.WithRecorder(rec))

	return rec, func() error {
		return rec.Close(context.Background())
	}
}

Wrap HTTP routes with pulse.HTTPMiddleware(rec, pulse.WithIgnorePaths("/healthz", "/readyz", pulsesight.StylesheetPath)). For persistent SQLite or Postgres storage, swap pulse.NewMemoryStore() for pulse/nock and attach pulsenock.QueryObserver(rec) and pulsequiver.Middleware(rec).

Design Notes

  • Non-blocking hot path: Events go into a bounded buffer and flush on a background loop (Start, Flush, Close). Overflow drops instead of stalling callers and increments atomic Dropped() and FailedFlushes() counters.
  • Sampling with safety exceptions: WithSampleRate reduces volume on healthy traffic while slow events (per WithSlowThreshold) and exceptions bypass sampling.
  • Zero-driver persistence: pulse/nock runs on fletch/nock (fnock.Executor) for both SQLite and Postgres without importing database drivers directly.
  • CSP-strict UI: pulsesight renders a light/dark ProGrade dashboard using CSS light-dark(), Inter + JetBrains Mono, and @alpinejs/csp with zero inline scripts or eval.

Demo

Run the synthetic traffic demo:

go run ./examples/demo

Development

GOWORK=off CGO_ENABLED=0 go test -race -count=1 ./...
CGO_ENABLED=0 scripts/lint.sh

scripts/lint.sh runs golangci-lint v2.15.0.

Documentation

  • docs/pulse.md: full reference for recorders, collectors, stores, and the Sight plugin.
  • skills/pulse/SKILL.md: concise agent instructions for wiring and maintaining Pulse.

License

Dual-licensed under MIT or Apache-2.0. See LICENSE-MIT and LICENSE-APACHE.

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

View Source
const (
	Minute = time.Minute
	Hour   = time.Hour
	Day    = 24 * time.Hour
)

The rollup periods a Recorder writes every event into.

View Source
const (
	HeapAlloc  = "heap_alloc"
	HeapInuse  = "heap_inuse"
	Sys        = "sys"
	Goroutines = "goroutines"
	GCPause    = "gc_pause"
	NumGC      = "num_gc"
)

The Runtime gauge keys StartRuntimeSampler records.

View Source
const HistogramBins = 16

HistogramBins is the number of bins of a Histogram.

View Source
const OtherKey = "(other)"

OtherKey is the key that events past WithMaxKeys are folded into.

Variables

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

HistogramBounds are the upper bounds of a Histogram's bins; the last bin has no upper bound.

View Source
var Periods = []time.Duration{Minute, Hour, Day}

Periods lists the rollup periods, shortest first.

Windows lists the windows, shortest first.

Functions

func DefaultRoute

func DefaultRoute(r *http.Request) string

DefaultRoute is the default route of a request; see WithRoute.

func Fingerprint

func Fingerprint(sql string) string

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

func HTTPMiddleware(rec *Recorder, opts ...HTTPOption) func(http.Handler) http.Handler

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

func NormalizePath(p string) string

NormalizePath replaces path segments that look like IDs (numbers, UUIDs, long hex or mixed alphanumeric tokens) with {id}.

func Series

func Series(buckets []Bucket, w Window, now time.Time, value func(Stats) int64) []int64

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

func TrackCache[V any](r *Recorder, keyPrefix string, get func() (V, bool)) (V, bool)

TrackCache calls get, records whether it found the value under keyPrefix as a "get", and returns what it returned.

func WrapHTTPClient

func WrapHTTPClient(rec *Recorder, c *http.Client) *http.Client

WrapHTTPClient returns a copy of c, or of http.DefaultClient when c is nil, whose calls are recorded.

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.

func (*Bucket) Merge

func (b *Bucket) Merge(o *Bucket)

Merge adds o's counts to b. o must have the same metric, key, period, and start, and be the later of the two for Last.

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

type Frame struct {
	Func string
	File string
	Line int
	App  bool
}

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.

func WithRoute

func WithRoute(fn func(*http.Request) string) HTTPOption

WithRoute sets how requests are grouped. Default: the method and the ServeMux pattern that matched (Request.Pattern), else the method and the path with numeric and ID-like segments replaced by {id}.

type Histogram

type Histogram [HistogramBins]int64

Histogram counts durations in fixed bins, so histograms of different buckets and nodes merge by adding.

func (*Histogram) Add

func (h *Histogram) Add(d time.Duration, n int64)

Add counts d n times.

func (*Histogram) Merge

func (h *Histogram) Merge(o *Histogram)

Merge adds o's counts to h.

func (Histogram) Quantile

func (h Histogram) Quantile(q float64, limit time.Duration) time.Duration

Quantile estimates the q-quantile (0 < q <= 1), interpolating within its bin. The result never exceeds limit when limit is positive, which keeps an estimate in the open last bin, or above the slowest event, honest.

func (Histogram) Total

func (h Histogram) Total() int64

Total is the number of durations counted.

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

func (s *MemoryStore) PruneBefore(_ context.Context, t time.Time) error

PruneBefore implements Store.

func (*MemoryStore) QueryRollups

func (s *MemoryStore) QueryRollups(_ context.Context, q Query) ([]Bucket, error)

QueryRollups implements Store.

func (*MemoryStore) TopSlow

func (s *MemoryStore) TopSlow(_ context.Context, q Query) ([]SlowGroup, error)

TopSlow 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

func WithBufferSize(n int) Option

WithBufferSize sets how many events wait for the flusher before new ones are dropped. Default 8192.

func WithClock

func WithClock(now func() time.Time) Option

WithClock sets the clock events are stamped with. Default time.Now.

func WithFlushInterval

func WithFlushInterval(d time.Duration) Option

WithFlushInterval sets how often rollups are written to the store. Default 5s.

func WithFrameworkPackages

func WithFrameworkPackages(prefixes ...string) Option

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

func WithLogger(l *slog.Logger) Option

WithLogger sets where failed flushes are logged. Default slog.Default().

func WithMaxEntries

func WithMaxEntries(n int) Option

WithMaxEntries caps the slow entries one flush writes. Default 1000.

func WithMaxKeys

func WithMaxKeys(n int) Option

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

func WithSampleRate(r float64) Option

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.

func WithSlowThreshold

func WithSlowThreshold(m Metric, d time.Duration) Option

WithSlowThreshold sets when an event of m counts as slow. Defaults: Requests, Jobs, and Outbound 1s; Queries 100ms.

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.

func LoadOverview

func LoadOverview(ctx context.Context, s Store, w Window, now time.Time) (*Overview, error)

LoadOverview reads the headline figures of w ending at now from s.

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

func (Query) LimitOr

func (q Query) LimitOr(def int) int

LimitOr returns q.Limit, or def when it is not positive.

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

func New(store Store, opts ...Option) *Recorder

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

func (r *Recorder) Close(ctx context.Context) error

Close stops the flusher and writes what is left. It waits for the final write until ctx is done.

func (*Recorder) Dropped

func (r *Recorder) Dropped() uint64

Dropped is how many events were dropped because the buffer was full.

func (*Recorder) FailedFlushes

func (r *Recorder) FailedFlushes() uint64

FailedFlushes is how many flushes the store refused; their rollups are lost.

func (*Recorder) Flush

func (r *Recorder) Flush(ctx context.Context) error

Flush writes every event recorded so far to the store and returns the store's error.

func (*Recorder) RecordCache

func (r *Recorder) RecordCache(op, keyPrefix string, hit bool)

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

func (r *Recorder) RecordException(_ context.Context, err error, stack []byte)

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

func (r *Recorder) RecordJob(queue, kind string, d time.Duration, err error)

RecordJob records one run of a job of kind on queue.

func (*Recorder) RecordOutbound

func (r *Recorder) RecordOutbound(method, host string, status int, d time.Duration, err error)

RecordOutbound records one outbound HTTP call to host. A transport error counts as failed with status 0. NewTransport calls it.

func (*Recorder) RecordQuery

func (r *Recorder) RecordQuery(_ context.Context, sql string, d time.Duration, err error)

RecordQuery records one SQL statement, grouped by its Fingerprint.

func (*Recorder) RecordQueueDepth

func (r *Recorder) RecordQueueDepth(queue string, depth int64)

RecordQueueDepth records how many jobs wait on queue now.

func (*Recorder) RecordRequest

func (r *Recorder) RecordRequest(route string, status int, d time.Duration, detail string)

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

func (r *Recorder) SampleRate() float64

SampleRate returns the share of ordinary events kept.

func (*Recorder) SampleRuntime

func (r *Recorder) SampleRuntime()

SampleRuntime records the Runtime gauges once.

func (*Recorder) SlowThreshold

func (r *Recorder) SlowThreshold(m Metric) time.Duration

SlowThreshold returns when an event of m counts as slow, or 0.

func (*Recorder) Start

func (r *Recorder) Start(ctx context.Context)

Start runs the flusher until ctx is done or Close is called. Calling it again while it runs does nothing.

func (*Recorder) StartRuntimeSampler

func (r *Recorder) StartRuntimeSampler(ctx context.Context, interval time.Duration)

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.

func (*Recorder) Store

func (r *Recorder) Store() Store

Store returns the store the Recorder writes to.

type SlowGroup

type SlowGroup struct {
	Key    string
	Count  int64
	Max    time.Duration
	Last   time.Time
	Detail string
}

SlowGroup is the slow entries of one key over a query's range.

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 Summarize

func Summarize(buckets []Bucket) []Stats

Summarize groups buckets by key, the busiest key first.

func Total

func Total(buckets []Bucket) Stats

Total adds up every bucket.

func (Stats) Avg

func (s Stats) Avg() time.Duration

Avg is the mean duration.

func (Stats) FailRate

func (s Stats) FailRate() float64

FailRate is Failed over Count, from 0 to 1.

func (Stats) MaxDuration

func (s Stats) MaxDuration() time.Duration

MaxDuration is Max as a duration.

func (Stats) Quantile

func (s Stats) Quantile(q float64) time.Duration

Quantile estimates the q-quantile duration, at most Max.

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

type Window struct {
	Key    string
	Label  string
	Span   time.Duration
	Period time.Duration
}

Window is a period a dashboard shows, read from rollups of Period.

func ParseWindow

func ParseWindow(key string) Window

ParseWindow returns the window keyed key, or Window1h.

func (Window) Query

func (w Window) Query(m Metric, now time.Time) Query

Query returns the query of m's rollups over w ending at now: the Span before now, widened to whole periods.

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.

Jump to

Keyboard shortcuts

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