Documentation
¶
Overview ¶
Package poller maintains a single "current value" that is refreshed by periodically calling a Getter.
It is the read-side counterpart to worker.Loop: instead of performing work on each tick, it caches the latest successfully fetched value so hot paths can read it (via Current) without blocking on the source. A failed poll leaves the cached value unchanged. Typical uses are feature flags, dynamic config, exchange rates, or any slowly-changing remote value callers want cheaply and concurrently. A Poller is a worker.Runnable, so it can be supervised in a worker.Group alongside servers and other workers. Start runs the polls under otel.Suppress, so they export no traces; a direct Poll keeps the trace of its caller.
The Getter gets the run context (bounded by PollTimeout, when set) and must return once it is canceled: Start does not return before the running Getter does, so a Getter that ignores its context holds the shutdown of the group up to its ShutdownTimeout.
Usage ¶
Seed an initial value, supervise the poller, and read the cached value concurrently:
p := poller.New(log, defaultRates, func(ctx context.Context) (Rates, error) {
return fetchRates(ctx)
}, poller.Config{
Name: "rates",
Interval: 30 * time.Second,
PollTimeout: 5 * time.Second,
}, poller.WithOnError(func(error) { pollFailures.Inc() }))
g.Add(p) // worker.Group supervises Start/Stop
rates := p.Current() // latest successful value (the initial until first poll)
Config ¶
- Name: identifies the poller in logs (default "poller").
- Interval: time between polls (default 1s).
- PollTimeout: bounds each Getter call (0 = inherit the run context).
Options ¶
- WithOnError(h): invoked with the error of each failed poll.
- WithOnPanic(h): a safetick.PanicHandler invoked when a poll panics.
Example ¶
A worker.Group supervises the poller next to the rest of the process: Start polls at once, then every Interval, until the group shuts down. Hot paths read the cached value with Current.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/assanoff/skit/poller"
"github.com/assanoff/skit/worker"
)
func main() {
// fetched only lets the example wait for the first poll.
fetched := make(chan struct{}, 1)
p := poller.New(nil, "default", func(context.Context) (string, error) {
select {
case fetched <- struct{}{}:
default:
}
return "remote", nil
}, poller.Config{Name: "flags", Interval: time.Minute})
g := worker.NewGroup(nil, worker.GroupConfig{ShutdownTimeout: 5 * time.Second})
g.Add(p)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- g.Run(ctx) }()
<-fetched
cancel() // the process shuts down
if err := <-done; err != nil {
log.Fatal(err)
}
fmt.Println(p.Current())
}
Output: remote
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// Name identifies the poller in logs (defaults to "poller").
Name string
// Interval between polls (defaults to 1s if non-positive).
Interval time.Duration
// PollTimeout bounds each Getter call (0 = inherit the run context).
PollTimeout time.Duration
}
Config configures a Poller.
type Getter ¶
Getter fetches the next value. It is called on each tick (and synchronously by Poll). A returned error leaves the current value unchanged.
type Option ¶ added in v0.14.0
type Option func(*options)
Option customizes a Poller.
func WithOnError ¶ added in v0.14.0
WithOnError sets a handler invoked with the error of each failed poll, e.g. to count failures. The error is logged regardless.
Example ¶
A failed poll leaves the cached value as it was; the WithOnError handler gets the error, to count it or to alert.
package main
import (
"context"
"errors"
"fmt"
"github.com/assanoff/skit/poller"
)
func main() {
down := true
p := poller.New(nil, "default", func(context.Context) (string, error) {
if down {
return "", errors.New("flags: source is down")
}
return "remote", nil
}, poller.Config{Name: "flags"}, poller.WithOnError(func(err error) {
fmt.Println("poll:", err)
}))
ctx := context.Background()
p.Poll(ctx)
fmt.Println(p.Current())
down = false
p.Poll(ctx)
fmt.Println(p.Current())
}
Output: poll: flags: source is down default remote
func WithOnPanic ¶ added in v0.14.0
func WithOnPanic(h safetick.PanicHandler) Option
WithOnPanic sets a handler invoked when a poll panics. The panic is always recovered and logged regardless.
type Poller ¶
type Poller[T any] struct { // contains filtered or unexported fields }
Poller caches the latest value returned by its Getter, refreshing it on a fixed interval. Reads via Current are safe for concurrent use.
func New ¶
func New[T any](log *slog.Logger, initial T, getter Getter[T], cfg Config, opts ...Option) *Poller[T]
New builds a Poller seeded with initial, which Current returns until the first successful poll. log may be nil.
func (*Poller[T]) Current ¶
func (p *Poller[T]) Current() T
Current returns the most recently fetched value (the New initial value until the first successful poll). Safe for concurrent use.
func (*Poller[T]) Poll ¶
Poll fetches once, synchronously, and updates the current value on success. On error the value is left unchanged and the WithOnError handler (if set) is invoked. A panic in the Getter is recovered so a single bad poll cannot crash the supervisor.
Example ¶
Poll fetches once, synchronously: Current returns the initial value until the first successful poll.
package main
import (
"context"
"fmt"
"time"
"github.com/assanoff/skit/poller"
)
func main() {
p := poller.New(nil, 0.0, func(context.Context) (float64, error) {
return 470.5, nil
}, poller.Config{Name: "usd-kzt", Interval: time.Minute})
fmt.Println(p.Current())
p.Poll(context.Background())
fmt.Println(p.Current())
}
Output: 0 470.5
func (*Poller[T]) Start ¶
Start polls immediately, then on every Interval, until ctx is canceled. It implements worker.Runnable: Start blocks until shutdown. The polls run under otel.Suppress, so they export no traces; a direct Poll keeps the trace of its caller. A poll in flight at shutdown gets the canceled ctx, and Start returns once its Getter does.