feat(nats): expose embedded broker to managed workers
This commit is contained in:
1 parent
aaa9e85dd4
commit
9d73bc7157
16 files changed
+678
-178
No files matched your search
+21
-15
@@ -100,6 +100,9 @@ type boot struct {
|
||||
// the embedded server's ClientURL(). Recorded so Daemon.ConnectedNATS
|
||||
// carries the real endpoint rather than an empty config URL.
|
||||
natsURL string
|
||||
// natsToken is the credential the daemon's client connected with at
|
||||
// startup. Embedded mode generates it; external mode resolves it once.
|
||||
natsToken string
|
||||
|
||||
containerPool *container.Pool
|
||||
storeBackend storage.Backend
|
||||
@@ -376,7 +379,12 @@ func (b *boot) connectNATS(ctx context.Context) error {
|
||||
// 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).
|
||||
host := ""
|
||||
if b.containerPool != nil {
|
||||
host = b.containerPool.HostGateway()
|
||||
}
|
||||
srv, err := nats.StartEmbedded(ctx, nats.EmbeddedOptions{
|
||||
Host: host,
|
||||
StoreDir: filepath.Join(filepath.Dir(cfg.DBPath), "nats"),
|
||||
}, log)
|
||||
if err != nil {
|
||||
@@ -385,6 +393,7 @@ func (b *boot) connectNATS(ctx context.Context) error {
|
||||
}
|
||||
b.addCleanup(func() { srv.Shutdown() })
|
||||
url = srv.ClientURL()
|
||||
natsToken = srv.Token()
|
||||
log.Info("embedded nats started", "url", url)
|
||||
}
|
||||
|
||||
@@ -402,6 +411,7 @@ func (b *boot) connectNATS(ctx context.Context) error {
|
||||
}
|
||||
b.natsClient = natsClient
|
||||
b.natsURL = url
|
||||
b.natsToken = natsToken
|
||||
b.addCleanup(func() { natsClient.Close() })
|
||||
log.Info("nats connected", "url", url)
|
||||
return nil
|
||||
@@ -414,15 +424,15 @@ func (b *boot) connectNATS(ctx context.Context) error {
|
||||
// feature they may not be exercising right now. Under a systemd unit
|
||||
// with Restart=on-failure it also turns a recoverable problem into a
|
||||
// crash loop with the real error scrolling past unread.
|
||||
func (b *boot) setupContainers(ctx context.Context) {
|
||||
func (b *boot) setupContainers(ctx context.Context) func() {
|
||||
containerPool, storeBackend, closeDocker := startContainers(ctx, b.cfg, b.log)
|
||||
b.containerPool = containerPool
|
||||
b.storeBackend = storeBackend
|
||||
b.addCleanup(closeDocker)
|
||||
// Sandboxing that was asked for and could not start must not silently
|
||||
// become no sandboxing: the daemon stays up, but tasks park rather than
|
||||
// running the agent loop on the host.
|
||||
b.sandboxRequired = b.cfg.Containers.Enabled && containerPool == nil
|
||||
return closeDocker
|
||||
}
|
||||
|
||||
// setupLLMAndChat wires the runtime, tool registry, model management,
|
||||
@@ -995,16 +1005,9 @@ func (b *boot) registerMinimaxTool(cfg config.Config, log *slog.Logger) {
|
||||
// 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: connectedNATS,
|
||||
ConnectedNATS: daemon.NATSEndpoint{URL: b.natsURL, Token: b.natsToken},
|
||||
Store: b.st,
|
||||
Bus: b.bus,
|
||||
Forge: b.forgeClient,
|
||||
@@ -1323,11 +1326,14 @@ func (b *boot) startServices(ctx context.Context) error {
|
||||
// setupBackends wires the optional runtime backends: the NATS client
|
||||
// and the container pool.
|
||||
func (b *boot) setupBackends(ctx context.Context) error {
|
||||
if err := b.connectNATS(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
b.setupContainers(ctx)
|
||||
return nil
|
||||
closeContainers := b.setupContainers(ctx)
|
||||
err := b.connectNATS(ctx)
|
||||
// Container discovery must precede embedded NATS so it can bind the
|
||||
// worker bridge gateway, but cleanup registration comes afterwards.
|
||||
// cleanups run LIFO: workers stop first, then the daemon client closes,
|
||||
// then the embedded server shuts down.
|
||||
b.addCleanup(closeContainers)
|
||||
return err
|
||||
}
|
||||
|
||||
// buildAgentAndWorkflows builds the agent runner and the workflow
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/moby/moby/client"
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/container"
|
||||
)
|
||||
|
||||
// setupContainers must discover the bridge before embedded NATS starts, but
|
||||
// its cleanup registration comes afterwards. boot.cleanup is LIFO, so this
|
||||
// ordering stops worker containers before closing the daemon client and the
|
||||
// embedded server they are connected to.
|
||||
func TestSetupBackendsRegistersContainerCleanupAfterNATS(t *testing.T) {
|
||||
fileset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fileset, "bootstrap.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
setupContainers := methodBody(t, file, "setupContainers")
|
||||
if methodCallPosition(setupContainers, "addCleanup") != token.NoPos {
|
||||
t.Fatal("setupContainers registers cleanup before NATS; LIFO would stop the broker before workers")
|
||||
}
|
||||
setupBackends := methodBody(t, file, "setupBackends")
|
||||
connect := methodCallPosition(setupBackends, "connectNATS")
|
||||
register := methodCallPosition(setupBackends, "addCleanup")
|
||||
if connect == token.NoPos || register == token.NoPos || register < connect {
|
||||
t.Fatalf("setupBackends call positions: connectNATS=%d addCleanup=%d, want container cleanup registered after connect", connect, register)
|
||||
}
|
||||
}
|
||||
|
||||
func methodBody(t *testing.T, file *ast.File, name string) *ast.BlockStmt {
|
||||
t.Helper()
|
||||
for _, decl := range file.Decls {
|
||||
fn, ok := decl.(*ast.FuncDecl)
|
||||
if ok && fn.Recv != nil && fn.Name.Name == name {
|
||||
return fn.Body
|
||||
}
|
||||
}
|
||||
t.Fatalf("method %s not found", name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func methodCallPosition(body *ast.BlockStmt, name string) token.Pos {
|
||||
position := token.NoPos
|
||||
ast.Inspect(body, func(node ast.Node) bool {
|
||||
call, ok := node.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
selector, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if ok && selector.Sel.Name == name && position == token.NoPos {
|
||||
position = call.Pos()
|
||||
}
|
||||
return true
|
||||
})
|
||||
return position
|
||||
}
|
||||
|
||||
// This is the native-daemon deployment seam: Docker supplies the host-side
|
||||
// gateway of the worker bridge, embedded NATS binds that address, and the
|
||||
// runtime credential shared with workers is required by the same listener.
|
||||
func TestConnectEmbeddedNATSUsesManagedWorkerBridge(t *testing.T) {
|
||||
const gateway = "127.0.0.1"
|
||||
dockerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/networks/workers"):
|
||||
writeDockerResponse(t, w, map[string]any{
|
||||
"Name": "workers",
|
||||
"Driver": "bridge",
|
||||
"Scope": "local",
|
||||
"IPAM": map[string]any{
|
||||
"Config": []map[string]string{{
|
||||
"Subnet": "127.0.0.0/8",
|
||||
"Gateway": gateway,
|
||||
}},
|
||||
},
|
||||
})
|
||||
case strings.HasSuffix(r.URL.Path, "/containers/json"):
|
||||
writeDockerResponse(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 := container.NewPool(t.Context(), container.Config{
|
||||
DockerClient: dockerClient,
|
||||
Network: "workers",
|
||||
RequireHostGateway: true,
|
||||
}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("container.NewPool = %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = pool.Close() })
|
||||
|
||||
b := &boot{
|
||||
cfg: config.Config{
|
||||
DBPath: filepath.Join(t.TempDir(), "archie.db"),
|
||||
NATS: config.NATSConfig{Mode: config.NATSModeEmbedded},
|
||||
},
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
containerPool: pool,
|
||||
}
|
||||
if err := b.connectNATS(t.Context()); err != nil {
|
||||
t.Fatalf("connectNATS = %v", err)
|
||||
}
|
||||
t.Cleanup(b.cleanup)
|
||||
|
||||
if !strings.HasPrefix(b.natsURL, "nats://"+gateway+":") {
|
||||
t.Errorf("connected NATS URL = %q, want bridge gateway %s", b.natsURL, gateway)
|
||||
}
|
||||
if b.natsToken == "" {
|
||||
t.Fatal("connected NATS token is empty")
|
||||
}
|
||||
if unauthenticated, connectErr := natsio.Connect(b.natsURL); connectErr == nil {
|
||||
unauthenticated.Close()
|
||||
t.Fatal("unauthenticated worker connection succeeded")
|
||||
}
|
||||
authenticated, err := natsio.Connect(b.natsURL, natsio.Token(b.natsToken))
|
||||
if err != nil {
|
||||
t.Fatalf("authenticated worker connection = %v", err)
|
||||
}
|
||||
authenticated.Close()
|
||||
}
|
||||
|
||||
func writeDockerResponse(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)
|
||||
}
|
||||
}
|
||||
+8
-7
@@ -979,13 +979,14 @@ func startContainers(
|
||||
}
|
||||
|
||||
pool, err := container.NewPool(ctx, container.Config{
|
||||
Image: cfg.Containers.Image,
|
||||
MaxConcurrency: cfg.Containers.MaxConcurrency,
|
||||
MaxUptime: cfg.Containers.MaxUptime.Std(),
|
||||
PullPolicy: cfg.Containers.PullPolicy,
|
||||
Network: cfg.Containers.Network,
|
||||
DockerClient: dockerCli,
|
||||
}, cfg.NATS.URL, log)
|
||||
Image: cfg.Containers.Image,
|
||||
MaxConcurrency: cfg.Containers.MaxConcurrency,
|
||||
MaxUptime: cfg.Containers.MaxUptime.Std(),
|
||||
PullPolicy: cfg.Containers.PullPolicy,
|
||||
Network: cfg.Containers.Network,
|
||||
DockerClient: dockerCli,
|
||||
RequireHostGateway: cfg.NATS.Mode == config.NATSModeEmbedded,
|
||||
}, log)
|
||||
if err != nil {
|
||||
// A missing image is recoverable by hand. The daemon sends no registry
|
||||
// credentials on pull (internal/container/pool.go), so a private
|
||||
|
||||
Reference in new issue
Block a user