nats

package module
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 19 Imported by: 0

README

messaging-nats

NATS and JetStream backends for messaging: the bus's second implementation, and the one that survives a restart.

Go Reference Pipeline coverage

Part of the phpboyscout Go toolkit. This is a provider module of messaging, and its documentation lives with the core: messaging.go.phpboyscout.uk. Its decisions are spec 0003.

Two backends

Core JetStream
what it is core NATS, over go/nats a JetStream stream the bus binds to, never creates
delivery modes AtMostOnce AtMostOnce, AtLeastOnce
survives a restart no yes, for a file-backed stream
overflow ShedNewest, core NATS's own ShedNewest on its at-most-once path; backpressure under at-least-once
conformance conformance.Run conformance.RunDurable, with a fixture that owns the store

Two backends rather than one with a flag, because Capabilities.SurvivesRestart is declared rather than discovered, and the two answer it differently.

Operating JetStream

The stream is the operator's: it must exist, be file-backed (a memory stream is refused at Open, because this backend declares that it survives a restart), and carry the subjects the bus will publish to. The bus creates consumers under DurableName and never deletes them.

AckWait is more than a lease. A message given back at retirement — never handed over, or in a handler's hand when the process stopped — is redelivered at once while the server is up, but a server restart forgets that and offers it again only when AckWait expires from its original delivery. So AckWait also bounds how late a message caught by a restart arrives; the default is thirty seconds.

A server restart can spend an attempt nobody saw. A redelivery that races a consumer's retirement is counted as sent and reaches no client; a live server offers it again under the same number, but a server restarted before the next pull has persisted it as delivered. With attempts left the message still arrives, an attempt poorer; on its last attempt it is never offered again, and Exhausted does not count it. So this backend declares RestartCanSpendUnseenAttempt (spec 0012). It needs a Nak on the second-to-last attempt, the process retiring within milliseconds of it, and the NATS server restarting before anything pulls again. The gap is nats-server's, and the report for it is issue 3.

A consumer deleted in the first moments of a subscription is noticed late. A source ends when its consumer is deleted, normally within milliseconds, but nats.go learns of the delete only through a pull already waiting on the consumer, and it sends the first pull lazily. A delete that lands before that pull is noticed by the missing-heartbeat check instead, up to thirty seconds later. Nothing hangs, and the source does end. This is a limit of the provider, measured on nats.go v1.54.0 and v1.55.0 (issue 5, spec 0010).

A declined message can wait before its next attempt. JetStream declares Capabilities.DelaysRedelivery, so a subscription's Backoff and Delivery.NackAfter work here: a decline with a delay is sent as NakWithDelay, and nats-server keeps the delay across its own restart (measured for go/messaging spec 0013). A message waiting out its delay holds one of the consumer's MaxAckPending slots, and this module leaves the server's default of 1000. A burst of declines with long delays can therefore stop the consumer being offered anything new until they fall due. The core NATS backend is at-most-once and redelivers nothing, so it declares no delay.

Choosing a wire format

Settings.Format writes every event, request and reply this backend sends. JetStreamSettings embeds Settings, so one pair of fields serves both backends. Unset, the writer is CloudEvents binary for the NATS binding, which is what this module has always written.

Settings.Reads is the chain a received message is read with. Exactly one format must claim a message. Unset, the chain is binary and then structured, so a consumer can read structured before any producer writes it. To move a deployment to structured, upgrade the readers first and switch the writers after.

nats.Core(nats.Settings{Client: c, Format: cloudevents.Structured()})
  • A reply goes out in the format its request arrived in, whatever this backend's own Format is, so a structured caller gets a structured answer. Failure replies follow the same rule.
  • Headers no format takes, such as Nats-Msg-Id on a JetStream message or a tracing header, reach a handler through Delivery.Foreign(). They are never sent on.
  • A message no format can read never reaches a handler. That covers a message no format claims, one two formats both claim (the reader refuses to guess between them), and one a format claims but cannot decode. It's logged and counted in Unreadable. Core drops it. JetStream declines it at once, so it spends its attempts quickly and the server stops offering it after MaxDeliver (spec 0015).

To exchange messages with .NET services, the MassTransit and NServiceBus formats work the same way, as a writer, in Reads beside the defaults, or both. Both conformance suites run under each:

nats.Core(nats.Settings{
	Client: c,
	Format: masstransit.MassTransit(),
	Reads:  []envelope.Format{cloudevents.Binary(cloudevents.NATS), cloudevents.Structured(), masstransit.MassTransit()},
})

MassTransit refuses at publish an ID that is not a UUID and a payload that is not JSON. Each format's rules are on its package: go/envelope-masstransit and go/envelope-nservicebus.

The CloudEvents formats are go/envelope-cloudevents's, the event is go/envelope's, and the decisions are spec 0014.

Status

Pre-1.0, tracking the core. Both backends are built and green under the conformance suite, Core under conformance.Run and JetStream under conformance.RunDurable.

Documentation

Overview

Package nats implements the backend contract of gitlab.com/phpboyscout/go/messaging over NATS, twice.

Core is core NATS: volatile, at-most-once, the shape the in-memory backend was built to mimic. JetStream is bound to a stream: it survives a restart and offers at-least-once, with the attempt count the server's, the lease a heartbeat from receipt, and a publish that is stored before it returns. They are two backends rather than one with a flag because Capabilities.SurvivesRestart is declared, not discovered, and the two answer it differently.

A NATS server restart can spend an attempt nobody saw: a redelivery racing a consumer's retirement is counted as sent and reaches no client, and a server restarted before the next pull never offers it again. On the last attempt that message is exhausted without Exhausted counting it, so JetStream declares Capabilities.RestartCanSpendUnseenAttempt (messaging spec 0012). The gap is nats-server's; messaging-nats issue 3 carries the report.

JetStream declares Capabilities.DelaysRedelivery, so a subscription's Backoff and Delivery.NackAfter work here: a decline with a delay is a NakWithDelay, which the server keeps across its own restart. A message waiting out its delay holds one of the consumer's MaxAckPending slots, and this module leaves the server's default of 1000, so a burst of long-delayed declines can stop the consumer being offered anything new until they fall due.

Settings.Format writes what a backend sends, CloudEvents binary for the NATS binding when unset, and Settings.Reads is the chain it reads with, binary then structured when unset. A reply is written in its request's format, and headers no format takes reach a handler as Delivery.Foreign (messaging spec 0014).

This module leans on gitlab.com/phpboyscout/go/nats for everything that module already does — the connection, reconnection, the draining close, credentials, the pending-limit bound, the JetStream context — and writes the consuming, publishing and acknowledging against nats.go through the context it hands out. It is an adapter between two contracts, not a NATS client, and github.com/nats-io appears nowhere else in the estate.

Specified by https://gitlab.com/phpboyscout/go/messaging/-/wikis/specs/0003-the-second-backend

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.NewSentinel("messaging_nats.closed", "messaging-nats: the session is closed")

ErrClosed is returned by Subscribe after Close, which would otherwise leave a source running beyond its session.

View Source
var ErrMemoryStream = errors.NewSentinel("messaging_nats.memory_stream",
	"messaging-nats: the stream is memory-storage, which does not survive a restart; this backend declares that it does")

ErrMemoryStream is returned by Open when the bound stream is memory-storage: the backend declares SurvivesRestart, and a memory stream would make that a lie the deployment told (0003 D9).

View Source
var ErrNoStream = errors.NewSentinel("messaging_nats.no_stream",
	"messaging-nats: the stream this backend is bound to does not exist; a bus binds to a stream and never creates one")

ErrNoStream is returned by Open when the stream the backend is bound to does not exist. The bus binds, and never creates (0005 D9, 0003 D9): a bus that created its own stream would let a typo silently create one with no retention policy.

View Source
var ErrSessionClosed = errors.NewSentinel("messaging-nats.session_closed",
	"messaging-nats: the session is closed")

ErrSessionClosed ends a request still waiting when its session closes, so it returns at once rather than at its deadline (0011 D3).

Functions

func Core

func Core(s Settings) messaging.Backend

Core is the core-NATS backend: volatile, at-most-once, shedding at its bound under NATS's own policy. It is the shape the in-memory backend was built to mimic, and passing the suite proves the mimicry faithful rather than the contract general (0003 Notes, on 0001 D9).

Example

The volatile backend: at-most-once over core NATS, nothing kept.

package main

import (
	"log/slog"
	"os"

	gonats "gitlab.com/phpboyscout/go/nats"

	nats "gitlab.com/phpboyscout/go/messaging-nats"
)

func main() {
	backend := nats.Core(nats.Settings{
		Client: gonats.ClientSettings{Name: "orders", URL: "nats://localhost:4222"},
		Logger: slog.New(slog.NewTextHandler(os.Stderr, nil)),
	})

	_ = backend.Capabilities().SurvivesRestart // false
}

func JetStream

func JetStream(s JetStreamSettings) messaging.Backend

JetStream is the backend bound to a stream: it survives a restart and offers at-least-once, with the attempt count the server's, the lease a heartbeat from receipt, and a publish that is stored before it returns. Its at-most-once path is core NATS on the same client (0003 D11), so a subscriber that asks for nothing durable gets nothing durable, and no consumer, no cursor and no replay.

Example

The durable backend: bound to a stream the operator created, file-backed. Subscribe at-least-once under a DurableName to keep a place in it across restarts.

package main

import (
	gonats "gitlab.com/phpboyscout/go/nats"

	nats "gitlab.com/phpboyscout/go/messaging-nats"
)

func main() {
	backend := nats.JetStream(nats.JetStreamSettings{
		Settings: nats.Settings{
			Client: gonats.ClientSettings{Name: "orders", URL: "nats://localhost:4222"},
		},
		Stream: "ORDERS",
	})

	_ = backend.Capabilities().SurvivesRestart // true
}

Types

type JetStreamSettings

type JetStreamSettings struct {
	Settings

	// Stream is the operator's stream, which must exist and be file-backed.
	Stream string
}

JetStreamSettings is Settings plus the stream to bind to.

type Settings

type Settings struct {
	Client      gonats.ClientSettings
	Credentials gonats.CredentialSource
	Options     []client.Option
	Logger      *slog.Logger

	// Format writes every event, request and reply this backend sends. Unset,
	// it is CloudEvents binary for the NATS binding (0014 D6).
	Format envelope.Format

	// Reads is the chain a received message is read with, strictly: one
	// format must claim it. Unset, it is binary for the NATS binding, then
	// structured.
	Reads []envelope.Format
}

Settings is what a backend connects with. The client's own settings and credential source are go/nats's, unchanged, because this module is an adapter between two contracts and not a NATS client; Options is where a test hands in an in-process server.

Jump to

Keyboard shortcuts

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