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

+107
View File
@@ -0,0 +1,107 @@
package daemon
import (
"encoding/json"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
dockercontainer "github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
"github.com/samcharles93/archie-core/internal/config"
archiecontainer "github.com/samcharles93/archie-core/internal/container"
)
// This pins the last handoff seam, not just its two halves: the runtime NATS
// endpoint frozen in Daemon becomes the environment on a container created on
// the same Docker network whose gateway embedded NATS binds.
func TestConnectedNATSEndpointReachesManagedContainerCreate(t *testing.T) {
const (
networkName = "workers"
gateway = "172.31.0.1"
containerID = "12345678901234567890123456789012"
token = "runtime-only-token"
)
var createRequest dockercontainer.CreateRequest
dockerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/networks/"+networkName):
writeContainerDockerJSON(t, w, map[string]any{
"Name": networkName,
"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/create"):
if err := json.NewDecoder(r.Body).Decode(&createRequest); err != nil {
t.Errorf("decode container create request: %v", err)
}
writeContainerDockerJSON(t, w, dockercontainer.CreateResponse{ID: containerID})
case strings.HasSuffix(r.URL.Path, "/containers/"+containerID+"/start"):
w.WriteHeader(http.StatusNoContent)
case strings.HasSuffix(r.URL.Path, "/containers/json"):
writeContainerDockerJSON(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 := archiecontainer.NewPool(t.Context(), archiecontainer.Config{
Image: "archie-agent:test",
Network: networkName,
DockerClient: dockerClient,
RequireHostGateway: true,
}, slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("container.NewPool = %v", err)
}
t.Cleanup(func() { _ = pool.Close() })
d := &Daemon{
Cfg: config.NewHolder(config.Config{}),
ConnectedNATS: NATSEndpoint{
URL: "nats://" + gateway + ":4222",
Token: token,
},
}
if _, err := pool.Acquire(t.Context(), nil, d.containerEnv(nil)); err != nil {
t.Fatalf("Pool.Acquire = %v", err)
}
if createRequest.HostConfig == nil || string(createRequest.HostConfig.NetworkMode) != networkName {
t.Fatalf("container network = %v, want %q", createRequest.HostConfig, networkName)
}
for _, want := range []string{
"NATS_URL=nats://" + gateway + ":4222",
"NATS_TOKEN=" + token,
} {
if !slices.Contains(createRequest.Env, want) {
t.Errorf("container env = %q, want %q", createRequest.Env, want)
}
}
}
func writeContainerDockerJSON(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)
}
}
+15 -11
View File
@@ -54,17 +54,23 @@ type WorktreeGrantIssuer interface {
Issue(task *store.Task) (token string, revoke func(), err error)
}
// NATSEndpoint is the broker address and credential archied connected with at
// startup. It is runtime state rather than configuration: embedded mode
// generates both values, and external secret references are resolved once.
type NATSEndpoint struct {
URL string
Token string
}
type Daemon struct {
// Cfg publishes the running configuration. Read through Cfg() so a
// reload swaps the published snapshot atomically. See config.Holder.
Cfg *config.Holder
// ConnectedNATS is the [nats] configuration the daemon's own client
// connected with at startup (the endpoint it publishes on). Container
// env is built from this, not from the live config, so a reload of
// nats.url/token_env cannot point new containers at a server the
// daemon is not publishing on. Zero value means NATS is not
// configured.
ConnectedNATS config.NATSConfig
// ConnectedNATS is the endpoint and credential the daemon's own client
// connected with at startup. Container env is built from this, not from
// live config or environment, so reload cannot point new containers at a
// broker the daemon is not publishing on. Zero value means no NATS.
ConnectedNATS NATSEndpoint
Store store.TaskStore
Forge forge.Forge
Trees *worktree.Manager
@@ -1168,10 +1174,8 @@ func (d *Daemon) containerEnv(task *store.Task) []string {
// the live config: a reloaded [nats] section must not point new
// containers at a server the daemon is not publishing on.
env = append(env, "NATS_URL="+d.ConnectedNATS.URL)
if tokenEnv := d.ConnectedNATS.TokenEnv; tokenEnv != "" {
if token := os.Getenv(tokenEnv); token != "" {
env = append(env, "NATS_TOKEN="+token)
}
if token := d.ConnectedNATS.Token; token != "" {
env = append(env, "NATS_TOKEN="+token)
}
// The agent process runs as root inside the container (no USER in the
// Dockerfile, no userns-remap), so a commit it writes to the bind-mounted
+7 -10
View File
@@ -305,20 +305,17 @@ func TestAllowConcurrentForTaskPrefersOwningIdentityRepo(t *testing.T) {
}
func TestContainerEnvIncludesConfiguredNATSCredentials(t *testing.T) {
t.Setenv("ARCHIE_NATS_SECRET", "test-nats-token")
// ConnectedNATS is the endpoint the daemon's own client connected with
// at startup; containerEnv deliberately reads this, not the live Cfg,
// so a reload of nats.url cannot point new containers at a server the
// daemon is not publishing on.
natsCfg := config.NATSConfig{
URL: "nats://nats.example:4222",
TokenEnv: "ARCHIE_NATS_SECRET",
}
// at startup; containerEnv deliberately reads this frozen runtime value,
// not live config or environment.
d := &Daemon{
Cfg: config.NewHolder(config.Config{}),
ConnectedNATS: natsCfg,
ConnectedNATS: NATSEndpoint{URL: "nats://nats.example:4222", Token: "test-nats-token"},
}
// Runtime credentials are frozen when the daemon connects. Mutating the
// source environment later must not send new workers to the same endpoint
// with a credential the broker never adopted.
t.Setenv("ARCHIE_NATS_SECRET", "changed-after-startup")
got := d.containerEnv(nil)
for _, want := range []string{