feat(nats): run an embedded server when no external NATS is configured

Wire github.com/nats-io/nats-server/v2 into production startup so a
single-process deployment gets reaction delivery and task distribution
over an in-process server rather than a separate one
(docs/prds/embedded-nats.md).

Meaning change: [nats].url empty used to mean "no NATS, use the SQLite
ClaimNext flow"; it now means "start an embedded NATS server". The old
behaviour is the explicit opt-out [nats].mode = "off". mode resolves from
url when unset (url set -> external, url empty -> embedded), and
agent.mode="nats" / [containers] now require mode="external" (an embedded
loopback server cannot be reached by agent workers or containers).

The daemon owns the embedded server's lifecycle: StartEmbedded before
dialing the client, Shutdown after the client closes (LIFO cleanups). The
embedded server binds loopback on a random port, enables JetStream in a
store dir under the data directory, and leaves its logger nil so a startup
failure surfaces as a Connect error rather than an os.Exit.

Retention becomes a nats.Config field (default WorkQueuePolicy) so a future
reaction stream can fan out under LimitsPolicy instead of the hardcoded
competing-consumer policy that starves a second consumer on overlapping
subjects.
This commit is contained in:
sam committed 2026-08-22 05:18:31 +10:00
1 parent b07cb7c312
commit c7987f0595
13 files changed
+622 -24

No files matched your search

+48 -12
View File
@@ -91,6 +91,11 @@ type boot struct {
web *webui.Server
natsClient *nats.Client
// natsURL is the endpoint the daemon's own client connected with at
// startup. For external mode it is cfg.NATS.URL; for embedded mode it is
// the embedded server's ClientURL(). Recorded so Daemon.ConnectedNATS
// carries the real endpoint rather than an empty config URL.
natsURL string
containerPool *container.Pool
storeBackend storage.Backend
@@ -324,22 +329,45 @@ func (b *boot) setupObservability() {
go persistAndBroadcastEvents(sink, b.st, b.web, log)
}
// connectNATS opens the optional NATS client (the SQLite flow is
// unchanged when [nats] is absent).
// connectNATS opens the NATS client. External mode dials cfg.NATS.URL;
// embedded mode starts an in-process nats-server and dials it, so single-
// process deployments get task distribution and reaction delivery without a
// separate server. Off mode returns nil and the SQLite ClaimNext flow runs.
func (b *boot) connectNATS(ctx context.Context) error {
cfg, log := b.cfg, b.log
if cfg.NATS.URL == "" {
if cfg.NATS.Mode == config.NATSModeOff {
return nil
}
natsToken, err := configuredNATSToken(cfg.NATS, os.Getenv)
if err != nil {
log.Error("nats credentials", "err", err)
return err
url := cfg.NATS.URL
var natsToken string
if cfg.NATS.Mode == config.NATSModeExternal {
var err error
natsToken, err = configuredNATSToken(cfg.NATS, os.Getenv)
if err != nil {
log.Error("nats credentials", "err", err)
return err
}
} else {
// Embedded. Start the in-process server before dialing, and register
// its shutdown BEFORE the client close below so the client closes
// first (cleanups run LIFO).
srv, err := nats.StartEmbedded(ctx, nats.EmbeddedOptions{
StoreDir: filepath.Join(filepath.Dir(cfg.DBPath), "nats"),
}, log)
if err != nil {
log.Error("embedded nats start failed", "err", err)
return err
}
b.addCleanup(func() { srv.Shutdown() })
url = srv.ClientURL()
log.Info("embedded nats started", "url", url)
}
// Composition owns the subject list: the bus must not know which
// subjects belong to which domain.
natsClient, err := nats.Connect(ctx, nats.Config{
URL: cfg.NATS.URL,
URL: url,
Token: natsToken,
Subjects: []string{workintake.SubjectTaskWildcard, agentexec.SubjectAgentWildcard},
FilterSubject: workintake.SubjectTaskWildcard,
@@ -349,8 +377,9 @@ func (b *boot) connectNATS(ctx context.Context) error {
return err
}
b.natsClient = natsClient
b.natsURL = url
b.addCleanup(func() { natsClient.Close() })
log.Info("nats connected", "url", cfg.NATS.URL)
log.Info("nats connected", "url", url)
return nil
}
@@ -544,8 +573,8 @@ func (b *boot) buildAgentRunner() error {
b.agentRunner = inproc
case "nats":
if b.natsClient == nil {
log.Error("agent.mode is nats but [nats] is not configured")
return fmt.Errorf("agent.mode is nats but [nats] is not configured")
log.Error("agent.mode is nats but nats is unavailable (nats.mode is off)")
return fmt.Errorf("agent.mode is nats but nats is unavailable (nats.mode is off)")
}
b.agentRunner = &agentexec.NATSRunner{
Bus: b.natsClient,
@@ -904,9 +933,16 @@ func (b *boot) registerStandaloneTools() {
// it shares with it.
func (b *boot) buildDaemon() {
cfg, log := b.cfg, b.log
// ConnectedNATS must carry the endpoint the daemon's own client connected
// with at startup, not the raw config: for embedded mode the config URL is
// empty, but container env must never see an empty NATS_URL. (Containers
// are rejected in embedded mode by validation, but the field should mean
// the same thing regardless of mode.)
connectedNATS := cfg.NATS
connectedNATS.URL = b.natsURL
b.d = &daemon.Daemon{
Cfg: config.NewHolder(cfg),
ConnectedNATS: cfg.NATS,
ConnectedNATS: connectedNATS,
Store: b.st,
Bus: b.bus,
Forge: b.forgeClient,
+10 -4
View File
@@ -168,11 +168,17 @@ max_tokens = 400000
wall_clock = "30m"
gate_max_failures = 5
# NATS JetStream for distributed task queue. Remove or leave commented out
# to run in single-process SQLite mode.
# NATS JetStream for task distribution and reaction delivery. mode selects
# how NATS is provided:
# "embedded" – in-process nats-server (the default; no external server)
# "external" – connect to url (required for agent.mode="nats" / [containers])
# "off" – no NATS; the SQLite ClaimNext flow is used for tasks
# Leave the section absent (or set no url) to run embedded; set mode="off"
# only to opt out of NATS entirely.
# [nats]
# url = "nats://localhost:4222"
# token_env = "NATS_TOKEN" # optional; named variable must be set
# mode = "embedded" # "embedded" | "external" | "off"
# url = "nats://localhost:4222" # required when mode = "external"
# token_env = "NATS_TOKEN" # optional; named variable must be set
# Unbound webhook capture: POST /webhooks/capture/{source} accepts and
# stores any inbound payload archie doesn't yet have a binding for, so it can
+86
View File
@@ -0,0 +1,86 @@
# Embedded NATS -- decision
**Status:** Decided, not yet implemented
**Date:** 2026-08-22
**Beads issue:** `archie-core-7d5u.2`
`event-sources-and-reactions.md` settled the reaction-delivery mechanism (reuse
`internal/infrastructure/eventbus/nats`, a second stream under a fan-out
retention policy) and left the deployment shape to this issue. This document
decides that shape. `github.com/nats-io/nats-server/v2` is already a direct
dependency, used today only in `_test.go` files; the gap is that production
startup only knows "external URL configured" vs "no NATS, use SQLite
`ClaimNext`".
## 1. Embedded runs alongside SQLite, not instead of it
The SQLite store remains authoritative for task state. NATS -- external or
embedded -- is the *distribution* path, and `drainNATS` already falls back to
`Store.ClaimNext` for requeued tasks (waiting_human approval, retry-parked)
that never went through a NATS publish. So wiring embedded NATS does not
remove the SQLite flow; it makes `Daemon.Tasks != nil` true in single-process
deployments, which routes poll→enqueue through `pollNATS` and drain through
`drainNATS` exactly as an external-NATS deployment already does. `ClaimNext`
stays as the requeue fallback inside `drainNATS`. No new drain path, no second
eventbus type.
## 2. Config: `[nats] mode = "embedded" | "external" | "off"`
`NATSConfig` gains a `mode` field. `url` no longer doubles as the on/off
switch -- that coupling is what made "no NATS" a permanent stance instead of a
deployment shape.
| mode | meaning |
|------------|----------------------------------------------------------------|
| `external` | connect to `url` (today's behaviour). `url` is required. |
| `embedded` | start an in-process nats-server; the client connects to it. |
| `off` | no NATS at all; the old SQLite-only flow (`ClaimNext`). |
Default resolution: `url` set → `external`; `url` empty and `mode` unset or
`embedded` → `embedded`; `mode = "off"` → `off`. `mode = "external"` with no
`url` is a validation error; `mode = "off"`/`"embedded"` with a `url` set is a
validation error. This is a meaning change and is stated as one: `url` empty
*used to mean* "no NATS, SQLite only"; it *now means* "embedded NATS", and
getting the old behaviour requires the explicit opt-out `mode = "off"`.
`agent.mode = "nats"` and `[containers]` require `mode = "external"` (a
container cannot reach an in-process loopback server, and embedded NATS is not
an agent-execution topology).
## 3. The daemon owns the embedded server's lifecycle
`internal/infrastructure/eventbus/nats` gains an `EmbeddedServer` type that
wraps `nats-server/v2/server.Server`, exposing only `ClientURL()` and
`Shutdown()`. The composition root (`cmd/archied/bootstrap.go`) starts it in
`connectNATS` (before dialing the client), binds it to `127.0.0.1` on a random
port, enables JetStream with a store dir under the daemon's data directory
(`<dir of DBPath>/nats`), and registers a cleanup that shuts the server down
*after* the client closes. Cleanup ordering is LIFO: the server shutdown is
registered before the client close, so the client closes first.
## Retention is a Config field, not a constant
`nats.Config` gains `Retention *jetstream.RetentionPolicy`, defaulting to
`jetstream.WorkQueuePolicy` in `withDefaults`, replacing the hardcoded value in
`Connect` (`client.go:65`). `WorkQueuePolicy` is correct for `ARCHIE_TASKS`
(one consumer claims each message) and wrong for reactions (fan-out). This is
the enabler for the second reaction stream: `event-sources-and-reactions.md`
requires it, and nothing here creates the reaction stream itself -- that is
provisioned by the beads that build reaction producers and consumers, which do
not exist yet. A test proves the parameterization: two overlapping `Subscribe`
consumers both receive a message under `LimitsPolicy` (fan-out) and starve
under `WorkQueuePolicy`, the exact trap `CLAUDE.md` documents.
## Packages this touches
- `internal/infrastructure/eventbus/nats`: `Retention` on `Config`, an
`EmbeddedServer` type.
- `internal/config`: `NATSConfig.Mode`.
- `internal/infrastructure/configuration`: `mode` defaulting and validation.
- `cmd/archied/bootstrap.go`: start/stop the embedded server; set
`Daemon.ConnectedNATS.URL` to the embedded client URL so container env (if
ever enabled) never receives an empty endpoint.
- `config.example.toml`: document `mode`. The `deployments/*` profiles are
unchanged on purpose: their absent `[nats]` section now selects embedded by
default, which is the intended single-process behaviour this issue exists to
provide, not a regression to paper over with `mode = "off"`.
+25 -4
View File
@@ -571,14 +571,35 @@ func cloneStringSlices(ss [][]string) [][]string {
return out
}
// NATSConfig configures NATS JetStream for task distribution. When URL is
// empty the existing SQLite ClaimNext flow is used unchanged.
// NATS mode values for NATSConfig.Mode. The zero value (empty) resolves from
// URL; these are the explicit spellings, shared with configuration validation
// so the two cannot drift.
const (
NATSModeEmbedded = "embedded"
NATSModeExternal = "external"
NATSModeOff = "off"
)
// NATSConfig configures NATS JetStream for task distribution and reaction
// delivery. The mode selects how NATS is provided:
//
// "embedded" – an in-process nats-server (default; no external server)
// "external" – connect to URL (required; the only mode agent.mode="nats"
// and [containers] can use)
// "off" – no NATS; the SQLite ClaimNext flow is used unchanged
//
// An empty Mode resolves from URL: URL set means "external", URL empty means
// "embedded". This is a meaning change from the previous behaviour, where an
// empty URL alone meant "no NATS, SQLite only" -- that old behaviour is now
// the explicit opt-out Mode == "off" (docs/prds/embedded-nats.md).
type NATSConfig struct {
// Mode selects embedded, external or off. Empty resolves from URL.
Mode string `toml:"mode" yaml:"mode"`
// URL is the NATS server address, e.g. "nats://localhost:4222".
// Empty means NATS is not configured.
// Required when Mode is "external"; must be empty otherwise.
URL string `toml:"url" yaml:"url"`
// TokenEnv optionally names an env var holding a NATS auth token.
// Empty means no authentication.
// Empty means no authentication. Ignored when Mode is "embedded".
TokenEnv string `toml:"token_env" yaml:"token_env"`
}
@@ -68,6 +68,7 @@ func (l *Loader) applyDefaults(cfg *config.Config) {
applyContainerDefaults(cfg)
applyToolPolicyDefaults(cfg)
applyCaptureDefaults(cfg)
applyNATSDefaults(cfg)
}
// applyCaptureDefaults fills the webhook capture endpoint's settings. See
@@ -191,6 +192,20 @@ func applyForgeDefaults(cfg *config.Config) {
}
}
// applyNATSDefaults resolves the nats mode from URL when the operator left it
// unset. URL set implies external; URL empty implies embedded. The previous
// behaviour -- URL empty meaning "no NATS, SQLite only" -- is now the explicit
// opt-out nats.mode = "off" (docs/prds/embedded-nats.md).
func applyNATSDefaults(cfg *config.Config) {
if cfg.NATS.Mode == "" {
if cfg.NATS.URL != "" {
cfg.NATS.Mode = config.NATSModeExternal
} else {
cfg.NATS.Mode = config.NATSModeEmbedded
}
}
}
// applyAgentDefaults picks the execution mode. Containers require the NATS
// transport, so enabling them selects it unless the operator said otherwise.
func applyAgentDefaults(cfg *config.Config) {
@@ -7,6 +7,30 @@ import (
"github.com/samcharles93/archie-core/internal/config"
)
func TestApplyNATSDefaultsResolvesMode(t *testing.T) {
tests := []struct {
name string
mode string
url string
want string
}{
{name: "url set implies external", url: "nats://localhost:4222", want: config.NATSModeExternal},
{name: "empty implies embedded", want: config.NATSModeEmbedded},
{name: "explicit off is preserved", mode: config.NATSModeOff, want: config.NATSModeOff},
{name: "explicit embedded is preserved", mode: config.NATSModeEmbedded, want: config.NATSModeEmbedded},
{name: "explicit external is preserved", mode: config.NATSModeExternal, url: "nats://localhost:4222", want: config.NATSModeExternal},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
cfg := &config.Config{NATS: config.NATSConfig{Mode: tc.mode, URL: tc.url}}
applyNATSDefaults(cfg)
if cfg.NATS.Mode != tc.want {
t.Errorf("applyNATSDefaults() mode = %q, want %q", cfg.NATS.Mode, tc.want)
}
})
}
}
func TestApplyCaptureDefaultsFillsZeroValues(t *testing.T) {
cfg := &config.Config{}
applyCaptureDefaults(cfg)
@@ -33,6 +33,7 @@ var (
agentModes = []string{agentModeInProcess, agentModeSubprocess, agentModeNATS}
forgeTypes = []string{forgeTypeGitHub, forgeTypeGitea, forgeTypeNone, forgeTypeOff, forgeTypeDisabled}
dispatchTriggers = []string{dispatchTriggerAssignee, dispatchTriggerLabel, dispatchTriggerEither}
natsModes = []string{config.NATSModeEmbedded, config.NATSModeExternal, config.NATSModeOff}
)
// Validate runs the same checks Loader applies before accepting a config,
@@ -75,6 +76,9 @@ func validate(cfg *config.Config) error {
if err := validatePollInterval(cfg); err != nil {
return err
}
if err := validateNATS(cfg); err != nil {
return err
}
if err := validateContainers(cfg); err != nil {
return err
}
@@ -228,6 +232,48 @@ func validateRepos(repos []config.Repo) error {
return nil
}
// effectiveNATSMode resolves an unset nats.mode from url without mutating cfg,
// so validation that reads the mode never has to know whether the operator
// spelled it or left it to default. validateNATS and validateContainers both
// consult it, so they cannot disagree about which mode a config is in.
func effectiveNATSMode(cfg *config.Config) string {
if cfg.NATS.Mode != "" {
return cfg.NATS.Mode
}
if cfg.NATS.URL != "" {
return config.NATSModeExternal
}
return config.NATSModeEmbedded
}
// validateNATS checks the nats mode and its consistency with url and the
// agent execution mode. It resolves an unset mode from url without mutating
// cfg, so Validate (which documents it does not apply defaults) accepts a
// hand-built config the same way Loader.File accepts its on-disk form.
func validateNATS(cfg *config.Config) error {
mode := effectiveNATSMode(cfg)
if !oneOf(mode, natsModes) {
return fmt.Errorf("%w: nats.mode %q (want %s)", ErrInvalidInput, cfg.NATS.Mode, list(natsModes))
}
switch mode {
case config.NATSModeExternal:
if cfg.NATS.URL == "" {
return fmt.Errorf("%w: nats.url is required when nats.mode is %q", ErrInvalidInput, config.NATSModeExternal)
}
case config.NATSModeEmbedded, config.NATSModeOff:
if cfg.NATS.URL != "" {
return fmt.Errorf("%w: nats.url must be empty when nats.mode is %q", ErrInvalidInput, mode)
}
}
// Agent execution over NATS needs workers that can reach the server. An
// embedded server binds loopback on a random port, which workers cannot
// discover, so agent.mode="nats" requires an external URL.
if cfg.Agent.Mode == agentModeNATS && mode != config.NATSModeExternal {
return fmt.Errorf("%w: nats.mode must be %q when agent.mode is %q", ErrInvalidInput, config.NATSModeExternal, agentModeNATS)
}
return nil
}
// validateContainers checks the combination that container execution
// requires: a NATS transport and somewhere to reach it.
func validateContainers(cfg *config.Config) error {
@@ -240,8 +286,8 @@ func validateContainers(cfg *config.Config) error {
if cfg.Agent.Mode != agentModeNATS {
return fmt.Errorf("%w: agent.mode must be %q when containers.enabled is true", ErrInvalidInput, agentModeNATS)
}
if cfg.NATS.URL == "" {
return fmt.Errorf("%w: [nats] url is required when containers.enabled is true", ErrInvalidInput)
if effectiveNATSMode(cfg) != config.NATSModeExternal {
return fmt.Errorf("%w: nats.mode must be %q when containers.enabled is true (containers cannot reach an embedded loopback server)", ErrInvalidInput, config.NATSModeExternal)
}
if cfg.Containers.VolumeTTL < 0 {
return fmt.Errorf("%w: containers.volume_ttl must not be negative", ErrInvalidInput)
@@ -189,6 +189,77 @@ func TestValidate_RejectsTheSameProblemsAsLoaderLoad(t *testing.T) {
}
}
// TestValidateNATS pins the nats mode contract from docs/prds/embedded-nats.md:
// an unset mode resolves from url without mutating cfg, external requires url,
// embedded/off forbid a url, and agent.mode="nats" requires external.
func TestValidateNATS(t *testing.T) {
tests := []struct {
name string
mode string
url string
agent string
wantErr bool
}{
{name: "unset mode with url resolves external", url: "nats://localhost:4222"},
{name: "unset mode without url resolves embedded"},
{name: "embedded with no url", mode: config.NATSModeEmbedded},
{name: "off with no url", mode: config.NATSModeOff},
{name: "external with url", mode: config.NATSModeExternal, url: "nats://localhost:4222"},
{name: "external without url", mode: config.NATSModeExternal, wantErr: true},
{name: "embedded with url", mode: config.NATSModeEmbedded, url: "nats://localhost:4222", wantErr: true},
{name: "off with url", mode: config.NATSModeOff, url: "nats://localhost:4222", wantErr: true},
{name: "unknown mode", mode: "not-a-mode", wantErr: true},
{name: "agent nats with embedded", mode: config.NATSModeEmbedded, agent: "nats", wantErr: true},
{name: "agent nats with external", mode: config.NATSModeExternal, url: "nats://localhost:4222", agent: "nats"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
cfg := minimalValidConfig()
cfg.NATS = config.NATSConfig{Mode: tc.mode, URL: tc.url}
if tc.agent != "" {
cfg.Agent.Mode = tc.agent
}
err := validateNATS(&cfg)
if tc.wantErr && err == nil {
t.Fatal("validateNATS() = nil, want an error")
}
if !tc.wantErr && err != nil {
t.Fatalf("validateNATS() = %v, want nil", err)
}
})
}
}
// TestValidateContainersResolvesNATSMode pins that validateContainers reads
// the *resolved* nats mode, not the raw field: a hand-built config with
// containers enabled and a url but no explicit mode must validate the same way
// the loader's on-disk form does (url implies external), rather than diverge
// because validateContainers saw an empty mode.
func TestValidateContainersResolvesNATSMode(t *testing.T) {
base := func() config.Config {
cfg := minimalValidConfig()
cfg.Containers = config.ContainerConfig{Enabled: true, Image: "archie-agent:latest"}
cfg.Agent.Mode = "nats"
return cfg
}
t.Run("unset mode with url resolves external", func(t *testing.T) {
cfg := base()
cfg.NATS.URL = "nats://localhost:4222"
if err := Validate(&cfg); err != nil {
t.Fatalf("Validate() = %v, want nil (unset mode + url resolves external)", err)
}
})
t.Run("embedded mode rejects containers", func(t *testing.T) {
cfg := base()
cfg.NATS.Mode = config.NATSModeEmbedded
if err := Validate(&cfg); err == nil {
t.Fatal("Validate() = nil, want an error for containers with embedded nats")
}
})
}
// Validate must run the exact same checks Loader.File applies internally --
// this pins that a config Validate accepts on its own, once the same
// defaults Loader.File would apply are filled in by hand, is also accepted
@@ -27,7 +27,8 @@ type Client struct {
}
// Connect dials the broker and provisions the stream and pull consumer. The
// stream uses work-queue retention on file storage.
// stream uses file storage and the retention policy from Config.Retention
// (defaulting to work-queue for task distribution).
//
// On any failure the partially-built connection is closed before returning, so
// a failed Connect leaks nothing.
@@ -62,7 +63,7 @@ func Connect(ctx context.Context, cfg Config, log *slog.Logger) (*Client, error)
Name: cfg.StreamName,
Subjects: cfg.Subjects,
Storage: jetstream.FileStorage,
Retention: jetstream.WorkQueuePolicy,
Retention: *cfg.Retention,
Duplicates: cfg.DedupWindow,
})
if err != nil {
@@ -3,6 +3,8 @@ package nats
import (
"fmt"
"time"
"github.com/nats-io/nats.go/jetstream"
)
// Defaults for Config. Previously these were unexported package constants,
@@ -46,6 +48,17 @@ type Config struct {
// Required.
FilterSubject string
// Retention is the stream's retention policy. Nil defaults to
// jetstream.WorkQueuePolicy (each message claimed by exactly one
// consumer), which is correct for ARCHIE_TASKS task distribution. A
// fan-out reaction stream passes jetstream.LimitsPolicy so every
// registered consumer sees every matching event; under WorkQueuePolicy a
// second consumer on an overlapping filter subject silently receives
// nothing (the trap documented in CLAUDE.md). The pointer form is what
// lets "unset" default to WorkQueuePolicy when the policy's zero value
// (LimitsPolicy) is a valid explicit choice.
Retention *jetstream.RetentionPolicy
// DedupWindow is how long JetStream remembers a Nats-Msg-Id, suppressing
// republished duplicates of the same issue within the window.
DedupWindow time.Duration
@@ -108,5 +121,9 @@ func (c Config) withDefaults() Config {
if c.InactiveTTL == 0 {
c.InactiveTTL = DefaultInactiveTTL
}
if c.Retention == nil {
policy := jetstream.WorkQueuePolicy
c.Retention = &policy
}
return c
}
@@ -0,0 +1,102 @@
package nats
import (
"context"
"fmt"
"log/slog"
"time"
"github.com/nats-io/nats-server/v2/server"
)
// EmbeddedServer owns an in-process NATS server with JetStream enabled. It
// wraps nats-server/v2/server.Server so the SDK type never leaks past this
// package: callers get only the client URL and Shutdown, never the server.
//
// The daemon embeds one of these for single-process deployments so reaction
// delivery and task distribution share the same transport whether NATS runs
// as a separate server or in-process (docs/prds/embedded-nats.md). The daemon
// owns the lifecycle: StartEmbedded before dialing the client, Shutdown after
// the client closes.
type EmbeddedServer struct {
srv *server.Server
log *slog.Logger
}
// EmbeddedOptions configures StartEmbedded.
type EmbeddedOptions struct {
// Host is the bind address. Empty means "127.0.0.1" (loopback only,
// which is correct: an embedded server carries no authentication).
Host string
// Port is the listen port. Zero means a random port.
Port int
// StoreDir is where JetStream persists streams. Empty means a temporary
// directory (streams do not survive a reboot). The daemon passes a dir
// under its data directory so the ARCHIE_TASKS and reaction streams are
// durable across daemon restarts.
StoreDir string
}
// StartEmbedded starts an in-process NATS server with JetStream enabled and
// returns it once it is ready for connections. The caller owns the returned
// server and must call Shutdown to stop it.
func StartEmbedded(ctx context.Context, opts EmbeddedOptions, log *slog.Logger) (*EmbeddedServer, error) {
if opts.Host == "" {
opts.Host = "127.0.0.1"
}
if opts.Port == 0 {
opts.Port = -1 // random port, so two daemons on one host cannot collide
}
if log == nil {
log = slog.New(slog.DiscardHandler)
}
srv, err := server.NewServer(&server.Options{
Host: opts.Host,
Port: opts.Port,
JetStream: true,
StoreDir: opts.StoreDir,
NoSigs: true, // the daemon owns signals, not the embedded server
// NoLog leaves the server's logger nil (ConfigureLogger is only ever
// called on reload). A nil logger makes the server's Fatalf a no-op
// rather than an os.Exit, so a JetStream startup failure cannot crash
// archied -- it surfaces instead as a Connect error below.
NoLog: true,
})
if err != nil {
return nil, fmt.Errorf("embedded nats create: %w", err)
}
srv.Start()
// Start is asynchronous; wait for the accept loop. If the daemon's ctx is
// already cancelled (shutdown racing boot), stop the server rather than
// wait the full readiness window. A ctx cancelled during the wait is
// tolerated: the wait is bounded, and a healthy server is ready in
// milliseconds.
if err := ctx.Err(); err != nil {
srv.Shutdown()
return nil, fmt.Errorf("embedded nats startup: %w", err)
}
if !srv.ReadyForConnections(10 * time.Second) {
srv.Shutdown()
return nil, fmt.Errorf("embedded nats server did not become ready")
}
log.Info("embedded nats ready", "url", srv.ClientURL())
return &EmbeddedServer{srv: srv, log: log}, nil
}
// ClientURL returns the address the server is listening on. It is the URL the
// client must dial, and the value the daemon records as the endpoint its own
// connection used.
func (e *EmbeddedServer) ClientURL() string { return e.srv.ClientURL() }
// Shutdown stops the server and waits for it to finish. It is safe to call on
// a nil server so callers can defer it unconditionally.
func (e *EmbeddedServer) Shutdown() {
if e == nil || e.srv == nil {
return
}
e.srv.Shutdown()
e.log.Debug("embedded nats stopped")
}
@@ -0,0 +1,55 @@
package nats
import (
"context"
"testing"
"github.com/nats-io/nats.go"
)
// TestStartEmbeddedLifecycle proves the in-process server starts with
// JetStream enabled, accepts a client that provisions a stream, and stops on
// Shutdown. It is the production path behind docs/prds/embedded-nats.md,
// distinct from the test-only natstest helper used elsewhere.
func TestStartEmbeddedLifecycle(t *testing.T) {
srv, err := StartEmbedded(t.Context(), EmbeddedOptions{StoreDir: t.TempDir()}, discardLogger())
if err != nil {
t.Fatalf("StartEmbedded = %v", err)
}
url := srv.ClientURL()
if url == "" {
t.Fatal("ClientURL() = empty, want the bound address")
}
// Connecting and provisioning a stream proves JetStream is live, not just
// the core NATS socket.
c, err := Connect(t.Context(), Config{
URL: url,
Subjects: []string{"embedded.test.>"},
FilterSubject: "embedded.test.>",
}, discardLogger())
if err != nil {
t.Fatalf("Connect to embedded server = %v", err)
}
c.Close()
srv.Shutdown()
// After Shutdown the port must refuse new connections, proving the server
// owns its own stop rather than leaking the goroutine.
if _, err := nats.Connect(url); err == nil {
t.Fatalf("nats.Connect(%q) after Shutdown = nil, want connection refused", url)
}
}
// TestStartEmbeddedShutdownOnCancelledContext pins that a cancelled ctx aborts
// startup rather than blocking the full readiness window during shutdown
// racing boot.
func TestStartEmbeddedShutdownOnCancelledContext(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
cancel()
if _, err := StartEmbedded(ctx, EmbeddedOptions{StoreDir: t.TempDir()}, discardLogger()); err == nil {
t.Fatal("StartEmbedded(cancelled ctx) = nil, want an error")
}
}
@@ -0,0 +1,118 @@
package nats
import (
"context"
"log/slog"
"sync"
"testing"
"time"
"github.com/nats-io/nats-server/v2/server"
natstest "github.com/nats-io/nats-server/v2/test"
"github.com/nats-io/nats.go/jetstream"
"github.com/samcharles93/archie-core/internal/eventbus"
)
func discardLogger() *slog.Logger { return slog.New(slog.DiscardHandler) }
// TestWithDefaultsRetention pins the retention default: unset defaults to
// WorkQueuePolicy (task distribution), and an explicit LimitsPolicy is left
// alone. The pointer form is what lets "unset" default to WorkQueuePolicy
// when the policy's zero value (LimitsPolicy) is a valid explicit choice.
func TestWithDefaultsRetention(t *testing.T) {
t.Run("unset defaults to work-queue", func(t *testing.T) {
cfg := (Config{}).withDefaults()
if cfg.Retention == nil {
t.Fatal("withDefaults().Retention = nil, want non-nil")
}
if *cfg.Retention != jetstream.WorkQueuePolicy {
t.Fatalf("withDefaults().Retention = %v, want %v", *cfg.Retention, jetstream.WorkQueuePolicy)
}
})
t.Run("explicit limits is preserved", func(t *testing.T) {
limits := jetstream.LimitsPolicy
cfg := (Config{Retention: &limits}).withDefaults()
if cfg.Retention == nil || *cfg.Retention != jetstream.LimitsPolicy {
t.Fatalf("withDefaults().Retention = %v, want %v", cfg.Retention, jetstream.LimitsPolicy)
}
})
}
// TestConnectRetentionFanout proves the reason retention must be a Config
// field: under LimitsPolicy two independent consumers each receive every
// matching message (fan-out), the behaviour reactions need and WorkQueuePolicy
// cannot provide. This is the exact trap CLAUDE.md documents -- a second
// consumer on an overlapping filter subject under WorkQueuePolicy silently
// gets nothing.
func TestConnectRetentionFanout(t *testing.T) {
srv := natstest.RunServer(&server.Options{Port: -1, JetStream: true, StoreDir: t.TempDir()})
t.Cleanup(srv.Shutdown)
limits := jetstream.LimitsPolicy
c, err := Connect(t.Context(), Config{
URL: srv.ClientURL(),
StreamName: "REACTIONS_FANOUT_TEST",
Subjects: []string{"reaction.fanout.test.>"},
FilterSubject: "reaction.fanout.test.>",
Retention: &limits,
}, discardLogger())
if err != nil {
t.Fatalf("Connect = %v", err)
}
t.Cleanup(c.Close)
var mu sync.Mutex
gotA := map[string]int{}
gotB := map[string]int{}
ctx, cancel := context.WithCancel(t.Context())
done := make(chan struct{}, 2)
subscriber := func(recv map[string]int) {
defer func() { done <- struct{}{} }()
_ = c.Subscribe(ctx, "reaction.fanout.test.>", func(m eventbus.Message) error {
mu.Lock()
recv[string(m.Data())]++
mu.Unlock()
return nil
})
}
go subscriber(gotA)
go subscriber(gotB)
// Publish after the consumers have had a chance to be created, but the
// Limits stream retains messages regardless of subscriber timing.
time.Sleep(200 * time.Millisecond)
if err := c.Publish(t.Context(), "reaction.fanout.test.1", []byte("x")); err != nil {
t.Fatalf("Publish x = %v", err)
}
if err := c.Publish(t.Context(), "reaction.fanout.test.2", []byte("y")); err != nil {
t.Fatalf("Publish y = %v", err)
}
// Both consumers must observe both messages; poll rather than sleep a
// fixed duration so a slow CI runner does not flake.
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
mu.Lock()
aFull := gotA["x"] >= 1 && gotA["y"] >= 1
bFull := gotB["x"] >= 1 && gotB["y"] >= 1
mu.Unlock()
if aFull && bFull {
break
}
time.Sleep(20 * time.Millisecond)
}
cancel()
<-done
<-done
mu.Lock()
defer mu.Unlock()
for name, got := range map[string]map[string]int{"A": gotA, "B": gotB} {
if got["x"] != 1 || got["y"] != 1 {
t.Errorf("consumer %s received %v, want x and y once each (fan-out failed)", name, got)
}
}
}