Documentation
¶
Overview ¶
Package bus provides sqi-server's NATS JetStream broker, embedded or external, and the subject and stream definitions sqi's messaging uses.
Subject naming ¶
Each subject class follows a hierarchical naming scheme so that JetStream stream subject-filters and consumer subject-bindings are intuitive:
work.lease.<worker>.<queue> — worker → server: request/reply work-lease batch task.status.<worker>.<job> — worker → server: task state transitions task.logs.<worker>.<task> — worker → server: log chunk ingestion worker.heartbeat.<worker> — worker → server: periodic liveness pings worker.register.<worker> — worker → server: capability advertisement worker.deregister.<worker> — worker → server: graceful departure notification task.cancel.<worker> — server → worker: interrupt a running task worker.control.<worker> — server → worker: request/reply power command sqi.marker.worker — server → server: ingest marker in SQI_WORKER sqi.marker.task — server → server: ingest marker in SQI_TASK
Every worker → server subject carries the publishing worker's ID directly after its class prefix, and so do the server → worker subjects, task.cancel.<worker> and worker.control.<worker>, so that a worker may subscribe to its own and no other worker's. That placement makes the broker's per-worker publish permissions expressible: NATS permissions are static per credential and JetStream does not stamp publisher identity onto a message, so a scheme keyed only by job, task and queue would offer no way to say "only this worker's own traffic", and no way for the server to learn who published a message it received. ParseWorkerSubject recovers the identity on the receiving side.
The marker subjects carry no worker and belong to the server alone: workers hold no grant on them, and their prefix keeps them out of ParseWorkerSubject.
The remaining tokens (<queue>, <job>, <task>) are the opaque string identifiers of the corresponding entity in the store. Callers build full subject strings using the helper functions below rather than constructing them by hand.
Index ¶
- Constants
- Variables
- func CheckBrokerVersion(v string) error
- func CheckGuard(ctx context.Context, js jetstream.JetStream, opts GuardOptions, ...) error
- func GrantsFingerprint() string
- func NewInstanceID() string
- func ParseWorkerSubject(subject string) (workerID, leaf string, ok bool)
- func PermanentPublishError(err error) bool
- func Reconnecting(nc *nats.Conn) bool
- func StreamNames() []string
- func TaskCancelSubject(workerID string) string
- func TaskLogsSubject(workerID, taskID string) string
- func TaskStatusSubject(workerID, jobID string) string
- func WorkLeaseSubject(workerID, queueID string) string
- func WorkerControlSubject(workerID string) string
- func WorkerDeregisterSubject(workerID string) string
- func WorkerDiagSubject(workerID string) string
- func WorkerHeartbeatSubject(workerID string) string
- func WorkerRegisterSubject(workerID string) string
- type AuthConfig
- type Broker
- type BrokerTLSConfig
- type Client
- func (c *Client) BusUpSince() time.Time
- func (c *Client) Close()
- func (c *Client) ConsumeTaskLogs(ctx context.Context, handler jetstream.MessageHandler) (jetstream.ConsumeContext, error)
- func (c *Client) ConsumeTaskStatus(ctx context.Context, handler jetstream.MessageHandler) (jetstream.ConsumeContext, error)
- func (c *Client) ConsumeWorker(ctx context.Context, handler jetstream.MessageHandler) (jetstream.ConsumeContext, error)
- func (c *Client) ConsumerAckFloor(ctx context.Context, consumer IngestConsumer) (uint64, error)
- func (c *Client) Drain(ctx context.Context) error
- func (c *Client) InterruptedAt() time.Time
- func (c *Client) PublishIngestMarkers(ctx context.Context, timeout time.Duration) error
- func (c *Client) PublishTaskCancel(ctx context.Context, workerID string, data []byte) error
- func (c *Client) PublishTaskLog(ctx context.Context, workerID, taskID string, data []byte) error
- func (c *Client) PublishTaskStatus(ctx context.Context, workerID, jobID string, data []byte) error
- func (c *Client) PublishWorkerDiag(_ context.Context, workerID string, data []byte) error
- func (c *Client) PublishWorkerHeartbeat(ctx context.Context, workerID string, data []byte) error
- func (c *Client) PublishWorkerRegister(ctx context.Context, workerID string, data []byte) error
- func (c *Client) RequestLease(ctx context.Context, workerID, queueID string, data []byte, ...) ([]byte, error)
- func (c *Client) RequestWorkerControl(ctx context.Context, workerID string, data []byte) ([]byte, error)
- func (c *Client) SubscribeLease(handler func(workerID, queueID string, data []byte) []byte) (*LeaseSubscription, error)
- func (c *Client) SubscribeWorkerDiag(handler func(subject string, data []byte)) (*nats.Subscription, error)
- type ClientTLSConfig
- type CredentialLookup
- type DurableConsumer
- type Embedded
- func (e *Embedded) AdvertiseURL(host string) (string, error)
- func (e *Embedded) Check(_ context.Context) error
- func (e *Embedded) ClientURL() string
- func (*Embedded) Identity() string
- func (e *Embedded) InProcessConn() (net.Conn, error)
- func (e *Embedded) NewClient() (*Client, error)
- func (e *Embedded) Revoke(ctx context.Context, workerID string) error
- func (e *Embedded) RevokeBudget() time.Duration
- func (e *Embedded) Shutdown()
- func (e *Embedded) Start(ctx context.Context) error
- type EmbeddedConfig
- type Guard
- type GuardHolder
- type GuardOptions
- type IngestConsumer
- type Layout
- type LeaseSubscription
- type Remote
- func (r *Remote) AdvertiseURL(string) (string, error)
- func (r *Remote) Check(_ context.Context) error
- func (r *Remote) Connected() (up bool, since time.Time)
- func (r *Remote) Identity() string
- func (r *Remote) LockForRestore(ctx context.Context) (*RestoreLock, error)
- func (r *Remote) NewClient() (*Client, error)
- func (r *Remote) Revoke(ctx context.Context, workerID string) error
- func (r *Remote) RevokeBudget() time.Duration
- func (r *Remote) SetCalloutActive(active bool)
- func (r *Remote) Shutdown()
- func (r *Remote) StandbyChecked() <-chan struct{}
- func (r *Remote) StandbyReady() error
- func (r *Remote) Start(ctx context.Context) error
- func (r *Remote) StartStandby(ctx context.Context, opts GuardOptions) error
- func (r *Remote) TakeLeadership(ctx context.Context, opts GuardOptions) error
- type RemoteAuthConfig
- type RemoteConfig
- type Responder
- func (r *Responder) Authorize(ctx context.Context, req *jwt.AuthorizationRequestClaims) (string, error)
- func (r *Responder) Handle(ctx context.Context, requestJWT []byte) (reply []byte)
- func (r *Responder) Listen(nc *nats.Conn) error
- func (r *Responder) Pause() (bool, error)
- func (r *Responder) Resume() (bool, error)
- func (r *Responder) Serve(ctx context.Context, nc *nats.Conn) error
- func (r *Responder) Stop()
- type ResponderConfig
- type RestoreLock
Constants ¶
const ( // WorkerConsumerMaxDeliver and TaskStatusConsumerMaxDeliver are the // delivery attempts the worker and task-status consumers allow a message. WorkerConsumerMaxDeliver = 11 TaskStatusConsumerMaxDeliver = 10 // WorkerConsumerAckWait and TaskStatusConsumerAckWait are how long the // broker waits for an ack before redelivering. WorkerConsumerAckWait = 10 * time.Second TaskStatusConsumerAckWait = 30 * time.Second // WorkerStreamMaxAge and TaskStreamMaxAge are how long SQI_WORKER and // SQI_TASK keep a message. WorkerStreamMaxAge = 2 * time.Minute TaskStreamMaxAge = 24 * time.Hour )
Redelivery and retention settings of the server-side consumers and their streams. The scheduler reads them to decide how long after an interruption its view of the store may lag a stream.
const ( // AccountAuth is the account that holds sqi's callout connection. Nothing // else lives in it. AccountAuth = brokerauth.AccountAuth // DefaultAccount is the account that holds sqi's streams, consumers, KV // bucket and workers, and sqi's data connection. Embedded mode always uses // it; external mode takes the name from configuration. DefaultAccount = "SQI" )
const ( // StreamTask captures task-status transitions reported by workers back to // the server. WorkQueuePolicy ensures each update is processed exactly once // by the server-side status consumer. StreamTask = "SQI_TASK" // StreamLogs captures log chunks emitted by running tasks. The server // persists each chunk to task_logs and acks it; REST and WebSocket read // task_logs. LimitsPolicy keeps the chunks for MaxAge (96 h) after ack as // a delivery buffer, but nothing reads them back from the stream. StreamLogs = "SQI_LOGS" // StreamWorker captures worker-registration and worker-heartbeat messages. // WorkQueuePolicy ensures the server processes each registration and // heartbeat ping exactly once. StreamWorker = "SQI_WORKER" // StreamCancel captures task-cancellation signals published by the server // to assigned workers; see [streamDefs] for how they are delivered. StreamCancel = "SQI_CANCEL" )
Stream name constants. Every JetStream stream owned by sqi-server uses the "SQI_" prefix so they are clearly identifiable if the embedded NATS instance is ever inspected externally.
const ( // SubjectTaskStatusPrefix is the prefix for task-status subjects. // Full subject: SubjectTaskStatusPrefix + "." + workerID + "." + jobID. SubjectTaskStatusPrefix = "task.status" // SubjectTaskLogsPrefix is the prefix for task-log subjects. // Full subject: SubjectTaskLogsPrefix + "." + workerID + "." + taskID. SubjectTaskLogsPrefix = "task.logs" // SubjectTaskCancelPrefix is the prefix for task-cancellation subjects. // Full subject: SubjectTaskCancelPrefix + "." + workerID. // The server publishes to the subject of the worker holding the task; the // worker subscribes to it once, before it asks for work, and interrupts // the run the message names. SubjectTaskCancelPrefix = "task.cancel" // SubjectWorkerHeartbeatPrefix is the prefix for worker liveness pings. // Full subject: SubjectWorkerHeartbeatPrefix + "." + workerID. SubjectWorkerHeartbeatPrefix = "worker.heartbeat" // SubjectWorkerRegisterPrefix is the prefix workers publish registration // messages under when they first connect or reconnect. // Full subject: SubjectWorkerRegisterPrefix + "." + workerID. SubjectWorkerRegisterPrefix = "worker.register" // SubjectWorkerDeregisterPrefix is the prefix workers publish under on // graceful shutdown so the server can mark the worker offline immediately // rather than waiting for heartbeat timeout. The server handler for these // subjects calls [store.WorkerStore.OfflineWorker], which marks the worker // offline and returns its in-flight tasks to the ready queue. // Full subject: SubjectWorkerDeregisterPrefix + "." + workerID. SubjectWorkerDeregisterPrefix = "worker.deregister" // SubjectWorkerControlPrefix is the prefix of the subject the server sends // a worker a power command on. Core NATS request/reply: the worker // subscribes to its own subject before it asks for work and answers each // request. No stream covers it (SQI_WORKER lists its three worker prefixes // by name, not "worker.>"), because a stream would answer the request with // a JetStream ack in place of the worker's reply. // Full subject: SubjectWorkerControlPrefix + "." + workerID. SubjectWorkerControlPrefix = "worker.control" // SubjectMarkerWorker and SubjectMarkerTask are the subjects of the ingest // markers: empty messages the scheduler publishes into SQI_WORKER and // SQI_TASK, and later receives on its own consumers. Handling one shows // that everything stored in the stream before it has been handled. The // "sqi." prefix sits outside "worker." and "task." so that no worker // subject pattern, grant or [ParseWorkerSubject] shape can match them. SubjectMarkerWorker = "sqi.marker.worker" SubjectMarkerTask = "sqi.marker.task" // SubjectWorkLeasePrefix is the prefix for worker work-lease requests. // Full subject: SubjectWorkLeasePrefix + "." + workerID + "." + queueID. // Core NATS request/reply — workers ask for work; the server replies with // a batch. SubjectWorkLeasePrefix = "work.lease" // WildcardQueueToken is the lease-subject queue token a queue-unaffiliated // worker (empty QueueIDs — "serve any queue") uses in place of a real queue // ID, so it requests on a valid subject (work.lease.<worker>._any) that the // server's work.lease.> subscription receives. An empty token would // produce an unroutable subject. The token is reserved (underscore prefix) // so it cannot collide with a real UUID queue ID; the server selects tasks // farm-wide and gates by worker eligibility, so the token's only role is // subject routing and wake-up bucketing. WildcardQueueToken = "_any" )
Subject prefix constants.
const GuardBucket = "SQI_SERVER"
GuardBucket is the JetStream KV bucket that holds the one-server-per-account guard in external broker mode.
const GuardPurposeRestore = "restore"
GuardPurposeRestore is the GuardHolder.Purpose of "sqi-server restore", which holds the account while it purges sqi's state from it.
const MinBrokerVersion = "2.14.8"
MinBrokerVersion is the oldest nats-server release sqi will connect to. It is the lowest entry of [seriesMinPatch], named in errors for brokers that predate every supported series.
const SubjectWorkerDiagPrefix = "worker.diag"
SubjectWorkerDiagPrefix is the prefix for worker diagnostic-log subjects. Full subject: SubjectWorkerDiagPrefix + "." + workerID.
Unlike the task-status, log and worker subjects, diagnostic logs use core NATS (not JetStream), like work leases: they are best-effort and never retained on the broker. The server keeps a bounded in-memory ring buffer instead.
Variables ¶
var ErrGuardHeld = errors.New("bus: another sqi-server holds this broker account")
ErrGuardHeld is returned, wrapped with the holder, when another sqi-server already holds the broker account.
var ErrStandbyUnchecked = errors.New("bus: this standby has not checked the external broker yet")
ErrStandbyUnchecked is what Remote.StandbyReady returns until a standby has checked its broker: no broker has answered yet, or the checks are under way.
var ErrUnknownCredential = errors.New("bus: no active credential for this key")
ErrUnknownCredential is wrapped by a CredentialLookup when no active credential has the key it was asked about.
Functions ¶
func CheckBrokerVersion ¶ added in v0.4.0
CheckBrokerVersion reports an error when v, a nats-server version as the broker advertises it (for example "2.15.2" or "2.15.3-RC.1"), is malformed or older than the minimum for its series. Versions are compared numerically as major.minor.patch; a pre-release suffix is ignored.
func CheckGuard ¶ added in v0.4.0
func CheckGuard(ctx context.Context, js jetstream.JetStream, opts GuardOptions, logger *slog.Logger) error
CheckGuard reports whether a standby may join: nil when the guard key is absent, held by a member of this database, or held by a server that stops refreshing it within one TTL; an error wrapping ErrGuardHeld when a server outside this database refreshes it. It never writes the key. A nil opts.IsMember makes every holder a non-member.
func GrantsFingerprint ¶ added in v0.4.0
func GrantsFingerprint() string
GrantsFingerprint is a hex SHA-256 of what a worker is granted: the permissions brokerauth.WorkerPermissions returns for a fixed sample worker ID, and the permission part of the user JWT the auth callout issues with them. Two servers with the same fingerprint authorize any worker identically, so it does not matter which of them the callout queue group picks; a standby whose fingerprint differs from the leader's leaves the group.
The encoding is canonical: subject lists are sorted, so the same grants listed in another order give the same fingerprint.
func NewInstanceID ¶ added in v0.4.0
func NewInstanceID() string
NewInstanceID returns a random identifier for one server process.
func ParseWorkerSubject ¶ added in v0.4.0
ParseWorkerSubject splits a worker → server subject into the ID of the worker that published it and the trailing token identifying the entity it concerns (the job for task status, the task for logs, the queue for a lease request; empty for the three worker-lifecycle subjects, which have no trailing token).
ok is false for anything that is not one of the six worker → server subject shapes, including subjects with an empty token and subjects whose worker or trailing token carries a NATS wildcard. A message whose subject does not carry one concrete identity is one the server cannot attribute to a worker, and callers must reject it rather than act on a partial parse.
func PermanentPublishError ¶ added in v0.4.0
PermanentPublishError reports whether err, from a worker's acknowledged publish, cannot be cured by publishing the same message again: it is over the broker's payload limit, or the connection closed for good. A worker's status and log publishers drop such a message rather than retry it.
func Reconnecting ¶ added in v0.4.0
Reconnecting reports whether nc is reconnecting, or making its first connection. A worker's acknowledged publishers send nothing then and retry later, so their retries do not pile up in the client's reconnect buffer and go out together, stale, when the connection comes back. The check and the publish are not atomic: a publish written just before the client notices a drop is still buffered and sent on reconnect, and the stream drops the later retries as duplicates of its message ID.
func StreamNames ¶ added in v0.4.0
func StreamNames() []string
StreamNames lists sqi's streams by name, in the order they are provisioned.
func TaskCancelSubject ¶
TaskCancelSubject returns the full NATS subject on which the given worker receives task-cancellation signals.
func TaskLogsSubject ¶
TaskLogsSubject returns the full NATS subject for log-chunk messages published by the given worker for the given task.
func TaskStatusSubject ¶
TaskStatusSubject returns the full NATS subject for task-status messages published by the given worker about the given job.
func WorkLeaseSubject ¶
WorkLeaseSubject returns the full NATS subject the given worker requests work on for the given queue.
func WorkerControlSubject ¶ added in v0.4.0
WorkerControlSubject returns the full NATS subject on which the given worker receives power commands.
func WorkerDeregisterSubject ¶ added in v0.4.0
WorkerDeregisterSubject returns the full NATS subject the given worker publishes its graceful-departure notification to.
func WorkerDiagSubject ¶
WorkerDiagSubject returns the full core-NATS subject a worker publishes its diagnostic log records to.
func WorkerHeartbeatSubject ¶ added in v0.4.0
WorkerHeartbeatSubject returns the full NATS subject the given worker publishes its liveness pings to.
func WorkerRegisterSubject ¶ added in v0.4.0
WorkerRegisterSubject returns the full NATS subject the given worker publishes its capability advertisement to.
Types ¶
type AuthConfig ¶ added in v0.4.0
type AuthConfig struct {
// Enabled sends every connection other than sqi's own through the
// auth-callout responder.
Enabled bool
// UserTTL is how long a worker's issued user JWT stays valid. The broker
// disconnects the worker at expiry and the reconnect is authorized
// afresh. Any positive value is accepted here; configuration enforces
// the operator-facing bounds.
UserTTL time.Duration
// Lookup resolves a worker's public nkey to its worker ID from the
// store's active credentials, at every connect.
Lookup CredentialLookup
}
AuthConfig controls worker authentication on the broker. The zero value leaves it off: anonymous connections are accepted into sqi's account.
type Broker ¶
type Broker interface {
// Start brings the broker up and provisions sqi's streams. It must be
// called once, before any other method.
Start(ctx context.Context) error
// Shutdown closes sqi's connections and stops the broker. It is safe to
// call more than once and concurrently with the other methods.
Shutdown()
// Check implements [health.Checker] for GET /readyz.
Check(ctx context.Context) error
// NewClient returns a typed client on sqi's data connection credential.
NewClient() (*Client, error)
// Revoke disconnects every live connection of workerID. It is called
// after the credential is revoked in the store, so the reconnect goes
// back through the callout and is refused.
Revoke(ctx context.Context, workerID string) error
// RevokeBudget is how long Revoke may need to finish, slack included,
// so a caller bounding it does not cut its final pass short. It
// depends on the broker's auth timeout and is known after Start.
RevokeBudget() time.Duration
// Identity names the broker and account sqi's streams live in, so a
// change of broker can be detected across restarts.
Identity() string
// AdvertiseURL is the broker URL discovery tells workers to use: the
// one configured for advertising, else the broker's own. host is this
// machine's discovery host name, for a broker whose URL is this machine.
// Call it after Start.
AdvertiseURL(host string) (string, error)
}
Broker is the NATS broker sqi-server runs on. Embedded hosts it inside the process; Remote connects to an operator-run server or cluster. Both modes share the same account layout (Layout) and authenticate workers through the same auth-callout Responder.
type BrokerTLSConfig ¶ added in v0.4.0
type BrokerTLSConfig struct {
// Enabled makes the broker require TLS on every client connection.
Enabled bool
// CertFile and KeyFile are the PEM certificate and key the broker
// presents. Both are validated at config load.
CertFile string
KeyFile string
// ClientCAFile, when set, requires each connecting worker to present a
// client certificate signed by this CA. It is a transport control
// layered on the nkey credential, never a substitute: the certificate
// decides who may open a connection, the nkey decides which worker they
// are.
ClientCAFile string
}
BrokerTLSConfig controls TLS on the embedded broker's client listener. Zero value leaves TLS off, which is the default.
This is bus's own view of the operator's nats.embedded.tls block, mapped by the caller, so that internal/bus does not import internal/config.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the typed NATS client sqi-server code publishes and subscribes through, which keeps the raw nats API out of its callers.
Obtain a Client via Broker.NewClient after the broker has been started. A Client should be shared across goroutines; its methods are safe for concurrent use.
func NewClient ¶
NewClient dials the broker at url, the embedded server in-process or an external cluster, and returns a connected Client. The connection reconnects without limit every 2 s, so a broker restart or a brief partition recovers on its own.
extraOpts are appended after the default options, so a caller can supply authentication (e.g. an nkey credential) without disturbing the reconnect behavior above. NewClient owns the reconnect, disconnect and asynchronous error handlers, which maintain Client.BusUpSince and Client.InterruptedAt: one passed in extraOpts is replaced.
Prefer Broker.NewClient over calling NewClient directly; the Broker supplies the URL, credential and TLS options for its mode.
func (*Client) BusUpSince ¶ added in v0.4.0
BusUpSince returns when the client's connection was last established or re-established, and the zero time while it is disconnected. Safe for concurrent use.
The scheduler uses it to avoid judging workers by heartbeats that could not have reached it: a heartbeat travels over the bus, so a broker outage looks exactly like every worker going silent at once.
func (*Client) Close ¶
func (c *Client) Close()
Close closes the underlying NATS connection immediately without draining. Prefer Client.Drain for graceful shutdown; use Close only when draining has already completed or is not possible.
func (*Client) ConsumeTaskLogs ¶
func (c *Client) ConsumeTaskLogs(ctx context.Context, handler jetstream.MessageHandler) (jetstream.ConsumeContext, error)
ConsumeTaskLogs creates or updates the server-side durable consumer for log-chunk messages (SQI_LOGS stream) and begins delivering them to handler. The returned ConsumeContext is tracked internally and stopped automatically during Client.Drain.
Ack / redelivery policy:
- AckWait 30 s — the server has 30 s to persist a log chunk to the store. The write is a single INSERT.
- MaxDeliver 10 — allows for transient DB errors without re-filling the stream indefinitely: with the scheduler's growing nak delay the deliveries span minutes, as the task-status consumer's do, so a chunk survives a store outage as long as its task's status does. After exhaustion the chunk is discarded; the stream is not read back by the API, so the gap stays.
- DeliverAllPolicy — redelivers unacked log chunks from before the last server restart so no output is permanently lost across restarts. A chunk already stored is acked without being written again (task_logs is unique on attempt and worker sequence).
func (*Client) ConsumeTaskStatus ¶
func (c *Client) ConsumeTaskStatus(ctx context.Context, handler jetstream.MessageHandler) (jetstream.ConsumeContext, error)
ConsumeTaskStatus creates or updates the server-side durable consumer for task-status messages (SQI_TASK stream) and begins delivering them to handler. The returned ConsumeContext is tracked internally and stopped automatically during Client.Drain.
Ack / redelivery policy:
- AckWait 30 s — the server has 30 s to persist a status update to the store before NATS redelivers.
- MaxDeliver 10 — allows for transient DB errors without dropping updates. The scheduler naks a failed message with a growing delay, so the ten deliveries span minutes of store outage, not milliseconds.
- DeliverAllPolicy — on first consumer creation, replay any unprocessed messages from before the last server restart so no state transitions are silently lost. NATS tracks the consumer sequence for existing durables, so subsequent starts pick up where they left off.
func (*Client) ConsumeWorker ¶
func (c *Client) ConsumeWorker(ctx context.Context, handler jetstream.MessageHandler) (jetstream.ConsumeContext, error)
ConsumeWorker creates or updates the server-side durable consumer for worker-registration and heartbeat messages (SQI_WORKER stream) and begins delivering them to handler. The returned ConsumeContext is tracked internally and stopped automatically during Client.Drain.
Ack / redelivery policy:
- AckWait 10 s — heartbeats are time-sensitive; a 10 s window is well within the scheduler's default 30 s heartbeat timeout, so a redelivery lands before a worker is wrongly marked offline.
- MaxDeliver 11. The scheduler naks a failed message with a growing delay (1, 2, 4, 8, 16, 30, 30 s…), so deliveries land at about 0, 1, 3, 7, 15, 31, 61, 91 and 121 s. The stream's 2-minute MaxAge removes the message before the ninth, so the last delivery is the eighth at about 91 s: a message outlives about 1.5 minutes of store outage (a PostgreSQL restart, an HA failover). A registration needs that, because a worker registers only at start and after a broker reconnect, and a dropped one leaves its worker idle and unseen until the next reconnect. A deregister or restart registration waiting for the task-status consumer is nak'd 2 s apart for up to seven deliveries and applied on the eighth, at about 14 s; if that apply fails it needs three more deliveries 30 s apart (at about 44, 74 and 104 s) to outlive the same outage, hence eleven. MaxAge still ends every other message at its eighth delivery. A heartbeat that arrives before its worker's registration is retried a second later. The growing delay bounds the pile-up of held-back heartbeats, and a held-back heartbeat is ignored when it lands after a later one was recorded, since heartbeats are ordered by their broker timestamp.
- DeliverAllPolicy — replays unprocessed registration/heartbeat messages on startup, ensuring no worker comes online without the server noticing.
func (*Client) ConsumerAckFloor ¶ added in v0.4.0
ConsumerAckFloor returns consumer's ack floor: the stream sequence at or below which the broker will deliver it nothing more. A message is at or below the floor once it has been acked or removed from the stream. A message whose deliveries have run out is passed by the floor only once the consumer then has no other message delivered and unacknowledged, which the next ack (an ingest marker's, every few seconds) brings about whenever the consumer is caught up. A message still to be delivered keeps the floor below it. It is one consumer-info request to the broker.
func (*Client) Drain ¶
Drain stops all consumers started by this Client, waits for in-flight message handlers to finish, and then drains the underlying NATS connection (flushing pending publish-acks and waiting for all outstanding messages to be delivered) and waits for it to close. It respects the given context deadline.
jetstream.ConsumeContext.Drain and nats.Conn.Drain only start a drain: both return at once and finish in the background. Drain waits for each consumer's Closed channel and then for the connection to reach CLOSED, so that when it returns the buffered messages have been handled. The server shuts the broker down, and on an external broker releases its account guard, as soon as Drain returns.
Call Drain before Client.Close or Broker.Shutdown for a clean shutdown: no in-flight messages are dropped and no pending publishes are lost. After Drain returns, no further messages will arrive at handlers. When ctx ends first, Drain stops the consumers, closes the connection and returns an error.
func (*Client) InterruptedAt ¶ added in v0.4.0
InterruptedAt returns the latest moment this client's connection or one of its consumers was interrupted, and the zero time if none has been. An interruption is a disconnect, a reconnect, a consumer error that means its pull was lost (jetstream.ErrNoHeartbeat, jetstream.ErrConsumerLeadershipChanged, nats.ErrNoResponders) or an asynchronous nats.ErrSlowConsumer. Safe for concurrent use.
Unlike Client.BusUpSince it stays set after the connection is back: a message the broker sent while a consumer's pull was lost is redelivered only after the consumer's AckWait, so the store can lag the stream for that long.
func (*Client) PublishIngestMarkers ¶ added in v0.4.0
PublishIngestMarkers publishes an empty message on SubjectMarkerWorker and on SubjectMarkerTask, and returns once the broker has stored both or their timeouts have passed. A consumer that handles one has handled every message stored in its stream before it. Each publish waits at most timeout on its own, so a stall on one stream does not cut the other short. Both publishes are attempted; the errors of those that failed are returned joined.
func (*Client) PublishTaskCancel ¶
PublishTaskCancel publishes a task-cancellation signal to workerID's task.cancel.<workerID> subject. The scheduler calls this for each task that was assigned or running when it was canceled, addressed to the worker holding it, which interrupts the run the message names without waiting for the next heartbeat timeout.
func (*Client) PublishTaskLog ¶
PublishTaskLog publishes a log chunk to the task.logs.<workerID>.<taskID> subject. Workers call this continuously as a task produces output; the server retains chunks in JetStream for later retrieval via the REST and WebSocket APIs.
func (*Client) PublishTaskStatus ¶
PublishTaskStatus publishes a task-status transition to the task.status.<workerID>.<jobID> subject. Workers call this when a task transitions to running, succeeded, failed, or canceled.
func (*Client) PublishWorkerDiag ¶
PublishWorkerDiag publishes a diagnostic log record to worker.diag.<workerID> over core NATS (fire-and-forget, no JetStream ack). Errors are returned but callers should treat them as non-fatal: diagnostics are best-effort.
func (*Client) PublishWorkerHeartbeat ¶
PublishWorkerHeartbeat publishes a heartbeat ping on the worker.heartbeat.<workerID> subject. Workers call this on a regular interval; the server-side heartbeat sweep marks workers offline when pings stop.
func (*Client) PublishWorkerRegister ¶
PublishWorkerRegister publishes a capability advertisement on the worker.register.<workerID> subject. Workers call this on first connect and after any reconnect so the server always has a current view of their capabilities.
func (*Client) RequestLease ¶
func (c *Client) RequestLease(ctx context.Context, workerID, queueID string, data []byte, timeout time.Duration) ([]byte, error)
RequestLease sends a core-NATS work-lease request for queueID on behalf of workerID and waits up to timeout for the server's reply. Returns nats.ErrNoResponders immediately if no server is subscribed, or nats.ErrTimeout if no reply arrives in time.
func (*Client) RequestWorkerControl ¶ added in v0.4.0
func (c *Client) RequestWorkerControl(ctx context.Context, workerID string, data []byte) ([]byte, error)
RequestWorkerControl sends a power command to workerID as a core-NATS request on worker.control.<workerID> and returns the worker's reply. ctx carries the timeout. It returns nats.ErrNoResponders at once when the worker is not subscribed, which is how a worker that is asleep or disconnected answers.
func (*Client) SubscribeLease ¶
func (c *Client) SubscribeLease(handler func(workerID, queueID string, data []byte) []byte) (*LeaseSubscription, error)
SubscribeLease subscribes to work-lease requests from all workers for all queues (work.lease.>) and replies with the bytes handler returns. The requesting worker's ID and the queue it asked about are taken from the subject. handler does its own long-poll blocking before returning; it must respect no work by returning an empty/again-marker payload of the caller's choosing.
func (*Client) SubscribeWorkerDiag ¶
func (c *Client) SubscribeWorkerDiag(handler func(subject string, data []byte)) (*nats.Subscription, error)
SubscribeWorkerDiag subscribes to all worker diagnostic subjects (worker.diag.>) over core NATS and invokes handler for each message with the concrete subject and raw payload. The returned subscription must be unsubscribed/drained by the caller (the server does this at shutdown).
type ClientTLSConfig ¶ added in v0.4.0
type ClientTLSConfig struct {
// CAFile verifies the broker's certificate in place of the system roots.
CAFile string
// CertFile and KeyFile are a client certificate, for brokers that
// require mutual TLS. Both or neither.
CertFile string
KeyFile string
// ServerName overrides the name the broker's certificate is checked
// against, which is otherwise the host of the URL dialed.
ServerName string
}
ClientTLSConfig is the client side of TLS to an external broker. The zero value adds nothing: a tls:// URL then verifies the broker against the system roots.
type CredentialLookup ¶ added in v0.4.0
CredentialLookup resolves a worker's public nkey to the worker ID of its active credential. It wraps ErrUnknownCredential when there is none (the key was never enrolled, or its credential was revoked). Any other error is a failure to answer, and denies the connection exactly as an unknown key does.
type DurableConsumer ¶ added in v0.4.0
DurableConsumer is a durable consumer and the stream it reads.
func RestoreTargets ¶ added in v0.4.0
func RestoreTargets() (streams []string, consumers []DurableConsumer)
RestoreTargets returns what RestoreLock.Purge empties: every one of sqi's streams, and the durable consumers a running sqi-server keeps on them.
type Embedded ¶ added in v0.4.0
type Embedded struct {
// contains filtered or unexported fields
}
Embedded is the NATS server sqi-server hosts in-process, with JetStream in the SQI account. It implements Broker.
sqi's own two connections are in-process (nats.InProcessServer): the data connection in SQI, which provisions the streams and backs every Client handed out by Embedded.NewClient, and, with auth on, the callout connection in AUTH, which answers authorization requests.
func NewEmbedded ¶ added in v0.4.0
func NewEmbedded(cfg EmbeddedConfig, logger *slog.Logger) *Embedded
NewEmbedded creates an Embedded broker with the given configuration and logger. Call Embedded.Start to boot it.
func (*Embedded) AdvertiseURL ¶ added in v0.4.0
AdvertiseURL returns EmbeddedConfig.AdvertiseURL when set, else nats:// (tls:// when the listener requires TLS) + host + the port the listener bound, read from the listener rather than the configuration.
func (*Embedded) Check ¶ added in v0.4.0
Check implements [health.Checker]. It returns nil when the embedded NATS server is running, the data connection is connected and, with auth on, so is the callout connection: without it every worker connect is refused.
func (*Embedded) ClientURL ¶ added in v0.4.0
ClientURL returns the URL network clients (workers) connect to. Returns an empty string if the broker has not been started yet. sqi-server's own connections do not use it; they are in-process.
func (*Embedded) Identity ¶ added in v0.4.0
Identity returns "embedded:SQI": the embedded broker always keeps sqi's streams in the SQI account of its own data directory.
func (*Embedded) InProcessConn ¶ added in v0.4.0
InProcessConn dials the current server in-process. Every in-process connection to the embedded broker dials through it rather than through one server, so when the broker restarts nats.go's reconnect lands on the new server.
func (*Embedded) NewClient ¶ added in v0.4.0
NewClient returns a connected Client on the data connection's credential, in-process, configured for automatic reconnection. It must be called after Embedded.Start returns successfully.
The returned Client should be shared across goroutines; create one per server component (or one shared instance for the whole server) rather than dialing repeatedly.
func (*Embedded) Revoke ¶ added in v0.4.0
Revoke disconnects every connection authorized as workerID. The callout names each worker connection after its worker ID, so the connections are found by that user name in the SQI account.
Call it after the credential is revoked in the store. When Revoke returns nil, the broker holds no connection for workerID whose authorization began before Revoke did:
- the first pass, at once, disconnects every connection present;
- the final pass runs once nats-server's auth timeout (plus [revokeSettleMargin]) has elapsed since Revoke began. nats-server abandons a callout after that timeout, so every authorization that was already in flight, perhaps on a store read from before the revocation, has by then either placed its connection, which this pass disconnects, or been refused.
Revoke therefore takes about the auth timeout (2s, or 3s with TLS). If ctx ends first it returns ctx's error after the first pass only. Any reconnect is authorized afresh against the store and refused.
func (*Embedded) RevokeBudget ¶ added in v0.4.0
RevokeBudget is how long Embedded.Revoke may need: the auth timeout and the settle margin, plus slack for a slow host. Zero before Start.
func (*Embedded) Shutdown ¶ added in v0.4.0
func (e *Embedded) Shutdown()
Shutdown closes sqi's connections and stops the embedded NATS server, waiting until it has exited before returning. It is safe to call Shutdown more than once; later calls do nothing.
With auth on, the callout subscription stops taking requests first and the authorizations already accepted are answered before the callout connection closes, for at most the responder's own per-request budget.
It is also safe to call concurrently with Revoke, Check, ClientURL and NewClient: the fields those methods read are captured under mu and nilled here under the same lock. The (possibly slow) nats-server calls below run after the lock is released.
func (*Embedded) Start ¶ added in v0.4.0
Start boots the embedded NATS server with sqi's account layout, enables JetStream on the SQI account, opens sqi's own connections, starts the auth-callout responder when auth is on, and provisions the streams.
Start must be called before any other method and must not be called more than once.
type EmbeddedConfig ¶ added in v0.4.0
type EmbeddedConfig struct {
// Addr is the TCP address the embedded NATS server binds to, in
// "host:port" form. Defaults to "0.0.0.0:4222" (all interfaces) so that
// workers which discover the server via mDNS can reach the broker at the
// advertised LAN host.
//
// Broker authentication is off by default. With it off, any host that
// can reach this port can register as a worker and receive assignments,
// on a LAN too, since the default binds all interfaces; sqi-server logs a
// warning at startup when the address is not loopback. Set
// nats.auth.enabled to require a per-worker credential, or bind this to
// 127.0.0.1:4222 for single-machine use. See docs/auth.md.
Addr string
// DataDir is the directory JetStream uses for file-backed stream storage.
// Created at startup if it does not exist.
DataDir string
// MaxStoreMB caps the SQI account's JetStream storage, in megabytes.
// A value of 0 means unlimited (not recommended for production).
MaxStoreMB int
// TLS configures transport encryption on the client listener. Zero value
// leaves the broker plaintext, which is the default.
TLS BrokerTLSConfig
// AdvertiseURL, when set, is the URL discovery advertises in place of
// one built from the discovery host and the listener's bound port.
AdvertiseURL string
// Auth configures worker authentication through the auth callout. Zero
// value leaves it off.
Auth AuthConfig
}
EmbeddedConfig holds the parameters of the NATS server sqi-server hosts in-process.
type Guard ¶ added in v0.4.0
type Guard struct {
// contains filtered or unexported fields
}
Guard is a held one-server-per-account lease. The holder refreshes it by compare-and-set until Guard.Release; a key left unrefreshed expires after the bucket's TTL, so a holder that dies frees the account.
type GuardHolder ¶ added in v0.4.0
type GuardHolder struct {
InstanceID string `json:"instance_id"`
Host string `json:"host"`
PID int `json:"pid"`
StartedAt time.Time `json:"started_at"`
// Purpose says what holds the account when it is not a running server:
// [GuardPurposeRestore] for "sqi-server restore". Empty for a server.
Purpose string `json:"purpose,omitempty"`
}
GuardHolder identifies the sqi-server that holds the guard. It is the JSON value stored under the guard key.
type GuardOptions ¶ added in v0.4.0
type GuardOptions struct {
// IsMember reports whether instanceID is a server of this database. A key
// held by a member is overwritten at once; a key held by anyone else is
// watched for one TTL before anything is decided. Nil means no server is
// a member, and acquiring does not watch.
IsMember func(instanceID string) bool
// OnLost is called once, on its own goroutine, when another holder takes
// the key. It may call back into the guard, [Guard.Release] included.
// Nil means only [Guard.Healthy] reports it.
OnLost func(error)
}
GuardOptions changes how the guard treats a key held by another server. The zero value refuses on any other holder.
type IngestConsumer ¶ added in v0.4.0
type IngestConsumer int
IngestConsumer names a server consumer whose progress the scheduler tracks: IngestWorker or IngestTaskStatus.
const ( // IngestWorker is the worker registration and heartbeat consumer // ([Client.ConsumeWorker]). IngestWorker IngestConsumer = iota // IngestTaskStatus is the task-status consumer ([Client.ConsumeTaskStatus]). IngestTaskStatus )
type Layout ¶ added in v0.4.0
type Layout struct {
// Account is the NATS account sqi's data lives in.
Account string
// AuthEnabled selects the auth-callout layout over the anonymous one.
AuthEnabled bool
// IssuerPub is the public account key the callout's user JWTs are signed
// with. Required with AuthEnabled.
IssuerPub string
// DataUserPub is the public user key of sqi's data connection.
DataUserPub string
// CalloutUserPub is the public user key of sqi's callout connection.
// Required with AuthEnabled; otherwise the AUTH account has no users.
CalloutUserPub string
// JetStreamMaxStore caps the file storage of Account's JetStream, in
// bytes. 0 means unlimited.
JetStreamMaxStore int64
}
Layout describes sqi's NATS account layout once, for both broker modes. Layout.Apply renders it as nats-server Options for the embedded broker; Layout.ConfigFragment renders the same layout as config-file text for an external cluster. The tests parse the fragment with nats-server's own config reader and compare the result with Apply's Options (accounts, each nkey's account and permissions, the callout, no_auth_user), and boot a server from each to check where JetStream places streams.
The layout has two accounts. Account holds sqi's data and its data connection, which authenticates as DataUserPub with brokerauth.ServerPermissions (">" both ways) and is safe only because the account boundary scopes it. AUTH holds the callout connection, CalloutUserPub.
With AuthEnabled, nats-server asks sqi's responder to authenticate every connection except the two sqi users, which are exempt through auth_users so that neither needs the responder to be running before it can connect. With auth off, there is no callout and anonymous connections are mapped to the data user, with its unrestricted grants inside the named account.
func (Layout) Apply ¶ added in v0.4.0
func (l Layout) Apply(o *natsserver.Options) error
Apply sets the layout on o: Accounts, Nkeys, AuthCallout or NoAuthUser, and AlwaysEnableNonce. It replaces Accounts and Nkeys outright, so it expects Options that do not already define users.
AlwaysEnableNonce is set in both modes. nats-server issues a nonce only when it has nkey users or trusted keys; the data user makes the first true here, but the flag keeps that from depending on how the layout is edited. The config-file form has no such key, so a cluster needs its own nkey users, which the fragment supplies.
JetStream is not part of Apply. nats-server exposes no Options field that enables it for one named account, so the caller starts the server with Options.JetStream and then calls Layout.EnableAccountJetStream.
func (Layout) ConfigFragment ¶ added in v0.4.0
ConfigFragment renders the layout as nats-server config text for an external cluster: an accounts block (Account with JetStream, AUTH, and an empty SYS), system_account, and then either an authorization block with auth_callout or a no_auth_user. The operator supplies everything else (listeners, TLS, clustering, the JetStream store).
SYS is declared with no users. A harness or operator that needs a system user uses Layout.ConfigFragmentWithSystemUser rather than appending a second accounts block, which nats-server does not merge.
It returns an error for a layout Layout.Apply would refuse: a reserved or malformed account name would otherwise render a duplicate map key, which the nats config parser resolves by silently keeping the last one.
func (Layout) ConfigFragmentWithSystemUser ¶ added in v0.4.0
ConfigFragmentWithSystemUser is Layout.ConfigFragment with one nkey user in the SYS account. An empty key leaves SYS without users. With auth on, the user is also added to auth_users, so it authenticates without the callout. A non-empty key must be a user public key distinct from sqi's own users.
func (Layout) EnableAccountJetStream ¶ added in v0.4.0
func (l Layout) EnableAccountJetStream(s *natsserver.Server) error
EnableAccountJetStream enables JetStream on Account of a server started with Options.JetStream and the layout applied. Without it, JetStream is on for the server but for no account, and every stream request fails.
type LeaseSubscription ¶ added in v0.4.0
type LeaseSubscription struct {
// contains filtered or unexported fields
}
LeaseSubscription is the server's subscription to work-lease requests.
func (*LeaseSubscription) Stop ¶ added in v0.4.0
func (l *LeaseSubscription) Stop(ctx context.Context, wake func()) error
Stop stops taking requests, then calls wake, then returns once every request already taken has been answered, or when ctx ends. wake is called exactly once, whatever Stop returns, and is where the caller releases the replies it holds back while stopping (see below).
The subscription is drained, so the client keeps delivering until the broker node it is connected to has stopped routing here: until then a request is delivered and answered, and after it one sent to that node finds no responder, and the worker retries after its brief backoff rather than waiting out its whole request timeout. On a cluster, a node that has not yet learnt the interest is gone still forwards a request, which is then dropped. The caller narrows that window by sending no reply while stopping until wake: a reply then follows the interest removal over the same route, so the requester's node has seen it go before the requester can ask again. Stop waits for the handlers because the server closes its connection right after the scheduler stops, and a reply sent after that is lost too.
func (*LeaseSubscription) Unsubscribe ¶ added in v0.4.0
func (l *LeaseSubscription) Unsubscribe() error
Unsubscribe removes the subscription at once, without waiting for the requests it has taken to be answered. Tests use it for cleanup; a server stops with LeaseSubscription.Stop.
type Remote ¶ added in v0.4.0
type Remote struct {
// contains filtered or unexported fields
}
Remote is an operator-run NATS server or cluster sqi-server connects to. It implements Broker.
sqi holds one data connection, in the configured account, which provisions the streams and whose dial options every Client from Remote.NewClient reuses. With worker authentication on it also holds the callout connection, in the AUTH account, which answers the cluster's authorization requests, and, when a system credential is configured, a system-account connection that revocation kicks workers through.
func NewRemote ¶ added in v0.4.0
func NewRemote(cfg RemoteConfig, logger *slog.Logger) *Remote
NewRemote creates a Remote broker with the given configuration and logger. Call Remote.Start to connect.
func (*Remote) AdvertiseURL ¶ added in v0.4.0
AdvertiseURL returns the first RemoteConfig.AdvertiseURLs entry, else the first of RemoteConfig.URLs. host is unused: the cluster's URLs are its own.
func (*Remote) Check ¶ added in v0.4.0
Check implements [health.Checker]. It returns nil while the data connection is connected and, with auth on, so is the callout connection: without it every worker connect is refused. The system connection is not checked: without it revocation waits for the user JWT's expiry, and Revoke reports that, but workers keep working. Check also returns the guard's Guard.Healthy error, so a server that lost its account reports degraded. A standby is not ready until its broker checks have passed (Remote.StandbyReady). It makes no round trip, so it answers within the health budget during a partition.
func (*Remote) Connected ¶ added in v0.4.0
Connected reports whether the data connection is up and, when it is, since when: the time it last connected or reconnected, in UTC. While it is down, and before Start or StartStandby and after Shutdown, it returns false and the zero time. Both are read from nats.go's connection handlers, which run just after the event, so a connection that has only just come up may be reported down for that moment. Safe for concurrent use.
func (*Remote) Identity ¶ added in v0.4.0
Identity returns "external:<account>@<cluster>", the cluster name being the one the broker reports. A broker that is not clustered reports none, so its server name stands in when the operator set one. Before Start, and for a standalone broker with no server name, it is "external:<account>".
func (*Remote) LockForRestore ¶ added in v0.4.0
func (r *Remote) LockForRestore(ctx context.Context) (*RestoreLock, error)
LockForRestore connects with the data credential alone, with no callout responder and no system connection, checks the broker's version and that the account has JetStream, and takes the account's guard as a restore. It returns an error wrapping ErrGuardHeld, and changes nothing, while an sqi-server runs on the account.
It changes nothing on the broker but the guard key: on an account no server has used it creates the guard bucket, and an existing bucket keeps its configuration. Call it on a Remote that is not started, and call RestoreLock.Release when done.
func (*Remote) NewClient ¶ added in v0.4.0
NewClient returns a connected Client on the data connection's credential and TLS settings, reconnecting without limit. It must be called after Remote.Start returns successfully.
func (*Remote) Revoke ¶ added in v0.4.0
Revoke disconnects every connection authorized as workerID, on every node of the cluster. The callout names each worker connection after its worker ID, so the connections are found by that user name in sqi's account. With worker authentication off there is nothing to revoke: any client may connect, so it returns nil.
Call it after the credential is revoked in the store. Without a system credential sqi cannot reach another client's connection, so Revoke only logs: the worker stays connected until its user JWT expires, at most UserTTL, and its reconnect is then refused.
With a system credential, when Revoke returns nil every node of the cluster has been asked and none holds a connection for workerID whose authorization began before Revoke did. As in Embedded.Revoke there are two passes, each a CONNZ request to every node followed by a KICK for each connection found:
- the first, at once, kicks every connection present;
- the final one runs once the cluster's auth timeout (the longest any node has reported, at Start or alongside an earlier pass, plus [revokeSettleMargin]) has elapsed since Revoke began. A node abandons a callout after that timeout, so every authorization that was already in flight, perhaps on a store read from before the revocation, has by then either placed its connection, which this pass kicks, or been refused.
A pass fails, and so does Revoke, when fewer nodes answer than sqi knows the cluster has, or when a kick is not confirmed: the worker may then still be connected. A cluster that has shrunk for good keeps failing revocations until sqi-server restarts and counts it afresh.
Each pass collects replies for [systemReplyWindow], so Revoke takes about the auth timeout plus that window (3.25s at nats-server's defaults, 4.25s with TLS); Remote.RevokeBudget says how long to allow. If ctx ends first it returns ctx's error, after the first pass at the most. Any reconnect is authorized afresh against the store and refused.
func (*Remote) RevokeBudget ¶ added in v0.4.0
RevokeBudget is how long Remote.Revoke may need: the cluster's auth timeout, the settle margin, the final pass's reply window and its kicks, and some slack. Zero when Revoke does not wait (auth off, or no system credential).
func (*Remote) SetCalloutActive ¶ added in v0.4.0
SetCalloutActive takes this server's auth-callout responder out of the sqi-auth queue group (false), so that every authorization request goes to the other servers in it, or puts it back (true). An HA standby whose worker grants differ from the leader's (GrantsFingerprint) leaves the group, so that a worker is never authorized differently depending on which server answers. Setting the state the responder is already in does nothing. It is safe to call concurrently with requests being answered, which complete; it does nothing with worker authentication off, and after Shutdown. On a standby whose checks have not passed it only records the state, which applies when they do; a standby refused by its checks never answers.
func (*Remote) Shutdown ¶ added in v0.4.0
func (r *Remote) Shutdown()
Shutdown closes sqi's connections to the broker. The broker itself is the operator's and keeps running. It is safe to call more than once and concurrently with the other methods.
With auth on, the callout subscription stops taking requests first and the authorizations already accepted are answered before the callout connection closes, for at most the responder's own per-request budget. The account's guard is released before the data connection closes.
func (*Remote) StandbyChecked ¶ added in v0.4.0
func (r *Remote) StandbyChecked() <-chan struct{}
StandbyChecked is closed once Remote.StandbyReady has its final outcome.
func (*Remote) StandbyReady ¶ added in v0.4.0
StandbyReady reports the outcome of a standby's broker checks (see Remote.StartStandby): ErrStandbyUnchecked until they have run, nil once they passed, and why they failed otherwise, such as an error wrapping ErrGuardHeld when a server of another database holds the account. A failure is final: the server cannot become ready or the leader, and should exit. For a broker started with Start it is nil once Start succeeds.
func (*Remote) Start ¶ added in v0.4.0
Start connects to the broker, checks its version, checks that JetStream is on for the account, and takes the account's one-server guard, so a second sqi-server on the same account fails Start with ErrGuardHeld before it touches anything the first one owns. It then creates or updates sqi's streams with the configured replica count. With worker authentication on it then starts answering the cluster's authorization requests and, when a system credential is configured, opens the system connection revocation uses. It must be called before any other method and must not be called more than once. An HA server calls Remote.StartStandby instead.
func (*Remote) StartStandby ¶ added in v0.4.0
func (r *Remote) StartStandby(ctx context.Context, opts GuardOptions) error
StartStandby starts the broker for a standby server of an HA group: it opens the data connection, and with worker authentication on the callout and system connections. It neither takes the account's guard nor creates any stream; Remote.TakeLeadership does both on promotion.
Before a standby does anything on the broker it checks it, as Start does (version, JetStream on the account), and checks the guard with CheckGuard under opts, so a standby pointed at an account a server of another database holds is refused, after watching that server's key for up to one TTL. The connect timeout bounds the broker checks, and the guard check may take [haGuardWatch] past it. Only once the checks pass does the standby answer the cluster's authorization requests, so that workers can connect while no server leads; until then a callout reaching the account may belong to that other farm, whose credentials this server does not have.
A standby does not need its broker to start. When a broker answers the first attempt, StartStandby runs the checks and returns their failure, if any, having shut the broker down, as Start does. When none does, StartStandby logs it and returns nil; the connections keep trying in the background, and the checks run once the data connection connects. Then a failure a retry may clear is logged and the checks run again; a refusal (version floor, no JetStream on the account, the guard held by another database's server) is final, logged and reported by Remote.StandbyReady, and the standby stays not ready and answers no callout. Remote.StandbyChecked is closed when the outcome is known, and Remote.Connected says whether the data connection is up.
RemoteConfig.InstanceID must be set. StartStandby must be called instead of Remote.Start, once.
func (*Remote) TakeLeadership ¶ added in v0.4.0
func (r *Remote) TakeLeadership(ctx context.Context, opts GuardOptions) error
TakeLeadership promotes a standby started with Remote.StartStandby: it checks the broker as Start does, takes the account's guard under opts, and creates or updates the streams with the configured replica count. It is Start's provisioning, under the HA guard. The guard is held under RemoteConfig.InstanceID, so the next leader recognizes it as a member's, and opts.OnLost hears when another server takes it.
It fails at once when the data connection is down: only a standby with a broker may lead. The connect timeout plus [haGuardWatch] bounds it, the watch of a key held by a server outside this database included. On failure nothing is held, and it may be called again; on success, a second call fails. Remote.Shutdown releases the guard.
type RemoteAuthConfig ¶ added in v0.4.0
type RemoteAuthConfig struct {
AuthConfig
// CalloutNkeySeedFile is the callout connection's user, in the AUTH
// account.
CalloutNkeySeedFile string
// IssuerSeedFile is the account nkey seed callout responses are signed
// with.
IssuerSeedFile string
// SystemCredsFile is an optional system-account user's nkey seed. With
// it, [Remote.Revoke] finds a worker's connections on every node and
// kicks them; without it, a revoked worker stays connected until its
// user JWT expires, UserTTL at the most.
//
// It is a raw nkey seed, not a .creds JWT file: in the non-operator
// account layout sqi uses, nats-server authenticates nkey users by their
// signature alone and ignores a user JWT.
SystemCredsFile string
}
RemoteAuthConfig is AuthConfig plus the keys the auth callout needs on an external broker.
type RemoteConfig ¶ added in v0.4.0
type RemoteConfig struct {
// URLs are the broker URLs, all tls:// or all nats://.
URLs []string
// AdvertiseURLs, when set, are what discovery tells workers to use in
// place of URLs; only the first is advertised.
AdvertiseURLs []string
// Account is the dedicated account sqi's streams and workers live in.
// The data connection's credential must place it there.
Account string
// NkeySeedFile and CredsFile are the data connection's credential, at
// most one of them. Neither means an unauthenticated account.
NkeySeedFile string
CredsFile string
// StreamReplicas is the replica count of every stream: 1, 3 or 5.
StreamReplicas int
// ConnectTimeout bounds startup: reaching a broker and finding JetStream
// on Account. Reconnects after startup are unbounded.
ConnectTimeout time.Duration
// TLS is the client-side TLS configuration of every connection sqi makes.
TLS ClientTLSConfig
// Auth configures worker authentication through the auth callout.
Auth RemoteAuthConfig
// InstanceID is this server's member instance id in an HA group, the one
// it records as a member of its database. It names the server in the
// account guard, so that the next leader recognizes a key a crashed
// leader left as a member's. [Remote.StartStandby] requires it. Empty
// gives every guard acquisition a fresh id.
InstanceID string
}
RemoteConfig holds the parameters of an operator-run NATS server or cluster sqi-server connects to.
It is bus's own view of the operator's nats.external block, which internal/config validates. The caller maps it, so that internal/bus does not import internal/config.
type Responder ¶ added in v0.4.0
type Responder struct {
// contains filtered or unexported fields
}
Responder answers nats-server's auth-callout requests. It is the single place that decides whether a worker may connect and with which permissions, so nothing in it may answer "allow" except through a successful Responder.Authorize.
func NewResponder ¶ added in v0.4.0
func NewResponder(cfg ResponderConfig) (*Responder, error)
NewResponder validates cfg and returns a Responder.
func (*Responder) Authorize ¶ added in v0.4.0
func (r *Responder) Authorize(ctx context.Context, req *jwt.AuthorizationRequestClaims) (string, error)
Authorize decides one request. On success it returns the signed user JWT to place the connection with; on any failure it returns an error and no JWT, after logging why.
func (*Responder) Handle ¶ added in v0.4.0
Handle answers one request as nats-server expects: a signed AuthorizationResponseClaims JWT, allowing with a user JWT or refusing with an error. It returns an empty reply, which nats-server reads as "not authorized", only when the request is so malformed that there is no user or server to address a response to.
func (*Responder) Listen ¶ added in v0.4.0
Listen is Responder.Serve without waiting for the server: the subscription reaches it when nc next sends, or, on a connection still trying to connect for the first time, as soon as it connects. Call it, or Serve, once.
func (*Responder) Pause ¶ added in v0.4.0
Pause takes the responder out of the callout queue group, so that the cluster sends every authorization request to the other servers in it. It reports whether the responder was serving. Requests already being answered are answered; requests delivered but not yet taken are dropped, and their connects are refused when the broker's auth timeout passes and retried by the workers. While nc is connected Pause returns once the server has the change, bounded by [calloutFlushTimeout]. It does nothing when the responder is not serving.
func (*Responder) Resume ¶ added in v0.4.0
Resume rejoins the callout queue group after Responder.Pause, and reports whether it did. It does nothing while serving, before Serve and after Stop.
func (*Responder) Serve ¶ added in v0.4.0
Serve subscribes the responder to the callout subject on nc as part of the shared queue group and replies to every request with Responder.Handle. Requests are handled concurrently, at most [calloutMaxInFlight] at a time. Serve returns once the subscription is registered on the server; ctx may carry no deadline, so that round trip is bounded by [calloutFlushTimeout]. Call it once, and Responder.Stop when the connection is about to close.
func (*Responder) Stop ¶ added in v0.4.0
func (r *Responder) Stop()
Stop stops the subscription Responder.Serve made from taking new requests and waits, for at most [calloutMaxTimeout], for the requests it already accepted to be answered, so a shutdown does not close the connection under them. It logs when some were not. A paused responder has no subscription to stop and only waits. Stop does nothing if Serve did not succeed, or on a second call.
type ResponderConfig ¶ added in v0.4.0
type ResponderConfig struct {
// Issuer signs every response and user JWT. It must hold an account
// seed; nats-server is configured to trust its public key.
Issuer nkeys.KeyPair
// Account is the name of the NATS account workers are placed in.
Account string
// UserTTL is how long an issued user JWT stays valid. nats-server
// disconnects the connection at that point and the worker reconnects
// through the callout again.
UserTTL time.Duration
// Lookup resolves a worker's key to its worker ID.
Lookup CredentialLookup
// Now returns the current time. Nil means time.Now.
Now func() time.Time
// Logger receives every denial. Nil means slog.Default.
Logger *slog.Logger
}
ResponderConfig configures a Responder.
type RestoreLock ¶ added in v0.4.0
type RestoreLock struct {
// contains filtered or unexported fields
}
RestoreLock is a broker account held by "sqi-server restore": a connection on the data credential, and the account's guard. While it is held no sqi-server can start on the account, and a server refused names the restore as the holder.
func (*RestoreLock) Purge ¶ added in v0.4.0
func (l *RestoreLock) Purge(ctx context.Context) error
Purge empties every one of sqi's streams and deletes the server's durable consumers, so that no message from before the restore replays against the restored database. A stream or consumer that does not exist, on an account no server finished starting on, is skipped. The streams keep their configuration, replica count included. Requests the cluster cannot serve yet are retried, each target on its own budget ([RestoreLock.targetDeadline]).
It refuses when the lock no longer holds the guard: another sqi-server may be running on the account.
func (*RestoreLock) Release ¶ added in v0.4.0
func (l *RestoreLock) Release()
Release gives the account's guard back and closes the connection. It is safe to call more than once.
Source Files
¶
- ackpublish.go
- broker.go
- callout.go
- client.go
- consumers.go
- control.go
- diag.go
- embedded.go
- embeddedrecover.go
- embeddedrestart.go
- grantsfp.go
- guard.go
- guardread.go
- layout.go
- lease.go
- markers.go
- natslog.go
- natslogbreak.go
- recoverprobe.go
- recoverprobe_fd.go
- remote.go
- remote_ha.go
- remote_restore.go
- streams.go
- subjects.go
- version.go