Documentation
¶
Overview ¶
Package coordination distributes ingestion work across worker processes.
Index ¶
- Constants
- Variables
- func ConnectJetStream(ctx context.Context, connName string) (jetstream.JetStream, *nats.Conn, error)
- func ConsumeAndAdvanceCursor(ctx context.Context, cursors CursorStore, delivery JobDelivery, ...) error
- func DialLeasePath(connName string) func(ctx context.Context) (LeasePath, error)
- func DialQueuePath(connName, plugin string) func(ctx context.Context) (QueuePath, error)
- func LoadCursorInto[T any](ctx context.Context, cursors CursorStore, key string, dst *T) (uint64, bool, error)
- func MarshalCursorPayload(v any, encryptionKey string) ([]byte, error)
- func NatsToken(name string) string
- func PublishJobsIfElected(ctx context.Context, scheduler Store, publisher JobPublisher, leaseKey string, ...)
- func RenewAndPersistCursor(ctx context.Context, store Store, cursors CursorStore, l Lease, ...) (Lease, Cursor, error)
- func RunJobConsumer(ctx context.Context, consumer JobConsumer, ...)
- func SchedulerLeaseKey(plugin string) string
- func SetupWithRetry[T any](ctx context.Context, dial func(ctx context.Context) (T, error), ...) (T, error)
- func UnmarshalCursorPayload[T any](data []byte, encryptionKey string) (T, error)
- type Clock
- type ConsumeWork
- type Cursor
- type CursorSnapshot
- type CursorStore
- type Heartbeat
- type Job
- type JobConsumer
- type JobDelivery
- type JobPublisher
- type Lease
- type LeasePath
- type LeasePathBuild
- type NATSCloser
- type NATSCursorStore
- type NATSJobConsumer
- type NATSJobPublisher
- type NATSStore
- func NewNATSSchedulerStore(ctx context.Context, js jetstream.JetStream, clock Clock) (*NATSStore, error)
- func NewNATSStore(ctx context.Context, js jetstream.JetStream, clock Clock) (*NATSStore, error)
- func NewNATSStoreWithBucket(ctx context.Context, js jetstream.JetStream, clock Clock, bucket string, ...) (*NATSStore, error)
- type QueuePath
- type QueuePathBuild
- type RealClock
- type Store
Constants ¶
const AcquireRetryInterval = HeartbeatInterval
const ( // CursorBucketName is exported so plugins can name the bucket in their logs // without keeping a copy of the string. CursorBucketName = "ingest_cursors" )
const HeartbeatInterval = LeaseTTL / 3
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" )
const LeaseTTL = bucketTTL
Must stay defined as bucketTTL: that is the TTL the server enforces.
const SchedulerLeaseTTL = schedulerBucketTTL
Only covers one tick's publish; it expires before the next, unrenewed.
Variables ¶
var ErrCursorConflict = errors.New("cursor: revision stale, another writer saved since Load")
var ErrCursorNotFound = errors.New("cursor: key has no persisted value yet")
Callers must treat this as "seed from now", never "seed from epoch".
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.
var ErrFenced = errors.New("lease fenced: revision stale, another holder took over")
var ErrHeld = errors.New("lease already held by a live owner")
var ErrMissingActivateWork = errors.New("coordination: ConsumeAndAdvanceCursor: first activation occurred but ConsumeWork.Activate is nil")
var ErrMissingResumeWork = errors.New("coordination: ConsumeAndAdvanceCursor: a cursor already exists for this key but ConsumeWork.Resume is nil")
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 DialQueuePath ¶
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 ¶
NATS has neither auth nor TLS here. Jobs stay unencrypted: their subject already carries tenant and group for routing.
func NatsToken ¶
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 ¶
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.
Types ¶
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 CursorSnapshot ¶
Must read the caller's live position; a captured payload never advances.
type CursorStore ¶
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)
}
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 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 ¶
type NATSJobConsumer ¶
type NATSJobConsumer struct {
// contains filtered or unexported fields
}
func NewNATSJobConsumer ¶
func (*NATSJobConsumer) Fetch ¶
func (c *NATSJobConsumer) Fetch(ctx context.Context) (JobDelivery, error)
type NATSJobPublisher ¶
type NATSJobPublisher struct {
// contains filtered or unexported fields
}
func NewNATSJobPublisher ¶
type NATSStore ¶
type NATSStore struct {
// contains filtered or unexported fields
}
func NewNATSSchedulerStore ¶
func NewNATSStore ¶
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.
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 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.