{"modulePath":"github.com/utmstack/UTMStack/plugins/shared","version":"v0.0.0-20261126134315-738f65073a40","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package coordination\n\nPackage coordination distributes ingestion work across worker processes.\n\n## Constants\n\n```go\nconst AcquireRetryInterval = HeartbeatInterval\n```\n\n```go\nconst (\n\t// CursorBucketName is exported so plugins can name the bucket in their logs\n\t// without keeping a copy of the string.\n\tCursorBucketName = \"ingest_cursors\"\n)\n```\n\n```go\nconst HeartbeatInterval = LeaseTTL / 3\n```\n\n```go\nconst (\n\t// LeaseBucketName is exported so plugins can name the bucket in their logs\n\t// without keeping a copy of the string.\n\t// Keys are prefixed with the plugin name, e.g. \"aws.\u003ctenantId\u003e/\u003cgroup\u003e\".\n\tLeaseBucketName = \"ingest_leases\"\n)\n```\n\n```go\nconst LeaseTTL = bucketTTL\n```\nMust stay defined as bucketTTL: that is the TTL the server enforces.\n\n```go\nconst SchedulerLeaseTTL = schedulerBucketTTL\n```\nOnly covers one tick's publish; it expires before the next, unrenewed.\n\n## Variables\n\n```go\nvar ErrCursorConflict = errors.New(\"cursor: revision stale, another writer saved since Load\")\n```\n\n```go\nvar ErrCursorNotFound = errors.New(\"cursor: key has no persisted value yet\")\n```\nCallers must treat this as \"seed from now\", never \"seed from epoch\".\n\n```go\nvar ErrCursorTooLarge = errors.New(\"cursor: payload exceeds the transport's maximum message size\")\n```\nSave 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.\n\n```go\nvar ErrFenced = errors.New(\"lease fenced: revision stale, another holder took over\")\n```\n\n```go\nvar ErrHeld = errors.New(\"lease already held by a live owner\")\n```\n\n```go\nvar ErrMissingActivateWork = errors.New(\"coordination: ConsumeAndAdvanceCursor: first activation occurred but ConsumeWork.Activate is nil\")\n```\n\n```go\nvar ErrMissingResumeWork = errors.New(\"coordination: ConsumeAndAdvanceCursor: a cursor already exists for this key but ConsumeWork.Resume is nil\")\n```\n\n```go\nvar ErrNoJobs = errors.New(\"queue: no job available within the fetch window\")\n```\nA normal idle result, never a failure. JetStream reports an expired pull with nats.ErrTimeout, the same error a network partition produces.\n\n## Functions\n\n```go\nfunc ConnectJetStream(ctx context.Context, connName string) (jetstream.JetStream, *nats.Conn, error)\n```\nConnectJetStream dials NATS\\_URL. The caller owns the returned \\*nats.Conn and must Close it. connName identifies this plugin to the server.\n\n```go\nfunc ConsumeAndAdvanceCursor(\n\tctx context.Context,\n\tcursors CursorStore,\n\tdelivery JobDelivery,\n\tcursorKey string,\n\twork ConsumeWork,\n) error\n```\nFailures 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.\n\n```go\nfunc DialLeasePath(connName string) func(ctx context.Context) (LeasePath, error)\n```\n\n```go\nfunc DialQueuePath(connName, plugin string) func(ctx context.Context) (QueuePath, error)\n```\n\n```go\nfunc LoadCursorInto[T any](ctx context.Context, cursors CursorStore, key string, dst *T) (uint64, bool, error)\n```\nAn 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.\n\n```go\nfunc MarshalCursorPayload(v any, encryptionKey string) ([]byte, error)\n```\nNATS has neither auth nor TLS here. Jobs stay unencrypted: their subject already carries tenant and group for routing.\n\n```go\nfunc NatsToken(name string) string\n```\nNatsToken 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.\n\n```go\nfunc PublishJobsIfElected(\n\tctx context.Context,\n\tscheduler Store,\n\tpublisher JobPublisher,\n\tleaseKey string,\n\tholder string,\n\tjobs []Job,\n\tonError func(job Job, err error),\n)\n```\nAny 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.\n\n```go\nfunc RenewAndPersistCursor(\n\tctx context.Context, store Store, cursors CursorStore,\n\tl Lease, ttl time.Duration,\n\tcursorKey string, cursorData []byte, cursorRev uint64,\n) (Lease, Cursor, error)\n```\nThe only sanctioned lease-path cursor write: Renew first, Save only if it succeeded, so a holder whose lease was taken over cannot reach Save.\n\n```go\nfunc RunJobConsumer(\n\tctx context.Context,\n\tconsumer JobConsumer,\n\thandle func(ctx context.Context, delivery JobDelivery) error,\n\tonError func(err error),\n)\n```\nNo error ends the loop: one group's transient failure must not stop ingestion for the rest. ErrNoJobs and cancellation never reach onError.\n\n```go\nfunc SchedulerLeaseKey(plugin string) string\n```\nThe plugin namespace is load-bearing: every queue-path plugin shares one bucket, so an unnamespaced key would elect one publisher across all of them.\n\n```go\nfunc SetupWithRetry[T any](ctx context.Context, dial func(ctx context.Context) (T, error), retryDelay time.Duration, onFailure func(err error)) (T, error)\n```\nMust 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.\n\n```go\nfunc UnmarshalCursorPayload[T any](data []byte, encryptionKey string) (T, error)\n```\nCursors written before a key was configured stay readable: Decrypt passes already-plaintext input through unchanged.\n\n## Types\n\n```go\ntype Clock interface {\n\tNow() time.Time\n}\n```\n\n```go\ntype ConsumeWork struct {\n\tResume func(ctx context.Context, job Job, cur Cursor) (next []byte, err error)\n\n\t// Called instead of Resume on first activation. The position it returns\n\t// must be seeded from \"now\", or the source's history is replayed whole.\n\tActivate func(ctx context.Context, job Job) (next []byte, err error)\n}\n```\n\n```go\ntype Cursor struct {\n\tData []byte\n\t// CAS token in CursorStore, unrelated to Lease.Revision.\n\tRevision uint64\n}\n```\n\n```go\ntype CursorSnapshot func() ([]byte, error)\n```\nMust read the caller's live position; a captured payload never advances.\n\n```go\ntype CursorStore interface {\n\tLoad(ctx context.Context, key string) (Cursor, error)\n\n\t// CAS write. c.Revision == 0 means \"create\" and fails if key exists; any\n\t// other value means \"update only if still current\".\n\tSave(ctx context.Context, key string, c Cursor) (Cursor, error)\n}\n```\n\n```go\ntype Heartbeat struct {\n\tLeases  Store\n\tCursors CursorStore\n\n\t// One key for both lease and cursor, so a successor finds the position.\n\tKey string\n\n\tSnapshot CursorSnapshot\n\n\tTTL time.Duration\n\n\tInterval time.Duration\n\n\t// Must be the same CancelFunc that stops the unit for any other reason:\n\t// refusing new work leaves a feed socket held open for hours.\n\tCancel context.CancelFunc\n\n\tOnError func(error)\n}\n```\n\n```go\nfunc (h Heartbeat) Run(ctx context.Context, lease Lease, cursorRev uint64)\n```\n\n```go\nfunc (h Heartbeat) Tick(ctx context.Context, lease Lease, cursorRev uint64) (Lease, uint64, error)\n```\nThe 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.\n\n```go\ntype Job struct {\n\tTenantID    string    `json:\"tenantId\"`\n\tGroupName   string    `json:\"groupName\"`\n\tWindowStart time.Time `json:\"windowStart\"`\n\tWindowEnd   time.Time `json:\"windowEnd\"`\n}\n```\nWindowStart and WindowEnd are a hint only: the consumer's authoritative position is CursorStore.Load, so they matter only on a first activation.\n\n```go\ntype JobConsumer interface {\n\tFetch(ctx context.Context) (JobDelivery, error)\n}\n```\nA 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.\n\n```go\ntype JobDelivery struct {\n\tJob Job\n\n\t// 1 on first delivery, incremented on every redelivery.\n\tNumDelivered uint64\n\n\tAck func() error\n\n\t// Requests immediate redelivery rather than waiting out AckWait.\n\tNak func() error\n}\n```\nExactly one of Ack or Nak must eventually be called.\n\n```go\ntype JobPublisher interface {\n\tPublish(ctx context.Context, job Job) error\n}\n```\n\n```go\ntype Lease struct {\n\t// Opaque and precomputed; Store implementations never parse it.\n\tKey string\n\t// The worker process that owns this lease.\n\tHolder string\n\t// Fencing token: increases on every Acquire or Renew, so a stale Lease\n\t// loses any later CAS.\n\tRevision uint64\n\t// When this lease becomes eligible for another Acquire.\n\tExpiresAt time.Time\n}\n```\nNo 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.\n\n```go\nfunc AcquireWithRetry(\n\tctx context.Context, store Store,\n\tkey, holder string,\n\tttl, retryInterval time.Duration,\n\tonError func(error),\n) (Lease, error)\n```\nNo 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.\n\n```go\ntype LeasePath struct {\n\tLeases  Store\n\tCursors CursorStore\n\n\t// Only non-nil on a successful setup.\n\tClose func()\n}\n```\n\n```go\nfunc SetupLeasePath(ctx context.Context, b LeasePathBuild) (LeasePath, error)\n```\nAtomic. Callers retry forever, so a connection left open on a late failure would leak one per attempt, and a partial LeasePath would ingest unowned.\n\n```go\ntype LeasePathBuild struct {\n\tConnect        func(ctx context.Context) (jetstream.JetStream, NATSCloser, error)\n\tNewLeaseStore  func(ctx context.Context, js jetstream.JetStream, clock Clock) (Store, error)\n\tNewCursorStore func(ctx context.Context, js jetstream.JetStream) (CursorStore, error)\n}\n```\n\n```go\nfunc DefaultLeasePathBuild(connName string) LeasePathBuild\n```\n\n```go\ntype NATSCloser interface {\n\tClose()\n}\n```\n\n```go\ntype NATSCursorStore struct {\n\t// contains filtered or unexported fields\n}\n```\nBacked by a bucket with no TTL. The lease bucket expires by deleting its keys, and position must survive exactly that moment.\n\n```go\nfunc NewNATSCursorStore(ctx context.Context, js jetstream.JetStream) (*NATSCursorStore, error)\n```\n\n```go\nfunc (s *NATSCursorStore) Load(ctx context.Context, key string) (Cursor, error)\n```\n\n```go\nfunc (s *NATSCursorStore) Save(ctx context.Context, key string, c Cursor) (Cursor, error)\n```\n\n```go\ntype NATSJobConsumer struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc NewNATSJobConsumer(ctx context.Context, js jetstream.JetStream, plugin string) (*NATSJobConsumer, error)\n```\n\n```go\nfunc NewNATSJobConsumerWithConfig(ctx context.Context, js jetstream.JetStream, plugin string, ackWait time.Duration, maxDeliver int) (*NATSJobConsumer, error)\n```\n\n```go\nfunc (c *NATSJobConsumer) Fetch(ctx context.Context) (JobDelivery, error)\n```\n\n```go\ntype NATSJobPublisher struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc NewNATSJobPublisher(ctx context.Context, js jetstream.JetStream, plugin string) (*NATSJobPublisher, error)\n```\n\n```go\nfunc (p *NATSJobPublisher) Publish(ctx context.Context, job Job) error\n```\n\n```go\ntype NATSStore struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc NewNATSSchedulerStore(ctx context.Context, js jetstream.JetStream, clock Clock) (*NATSStore, error)\n```\n\n```go\nfunc NewNATSStore(ctx context.Context, js jetstream.JetStream, clock Clock) (*NATSStore, error)\n```\n\n```go\nfunc NewNATSStoreWithBucket(ctx context.Context, js jetstream.JetStream, clock Clock, bucket string, ttl time.Duration) (*NATSStore, error)\n```\nExpiry on NATS is a property of the bucket, not the clock, so a caller needing a different TTL needs a different bucket.\n\n```go\nfunc (s *NATSStore) Acquire(ctx context.Context, key, holder string, ttl time.Duration) (Lease, error)\n```\n\n```go\nfunc (s *NATSStore) Release(ctx context.Context, l Lease) error\n```\nRevision-guarded on purpose: unguarded, a holder that froze past its TTL and then called Release would delete the lease a successor had already won.\n\n```go\nfunc (s *NATSStore) Renew(ctx context.Context, l Lease, ttl time.Duration) (Lease, error)\n```\n\n```go\ntype QueuePath struct {\n\tScheduler Store\n\tPublisher JobPublisher\n\tConsumer  JobConsumer\n\tCursors   CursorStore\n\n\t// Only non-nil on a successful setup.\n\tClose func()\n}\n```\n\n```go\nfunc SetupQueuePath(ctx context.Context, b QueuePathBuild) (QueuePath, error)\n```\nAtomic. 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.\n\n```go\ntype QueuePathBuild struct {\n\tConnect           func(ctx context.Context) (jetstream.JetStream, NATSCloser, error)\n\tNewSchedulerStore func(ctx context.Context, js jetstream.JetStream, clock Clock) (Store, error)\n\tNewJobPublisher   func(ctx context.Context, js jetstream.JetStream) (JobPublisher, error)\n\tNewJobConsumer    func(ctx context.Context, js jetstream.JetStream) (JobConsumer, error)\n\tNewCursorStore    func(ctx context.Context, js jetstream.JetStream) (CursorStore, error)\n}\n```\n\n```go\nfunc DefaultQueuePathBuild(connName, plugin string) QueuePathBuild\n```\n\n```go\ntype RealClock struct{}\n```\n\n```go\nfunc (RealClock) Now() time.Time\n```\n\n```go\ntype Store interface {\n\tAcquire(ctx context.Context, key, holder string, ttl time.Duration) (Lease, error)\n\n\tRenew(ctx context.Context, l Lease, ttl time.Duration) (Lease, error)\n\n\tRelease(ctx context.Context, l Lease) error\n}\n```\nOwnership only. The lease path writes cursors via RenewAndPersistCursor.\n\n","path":"github.com/utmstack/UTMStack/plugins/shared/coordination","name":"coordination","synopsis":"Package coordination distributes ingestion work across worker processes.","isRedistributable":true}
