feat(nats): expose embedded broker to managed workers

This commit is contained in:
sam committed 2026-08-24 14:56:57 +10:00
1 parent aaa9e85dd4
commit 9d73bc7157
16 files changed
+678 -178

No files matched your search

@@ -278,10 +278,10 @@ func effectiveNATSMode(cfg *config.Config) string {
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.
// validateNATS checks the nats mode and its consistency with url. 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) {
@@ -297,17 +297,15 @@ func validateNATS(cfg *config.Config) error {
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)
if cfg.Agent.Mode == agentModeNATS && mode == config.NATSModeEmbedded && !cfg.Containers.Enabled {
return fmt.Errorf("%w: containers.enabled must be true when agent.mode is %q and nats.mode is %q", ErrInvalidInput, agentModeNATS, config.NATSModeEmbedded)
}
return nil
}
// validateContainers checks the combination that container execution
// requires: a NATS transport and somewhere to reach it.
// validateContainers checks the combination container execution requires.
// Embedded and external NATS are both worker-reachable deployment shapes;
// composition resolves the Docker bridge gateway for embedded mode.
func validateContainers(cfg *config.Config) error {
if !cfg.Containers.Enabled {
return nil
@@ -318,8 +316,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 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 effectiveNATSMode(cfg) == config.NATSModeOff {
return fmt.Errorf("%w: nats.mode must not be %q when containers.enabled is true", ErrInvalidInput, config.NATSModeOff)
}
if cfg.Containers.VolumeTTL < 0 {
return fmt.Errorf("%w: containers.volume_ttl must not be negative", ErrInvalidInput)
@@ -192,14 +192,16 @@ 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.
// embedded/off forbid a url, and NATS agent execution works with either
// embedded or external broker deployment.
func TestValidateNATS(t *testing.T) {
tests := []struct {
name string
mode string
url string
agent string
wantErr bool
name string
mode string
url string
agent string
containers bool
wantErr bool
}{
{name: "unset mode with url resolves external", url: "nats://localhost:4222"},
{name: "unset mode without url resolves embedded"},
@@ -210,7 +212,8 @@ func TestValidateNATS(t *testing.T) {
{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 embedded requires containers", mode: config.NATSModeEmbedded, agent: "nats", wantErr: true},
{name: "agent nats with embedded containers", mode: config.NATSModeEmbedded, agent: "nats", containers: true},
{name: "agent nats with external", mode: config.NATSModeExternal, url: "nats://localhost:4222", agent: "nats"},
}
for _, tc := range tests {
@@ -220,6 +223,9 @@ func TestValidateNATS(t *testing.T) {
if tc.agent != "" {
cfg.Agent.Mode = tc.agent
}
if tc.containers {
cfg.Containers.Enabled = true
}
err := validateNATS(&cfg)
if tc.wantErr && err == nil {
t.Fatal("validateNATS() = nil, want an error")
@@ -252,11 +258,11 @@ func TestValidateContainersResolvesNATSMode(t *testing.T) {
}
})
t.Run("embedded mode rejects containers", func(t *testing.T) {
t.Run("embedded mode supports 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")
if err := Validate(&cfg); err != nil {
t.Fatalf("Validate() = %v, want nil for managed containers with embedded nats", err)
}
})
}
@@ -2,6 +2,7 @@ package nats
import (
"context"
"crypto/rand"
"fmt"
"log/slog"
"time"
@@ -19,14 +20,16 @@ import (
// owns the lifecycle: StartEmbedded before dialing the client, Shutdown after
// the client closes.
type EmbeddedServer struct {
srv *server.Server
log *slog.Logger
srv *server.Server
log *slog.Logger
token string
}
// 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 is the bind address. Empty means "127.0.0.1" (loopback only).
// Container-backed deployments pass the host gateway address of the
// Docker bridge their workers join.
Host string
// Port is the listen port. Zero means a random port.
Port int
@@ -50,13 +53,15 @@ func StartEmbedded(ctx context.Context, opts EmbeddedOptions, log *slog.Logger)
if log == nil {
log = slog.New(slog.DiscardHandler)
}
token := rand.Text()
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
Host: opts.Host,
Port: opts.Port,
JetStream: true,
StoreDir: opts.StoreDir,
Authorization: token,
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
@@ -83,7 +88,7 @@ func StartEmbedded(ctx context.Context, opts EmbeddedOptions, log *slog.Logger)
}
log.Info("embedded nats ready", "url", srv.ClientURL())
return &EmbeddedServer{srv: srv, log: log}, nil
return &EmbeddedServer{srv: srv, log: log, token: token}, nil
}
// ClientURL returns the address the server is listening on. It is the URL the
@@ -91,6 +96,11 @@ func StartEmbedded(ctx context.Context, opts EmbeddedOptions, log *slog.Logger)
// connection used.
func (e *EmbeddedServer) ClientURL() string { return e.srv.ClientURL() }
// Token returns the per-start credential required by every embedded NATS
// client. Composition keeps it in memory and passes it only to the daemon's
// client and managed worker environments; it must never be logged or persisted.
func (e *EmbeddedServer) Token() string { return e.token }
// 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() {
@@ -21,11 +21,20 @@ func TestStartEmbeddedLifecycle(t *testing.T) {
if url == "" {
t.Fatal("ClientURL() = empty, want the bound address")
}
if unauthenticated, connectErr := nats.Connect(url); connectErr == nil {
unauthenticated.Close()
t.Fatal("unauthenticated connection succeeded, want embedded NATS to require its per-start token")
}
token := srv.Token()
if token == "" {
t.Fatal("Token() = empty, want a generated runtime token")
}
// Connecting and provisioning a stream proves JetStream is live, not just
// the core NATS socket.
c, err := Connect(t.Context(), Config{
URL: url,
Token: token,
Subjects: []string{"embedded.test.>"},
FilterSubject: "embedded.test.>",
}, discardLogger())