pool

package
v1.11.1 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 26 Imported by: 2

README

Dedicated Worker Pool

The pool package builds on top of the Pulse rmap and streaming packages to provide scalable and reliable dedicated worker pools.

Overview

A dedicated worker pool uses a consistent hashing algorithm to route keyed work to workers. Durable jobs use the key to choose the worker that owns and executes the job. Keyed messages use the same hash ring for short-lived work without creating job ownership.

Workers can be added or removed from the pool dynamically. Jobs get automatically re-assigned to workers when the pool grows or shrinks. This makes it possible to implement auto-scaling solutions, for example based on queueing delays.

Pulse uses the Jump Consistent Hash algorithm to assign keys to workers, which provides a good balance between load balancing and worker assignment stability.

%%{init: {'themeVariables': { 'edgeLabelBackground': '#7A7A7A'}}}%%
flowchart LR
    A[Producer]
    subgraph Pool["<span style='margin: 0 10px;'>Routing Pool Node</span>"]
        Sink["Job Sink"]
    end
    subgraph Worker[Worker Pool Node]
        Reader
        B[Worker]
    end
    A-->|Job or Message + Key|Sink
    Sink-.->|Worker Event|Reader
    Reader-.->|Worker Event|B

    classDef userCode fill:#9A6D1F, stroke:#D9B871, stroke-width:2px, color:#FFF2CC;
    classDef pulse fill:#25503C, stroke:#5E8E71, stroke-width:2px, color:#D6E9C6;

    class A,B userCode;
    class Pool,Sink,Reader,Worker pulse;

    linkStyle 0 stroke:#DDDDDD,color:#DDDDDD,stroke-width:3px;
    linkStyle 1 stroke:#DDDDDD,color:#DDDDDD,stroke-width:3px;
    linkStyle 2 stroke:#DDDDDD,color:#DDDDDD,stroke-width:3px;

Usage

Job producer:

	rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
	node, err := pool.AddNode(ctx, "example", rdb, pool.WithClientOnly())
	if err != nil {
		panic(err)
	}
	if err := node.DispatchJob(ctx, "key", []byte("payload")); err != nil {
		panic(err)
	}

Worker:

	rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
	node, err := pool.AddNode(ctx, "example", rdb)
	if err != nil {
		panic(err)
	}
	handler := &JobHandler{}
	_, err := node.AddWorker(context.Background(), handler)
  if err != nil {
		panic(err)
	}

Job handler:

type JobHandler struct {
	// ...
}

// Pulse calls this method to start a job that was assigned to this worker.
func (h *JobHandler) Start(job *pool.Job) error {
	// ...
}

// Pulse calls this method to stop a job that was assigned to this worker.
func (h *JobHandler) Stop(key string) error {
	// ...
}

// Pulse calls this method when a message key hashes to this worker.
func (h *JobHandler) HandleMessage(key string, payload []byte) error {
	// ...
}

// Pulse calls this method when this worker owns the notified job key.
func (h *JobHandler) HandleNotification(key string, payload []byte) error {
	// ...
}
Creating A Pool

The function AddNode is used to create a new pool node. It takes as input a name, a Redis client and a set of options.

Pool AddNode

The AddNode function returns a new pool node and an error. The pool node should be closed when it is no longer needed (see below).

The options are used to configure the pool node. The following options are available:

  • WithClientOnly - specifies that this node will only be used to dispatch jobs to workers in other nodes, and will not run any workers itself.
  • WithLogger - sets the logger to be used by the pool node.
  • WithWorkerTTL - sets the worker time-to-live (TTL). This is the maximum duration a worker can go without sending a health check before it's considered inactive and removed from the pool. If a worker doesn't report its status within this time frame, it will be removed, allowing the pool to reassign its jobs to other active workers. It is immutable for the pool generation and every node, including client-only nodes, must configure the same value. The same Redis-time threshold governs stale workers and stale nodes. The default value is 30 seconds.
  • WithRequeueTimeout - bounds one local worker's concurrent requeue handoff attempt during graceful removal or Close. It does not govern remote takeover: WithWorkerTTL determines stale-worker liveness and Redis owns a renewable cleanup lease for each stale worker. Pulse cannot forcibly terminate application handler goroutines. The default is 2 minutes. WithWorkerShutdownTTL remains as a deprecated v1-compatible alias.
  • WithMaxQueuedJobs - sets the immutable generation-wide count of active job-key admissions. Admission fails with ErrPoolCapacity at the limit. The default is 1000.
  • WithDispatchTimeout - sets how long a caller waits for the worker result. Timeout removes only the local waiter; durable admission remains until a definitive worker completion. The default is 40 seconds.
  • WithDispatchResultRetention - sets the immutable generation-wide replay window for terminal DispatchJobOnce results. It must exceed both dispatch timeout and recovery grace. During this window, any node retrying the same dispatch ID and exact identity receives the original event ID and terminal outcome. After expiry that replay guarantee ends and the ID may be admitted as a new dispatch. The default is five minutes.
  • WithRecoveryGrace - sets sink stale recovery and orphan convergence grace. The default is 20 seconds. WithAckGracePeriod remains as a deprecated v1-compatible alias.
  • WithCleanupLease - sets the immutable durable pool-cleanup owner lease. Cleanup renews this Redis-time lease before each destructive generation-owned step; if the owner dies, another process may take over only after the lease is stale. It does not govern worker or node liveness. The default is 30 seconds.

DispatchJobOnce accepts a caller-owned, globally unique dispatch ID. One Lua operation stores its exact length-delimited job-key and payload identity, claims the separate job-key admission index, appends the untrimmed start event, and records its event ID. An exact retry returns that event ID or its original terminal outcome; reusing the ID with different bytes returns ErrDispatchConflict. Another active dispatch for the key returns ErrJobExists. Terminal settlement atomically persists the result, clears admission, acknowledges the consumer event, advances recovery, and deletes the settled event. Active dispatch records have no expiry. Settlement removes them from the active cleanup index and applies DispatchResultRetention to the per-dispatch terminal record, bounding replay memory. Callers on every node use local completion only as a wake-up hint and re-read that record after polling, notification, cancellation, and timeout edges. Once a handler returns, its node owns retrying settlement independently of worker intake cancellation. Worker removal and graceful node closure join those obligations and report an error while any remain pending. If the process dies first, the original pool event remains pending with its dispatch ID and active record; sink recovery may re-execute the handler under that same identity. Because a process can die after the handler's external side effect but before settlement, handlers must make those side effects idempotent or fence them with the dispatch identity. Pool events are never MAXLEN-trimmed while unsettled.

Schedulers acquire one renewable Redis-time owner for each due transition. That exact owner remains fenced across planning, start/apply/stop work, authoritative ownership scans, and canonical next-time commit; no later tick can be claimed while the transition remains live. Each job first receives one persisted scheduler dispatch ID and is then admitted through the same owner fence. A foreign ErrJobExists never proves scheduler ownership. Stop and StopAll publish a stop only when both the transition lease and exact scheduler dispatch capability remain current, so ordinary jobs and jobs owned by another schedule are untouched. The v1 JobProducer.Plan() contract remains supported and is inherently non-cancellable. Producers whose planning may block should also implement ContextJobProducer.PlanContext(ctx); the scheduler prefers that method, and Node.Close cancels and joins it.

StopJob durably publishes a stop request and returns after Redis accepts that request. It does not mean the current handler has already completed; observe worker/job state when completion matters.

Quiescent upgrades

This is a persisted pool-format cutover, not a Go API major-version migration; the v1 producer interface and deprecated option aliases remain source compatible.

The generation/resource and dispatch wire formats do not support mixed versions. Upgrade a pool by: (1) stop every producer, client-only node, routing node, worker, and scheduler; (2) verify every flat map listed below contains no user entries, discover and check legacy per-producer scheduler maps, and verify the flat pool stream has no entries or groups; (3) deploy the new version everywhere; (4) start one node and verify its resource manifest has format_version=7, generation-qualified scheduler resources, and the intended max_queued_jobs, worker_ttl_ms, cleanup_lease_ms, and dispatch_result_retention_ms; then (5) resume the remaining nodes and producers. The first upgraded node refuses to adopt manifestless legacy resources while any actual flat resource proves a writer may still be active, returning ErrQuiescenceRequired.

For a pool named $POOL, inspect the exact standalone-Redis evidence before deploying. Every map below must contain no fields except rmap metadata (=rev/=kind), and both stream commands must report no retained work or consumer groups:

redis-cli HGETALL "map:${POOL}:node-keepalive:content"
redis-cli HGETALL "map:${POOL}:shutdown:content"
redis-cli HGETALL "map:${POOL}:workers:content"
redis-cli HGETALL "map:${POOL}:worker-keepalive:content"
redis-cli HGETALL "map:${POOL}:worker-cleanup:content"
redis-cli HGETALL "map:${POOL}:jobs:content"
redis-cli HGETALL "map:${POOL}:pending-jobs:content"
redis-cli HGETALL "map:${POOL}:dispatches:content"
redis-cli HGETALL "map:${POOL}:job-payloads:content"
redis-cli HGETALL "map:${POOL}:tickers:content"
redis-cli HGETALL "map:${POOL}:scheduler-jobs:content"
redis-cli --scan --pattern "map:${POOL}:*:content"
redis-cli XLEN "pulse:stream:${POOL}:pool"
redis-cli XINFO GROUPS "pulse:stream:${POOL}:pool"
redis-cli --scan --pattern "pulse:stream:${POOL}:node:*"

Inspect every key returned by the scheduler-map scan; legacy versions created dynamic map:${POOL}:<producer>:content hashes. Any non-metadata field requires the old writer to be stopped before upgrade. Once all listed evidence proves quiescence, first adoption may delete orphaned bare pulse:stream:${POOL}:node:<node-id> streams that have no lifecycle record. This store-owned upgrade cleanup is not part of normal Stream.Destroy.

After the first upgraded node starts, verify the selected generation contract with redis-cli HGETALL "pulse:pool:${POOL}:resources".

Rollback requires the same stop-all-users boundary. Do not start an older binary against a manifest already marked format 7; restore Redis from the pre-upgrade snapshot or complete cleanup and create a fresh pool generation before starting the older version.

Closing A Node

The Close method closes the pool node and releases all resources associated with it. It should be called when the node is no longer needed. Closing is an admission stop: once local closure begins, the node rejects new workers, job or message dispatches, stop requests, and notifications while already admitted operations finish. A job delivery that reaches a stopped worker before handler acceptance stays pending for routing to another worker; Pulse does not call that handler or report a terminal failure.

Successful Close waits for JobHandler.Stop to release every locally accepted job. This local obligation does not depend on which node owns job requeue, and still applies after distributed pool cleanup has completed. Pulse retains saved job records for requeue even after local handlers stop. If another cleanup owner holds the requeue lease, closing leaves those records for that owner to finish. A failed Stop is returned as an error, leaves the node unclosed, and retains the failed local jobs for a later Close attempt. Pulse cannot forcibly stop application goroutines; handlers must release their work before returning success from Stop.

If the preliminary Redis cleanup-state read fails, Close still attempts the ordinary local shutdown and cleanup before returning that read error together with any shutdown error. New work is rejected at the existing local closure transition, not while the preliminary read is still pending. Failed Stops and unfinished cleanup remain available for another attempt; successful Stops are not repeated. 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.

Pool Close

Note that closing a pool node does not stop remote workers. It only stops the local pool node. Remote workers can be stopped by calling the Shutdown method described below.

Shutting Down A Pool

The Shutdown method shuts down the entire pool by stopping all its workers gracefully. It should be called when the pool is no longer needed. Shutdown publishes one Redis-owned obligation even when a local Close is concurrent. Each worker joins intake and releases its locally accepted handlers in one Stop phase. Node cleanup then reads the saved worker job list directly from storage, deletes its payloads, and removes the worker records without requeuing jobs. A failed Stop or saved-job cleanup returns an error and leaves local closure unfinished for another Shutdown attempt. Failed Stops remain locally visible; saved worker records remain available until payload cleanup succeeds. Successful Stops are not repeated because storage cleanup needs a retry. IsClosed reports local node closure, which may finish before the pool-wide shutdown completes. After every live node detaches, final cleanup is owned by a persisted owner-and-lease claim based on Redis time. Another process can reclaim an expired claim and finish cleanup, so an interrupted shutdown cannot permanently block reuse of the pool name. Successful cleanup compacts the claim to one bounded generation completion marker. Every destructive stream or map mutation atomically verifies the exact cleanup generation, owner, and unexpired lease; a paused former owner cannot delete resources created after takeover and pool reuse.

Stale worker and node takeover use the same rule at a narrower scope. One Lua operation reads the authoritative heartbeat, compares it with immutable WorkerTTL using Redis time, and installs an exact owner/fence. Heartbeat scripts reject that fence, and every mutation a resumed stale process could attempt re-verifies liveness at its own Redis linearization point: a worker start claim re-checks the worker's registration and cleanup fence, and job dispatch plus every scheduler transition and ownership script re-check the node's keep-alive registration and node-cleanup field. Graceful shutdown and stale-worker takeover share one requeue lease: a stopping worker self-acquires it (atomically deactivating its registration) and republishes through the same lease-fenced stable publication records the cleanup owner uses, so exactly one party requeues each job and an interrupted graceful requeue is finished by takeover after lease expiry. Requeue, dispatch-release, stream destruction, and discovery removal verify the same unexpired owner token.

The pool stream generation selects every shared map and stream as one immutable resource manifest. The first deployment seen by this version adopts existing flat names without migration. After explicit shutdown cleanup, the next generation uses qualified names. A paused stale node therefore retains access only to its old keepalive, worker, job, ticker, scheduler, dispatch-record, and stream resources and cannot mutate a reused pool. Every node-owned map mutation also checks that exact stream generation inside the same Redis operation, preventing a paused stale node from recreating an old map key after cleanup.

Pool Shutdown

See the Data Flows section below for more details on the shutdown process.

Creating A Worker

The function AddWorker is used to create a new worker. It takes as input a job handler object.

Worker AddWorker

The job handler must implement the Start and Stop methods used to start and stop durable jobs. The handler may also implement HandleMessage to receive keyed messages and HandleNotification to receive job-scoped notifications.

Worker JobHandler

The AddWorker function returns a new worker and an error. Workers can be removed from pool nodes using the RemoveWorker method.

Successful RemoveWorker joins worker intake and waits for Stop to release every accepted local job before removing the worker locally. Saved jobs remain available for requeue by this worker or another cleanup owner. A failed Stop retains the worker and failed local jobs so removal can be retried.

Dispatching A Job

The DispatchJob method is used to dispatch a new job to the pool. It takes as input a job key and a job payload.

Pool DispatchJob

The job key is used to route the job to the proper worker. If the worker starts the job successfully, the worker owns that key until the job stops or moves during rebalancing. The job payload is passed to the worker's Start method. Repeated recovery deliveries of the same key and exact payload bytes to that worker acknowledge the accepted job without calling Start again. A conflicting payload is rejected without changing the running handler, its ownership, or its stored payload. Exact dispatch retries still validate their original key and payload against the durable dispatch record. Recovery also restores missing ownership or payload entries from the accepted job, after atomically verifying that no other worker, pending dispatch, or different payload occupies the key. A failed repair leaves the running handler intact and never runs failed-start cleanup. These checks run in the same local critical section as starts, stops, and rebalancing; a recovery delivery waiting through a move is routed to the current worker before it can start again.

Pulse establishes the durable dispatch record in the same operation that publishes the start event, so even an immediate worker acknowledgement cannot outrun correlation. Concurrent local retries share one broadcast completion signal. If a caller cancels or times out while completion is unknown, Pulse retains job-key admission and removes only that caller's wait. Definitive worker acknowledgement persists the terminal record and releases admission even if the caller or dispatching process is gone. Job keys are reusable command identities: while a start is pending or the job is running, duplicates return ErrJobExists; after definitive completion and a later stop removes ownership, the same key may be dispatched again. DispatchJob also returns errors for invalid keys, duplicate active/pending jobs, and worker start failures.

If a worker's Start handler fails, Pulse atomically removes that worker's ownership and the durable payload before it publishes the failure acknowledgement or releases singleton admission. A Redis failure during this cleanup leaves the start event pending for retry; it is never reported as complete with orphaned ownership or payload.

Dispatching A Message

The DispatchMessage method sends a keyed, fire-and-forget message to the worker currently assigned by the pool hash ring. Messages are the right primitive for short-lived work that needs stable key-based routing but must not create a durable job.

Pool streams are poison-message tolerant: malformed external binary envelopes, jobs, acknowledgements, and keyed payloads are logged and acknowledged as terminal malformed input. Routing and worker loops continue processing later valid events.

Messages do not write job payloads and do not require any worker to own a job with the same key. The receiving worker must implement HandleMessage. A message handler can return ErrRequeue to leave the message pending for redelivery; any other error is treated as terminal.

Notifications

Nodes can send notifications to workers using the NotifyWorker method. A notification is a job control event: it targets the worker that currently owns an existing job key and passes the notification payload to that worker's HandleNotification method.

Use NotifyWorker when the message only makes sense for the active owner of an existing job. Use DispatchMessage when there is no durable job with the same key.

Stopping A Job

The StopJob method is used to stop a job. It takes a job key as input and returns an error if the job could not be stopped. This can happen if the job key is invalid, the node is closed or the pool shutdown.

Scheduling

The Schedule method of the Node struct can be used to schedule jobs to be dispatched or stopped on a recurring basis. The method takes as input a job producer and invokes it at the specified interval. The job producer returns a list of jobs to be started and stopped.

The producer's shared ticker establishes distributed ownership before the initial Plan and every later transition, so same-name producers on different nodes do not plan concurrently. Applied job ownership is canonical in the generation-qualified scheduler map. Planning, dispatch, stop, and ownership-map failures return to the tick owner and are retried on a later owned transition; they are never treated as successful progress. Scheduler intervals use millisecond precision and must be at least one millisecond.

Schedule makes it possible to maintain a pool of jobs for example in a multi-tenant system. See the examples for more details.

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

Constants

This section is empty.

Variables

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

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

type Node struct {
	ID       string
	PoolName string
	// contains filtered or unexported fields
}

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

func (node *Node) AddWorker(ctx context.Context, handler JobHandler) (*Worker, error)

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

func (node *Node) Close(ctx context.Context) error

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

func (node *Node) DispatchJob(ctx context.Context, key string, payload []byte) error

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

func (node *Node) DispatchMessage(ctx context.Context, key string, payload []byte) error

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

func (node *Node) IsClosed() bool

IsClosed returns true if the node is closed.

func (*Node) IsShutdown

func (node *Node) IsShutdown() bool

IsShutdown returns true if the pool is shutdown.

func (*Node) JobKeys added in v1.0.1

func (node *Node) JobKeys() []string

JobKeys returns the list of keys of the jobs running in the pool.

func (*Node) JobPayload added in v1.0.1

func (node *Node) JobPayload(key string) ([]byte, bool)

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

func (node *Node) NotifyWorker(ctx context.Context, key string, payload []byte) error

NotifyWorker notifies the worker that currently owns the job with the given key.

func (*Node) PoolWorkers added in v1.0.1

func (node *Node) PoolWorkers() []*Worker

PoolWorkers returns the list of workers running in the entire pool.

func (*Node) RemoveWorker

func (node *Node) RemoveWorker(ctx context.Context, w *Worker) error

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

func (node *Node) Schedule(ctx context.Context, producer JobProducer, interval time.Duration) error

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

func (node *Node) Shutdown(ctx context.Context) error

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.

func (*Node) StopJob

func (node *Node) StopJob(ctx context.Context, key string) error

StopJob durably publishes a stop request for the job with the given key. Success means Redis accepted the request, not that the handler has completed.

func (*Node) Workers

func (node *Node) Workers() []*Worker

Workers returns the list of workers running in the local node.

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

type Ticker struct {
	C <-chan time.Time
	// contains filtered or unexported fields
}

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

func (*Ticker) Stop added in v0.0.3

func (t *Ticker) Stop()

Stop turns off a ticker. After Stop, no more ticks will be sent. Stop does not close the channel, to prevent a concurrent goroutine reading from the channel from seeing an erroneous "tick".

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.

func (*Worker) IsStopped added in v1.0.5

func (w *Worker) IsStopped() bool

IsStopped reports whether worker intake has stopped accepting deliveries. Accepted handlers may still be stopping or waiting for a failed Stop to retry.

func (*Worker) Jobs

func (w *Worker) Jobs() []*Job

Jobs returns the jobs handled by the worker.

Jump to

Keyboard shortcuts

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