Documentation
¶
Overview ¶
Package pool keeps final pool cleanup as a Redis-leased obligation. The cleanup record is bounded to one generation, any process may reclaim an expired owner, and the shutdown admission fence remains present until every shared stream and map has been removed.
Nodes own local workers, schedules, and dispatch outcomes. Close joins local work and stops accepted handlers before detaching node resources. Workers holding a requeue lease own saved job recovery; local removal preserves those records when another cleanup owner must finish the recovery.
Stale-node cleanup uses the node keep-alive map as one Redis-owned lease record. Heartbeat expiry, cleanup fencing, stream destruction, and discovery removal are decided by Redis TIME and exact owner tokens.
Pool map mutations share the pool stream's Redis-owned generation fence. Worker and node operations use these recipes so cleanup and stale processes cannot interleave a lifecycle check with recreation of a deleted old map.
Package pool binds every shared Redis resource to one pool-stream incarnation. Existing deployments are adopted in place once; resources created after explicit cleanup are generation-qualified.
Scheduler transitions use one Redis-time lease from due-time claim through Plan, job mutations, canonical ownership scans, and next-time commit. Every mutating script verifies the exact pool generation, owner token, fence, and unexpired lease so a paused predecessor cannot apply work after takeover.
Package pool keeps its cross-map coordination scripts close to the pool admission code. These scripts preserve the rmap notification contract while making singleton job admission one atomic Redis operation.
Node-owned settlement separates durable handler outcomes from worker intake. Once a handler returns, worker removal may stop Redis intake but cannot cancel the exact dispatch obligation that atomically records the result and settles the original pool event.
Workers translate pool deliveries into handler starts and stops. A running job keeps its ownership across repeated deliveries until it stops or moves. Local shutdown releases accepted handlers before distributed recovery begins; saved job records remain available even after the local handlers stop.
Stale-worker recovery is owned by one Redis-time lease capability. Requeue publication verifies generation, owner token, fence, and lease in the same Lua operation and records a stable worker/job publication key, preventing overlap and ABA duplicates after takeover.
An accepted handler can outlive a missing durable ownership entry. Recovery restores that entry from the running job without starting its handler again, but never replaces another worker, pending dispatch, or different payload.
Worker registration saves the worker's identity and first heartbeat together. Pool cleanup therefore observes either no worker or a worker with a current heartbeat. Repeated registration cannot revive a destroyed worker stream.
Index ¶
- Variables
- type ContextJobProducer
- type Job
- type JobHandler
- type JobParam
- type JobPlan
- type JobProducer
- type MessageHandler
- type Node
- func (node *Node) AddWorker(ctx context.Context, handler JobHandler) (*Worker, error)
- func (node *Node) Close(ctx context.Context) error
- func (node *Node) DispatchJob(ctx context.Context, key string, payload []byte) error
- func (node *Node) DispatchJobOnce(ctx context.Context, dispatchID, key string, payload []byte) (string, error)
- func (node *Node) DispatchMessage(ctx context.Context, key string, payload []byte) error
- func (node *Node) IsClosed() bool
- func (node *Node) IsShutdown() bool
- func (node *Node) JobKeys() []string
- func (node *Node) JobPayload(key string) ([]byte, bool)
- func (node *Node) NewTicker(ctx context.Context, name string, d time.Duration, opts ...TickerOption) (*Ticker, error)
- func (node *Node) NotifyWorker(ctx context.Context, key string, payload []byte) error
- func (node *Node) PoolWorkers() []*Worker
- func (node *Node) RemoveWorker(ctx context.Context, w *Worker) error
- func (node *Node) Schedule(ctx context.Context, producer JobProducer, interval time.Duration) error
- func (node *Node) Shutdown(ctx context.Context) error
- func (node *Node) StopJob(ctx context.Context, key string) error
- func (node *Node) Workers() []*Worker
- type NodeOption
- func WithAckGracePeriod(grace time.Duration) NodeOption
- func WithCleanupLease(lease time.Duration) NodeOption
- func WithClientOnly() NodeOption
- func WithDispatchResultRetention(retention time.Duration) NodeOption
- func WithDispatchTimeout(timeout time.Duration) NodeOption
- func WithJobSinkBlockDuration(d time.Duration) NodeOption
- func WithLogger(logger pulse.Logger) NodeOption
- func WithMaxQueuedJobs(max int) NodeOption
- func WithRecoveryGrace(grace time.Duration) NodeOption
- func WithRequeueTimeout(timeout time.Duration) NodeOption
- func WithWorkerShutdownTTL(ttl time.Duration) NodeOption
- func WithWorkerTTL(ttl time.Duration) NodeOption
- type NotificationHandler
- type Ticker
- type TickerOption
- type Worker
Constants ¶
This section is empty.
Variables ¶
var ( // ErrJobExists is returned when attempting to dispatch a job with a key that already exists. ErrJobExists = errors.New("job already exists") // ErrPoolCapacity is returned when active pending dispatches have reached // the generation's immutable MaxQueuedJobs contract. ErrPoolCapacity = errors.New("pool dispatch capacity reached") // ErrDispatchConflict is returned when a dispatch ID is reused with // different exact job key or payload bytes. ErrDispatchConflict = errors.New("pool dispatch idempotency conflict") // ErrPoolGenerationLost is returned when a node mutates an inactive pool. ErrPoolGenerationLost = errors.New("pool generation lost") // ErrPoolConfigMismatch is returned when node configuration differs from // the active generation's immutable configuration. ErrPoolConfigMismatch = errors.New("pool configuration mismatch") // ErrQuiescenceRequired is returned when legacy resources prove that old // pool writers are still active during a hard upgrade. ErrQuiescenceRequired = errors.New("pool quiescence required") )
var ErrRequeue = errors.New("requeue")
ErrRequeue indicates that a worker failed to process a job's start or stop operation and requests the job to be requeued for another attempt.
var (
ErrScheduleStop = fmt.Errorf("stop")
)
ErrScheduleStop is returned by JobProducer.Plan or ContextJobProducer.PlanContext to stop the corresponding schedule.
Functions ¶
This section is empty.
Types ¶
type ContextJobProducer ¶ added in v1.10.0
type ContextJobProducer interface {
JobProducer
PlanContext(ctx context.Context) (*JobPlan, error)
}
ContextJobProducer adds cancellable planning without breaking the v1 JobProducer contract. The scheduler prefers PlanContext when implemented; Node.Close cancels its context and joins the in-flight transition.
type Job ¶
type Job struct {
// Key is used to identify the worker that handles the job.
Key string
// Payload is the job payload.
Payload []byte
// CreatedAt is the time the job was created.
CreatedAt time.Time
// Requeued indicates that this start event moves or recovers an existing
// durable job payload rather than admitting a new dispatched job.
Requeued bool
// Worker is the worker that handles the job.
Worker *Worker
// NodeID is the ID of the node that created the job.
NodeID string
// contains filtered or unexported fields
}
Job is a job that can be added to a worker.
type JobHandler ¶
type JobHandler interface {
// Start accepts a job and returns after the handler has started its work.
// While that job remains accepted on this worker, repeated recovery
// deliveries with the same key and payload do not call Start again.
// Recovery after process loss may call Start on another worker, so
// external effects must still tolerate a replay.
// If intake stops before acceptance, Pulse leaves the delivery pending
// without calling Start. Start errors other than ErrRequeue remain
// terminal once their saved ownership and payload have been removed.
Start(job *Job) error
// Stop releases the accepted job before its key stops or moves. Pulse
// serializes Start and Stop calls for each worker. Close, RemoveWorker,
// and Shutdown wait for successful Stops regardless of recovery ownership.
// A failed Stop leaves the local job available for another stop attempt.
// A successful Stop is not repeated when saved-job cleanup needs a retry.
Stop(key string) error
}
JobHandler starts and stops jobs owned by a worker.
type JobParam ¶ added in v0.0.3
type JobParam struct {
// Key is the job key.
Key string
// Payload is the job payload.
Payload []byte
}
JobParam represents a job to start.
type JobPlan ¶ added in v0.0.3
type JobPlan struct {
// Jobs to start.
Start []*JobParam
// Job keys to stop.
Stop []string
// StopAll indicates that all jobs not in Jobs should be
// stopped. Stop is ignored if StopAll is true.
StopAll bool
}
JobPlan represents a list of jobs to start and job keys to stop.
type JobProducer ¶ added in v0.0.3
type JobProducer interface {
// Name returns the name of the producer. Schedule calls Plan on
// only one of the producers with identical names across all
// nodes.
Name() string
// Plan computes the list of jobs to start and job keys to stop.
// Returning ErrScheduleStop indicates that the recurring
// schedule should be stopped. Legacy Plan calls cannot be cancelled;
// implement ContextJobProducer when planning may block.
Plan() (*JobPlan, error)
}
JobComputeFunc is the function called by the scheduler to compute jobs. It returns the list of jobs to start and job keys to stop.
type MessageHandler ¶ added in v1.7.0
type MessageHandler interface {
// HandleMessage handles a keyed message.
HandleMessage(key string, payload []byte) error
}
MessageHandler handles keyed messages that are routed by the pool hash ring without requiring a running job with the same key. Returning ErrRequeue leaves the message pending for redelivery; any other error is terminal.
type Node ¶
Node is a pool of workers.
func AddNode ¶
func AddNode(ctx context.Context, poolName string, rdb *redis.Client, opts ...NodeOption) (_ *Node, resultErr error)
AddNode adds a new node to the pool with the given name and returns it. The node can be used to dispatch jobs and add new workers. A node also routes dispatched jobs to the proper worker and acks the corresponding events once the worker acks the job.
The options WithClientOnly can be used to create a node that can only be used to dispatch jobs. Such a node does not route or process jobs in the background.
func (*Node) AddWorker ¶
AddWorker adds a new worker to the pool and returns it. The worker starts processing jobs immediately. handler can optionally implement the NotificationHandler and MessageHandler interfaces to handle job-scoped notifications and hash-routed messages.
func (*Node) Close ¶
Close rejects new node work once local closure begins, stops workers, requeues their jobs, and detaches the node's Redis-owned resources. It does not close the caller-owned Redis client or stop workers in other nodes. Success requires Stop to have released every locally accepted job, even when another cleanup owner requeues the saved jobs or pool cleanup has already completed. A Stop failure retains failed jobs and leaves the node unclosed for another attempt. A distributed detach failure also leaves the node unclosed, so Close may be retried with a fresh context. If the preliminary cleanup-state read fails, Close still attempts ordinary local shutdown and cleanup, and returns the read error together with any shutdown error. This error path newly publishes local closure only after ordinary close succeeds. If another close operation has already closed the node, its existing state is preserved. The failed read itself establishes neither pool-wide cleanup completion nor shutdown. One of Shutdown or Close should be called before the node is garbage collected unless it is client-only.
func (*Node) DispatchJob ¶
DispatchJob dispatches a job to the worker in the pool that is assigned to the job key using consistent hashing. It returns: - nil if the job is successfully dispatched and started by a worker - ErrJobExists if a job with the same key already exists in the pool - an error returned by the worker's start handler if the job fails to start - an error if the pool is closed or if there's a failure in adding the job
The method blocks until one of the above conditions is met.
func (*Node) DispatchJobOnce ¶ added in v1.10.0
func (node *Node) DispatchJobOnce( ctx context.Context, dispatchID, key string, payload []byte, ) (string, error)
DispatchJobOnce atomically publishes one start event for dispatchID and waits for its worker result. Retrying the same dispatchID returns the same Redis event ID and never starts a duplicate handler.
func (*Node) DispatchMessage ¶ added in v1.7.0
DispatchMessage sends a keyed message to the worker currently assigned by the pool hash ring. Messages do not create job ownership and are intended for fire-and-forget work that should be load-balanced by key.
func (*Node) IsShutdown ¶
IsShutdown returns true if the pool is shutdown.
func (*Node) JobKeys ¶ added in v1.0.1
JobKeys returns the list of keys of the jobs running in the pool.
func (*Node) JobPayload ¶ added in v1.0.1
JobPayload returns the payload of the job with the given key. It returns: - (payload, true) if the job exists and has a payload - (nil, true) if the job exists but has an empty payload - (nil, false) if the job does not exist
func (*Node) NewTicker ¶ added in v0.0.3
func (node *Node) NewTicker(ctx context.Context, name string, d time.Duration, opts ...TickerOption) (*Ticker, error)
NewTicker returns a new Ticker that behaves similarly to time.Ticker, but instead delivers the current time on the channel to only one of the nodes that invoked NewTicker with the same name.
func (*Node) NotifyWorker ¶
NotifyWorker notifies the worker that currently owns the job with the given key.
func (*Node) PoolWorkers ¶ added in v1.0.1
PoolWorkers returns the list of workers running in the entire pool.
func (*Node) RemoveWorker ¶
RemoveWorker joins worker intake and waits for Stop to release every locally accepted job before removing the worker locally. Saved jobs are requeued by the worker or another cleanup owner. A Stop failure retains the worker and failed jobs so RemoveWorker can be retried.
func (*Node) Schedule ¶ added in v0.0.3
Schedule starts a distributed schedule. The shared ticker establishes per-producer ownership before every Plan call, including the initial call, so only one node computes or applies each transition. The node owns the schedule goroutine and ticker: caller cancellation stops this schedule, and Node.Close cancels and joins every remaining schedule before returning.
func (*Node) Shutdown ¶
Shutdown stops the pool workers gracefully across all nodes. It notifies all workers and waits until they are completed. Shutdown prevents the pool nodes from creating new workers and the pool workers from accepting new jobs. After successful Shutdown, the node object cannot be used anymore and should be discarded. A local Stop or saved-job cleanup failure leaves the node unclosed and available for another Shutdown attempt. Successful Stops are not repeated when saved-job cleanup fails. IsClosed describes local closure, which can finish before pool-wide cleanup. One of Shutdown or Close should be called before the node is garbage collected unless it is client-only.
type NodeOption ¶
type NodeOption func(*nodeOptions)
NodeOption is a worker creation option.
func WithAckGracePeriod ¶ added in v1.0.0
func WithAckGracePeriod(grace time.Duration) NodeOption
WithAckGracePeriod is the deprecated v1 name for WithRecoveryGrace. Deprecated: use WithRecoveryGrace.
func WithCleanupLease ¶ added in v1.10.0
func WithCleanupLease(lease time.Duration) NodeOption
WithCleanupLease sets the immutable Redis-time lease for takeover of interrupted pool-generation cleanup. Worker and node stale reaping use WithWorkerTTL instead.
func WithClientOnly ¶
func WithClientOnly() NodeOption
WithClientOnly sets the pool to be client only. A client-only pool only supports dispatching jobs to workers and does not start background goroutines to route jobs.
func WithDispatchResultRetention ¶ added in v1.10.0
func WithDispatchResultRetention(retention time.Duration) NodeOption
WithDispatchResultRetention sets how long a settled DispatchJobOnce record remains replayable. After expiry the dispatch ID may be admitted as new. The value is immutable for a pool generation and must exceed both DispatchTimeout and RecoveryGrace. The default is five minutes.
func WithDispatchTimeout ¶ added in v1.10.0
func WithDispatchTimeout(timeout time.Duration) NodeOption
WithDispatchTimeout sets how long DispatchJob waits for a definitive worker response. Timing out removes only the local waiter.
func WithJobSinkBlockDuration ¶
func WithJobSinkBlockDuration(d time.Duration) NodeOption
WithJobSinkBlockDuration sets the duration to block when reading from the job stream. The default is 5s. This option is mostly useful for testing.
func WithLogger ¶
func WithLogger(logger pulse.Logger) NodeOption
WithLogger sets the handler used to report temporary errors.
func WithMaxQueuedJobs ¶
func WithMaxQueuedJobs(max int) NodeOption
WithMaxQueuedJobs sets the maximum number of jobs that can be queued in the pool. The default is 1000.
func WithRecoveryGrace ¶ added in v1.10.0
func WithRecoveryGrace(grace time.Duration) NodeOption
WithRecoveryGrace sets the sink idle-recovery and orphan convergence grace.
func WithRequeueTimeout ¶ added in v1.10.0
func WithRequeueTimeout(timeout time.Duration) NodeOption
WithRequeueTimeout sets the timeout for one local worker's concurrent requeue handoff attempt during graceful removal or Close. It does not control remote stale-worker detection or cleanup ownership; those use WithWorkerTTL and a renewable Redis-time lease. The default is 2 minutes.
func WithWorkerShutdownTTL ¶
func WithWorkerShutdownTTL(ttl time.Duration) NodeOption
WithWorkerShutdownTTL is the deprecated v1 name for WithRequeueTimeout. Deprecated: use WithRequeueTimeout.
func WithWorkerTTL ¶
func WithWorkerTTL(ttl time.Duration) NodeOption
WithWorkerTTL sets the immutable pool-generation threshold for stale workers and nodes. Every node must configure the same value before joining. The default is 30s. A lower number causes more frequent keep-alive updates.
type NotificationHandler ¶
type NotificationHandler interface {
// HandleNotification handles a job-scoped notification.
HandleNotification(key string, payload []byte) error
}
NotificationHandler handles notifications for jobs owned by the worker.
type Ticker ¶ added in v0.0.3
Ticker represents a clock that periodically sends ticks to one of the pool nodes which created a ticker with the same name.
func (*Ticker) Close ¶ added in v1.4.4
func (t *Ticker) Close()
Close stops the ticker locally.
Close does not delete the shared ticker-map entry. Use Close when a node wants to stop processing ticks without affecting other nodes that may be participating in the same distributed ticker.
Close does not close the tick channel to avoid racing with concurrent receivers (matching time.Ticker semantics).
type TickerOption ¶ added in v0.0.3
type TickerOption func(*tickerOptions)
TickerOption is a worker creation option.
func WithTickerLogger ¶ added in v0.0.3
func WithTickerLogger(logger pulse.Logger) TickerOption
WithTickerLogger sets the handler used to report temporary errors.
type Worker ¶
type Worker struct {
// Unique worker ID
ID string
// Time worker was created.
CreatedAt time.Time
// contains filtered or unexported fields
}
Worker is a worker that handles jobs with a given payload type.





