coord

package
v0.30.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 6 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package coord is cross-pod coordination for app components over a shared store. A Notifier publishes rare transitions; a Watcher keeps a local copy of a changed-set current by push, with a version watermark bounding a lost message; a Ticker, an optional helper for components that sync local state on a schedule, sends every participant's commands in one pipeline per beat, keeps the failure clock and counts live processes.

Out of scope: what the commands mean (breakers, cooldowns and their key formats belong to the components), scripts and multi-key atomicity, and the store client itself (callers implement Store). It is not part of package engine and imports only the standard library.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Batch

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

Batch collects a beat's commands: participants append, the ticker sends them all in one pipeline.

func (*Batch) Add

func (b *Batch) Add(c Cmd)

Add appends one command to this beat's pipeline.

type Cmd

type Cmd struct {
	Op    Op
	Key   string
	Args  [2]int64
	Value []byte
	Reply func(Reply)
}

Cmd is one pipelined command. Reply receives the answer; nil Reply discards it.

type Notifier

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

Notifier is pub/sub with a bounded outbound queue: Publish never blocks, a full queue or a failed send drops the message and counts it. Transitions publish here; a Watcher's watermark bounds what a lost message costs.

func NewNotifier

func NewNotifier(s Store, queue int, timeout time.Duration, onDrop func()) *Notifier

NewNotifier returns a notifier holding at most queue unsent messages. timeout bounds each send (0 means one second), so a hung store drops messages instead of stalling the queue. onDrop, when set, is called once per dropped message.

func (*Notifier) Publish

func (n *Notifier) Publish(topic string, payload []byte)

Publish queues payload for topic; never blocks.

func (*Notifier) Subscribe

func (n *Notifier) Subscribe(ctx context.Context, topic string, fn func([]byte)) error

Subscribe delivers topic's payloads to fn until ctx ends.

type Op

type Op uint8

Op enumerates the store commands the tick and watchers use: plain single-key commands, no scripts. Kept narrow because every Op widens what each Store implementation must support.

const (
	OpIncrBy           Op = iota + 1 // Key, Args[0] delta → Int
	OpGet                            // Key → Bytes (nil when missing)
	OpSet                            // Key, Value, Args[1] ttl ms (0 = none)
	OpPExpire                        // Key, Args[1] ttl ms
	OpZAdd                           // Key, Args[0] score, Value member
	OpZCount                         // Key, Args[0] min, Args[1] max → Int
	OpZRangeByScore                  // Key, Args[0] min, Args[1] max → List members, Int highest score among them
	OpZRemRangeByScore               // Key, Args[0] min, Args[1] max
)

type Participant

type Participant interface {
	Collect(t Tick, b *Batch)
}

Participant is one component's sync adapter. Collect runs on the tick goroutine, appends the commands for entries due now with Reply closures that apply the store's answer, and must not block.

type Reply

type Reply struct {
	Int   int64
	Bytes []byte
	List  [][]byte
	Err   error
}

Reply is one command's answer.

type Status

type Status struct {
	LastGood  time.Time
	Outage    bool // past Grace with no good beat
	LivePods  int  // from presence at the last good beat; 1 without presence
	LastDelay time.Duration
}

Status is the failure model participants read at decision time.

type Store

type Store interface {
	// Pipeline sends cmds in one round trip and calls each Reply in order
	// before returning; a per-command failure goes in Reply.Err. A returned
	// error means the round trip failed and Replies may not have run.
	Pipeline(ctx context.Context, cmds []Cmd) error
	// Publish sends payload to channel's subscribers and returns once ctx ends at the latest.
	Publish(ctx context.Context, channel string, payload []byte) error
	// Subscribe delivers payloads to fn until ctx ends or stop is called, reconnecting internally. Payloads published while disconnected are lost without a signal; a Watcher's watermark re-list recovers them. err reports only a failed initial subscribe.
	Subscribe(ctx context.Context, channel string, fn func([]byte)) (stop func(), err error)
}

Store is everything coord needs from the backing store: one ordered pipeline round trip and pub/sub.

type Tick

type Tick struct {
	N   uint64
	Now time.Time
}

Tick is one scheduler beat. N increases by one per beat; a participant syncs an entry when N is a multiple of the entry's period in beats. The final beat Close sends has N = 0, which makes every entry due.

type Ticker

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

Ticker drives the beat, sends the pipeline, keeps the failure clock and writes presence. One per process.

func NewTicker

func NewTicker(s Store, o TickerOptions) *Ticker

NewTicker returns a ticker over s; Register participants, then Run.

func (*Ticker) Close

func (t *Ticker) Close() error

Close stops Run, then collects once more and sends with a 2 s deadline, so a shutdown loses nothing counted.

func (*Ticker) Register

func (t *Ticker) Register(p Participant)

Register adds a participant; before Run.

func (*Ticker) Run

func (t *Ticker) Run(ctx context.Context) error

Run beats every MinPeriod until ctx ends or Close is called; one goroutine.

func (*Ticker) Status

func (t *Ticker) Status() Status

Status reports the failure model; safe from any goroutine.

type TickerHooks

type TickerHooks struct {
	OnTick    func(cmds int, dur time.Duration, err error)
	OnLag     func(lag time.Duration) // a beat that failed by lag alone or with an error
	OnOutage  func(since time.Time)   // first failed beat past Grace; since = last good beat
	OnRecover func(down time.Duration)
}

TickerHooks are the observation points; every field is optional.

type TickerOptions

type TickerOptions struct {
	MinPeriod time.Duration // beat period, default 50 ms
	Grace     time.Duration // failed beats tolerated before Outage, default 1 s
	// LagFailAfter is the beat lag past which a beat counts as failed for the
	// grace clock; default 4 × MinPeriod.
	LagFailAfter time.Duration
	// PodID, PresenceKey and PresenceTTL make every beat write this process
	// into a sorted set and count live processes for Status.LivePods; an
	// empty PodID disables presence (LivePods = 1). PresenceTTL defaults to
	// 2 × Grace.
	PodID       string
	PresenceKey string
	PresenceTTL time.Duration
	Hooks       TickerHooks
}

TickerOptions configures a Ticker; zero durations take the defaults.

type WatchOptions

type WatchOptions struct {
	Key       string // the sorted set of member → version, hash-tagged
	Topic     string // pub/sub channel carrying member ids; empty = poll only
	Every     time.Duration
	FullEvery time.Duration // 0 = never after the first list
	Apply     func(members [][]byte)
	Full      func(members [][]byte) // nil = Apply
}

WatchOptions configures one Watcher.

type Watcher

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

Watcher is list-then-watch over one changed-set: it lists the whole set once, applies pushes at once, re-lists the members above the highest version it has seen every Every, and the whole set every FullEvery. Apply and Full run on the Run goroutine only.

func NewWatcher

func NewWatcher(s Store, n *Notifier, o WatchOptions) *Watcher

NewWatcher returns a watcher; n may be nil for poll-only.

func (*Watcher) Run

func (w *Watcher) Run(ctx context.Context) error

Run watches until ctx ends. It subscribes before the first list, so a change between the two is seen at least once.

Jump to

Keyboard shortcuts

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