coordination

package
v0.0.0-...-738f650 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: AGPL-3.0 Imports: 11 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 coordination distributes ingestion work across worker processes.

Index

Constants

View Source
const AcquireRetryInterval = HeartbeatInterval
View Source
const (
	// CursorBucketName is exported so plugins can name the bucket in their logs
	// without keeping a copy of the string.
	CursorBucketName = "ingest_cursors"
)
View Source
const HeartbeatInterval = LeaseTTL / 3
View Source
const (
	// LeaseBucketName is exported so plugins can name the bucket in their logs
	// without keeping a copy of the string.
	// Keys are prefixed with the plugin name, e.g. "aws.<tenantId>/<group>".
	LeaseBucketName = "ingest_leases"
)
View Source
const LeaseTTL = bucketTTL

Must stay defined as bucketTTL: that is the TTL the server enforces.

View Source
const SchedulerLeaseTTL = schedulerBucketTTL

Only covers one tick's publish; it expires before the next, unrenewed.

Variables

View Source
var ErrCursorConflict = errors.New("cursor: revision stale, another writer saved since Load")
View Source
var ErrCursorNotFound = errors.New("cursor: key has no persisted value yet")

Callers must treat this as "seed from now", never "seed from epoch".

View Source
var ErrCursorTooLarge = errors.New("cursor: payload exceeds the transport's maximum message size")

Save exceeded the transport's max message payload: 1,048,576 bytes on the deployed nats:2.10-alpine v2.10.29 server. It will fail identically on retry.

View Source
var ErrFenced = errors.New("lease fenced: revision stale, another holder took over")
View Source
var ErrHeld = errors.New("lease already held by a live owner")
View Source
var ErrMissingActivateWork = errors.New("coordination: ConsumeAndAdvanceCursor: first activation occurred but ConsumeWork.Activate is nil")
View Source
var ErrMissingResumeWork = errors.New("coordination: ConsumeAndAdvanceCursor: a cursor already exists for this key but ConsumeWork.Resume is nil")
View Source
var ErrNoJobs = errors.New("queue: no job available within the fetch window")

A normal idle result, never a failure. JetStream reports an expired pull with nats.ErrTimeout, the same error a network partition produces.

Functions

func ConnectJetStream

func ConnectJetStream(ctx context.Context, connName string) (jetstream.JetStream, *nats.Conn, error)

ConnectJetStream dials NATS_URL. The caller owns the returned *nats.Conn and must Close it. connName identifies this plugin to the server.

func ConsumeAndAdvanceCursor

func ConsumeAndAdvanceCursor(
	ctx context.Context,
	cursors CursorStore,
	delivery JobDelivery,
	cursorKey string,
	work ConsumeWork,
) error

Failures without a cursor are neither Saved nor Acked, so AckWait drives redelivery; a failure with a returned cursor (partial progress) is Saved and Acked so one slow source cannot hammer the same window. On ErrCursorConflict the write is dropped but the job is Acked anyway: the work already published.

func DialLeasePath

func DialLeasePath(connName string) func(ctx context.Context) (LeasePath, error)

func DialQueuePath

func DialQueuePath(connName, plugin string) func(ctx context.Context) (QueuePath, error)

func LoadCursorInto

func LoadCursorInto[T any](ctx context.Context, cursors CursorStore, key string, dst *T) (uint64, bool, error)

An absent cursor returns found=false, no error, dst untouched: callers must treat that as "seed from now". A decode failure still returns the stored revision, or the next Save means "create" on a live key and fails forever.

func MarshalCursorPayload

func MarshalCursorPayload(v any, encryptionKey string) ([]byte, error)

NATS has neither auth nor TLS here. Jobs stay unencrypted: their subject already carries tenant and group for routing.

func NatsToken

func NatsToken(name string) string

NatsToken encodes an arbitrary caller-supplied name for use as a NATS KV key or subject token. base64url (no padding) is injective and its alphabet stays within both charsets, so distinct names never share a key.

func PublishJobsIfElected

func PublishJobsIfElected(
	ctx context.Context,
	scheduler Store,
	publisher JobPublisher,
	leaseKey string,
	holder string,
	jobs []Job,
	onError func(job Job, err error),
)

Any acquire failure is a silent no-op; a second publisher would only duplicate jobs. A Publish failure must not abort the rest of the tick.

func RenewAndPersistCursor

func RenewAndPersistCursor(
	ctx context.Context, store Store, cursors CursorStore,
	l Lease, ttl time.Duration,
	cursorKey string, cursorData []byte, cursorRev uint64,
) (Lease, Cursor, error)

The only sanctioned lease-path cursor write: Renew first, Save only if it succeeded, so a holder whose lease was taken over cannot reach Save.

func RunJobConsumer

func RunJobConsumer(
	ctx context.Context,
	consumer JobConsumer,
	handle func(ctx context.Context, delivery JobDelivery) error,
	onError func(err error),
)

No error ends the loop: one group's transient failure must not stop ingestion for the rest. ErrNoJobs and cancellation never reach onError.

func SchedulerLeaseKey

func SchedulerLeaseKey(plugin string) string

The plugin namespace is load-bearing: every queue-path plugin shares one bucket, so an unnamespaced key would elect one publisher across all of them.

func SetupWithRetry

func SetupWithRetry[T any](ctx context.Context, dial func(ctx context.Context) (T, error), retryDelay time.Duration, onFailure func(err error)) (T, error)

Must never fall back to proceeding without a successful dial. nats.MaxReconnects(-1) only protects an already-established connection, and `docker stack deploy` ignores depends_on, so NATS may be down at startup.

func UnmarshalCursorPayload

func UnmarshalCursorPayload[T any](data []byte, encryptionKey string) (T, error)

Cursors written before a key was configured stay readable: Decrypt passes already-plaintext input through unchanged.

Types

type Clock

type Clock interface {
	Now() time.Time
}

type ConsumeWork

type ConsumeWork struct {
	Resume func(ctx context.Context, job Job, cur Cursor) (next []byte, err error)

	// Called instead of Resume on first activation. The position it returns
	// must be seeded from "now", or the source's history is replayed whole.
	Activate func(ctx context.Context, job Job) (next []byte, err error)
}

type Cursor

type Cursor struct {
	Data []byte
	// CAS token in CursorStore, unrelated to Lease.Revision.
	Revision uint64
}

type CursorSnapshot

type CursorSnapshot func() ([]byte, error)

Must read the caller's live position; a captured payload never advances.

type CursorStore

type CursorStore interface {
	Load(ctx context.Context, key string) (Cursor, error)

	// CAS write. c.Revision == 0 means "create" and fails if key exists; any
	// other value means "update only if still current".
	Save(ctx context.Context, key string, c Cursor) (Cursor, error)
}

type Heartbeat

type Heartbeat struct {
	Leases  Store
	Cursors CursorStore

	// One key for both lease and cursor, so a successor finds the position.
	Key string

	Snapshot CursorSnapshot

	TTL time.Duration

	Interval time.Duration

	// Must be the same CancelFunc that stops the unit for any other reason:
	// refusing new work leaves a feed socket held open for hours.
	Cancel context.CancelFunc

	OnError func(error)
}

func (Heartbeat) Run

func (h Heartbeat) Run(ctx context.Context, lease Lease, cursorRev uint64)

func (Heartbeat) Tick

func (h Heartbeat) Tick(ctx context.Context, lease Lease, cursorRev uint64) (Lease, uint64, error)

The caller carries the returned lease and revision into the next tick. On ErrFenced both are zero and the unit must stop; otherwise the lease is held.

type Job

type Job struct {
	TenantID    string    `json:"tenantId"`
	GroupName   string    `json:"groupName"`
	WindowStart time.Time `json:"windowStart"`
	WindowEnd   time.Time `json:"windowEnd"`
}

WindowStart and WindowEnd are a hint only: the consumer's authoritative position is CursorStore.Load, so they matter only on a first activation.

type JobConsumer

type JobConsumer interface {
	Fetch(ctx context.Context) (JobDelivery, error)
}

A job exceeding MaxDeliver is dropped by JetStream with no signal and no dead-letter subject. No DLQ is needed: a failed job never advanced the cursor, so the next tick republishes the group and retries the same window.

type JobDelivery

type JobDelivery struct {
	Job Job

	// 1 on first delivery, incremented on every redelivery.
	NumDelivered uint64

	Ack func() error

	// Requests immediate redelivery rather than waiting out AckWait.
	Nak func() error
}

Exactly one of Ack or Nak must eventually be called.

type JobPublisher

type JobPublisher interface {
	Publish(ctx context.Context, job Job) error
}

type Lease

type Lease struct {
	// Opaque and precomputed; Store implementations never parse it.
	Key string
	// The worker process that owns this lease.
	Holder string
	// Fencing token: increases on every Acquire or Renew, so a stale Lease
	// loses any later CAS.
	Revision uint64
	// When this lease becomes eligible for another Acquire.
	ExpiresAt time.Time
}

No position field: this bucket's TTL deletes the key, and failover happens by that expiry, so a position here would die exactly when a successor needed it.

func AcquireWithRetry

func AcquireWithRetry(
	ctx context.Context, store Store,
	key, holder string,
	ttl, retryInterval time.Duration,
	onError func(error),
) (Lease, error)

No error ends the loop: giving up would leave the unit ingested by nobody. ErrHeld never reaches onError; a contended key is the expected steady state.

type LeasePath

type LeasePath struct {
	Leases  Store
	Cursors CursorStore

	// Only non-nil on a successful setup.
	Close func()
}

func SetupLeasePath

func SetupLeasePath(ctx context.Context, b LeasePathBuild) (LeasePath, error)

Atomic. Callers retry forever, so a connection left open on a late failure would leak one per attempt, and a partial LeasePath would ingest unowned.

type LeasePathBuild

type LeasePathBuild struct {
	Connect        func(ctx context.Context) (jetstream.JetStream, NATSCloser, error)
	NewLeaseStore  func(ctx context.Context, js jetstream.JetStream, clock Clock) (Store, error)
	NewCursorStore func(ctx context.Context, js jetstream.JetStream) (CursorStore, error)
}

func DefaultLeasePathBuild

func DefaultLeasePathBuild(connName string) LeasePathBuild

type NATSCloser

type NATSCloser interface {
	Close()
}

type NATSCursorStore

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

Backed by a bucket with no TTL. The lease bucket expires by deleting its keys, and position must survive exactly that moment.

func NewNATSCursorStore

func NewNATSCursorStore(ctx context.Context, js jetstream.JetStream) (*NATSCursorStore, error)

func (*NATSCursorStore) Load

func (s *NATSCursorStore) Load(ctx context.Context, key string) (Cursor, error)

func (*NATSCursorStore) Save

func (s *NATSCursorStore) Save(ctx context.Context, key string, c Cursor) (Cursor, error)

type NATSJobConsumer

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

func NewNATSJobConsumer

func NewNATSJobConsumer(ctx context.Context, js jetstream.JetStream, plugin string) (*NATSJobConsumer, error)

func NewNATSJobConsumerWithConfig

func NewNATSJobConsumerWithConfig(ctx context.Context, js jetstream.JetStream, plugin string, ackWait time.Duration, maxDeliver int) (*NATSJobConsumer, error)

func (*NATSJobConsumer) Fetch

func (c *NATSJobConsumer) Fetch(ctx context.Context) (JobDelivery, error)

type NATSJobPublisher

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

func NewNATSJobPublisher

func NewNATSJobPublisher(ctx context.Context, js jetstream.JetStream, plugin string) (*NATSJobPublisher, error)

func (*NATSJobPublisher) Publish

func (p *NATSJobPublisher) Publish(ctx context.Context, job Job) error

type NATSStore

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

func NewNATSSchedulerStore

func NewNATSSchedulerStore(ctx context.Context, js jetstream.JetStream, clock Clock) (*NATSStore, error)

func NewNATSStore

func NewNATSStore(ctx context.Context, js jetstream.JetStream, clock Clock) (*NATSStore, error)

func NewNATSStoreWithBucket

func NewNATSStoreWithBucket(ctx context.Context, js jetstream.JetStream, clock Clock, bucket string, ttl time.Duration) (*NATSStore, error)

Expiry on NATS is a property of the bucket, not the clock, so a caller needing a different TTL needs a different bucket.

func (*NATSStore) Acquire

func (s *NATSStore) Acquire(ctx context.Context, key, holder string, ttl time.Duration) (Lease, error)

func (*NATSStore) Release

func (s *NATSStore) Release(ctx context.Context, l Lease) error

Revision-guarded on purpose: unguarded, a holder that froze past its TTL and then called Release would delete the lease a successor had already won.

func (*NATSStore) Renew

func (s *NATSStore) Renew(ctx context.Context, l Lease, ttl time.Duration) (Lease, error)

type QueuePath

type QueuePath struct {
	Scheduler Store
	Publisher JobPublisher
	Consumer  JobConsumer
	Cursors   CursorStore

	// Only non-nil on a successful setup.
	Close func()
}

func SetupQueuePath

func SetupQueuePath(ctx context.Context, b QueuePathBuild) (QueuePath, error)

Atomic. Callers retry forever, so a connection left open on a late failure would leak one per attempt, and a partial QueuePath would skip the election.

type QueuePathBuild

type QueuePathBuild struct {
	Connect           func(ctx context.Context) (jetstream.JetStream, NATSCloser, error)
	NewSchedulerStore func(ctx context.Context, js jetstream.JetStream, clock Clock) (Store, error)
	NewJobPublisher   func(ctx context.Context, js jetstream.JetStream) (JobPublisher, error)
	NewJobConsumer    func(ctx context.Context, js jetstream.JetStream) (JobConsumer, error)
	NewCursorStore    func(ctx context.Context, js jetstream.JetStream) (CursorStore, error)
}

func DefaultQueuePathBuild

func DefaultQueuePathBuild(connName, plugin string) QueuePathBuild

type RealClock

type RealClock struct{}

func (RealClock) Now

func (RealClock) Now() time.Time

type Store

type Store interface {
	Acquire(ctx context.Context, key, holder string, ttl time.Duration) (Lease, error)

	Renew(ctx context.Context, l Lease, ttl time.Duration) (Lease, error)

	Release(ctx context.Context, l Lease) error
}

Ownership only. The lease path writes cursors via RenewAndPersistCursor.

Jump to

Keyboard shortcuts

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