worker

package
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package worker is the standard primitive for the background work gopherstack services run: periodic "janitor" sweeps, one-shot delayed state transitions, and tracked goroutines.

All of it is owned by Group, a per-service supervisor constructed from the service/lifecycle context (never context.Background). A Group roots every task at that context, logs via the context logger, recovers panics (recording a "panic" task to the injected Metrics) so one failure never takes down a goroutine or the process, and joins everything deterministically on Group.Stop. This removes the hand-rolled time.NewTicker / time.AfterFunc / go func copies that each risked a missing Stop, a leaked goroutine, or an unrecovered panic.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Group

type Group struct {
	// contains filtered or unexported fields
}

Group supervises all of a backend's background work — periodic sweeps, one-shot delayed callbacks, and tracked goroutines — under a single cancellable lifecycle rooted at the service context. It owns the cross-cutting concerns so sweeps only do work: every callback is panic-recovered (logged via the injected logger and recorded as a "panic" task), each periodic sweep's task status is emitted to the injected Metrics, and Stop deterministically cancels everything, stops pending timers, and joins the goroutines it owns — so nothing outlives the service.

Construct one per service from the service/lifecycle context (never context.Background) and call Stop from the service's Shutdown/Close.

func NewGroup

func NewGroup(ctx context.Context, service string, opts ...GroupOption) *Group

NewGroup returns a Group whose work derives from ctx (the service/lifecycle context) and is attributed to service. It always logs via the logger carried by ctx (logger.Load) and records telemetry via pkgs/telemetry by default; override the telemetry sink with WithMetrics.

func (*Group) After

func (g *Group) After(component string, d time.Duration, fn func())

After schedules fn to run once after d. It is the resilient, stoppable replacement for raw time.AfterFunc: the timer is tracked so Stop cancels it, and fn is panic-recovered. No-op after Stop.

func (*Group) Go

func (g *Group) Go(component string, fn func(context.Context))

Go runs fn in a tracked, panic-recovered goroutine that Stop joins. fn should return when its context is cancelled (Stop cancels it). No-op after Stop.

func (*Group) Stop

func (g *Group) Stop()

Stop cancels the group context, stops every pending one-shot timer, and waits for all Go/Ticker goroutines to return. Safe to call multiple times.

func (*Group) Ticker

func (g *Group) Ticker(
	component string,
	interval, timeout time.Duration,
	sweep func(context.Context),
	opts ...Option,
)

Ticker runs sweep once per interval until Stop, as a tracked goroutine. Each sweep is panic-recovered and its task status ("success"/"panic") is recorded to the group's Metrics; when timeout > 0 each sweep is bounded by that deadline. Pass WithImmediate to sweep once before the first tick.

type GroupOption

type GroupOption func(*groupConfig)

GroupOption configures a Group at construction.

func WithMetrics

func WithMetrics(m Metrics) GroupOption

WithMetrics sets the telemetry sink. Defaults to a pkgs/telemetry-backed implementation; override it to capture worker telemetry in tests.

type Metrics

type Metrics interface {
	RecordTask(service, component, status string)
}

Metrics records background-worker telemetry the Group emits on its own behalf (currently the "panic" task recorded when a sweep/goroutine/timer panics). A Group is given one at construction, defaulting to a pkgs/telemetry-backed implementation; tests inject a fake to assert on it. Sweeps continue to emit their own success/items/depth telemetry, which is often finer-grained than the ticker that drives them.

type Option

type Option func(*config)

Option customises an individual ticker sweep (used by both RunTicker and Group.Ticker). Options are additive so the primitive can absorb every janitor variant without a parameter explosion.

func WithImmediate

func WithImmediate() Option

WithImmediate runs the sweep once before the first tick, for janitors that perform an initial pass at start-up rather than waiting a full interval.

func WithOnPanic

func WithOnPanic(fn func(any)) Option

WithOnPanic registers a hook invoked after a recovered sweep panic has been logged. The default behaviour (log, record a panic task, continue) always applies; the hook is for callers that additionally need to flip a flag.

type Runner added in v1.1.1

type Runner interface {
	Run(context.Context)
}

Runner is a single blocking task that runs until its context is cancelled, such as a service janitor's Run method.

type SingleRun added in v1.1.1

type SingleRun struct {
	// contains filtered or unexported fields
}

SingleRun manages the start/stop lifecycle of one Runner — typically a service's optional background janitor — under a single lock, so every service's StartWorker/Shutdown pair shares the exact same panic-safe shape: Start is a no-op if a run is already active, and Stop cancels the active run (if any) and waits for it to exit, or for the caller's context to be done, whichever happens first. The zero value is ready to use.

func (*SingleRun) Start added in v1.1.1

func (s *SingleRun) Start(ctx context.Context, r Runner)

Start runs r in its own goroutine, derived from ctx, unless a run started by an earlier Start is still active (in which case Start is a no-op). It returns immediately; the run happens asynchronously.

func (*SingleRun) Stop added in v1.1.1

func (s *SingleRun) Stop(ctx context.Context)

Stop cancels the active run, if any, and waits for it to exit or for ctx to be done. It is a no-op if no run is active, and safe to call more than once (a subsequent call finds no active run and returns immediately).

Jump to

Keyboard shortcuts

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