Documentation
¶
Overview ¶
Package hourglass provides delayed jobs and cron for Go: durable truth in SQL, second-level fire precision from an in-process hierarchical time wheel. See README ("How it works") for the timing contract.
Index ¶
- Constants
- Variables
- func RegisterExecutorServer(srv *grpc.Server, es *executorServer)
- func ShardFor(id string) int
- type Clock
- type Cluster
- type Config
- type ExecAck
- type ExecRequest
- type ExecutorClient
- type Handle
- func (h *Handle) Cancel(ctx context.Context, id, reason string) error
- func (h *Handle) Close() error
- func (h *Handle) Eng() *engine
- func (h *Handle) Every(ctx context.Context, topic, spec string) (string, error)
- func (h *Handle) Get(ctx context.Context, id string) (*Job, error)
- func (h *Handle) ListDead(ctx context.Context, topic string, limit int) ([]Job, error)
- func (h *Handle) Ping(ctx context.Context) error
- func (h *Handle) Register(topic string, fn Handler)
- func (h *Handle) ReplayAllDead(ctx context.Context) (int, error)
- func (h *Handle) ReplayDead(ctx context.Context, id string) error
- func (h *Handle) Run(ctx context.Context)
- func (h *Handle) Stats(ctx context.Context) (*Stats, error)
- func (h *Handle) Submit(ctx context.Context, topic string, payload []byte, opts ...SubmitOption) (string, error)
- type Handler
- type Job
- type Node
- func (n *Node) AddShard(ctx context.Context, shard int) error
- func (n *Node) Cancel(ctx context.Context, id, reason string) error
- func (n *Node) Close() error
- func (n *Node) EnginesForTest() map[string]struct{}
- func (n *Node) Get(ctx context.Context, id string) (*Job, error)
- func (n *Node) Handover(ctx context.Context, shard int) error
- func (n *Node) KillForTest()
- func (n *Node) Register(topic string, h Handler)
- func (n *Node) Run(ctx context.Context)
- func (n *Node) Submit(ctx context.Context, topic string, payload []byte, opts ...SubmitOption) (string, error)
- type Receipt
- type ScanUnit
- type State
- type StateCount
- type Stats
- type Store
- type StoreExt
- type SubmitOption
Constants ¶
const DefaultShards = 256
DefaultShards is the fixed logical shard count (Redis Cluster precedent: fixed slot count written into the schema; scaling moves ownership, never recomputes placement).
Variables ¶
var ( ErrEmptyTopic = errors.New("hourglass: empty topic") ErrMissingDue = errors.New("hourglass: no due time (use At or Delay)") )
ErrEmptyTopic and ErrMissingDue are submit-time contract violations.
var ErrWheelFull = errors.New("hourglass: wheel at capacity")
ErrWheelFull is returned by Offer when the wheel is at capacity; the admission loop must release the surplus back to waiting.
Functions ¶
func RegisterExecutorServer ¶
RegisterExecutorServer registers the executor service on a gRPC server.
Types ¶
type Cluster ¶
type Cluster struct {
// contains filtered or unexported fields
}
Cluster drives one engine per owned shard over one store. This is the scheduling-plane scale-out unit of cluster mode: adding a process adds shard ownership, and each shard's admission loop and wheel run independently (share-nothing between shards).
Ownership (which process holds which shards) is the registry's job (etcd leases + epoch fencing — README, "How it works"); Cluster is the per-process executor of whatever ownership it is handed.
func (*Cluster) DropShard ¶
DropShard stops one shard's engine (graceful handoff step 1: the registry revokes ownership, the old owner drains).
func (*Cluster) KillForTest ¶
func (c *Cluster) KillForTest()
KillForTest stops every engine WITHOUT draining: unfired wheel entries are abandoned in the acquired state for the next owner to reclaim (hard-kill semantics; the process is gone, the rows remain).
type Config ¶
type Config struct {
MySQL string // mysql dsn, e.g. "user:pass@tcp(host:3306)/hourglass"
Etcd []string // etcd endpoints
Shards []int // shards this node will try to own (claim races decide)
LeaseTTL time.Duration // etcd lease ttl (default 15s)
Engine engineConfig // optional engine tuning (zero values take defaults)
}
Config configures a cluster node.
type ExecAck ¶
ExecAck answers one request. RescheduleAt (unix seconds, 0 = none) requeues the job — self-chaining reserved from day one.
type ExecRequest ¶
type ExecRequest struct {
FiredId string // receipt id: the ack identity (lesson #4)
JobId string
Topic string
Payload []byte
Attempt int
}
ExecRequest is one execution command pushed to a remote executor.
type ExecutorClient ¶
type ExecutorClient struct {
// contains filtered or unexported fields
}
ExecutorClient is the client side of the exec face.
func NewExecutorClient ¶
func NewExecutorClient(cc *grpc.ClientConn) *ExecutorClient
NewExecutorClient builds an exec client on a live connection.
func (*ExecutorClient) Exec ¶
func (c *ExecutorClient) Exec(ctx context.Context, req *ExecRequest) (*ExecAck, error)
Exec pushes one command.
type Handle ¶
type Handle struct {
// contains filtered or unexported fields
}
Handle is an hourglass engine bound to one store.
func OpenWithClock ¶
OpenWithClock is Open with an injected clock (deterministic tests, simulated time).
func (*Handle) Cancel ¶
Cancel revokes a job before its fire moment; the row persists as a receipt. Cancel after fire is rejected.
func (*Handle) Close ¶
Close stops the engine (workers, wheel, in-flight flushes) and releases the store.
func (*Handle) Eng ¶
func (h *Handle) Eng() *engine
Eng exposes the internal engine for package tests (CLI integration drives admission deterministically). Not part of the stable API.
func (*Handle) Every ¶
Every schedules a recurring job from a standard 5-field cron expression; the same job row reschedules after each completion.
func (*Handle) ListDead ¶
ListDead lists dead-lettered jobs, newest first, optionally filtered by topic, for `hourglass dlq ls`.
func (*Handle) ReplayAllDead ¶
ReplayAllDead requeues every dead job; returns the count.
func (*Handle) ReplayDead ¶
ReplayDead requeues one dead job: dead -> waiting, attempts reset, due = now. The engine's next admission picks it up.
func (*Handle) Run ¶
Run drives the engine until ctx is done: admission steps on a one- second cadence, wheel ticks between them. Blocks; run it in a goroutine.
type Handler ¶
Handler runs one job's business logic. Handlers must be idempotent: delivery is at-least-once.
type Job ¶
type Job struct {
ID string
Topic string
Payload []byte
Due time.Time
State State
Cron string // non-empty: recurring; reschedules on completion
// ScheduledAt is the pre-jitter time; Due is what the wheel obeys.
ScheduledAt time.Time
Attempts int // fires so far (including the current one)
MaxAttempts int // 1 = no retries; exhausted -> dead
Backoff time.Duration // delay before the next attempt
Shard int // shard key (hash placement, computed once at submit)
// CreatedAt is the submit time (persisted; used by stores).
CreatedAt time.Time
CancelReason string // set when State == canceled
}
Job is one durable delayed job.
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node is one process's membership in the scheduling fleet: the store, the shard registry, and one engine per owned shard. Adding a process adds shard ownership — that is the scale story.
func Join ¶
Join connects to MySQL and etcd, claims the configured shards (races decide ownership; unclaimed shards here are simply owned by peers), and returns a ready node. Call Run to drive scheduling.
func (*Node) AddShard ¶
AddShard claims one shard and starts its engine if the claim wins. A lost claim is not an error (a peer owns it).
func (*Node) Close ¶
Close hands nothing over (use Handover per shard for graceful exit) and releases everything.
func (*Node) EnginesForTest ¶
EnginesForTest exposes owned shard engines (bench tooling).
func (*Node) Handover ¶
Handover performs the graceful handoff ordering (lesson #12): the CALLER ensures the new owner is ready first; this node then stops admitting, drains its wheel (unfired entries return to waiting), and releases the shard. No in-flight job is lost; the new owner's misfire rescan re-admits what was drained.
func (*Node) KillForTest ¶
func (n *Node) KillForTest()
KillForTest simulates a hard kill: engines stop mid-flight (rows stay acquired) and the etcd session dies WITHOUT handover — leases expire and peers take over via reclaim. The node must not be used afterwards except Close.
type Receipt ¶
type Receipt struct {
ID string
JobID string
Kind string // fired | completed | dead | canceled
Attempt int
Error string
Reason string // cancel reason
At time.Time
}
Receipt is one durable execution-log row: every state transition of interest is a row the user can SELECT. "Did this side effect happen?" is a query on every deployment shape (README: Contracts).
type ScanUnit ¶
type ScanUnit string
ScanUnit is one unit of admission scanning: the whole table for SQLite, one partition for MySQL/TiDB.
type State ¶
type State string
State is the lifecycle state of a job.
const ( // Waiting: admitted by nobody yet; the quiet row. Waiting State = "waiting" // Acquired: CAS'd by an admission loop; held in the wheel. Acquired State = "acquired" // Fired: the wheel fired; handler dispatched. Fired State = "fired" // Completed: terminal success. Completed State = "completed" // Dead: terminal failure; dead-lettered. Dead State = "dead" // Canceled: revoked before fire; persists as a receipt. Canceled State = "canceled" )
type StateCount ¶
StateCount is one row of the by-state breakdown.
type Stats ¶
type Stats struct {
JobsByState []StateCount
TotalJobs int64
TotalReceipts int64
OldestTerminal time.Time // oldest terminal row still kept (retention age)
}
Stats is the store-level overview for `hourglass stats`.
type Store ¶
type Store interface {
Ping(ctx context.Context) error
Insert(ctx context.Context, j *Job) error
Get(ctx context.Context, id string) (*Job, error)
// Select waiting jobs in [from, to] ordered by due time, limit n.
Select(ctx context.Context, unit ScanUnit, from, to time.Time, n int) ([]Job, error)
// Acquire CAS's waiting -> acquired for exactly these ids, under
// this epoch; it returns only the winners, re-read from the store.
Acquire(ctx context.Context, unit ScanUnit, epoch uint64, ids []string) ([]Job, error)
// contains filtered or unexported methods
}
Store is the persistence seam: the database keeps the long horizon. SQLite implements one scan unit (embedded); MySQL/TiDB implement shard-scoped scans plus lease reclaim (cluster).
type StoreExt ¶
type StoreExt interface {
Store
Reclaim(ctx context.Context, unit ScanUnit, epoch uint64, ttl time.Duration) (int, error)
}
StoreExt is the cluster-only extension: lease-based reclaim (the shared database as arbiter; etcd only owns epochs).
type SubmitOption ¶
type SubmitOption func(*submitConfig)
SubmitOption mutates a job before it is persisted.
func Delay ¶
func Delay(d time.Duration) SubmitOption
Delay schedules the job relative to submit time.
func InShard ¶
func InShard(n int) SubmitOption
InShard forces the shard placement (tests, ops tooling; default is hash(id)).
func Jitter ¶
func Jitter(w time.Duration) SubmitOption
Jitter disperses the due time by rand(0, w), drawn once at submit and stored: hot minutes melt before they form (README). Default zero.
func Retries ¶
func Retries(n int) SubmitOption
Retries sets additional attempts after the first failure. Retries(2) = 3 total attempts. Default 0 (single attempt).
func RetryBackoff ¶
func RetryBackoff(d time.Duration) SubmitOption
RetryBackoff sets the delay before a failed attempt refires. Default 30s. The delay is constant; exponential growth is a v1.x knob.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
benchplot
command
benchplot renders SVG charts from hourglass-bench artifacts (bench-results/*.json).
|
benchplot renders SVG charts from hourglass-bench artifacts (bench-results/*.json). |
|
hourglass
command
|
|
|
hourglass-bench
command
|