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

+44
View File
@@ -0,0 +1,44 @@
package container
import (
"context"
"fmt"
"github.com/moby/moby/client"
)
// NetworkName is the Docker network managed worker containers join.
func (p *Pool) NetworkName() string { return p.network }
// HostGateway is the host-side IPv4 gateway of NetworkName. It is non-empty
// only when Config.RequireHostGateway requested embedded broker reachability.
func (p *Pool) HostGateway() string { return p.hostGateway }
func resolveHostGateway(
ctx context.Context,
cli *client.Client,
networkName string,
required bool,
) (string, error) {
if !required {
return "", nil
}
result, err := cli.NetworkInspect(ctx, networkName, client.NetworkInspectOptions{})
if err != nil {
return "", fmt.Errorf("inspect Docker network %q for embedded NATS: %w", networkName, err)
}
network := result.Network.Network
if network.Driver != "bridge" {
return "", fmt.Errorf("docker network %q uses driver %q, want bridge for embedded NATS", networkName, network.Driver)
}
if network.Scope != "" && network.Scope != "local" {
return "", fmt.Errorf("docker network %q has scope %q, want local for embedded NATS", networkName, network.Scope)
}
for _, ipam := range network.IPAM.Config {
gateway := ipam.Gateway
if gateway.IsValid() && gateway.Is4() && !gateway.IsUnspecified() {
return gateway.String(), nil
}
}
return "", fmt.Errorf("docker network %q has no usable IPv4 host gateway for embedded NATS", networkName)
}
+160
View File
@@ -0,0 +1,160 @@
package container
import (
"encoding/json"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/moby/moby/client"
)
// A native archied process is not itself attached to a Docker network. When
// embedded NATS must be reachable by managed workers, the pool therefore uses
// Docker's default bridge and exposes its host-side gateway to composition.
func TestNewPoolResolvesDefaultBridgeGatewayForNativeDaemon(t *testing.T) {
hostname, err := os.Hostname()
if err != nil {
t.Fatal(err)
}
const gateway = "172.31.0.1"
dockerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/containers/"+hostname+"/json"):
http.Error(w, `{"message":"no such container"}`, http.StatusNotFound)
case strings.HasSuffix(r.URL.Path, "/networks/bridge"):
writeDockerJSON(t, w, map[string]any{
"Name": "bridge",
"Driver": "bridge",
"Scope": "local",
"IPAM": map[string]any{
"Config": []map[string]string{{
"Subnet": "172.31.0.0/16",
"Gateway": gateway,
}},
},
})
case strings.HasSuffix(r.URL.Path, "/containers/json"):
writeDockerJSON(t, w, []any{})
default:
http.Error(w, fmt.Sprintf("unexpected Docker API path %s", r.URL.Path), http.StatusNotFound)
}
}))
t.Cleanup(dockerAPI.Close)
dockerClient, err := client.New(client.WithHost(dockerAPI.URL), client.WithAPIVersion("1.55"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = dockerClient.Close() })
pool, err := NewPool(t.Context(), Config{
DockerClient: dockerClient,
RequireHostGateway: true,
}, discardLogger())
if err != nil {
t.Fatalf("NewPool = %v", err)
}
t.Cleanup(func() { _ = pool.Close() })
access, ok := any(pool).(interface {
NetworkName() string
HostGateway() string
})
if !ok {
t.Fatal("Pool does not expose its resolved worker network and host gateway")
}
if got := access.NetworkName(); got != "bridge" {
t.Errorf("NetworkName() = %q, want bridge", got)
}
if got := access.HostGateway(); got != gateway {
t.Errorf("HostGateway() = %q, want %q", got, gateway)
}
}
func TestNewPoolRejectsUnreachableEmbeddedNetwork(t *testing.T) {
tests := []struct {
name string
statusCode int
network map[string]any
}{
{
name: "inspect failure",
statusCode: http.StatusInternalServerError,
},
{
name: "non bridge driver",
network: map[string]any{
"Name": "workers", "Driver": "overlay", "Scope": "local",
"IPAM": map[string]any{"Config": []map[string]string{{"Gateway": "172.31.0.1"}}},
},
},
{
name: "non local scope",
network: map[string]any{
"Name": "workers", "Driver": "bridge", "Scope": "swarm",
"IPAM": map[string]any{"Config": []map[string]string{{"Gateway": "172.31.0.1"}}},
},
},
{
name: "no IPv4 gateway",
network: map[string]any{
"Name": "workers", "Driver": "bridge", "Scope": "local",
"IPAM": map[string]any{"Config": []map[string]string{{"Gateway": "fd00::1"}}},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dockerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/networks/workers"):
if tt.statusCode != 0 {
http.Error(w, `{"message":"network inspect failed"}`, tt.statusCode)
return
}
writeDockerJSON(t, w, tt.network)
case strings.HasSuffix(r.URL.Path, "/containers/json"):
writeDockerJSON(t, w, []any{})
default:
http.Error(w, fmt.Sprintf("unexpected Docker API path %s", r.URL.Path), http.StatusNotFound)
}
}))
t.Cleanup(dockerAPI.Close)
dockerClient, err := client.New(client.WithHost(dockerAPI.URL), client.WithAPIVersion("1.55"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = dockerClient.Close() })
pool, err := NewPool(t.Context(), Config{
DockerClient: dockerClient,
Network: "workers",
RequireHostGateway: true,
}, discardLogger())
if err == nil {
_ = pool.Close()
t.Fatal("NewPool = nil error, want embedded reachability validation failure")
}
})
}
}
func writeDockerJSON(t *testing.T, w http.ResponseWriter, value any) {
t.Helper()
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(value); err != nil {
t.Errorf("encode Docker response: %v", err)
}
}
func discardLogger() *slog.Logger {
return slog.New(slog.DiscardHandler)
}
+35 -17
View File
@@ -72,17 +72,19 @@ func WriteTaskJSON(workspace string, payload TaskPayload) error {
// Pool manages a set of Docker containers running archie-agent.
type Pool struct {
cli *client.Client
ownCli bool // true when the pool created the client (owns Close)
cfg Config
log *slog.Logger
natsURL string
// network is the user-defined Docker network spawned containers join,
// detected from the daemon's own container so they can resolve
// sibling services (nats, etc.) by compose service name. Empty when
// the daemon isn't running in a container on such a network, or when
// detection fails -- Docker then falls back to its default bridge.
cli *client.Client
ownCli bool // true when the pool created the client (owns Close)
cfg Config
log *slog.Logger
// network is the Docker network spawned containers join. External broker
// deployments may leave it empty to use Docker's implicit default bridge;
// embedded deployments resolve that default explicitly as "bridge" so its
// host gateway can be inspected.
network string
// hostGateway is the local IPv4 gateway of network. It is populated when
// embedded broker reachability is required, so native composition can bind
// the listener to an address visible only to workers on this bridge.
hostGateway string
mu sync.Mutex
active int
@@ -107,6 +109,9 @@ type Config struct {
// NewPool creates its own via client.New(client.FromEnv). Pass a
// shared client to avoid multiple independent connections.
DockerClient *client.Client
// RequireHostGateway resolves and validates a local Docker bridge gateway.
// Embedded NATS needs this address; external brokers do not.
RequireHostGateway bool
}
// NewPool connects to the Docker daemon, optionally pulls the image,
@@ -114,7 +119,7 @@ type Config struct {
//
// If cfg.DockerClient is set, it is reused (caller owns Close).
// Otherwise a new client is created via client.FromEnv (pool owns Close).
func NewPool(ctx context.Context, cfg Config, natsURL string, log *slog.Logger) (*Pool, error) {
func NewPool(ctx context.Context, cfg Config, log *slog.Logger) (*Pool, error) {
cli := cfg.DockerClient
if cli == nil {
var err error
@@ -128,14 +133,27 @@ func NewPool(ctx context.Context, cfg Config, natsURL string, log *slog.Logger)
if network == "" {
network = selfNetwork(ctx, cli, log)
}
if cfg.RequireHostGateway && network == "" {
// A native daemon is not itself attached to a Docker network. Its
// managed workers use Docker's default bridge unless configured
// otherwise, so that is the bridge whose host gateway must be bound.
network = "bridge"
}
hostGateway, err := resolveHostGateway(ctx, cli, network, cfg.RequireHostGateway)
if err != nil {
if cfg.DockerClient == nil {
_ = cli.Close()
}
return nil, err
}
p := &Pool{
cli: cli,
cfg: cfg,
log: log,
natsURL: natsURL,
ownCli: cfg.DockerClient == nil,
network: network,
cli: cli,
cfg: cfg,
log: log,
ownCli: cfg.DockerClient == nil,
network: network,
hostGateway: hostGateway,
}
// Pull image if needed.