jetstreamutil

package module
v0.0.0-...-eb0971a Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 9 Imported by: 2 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.

README

JetStream Utilities

github.com/chattocorp/chatto/pkg/jetstreamutil provides small, application-neutral helpers for NATS JetStream clients:

  • key-value reads through the stream leader, so that a read sees every committed write;
  • retried provisioning of streams, key-value buckets, and object stores; and
  • consistent classification of optimistic-concurrency conflicts.

Applications own resource names, configurations, identity metadata, timeout policy, and the decisions that they make from key-value state. The module depends only on nats.go.

Provision JetStream resources

CreateJetStreamResourceWithRetry runs a repeatable resource callback with a bounded JetStreamResourceRetryPolicy. Applications choose MaxAttempts (including the first call) and RetryDelay. After failed attempt N, the helper waits for N times RetryDelay. A positive MaxRetryDelay instead selects exponential backoff, capped at that value, with each wait randomly selected between half and all of the capped delay. A positive RequestTimeout sets a separate deadline for each callback. The helper rejects invalid policy values.

The helper retries request deadline errors only while the parent context is active. It also retries NATS timeouts, missing responders, cluster-unavailable errors, and the specific JetStream store-creation and stream-name conflict errors used during concurrent provisioning. Parent cancellation or expiry stops the operation and takes precedence over the callback result. Other errors and retry exhaustion remain fatal to the caller.

Callbacks must honor the context and be safe to repeat when the server has already committed an operation but its response was lost. Use this helper for streams, KV buckets, and Object Stores, not event writes. Applications retain resource names, configuration, identity metadata, and timeout policy. With nats.go, the default request timeout applies only when the supplied context has no deadline. Use RequestTimeout to bound each attempt when the parent has a longer deadline. An expired parent deadline cannot be retried.

Read key-value buckets consistently

JetStream serves jetstream.KeyValue.Get through DirectGet when a bucket allows it, and buckets that nats.go creates allow it. Any replica can then answer. A follower that lags behind a committed write returns an older revision or no entry. A read that must see a preceding write, or that decides an OCC update, a claim, or a revocation, then works from stale state.

KeyValue wraps a bucket handle and keeps its complete jetstream.KeyValue interface. It supports only the default JetStream API: NewKeyValue rejects a context with a domain or a different API prefix. Get and GetRevision read through the stream leader and keep the semantics of the bucket's own methods. Latest returns the newest entry for a key or wildcard filter, including delete, purge, and expiry markers. UpdateWithTTL replaces a revision and sets a new per-message TTL, which the bucket API supports only on Create. DeleteAt deletes a revision and returns the revision of the delete marker, so that the caller can wait until a watcher observes the deletion. Both report a revision conflict as jetstream.ErrKeyRevisionMismatch.

GetAnyReplica is the bucket's own read, for hot paths. Any replica can answer, so the result can be an older revision, or a miss for an entry that the replica has not applied yet. Accept a result from GetAnyReplica, but decide a negative result again with Get: a missing entry, or an entry that causes a rejection. Skip that second read only where a wrong negative result is harmless. Use GetAnyReplica only where an older revision that the caller accepts cannot cause a wrong decision.

bucket, err := js.CreateOrUpdateKeyValue(ctx, config)
if err != nil {
	return err
}
kv, err := jetstreamutil.NewKeyValue(js, bucket)
if err != nil {
	return err
}

entry, err := kv.Get(ctx, key) // sees every committed write

cached, err := kv.GetAnyReplica(ctx, key) // hot path; can be an older revision
if errors.Is(err, jetstream.ErrKeyNotFound) {
	cached, err = kv.Get(ctx, key) // decide the miss through the leader
}

Bind every bucket handle that the application reads through NewKeyValue, so that code that receives a jetstream.KeyValue also gets the leader-routed Get. Watchers, key listings, and history remain the bucket's own. The bucket's Create also reads a delete marker through a direct get. It can thus return jetstream.ErrKeyExists for a key that a lagging replica still shows.

Classify OCC conflicts

IsSequenceConflict reports whether an error is a JetStream optimistic-concurrency conflict: an expected-last-sequence mismatch from a stream publish, or jetstream.ErrKeyExists or jetstream.ErrKeyRevisionMismatch from a key-value write. JetStream uses a different error code for streams with more than one replica; the function recognizes both.

Status

This module is an incubation surface shared by Chatto and Authling. Its API is not yet covered by a stability promise, and releases remain pre-1.0.

Development

Run the module tests independently:

mise test-jetstreamutil

From this directory, the equivalent standalone check is:

GOWORK=off go test ./...

License

The module is licensed under Apache-2.0. Its permissive license does not imply API stability.

Documentation

Overview

Package jetstreamutil provides application-neutral helpers for NATS JetStream: key-value reads through the stream leader, retried resource provisioning, and consistent classification of OCC conflicts.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateJetStreamResourceWithRetry

func CreateJetStreamResourceWithRetry[T any](ctx context.Context, policy JetStreamResourceRetryPolicy, create func(context.Context) (T, error)) (T, error)

CreateJetStreamResourceWithRetry retries transient JetStream provisioning errors. create must honor ctx and be safe to repeat after a remotely successful operation whose response was lost. Use it for resource provisioning, not event publishing. Resource names, configuration, metadata, and request timeouts remain caller-owned. A request deadline is retryable only while the parent ctx remains active. Parent cancellation or expiry takes precedence over the callback result. Exhaustion returns the last operation error, and every failure returns the zero value of T.

func IsSequenceConflict

func IsSequenceConflict(err error) bool

IsSequenceConflict reports whether err is a JetStream optimistic-concurrency conflict caused by an expected-last-sequence mismatch. pkg/events keeps a private copy so that it does not depend on this module; change both together.

Types

type JetStreamResourceRetryPolicy

type JetStreamResourceRetryPolicy struct {
	// MaxAttempts includes the initial call and must be positive.
	MaxAttempts int
	// RetryDelay is the initial exponential delay when MaxRetryDelay is positive.
	// Otherwise it is multiplied by the failed attempt number. It must be
	// non-negative and the largest linear delay must fit in time.Duration.
	RetryDelay time.Duration
	// MaxRetryDelay selects exponential backoff with equal jitter when positive.
	// Each wait is between half and all of the exponential delay, capped here.
	// Zero preserves linear backoff. It must be at least RetryDelay.
	MaxRetryDelay time.Duration
	// RequestTimeout bounds each callback when positive, independently of the
	// overall startup context. Zero leaves request deadlines to the caller.
	RequestTimeout time.Duration
}

JetStreamResourceRetryPolicy bounds retries of repeatable resource provisioning. Applications choose the retry budget; the framework does not own resource policy.

type KeyValue

type KeyValue struct {
	jetstream.KeyValue
	// contains filtered or unexported fields
}

KeyValue is a jetstream.KeyValue whose Get, GetRevision, and Latest observe every committed write.

JetStream serves KeyValue.Get through DirectGet when the bucket allows it, which is the default for buckets that nats.go creates. Any replica can then answer, and a follower can lag behind a write that already committed: it returns an older revision or no entry. Read-your-writes, OCC updates, claims, and revocations then decide from stale state.

KeyValue routes Get, GetRevision, and Latest through the stream leader, and adds UpdateWithTTL, DeleteAt, and GetAnyReplica. Every other method is the bound bucket's, including watchers, key listings, and history. The bucket's Create also checks for a delete marker through DirectGet, so it can report jetstream.ErrKeyExists for a key that a lagging replica still shows. GetAnyReplica is the opt-in fast read for hot paths.

The bucket must be a plain bucket on the default JetStream API: not a mirror, not in another domain, and not reached through a subject transform or API prefix.

func NewKeyValue

func NewKeyValue(js jetstream.JetStream, bucket jetstream.KeyValue) (*KeyValue, error)

NewKeyValue binds leader-routed reads to bucket. It rejects a JetStream context with a domain or a non-default API prefix.

func (*KeyValue) DeleteAt

func (kv *KeyValue) DeleteAt(ctx context.Context, key string, revision uint64) (uint64, error)

DeleteAt deletes key if its latest revision is revision, and returns the revision of the delete marker. jetstream.KeyValue.Delete does not return it, but a caller needs it to wait until a watcher observes the deletion. It returns an error that matches jetstream.ErrKeyRevisionMismatch on a revision conflict.

func (*KeyValue) Get

Get returns the latest committed entry for key through the stream leader. Like jetstream.KeyValue.Get, it returns jetstream.ErrKeyNotFound for a missing, deleted, purged, or expired key.

func (*KeyValue) GetAnyReplica

func (kv *KeyValue) GetAnyReplica(ctx context.Context, key string) (jetstream.KeyValueEntry, error)

GetAnyReplica is the bucket's own Get. When the bucket allows direct gets, any replica can answer, so the result can be an older revision, or a miss for an entry that a lagging replica has not applied yet. Use it on hot paths to accept a result quickly, and decide a negative result again with Get.

func (*KeyValue) GetRevision

func (kv *KeyValue) GetRevision(ctx context.Context, key string, revision uint64) (jetstream.KeyValueEntry, error)

GetRevision returns the entry for key at revision through the stream leader. It returns jetstream.ErrKeyNotFound when that revision belongs to another key or removes this one. Revision 0 means the latest revision, as in nats.go.

func (*KeyValue) Latest

func (kv *KeyValue) Latest(ctx context.Context, filter string) (jetstream.KeyValueEntry, error)

Latest returns the newest entry whose key matches filter, read through the stream leader. filter can contain the wildcards `*` and `>`. Unlike Get, Latest also returns a delete, purge, or expiry marker; its Operation is jetstream.KeyValueDelete or jetstream.KeyValuePurge. It returns jetstream.ErrKeyNotFound only when no message matches.

func (*KeyValue) UpdateWithTTL

func (kv *KeyValue) UpdateWithTTL(ctx context.Context, key string, value []byte, revision uint64, ttl time.Duration) (uint64, error)

UpdateWithTTL replaces key if its latest revision is revision, and sets a new per-message TTL. jetstream.KeyValue supports a TTL on Create only. The bucket must allow per-message TTLs. It returns the new revision, or an error that matches jetstream.ErrKeyRevisionMismatch on a revision conflict.

Jump to

Keyboard shortcuts

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