refactor(agent): move worker runtime into application layer
cmd/archie-agent used to own worker construction, NATS lifecycle, task execution, MCP setup, and workflow wiring. It now owns process input only and invokes internal/app/agentworker, while transport-specific NATS, boot-brief, and git-safety mechanics live under infrastructure.
This commit is contained in:
1 parent
0243c13d37
commit
45345cdfb6
35 files changed
+2901
-689
No files matched your search
@@ -0,0 +1,36 @@
|
||||
package agentboot
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/container"
|
||||
)
|
||||
|
||||
// TaskID reads the daemon-owned boot brief at <mountDir>/.git/task.json.
|
||||
// An absent brief selects shared-worker mode. Any other read error, malformed
|
||||
// JSON, or non-positive task ID is a startup error: a container with invalid
|
||||
// dedicated-task metadata must never join the shared queue.
|
||||
func TaskID(mountDir string) (taskID int64, dedicated bool, err error) {
|
||||
path := filepath.Join(mountDir, ".git", "task.json")
|
||||
data, err := os.ReadFile(path)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return 0, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, false, fmt.Errorf("read %s: %w", path, err)
|
||||
}
|
||||
|
||||
var payload container.TaskPayload
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
return 0, false, fmt.Errorf("decode %s: %w", path, err)
|
||||
}
|
||||
if payload.ID <= 0 {
|
||||
return 0, false, fmt.Errorf("decode %s: task ID must be positive, got %d", path, payload.ID)
|
||||
}
|
||||
return payload.ID, true, nil
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package agentboot
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/container"
|
||||
)
|
||||
|
||||
func bootGitDir(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(dir, ".git"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
func TestTaskIDDistinguishesSharedDedicatedAndInvalidBoots(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
payload []byte
|
||||
write bool
|
||||
wantID int64
|
||||
wantOK bool
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "absent uses shared mode"},
|
||||
{name: "valid uses dedicated mode", payload: mustTaskPayload(t, container.TaskPayload{ID: 42}), write: true, wantID: 42, wantOK: true},
|
||||
{name: "malformed fails closed", payload: []byte("not json"), write: true, wantErr: true},
|
||||
{name: "zero ID fails closed", payload: mustTaskPayload(t, container.TaskPayload{}), write: true, wantErr: true},
|
||||
{name: "negative ID fails closed", payload: mustTaskPayload(t, container.TaskPayload{ID: -1}), write: true, wantErr: true},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
dir := bootGitDir(t)
|
||||
if test.write {
|
||||
if err := os.WriteFile(filepath.Join(dir, ".git", "task.json"), test.payload, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
id, ok, err := TaskID(dir)
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("TaskID() error = %v, wantErr %v", err, test.wantErr)
|
||||
}
|
||||
if id != test.wantID || ok != test.wantOK {
|
||||
t.Fatalf("TaskID() = (%d, %v), want (%d, %v)", id, ok, test.wantID, test.wantOK)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskIDFailsClosedOnNonMissingReadError(t *testing.T) {
|
||||
dir := bootGitDir(t)
|
||||
path := filepath.Join(dir, ".git", "task.json")
|
||||
if err := os.Mkdir(path, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
id, dedicated, err := TaskID(dir)
|
||||
if err == nil {
|
||||
t.Fatal("TaskID() error = nil for unreadable task.json path")
|
||||
}
|
||||
if id != 0 || dedicated {
|
||||
t.Fatalf("TaskID() = (%d, %v), want (0, false)", id, dedicated)
|
||||
}
|
||||
}
|
||||
|
||||
func mustTaskPayload(t *testing.T, payload container.TaskPayload) []byte {
|
||||
t.Helper()
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package agentgit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// gitRunner runs a git invocation and returns its combined output. Injected so
|
||||
// the safe.directory configuration can be tested without a git binary.
|
||||
type gitRunner func(ctx context.Context, args ...string) ([]byte, error)
|
||||
|
||||
// runGit is the production gitRunner.
|
||||
func runGit(ctx context.Context, args ...string) ([]byte, error) {
|
||||
return exec.CommandContext(ctx, "git", args...).CombinedOutput()
|
||||
}
|
||||
|
||||
// MarkSafe adds mountDir to git's global safe.directory list on a best-effort basis.
|
||||
func MarkSafe(ctx context.Context, mountDir string, log *slog.Logger) bool {
|
||||
return markSafe(ctx, mountDir, runGit, log)
|
||||
}
|
||||
|
||||
// markSafe adds mountDir to git's global safe.directory list.
|
||||
//
|
||||
// The daemon bind-mounts the task worktree into the container from the host,
|
||||
// so the directory is owned by a UID the container user is not. Git refuses to
|
||||
// operate in a repository it does not own ("detected dubious ownership"), and
|
||||
// the Go toolchain shells out to git for VCS stamping during build/test/vet --
|
||||
// so without this every gate fails before the agent does any real work.
|
||||
//
|
||||
// Best-effort by design: git may be absent from a minimal image, and an agent
|
||||
// working a repo with no gate commands never needs it. A failure is logged and
|
||||
// the agent continues. Returns true only when git accepted the configuration.
|
||||
//
|
||||
// The mount is checked first so that running archie-agent directly on a host
|
||||
// (shared queue-group mode, no container) does not write to the operator's own
|
||||
// ~/.gitconfig for a path that was never mounted.
|
||||
func markSafe(ctx context.Context, mountDir string, run gitRunner, log *slog.Logger) bool {
|
||||
info, err := os.Stat(mountDir)
|
||||
if err != nil || !info.IsDir() {
|
||||
log.Debug("git safe.directory skipped: no worktree mounted", "dir", mountDir)
|
||||
return false
|
||||
}
|
||||
|
||||
out, err := run(ctx, "config", "--global", "--add", "safe.directory", mountDir)
|
||||
if err != nil {
|
||||
log.Warn("git safe.directory config failed -- gates that shell out to git may fail",
|
||||
"dir", mountDir,
|
||||
"err", err,
|
||||
"output", strings.TrimSpace(string(out)),
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
log.Info("git safe.directory configured", "dir", mountDir)
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package agentgit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMarkWorktreeSafe(t *testing.T) {
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
present := func(t *testing.T) string { t.Helper(); return t.TempDir() }
|
||||
absent := func(t *testing.T) string { t.Helper(); return t.TempDir() + "/never-mounted" }
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
mountDir func(t *testing.T) string
|
||||
runErr error
|
||||
want bool
|
||||
wantRuns int
|
||||
}{
|
||||
{
|
||||
name: "configures git when the worktree is mounted",
|
||||
mountDir: present,
|
||||
want: true,
|
||||
wantRuns: 1,
|
||||
},
|
||||
{
|
||||
name: "git failure is best-effort",
|
||||
mountDir: present,
|
||||
runErr: errors.New("exit status 1"),
|
||||
want: false,
|
||||
wantRuns: 1,
|
||||
},
|
||||
{
|
||||
name: "git missing is best-effort",
|
||||
mountDir: present,
|
||||
runErr: errors.New(`exec: "git": executable file not found in $PATH`),
|
||||
want: false,
|
||||
wantRuns: 1,
|
||||
},
|
||||
{
|
||||
name: "no mounted worktree leaves git config untouched",
|
||||
mountDir: absent,
|
||||
want: false,
|
||||
wantRuns: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := tc.mountDir(t)
|
||||
var runs [][]string
|
||||
run := func(_ context.Context, args ...string) ([]byte, error) {
|
||||
runs = append(runs, args)
|
||||
return []byte("output"), tc.runErr
|
||||
}
|
||||
|
||||
got := markSafe(context.Background(), dir, run, log)
|
||||
|
||||
if got != tc.want {
|
||||
t.Fatalf("markSafe() = %v, want %v", got, tc.want)
|
||||
}
|
||||
if len(runs) != tc.wantRuns {
|
||||
t.Fatalf("git invoked %d times, want %d (%v)", len(runs), tc.wantRuns, runs)
|
||||
}
|
||||
if tc.wantRuns == 0 {
|
||||
return
|
||||
}
|
||||
wantArgs := []string{"config", "--global", "--add", "safe.directory", dir}
|
||||
if !reflect.DeepEqual(runs[0], wantArgs) {
|
||||
t.Fatalf("git args = %v, want %v", runs[0], wantArgs)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A mount path that is a file, not a directory, is not a worktree: git must
|
||||
// not be reconfigured for it.
|
||||
func TestMarkWorktreeSafeIgnoresNonDirectory(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
file := filepath.Join(dir, "worktree")
|
||||
if err := os.WriteFile(file, []byte("not a worktree"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
invoked := false
|
||||
run := func(_ context.Context, _ ...string) ([]byte, error) {
|
||||
invoked = true
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if got := markSafe(context.Background(), file, run, slog.New(slog.DiscardHandler)); got {
|
||||
t.Fatal("markSafe() = true for a non-directory mount path, want false")
|
||||
}
|
||||
if invoked {
|
||||
t.Fatal("git was invoked for a non-directory mount path")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInfrastructureDoesNotImportApplication(t *testing.T) {
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, path := range files {
|
||||
if strings.HasSuffix(path, "_test.go") {
|
||||
continue
|
||||
}
|
||||
file, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, imported := range file.Imports {
|
||||
name, err := strconv.Unquote(imported.Path.Value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(name, "/internal/app/") {
|
||||
t.Errorf("%s imports application package %q", path, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
// Package nats implements the agent worker's broker and RPC boundaries over NATS.
|
||||
// Raw NATS SDK types and wire encoding stay in this infrastructure package.
|
||||
package nats
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
"github.com/samcharles93/archie-core/internal/eventbus"
|
||||
"github.com/samcharles93/archie-core/internal/forgerpc"
|
||||
busnats "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/storerpc"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"github.com/samcharles93/archie-core/internal/worktreerpc"
|
||||
)
|
||||
|
||||
// Config contains the process and deployment inputs for the worker transport.
|
||||
// Stream subjects, filtering, and delivery timing are transport invariants.
|
||||
type Config struct {
|
||||
URL string
|
||||
Token string
|
||||
ConsumerName string
|
||||
}
|
||||
|
||||
const (
|
||||
stagePollTimeout = 5 * time.Second
|
||||
stageAckWait = 30 * time.Minute
|
||||
taskSubscriptionFlushTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
// ErrCoreConnectionUnavailable identifies failure to obtain the core-NATS
|
||||
// connection after the durable bus connected successfully.
|
||||
var ErrCoreConnectionUnavailable = errors.New("core NATS connection unavailable")
|
||||
|
||||
type sdkSubscription interface {
|
||||
Unsubscribe() error
|
||||
}
|
||||
|
||||
// Transport owns the worker's durable event bus and its shared core-NATS connection.
|
||||
type Transport struct {
|
||||
bus *busnats.Client
|
||||
conn *natsio.Conn
|
||||
|
||||
subscribe func(string, natsio.MsgHandler) (sdkSubscription, error)
|
||||
queueSubscribe func(string, string, natsio.MsgHandler) (sdkSubscription, error)
|
||||
flush func(time.Duration) error
|
||||
}
|
||||
|
||||
type busConnector func(context.Context, busnats.Config, *slog.Logger) (*busnats.Client, error)
|
||||
|
||||
// Connect establishes both worker transports over one NATS connection.
|
||||
func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport, error) {
|
||||
return connect(ctx, config, log, busnats.Connect)
|
||||
}
|
||||
|
||||
func connect(ctx context.Context, config Config, log *slog.Logger, connectBus busConnector) (*Transport, error) {
|
||||
bus, err := connectBus(ctx, busnats.Config{
|
||||
URL: config.URL,
|
||||
Token: config.Token,
|
||||
Subjects: []string{workintake.SubjectTaskWildcard, agentexec.SubjectAgentWildcard},
|
||||
ConsumerName: config.ConsumerName,
|
||||
FilterSubject: agentexec.SubjectAgentWildcard,
|
||||
PollTimeout: stagePollTimeout,
|
||||
AckWait: stageAckWait,
|
||||
}, log)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return transportFromBus(bus)
|
||||
}
|
||||
|
||||
func transportFromBus(bus *busnats.Client) (*Transport, error) {
|
||||
conn, err := bus.CoreConn()
|
||||
if err != nil {
|
||||
bus.Close()
|
||||
return nil, fmt.Errorf("%w: %w", ErrCoreConnectionUnavailable, err)
|
||||
}
|
||||
return &Transport{
|
||||
bus: bus,
|
||||
conn: conn,
|
||||
subscribe: func(subject string, handler natsio.MsgHandler) (sdkSubscription, error) {
|
||||
return conn.Subscribe(subject, handler)
|
||||
},
|
||||
queueSubscribe: func(subject, queue string, handler natsio.MsgHandler) (sdkSubscription, error) {
|
||||
return conn.QueueSubscribe(subject, queue, handler)
|
||||
},
|
||||
flush: conn.FlushTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Close releases all broker resources.
|
||||
func (t *Transport) Close() { t.bus.Close() }
|
||||
|
||||
type stageMessage struct {
|
||||
wire eventbus.Message
|
||||
request agentexec.AgentRequestMessage
|
||||
requestErr error
|
||||
replyAddress string
|
||||
encode func(any) ([]byte, error)
|
||||
respond func(context.Context, string, []byte) error
|
||||
}
|
||||
|
||||
var _ agentexec.StageMessage = (*stageMessage)(nil)
|
||||
|
||||
// FetchStage receives and decodes the next durable single-stage request while
|
||||
// retaining its reply inbox and acknowledgement controls inside infrastructure.
|
||||
func (t *Transport) FetchStage(ctx context.Context) (agentexec.StageMessage, error) {
|
||||
wire, err := t.bus.Fetch(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newStageMessage(wire, t.bus.Respond), nil
|
||||
}
|
||||
|
||||
func newStageMessage(wire eventbus.Message, respond func(context.Context, string, []byte) error) agentexec.StageMessage {
|
||||
message := &stageMessage{wire: wire, encode: json.Marshal, respond: respond}
|
||||
if err := json.Unmarshal(wire.Data(), &message.request); err != nil {
|
||||
message.requestErr = fmt.Errorf("decode request: %w", err)
|
||||
return message
|
||||
}
|
||||
var err error
|
||||
message.replyAddress, err = wire.ReplyAddress()
|
||||
if err != nil {
|
||||
message.requestErr = fmt.Errorf("stage request on %s: %w", wire.Subject(), err)
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
func (m *stageMessage) Request() (agentexec.AgentRequestMessage, error) {
|
||||
return m.request, m.requestErr
|
||||
}
|
||||
|
||||
func (m *stageMessage) Respond(ctx context.Context, response *agentexec.AgentResponseEnvelope) error {
|
||||
data, err := m.encode(response)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode response: %w", err)
|
||||
}
|
||||
if err := m.respond(ctx, m.replyAddress, data); err != nil {
|
||||
return fmt.Errorf("publish response: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *stageMessage) Ack() error { return m.wire.Ack() }
|
||||
func (m *stageMessage) Nak() error { return m.wire.Nak() }
|
||||
|
||||
func (m *stageMessage) LogAttributes() []any {
|
||||
if m.replyAddress == "" {
|
||||
return nil
|
||||
}
|
||||
return []any{"reply_to", m.replyAddress}
|
||||
}
|
||||
|
||||
// LogPublisher returns the narrow fire-and-forget capability used by system logs.
|
||||
func (t *Transport) LogPublisher() agentexec.LogPublisher { return t.conn }
|
||||
|
||||
// RemoteTrees is the proxied half of workflow.Trees.
|
||||
type RemoteTrees interface {
|
||||
Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string) (dir, branch string, err error)
|
||||
Push(ctx context.Context, owner, repo string, issue int, branch string) error
|
||||
}
|
||||
|
||||
// The top-level forgerpc, storerpc, and worktreerpc packages remain legacy
|
||||
// infrastructure with an open final destination. This adapter is their single
|
||||
// worker composition point until that broader migration is approved.
|
||||
|
||||
// Forger constructs the identity-scoped forge RPC client.
|
||||
func (t *Transport) Forger(identity string, timeout time.Duration) workflow.Forger {
|
||||
return &forgerpc.Client{Conn: t.conn, Timeout: timeout, Identity: identity}
|
||||
}
|
||||
|
||||
// Store constructs the workflow store RPC client.
|
||||
func (t *Transport) Store(timeout time.Duration) store.WorkflowStore {
|
||||
return &storerpc.Client{Conn: t.conn, Timeout: timeout}
|
||||
}
|
||||
|
||||
// Trees constructs the identity-scoped worktree RPC client.
|
||||
func (t *Transport) Trees(identity string, timeout time.Duration) RemoteTrees {
|
||||
return &worktreerpc.Client{Conn: t.conn, Timeout: timeout, Identity: identity}
|
||||
}
|
||||
|
||||
// TaskHandler executes one decoded full-task request.
|
||||
type TaskHandler func(context.Context, taskrun.Request) (*taskrun.Response, error)
|
||||
|
||||
// Subscription is a taskrun subscription owned by the worker lifecycle.
|
||||
type Subscription interface {
|
||||
Close() error
|
||||
}
|
||||
|
||||
type subscription struct{ sub sdkSubscription }
|
||||
|
||||
func (s subscription) Close() error { return s.sub.Unsubscribe() }
|
||||
|
||||
const (
|
||||
taskRunSubjectPrefix = "archie.taskrun."
|
||||
taskRunSubjectWildcard = taskRunSubjectPrefix + ">"
|
||||
taskRunQueueGroup = "archie-taskrun-workers"
|
||||
)
|
||||
|
||||
// SubjectForTask returns the canonical core-NATS subject for one full-task handoff.
|
||||
func SubjectForTask(taskID int64) string {
|
||||
return fmt.Sprintf("%s%d", taskRunSubjectPrefix, taskID)
|
||||
}
|
||||
|
||||
func taskIDFromSubject(subject string) (int64, error) {
|
||||
value, ok := strings.CutPrefix(subject, taskRunSubjectPrefix)
|
||||
if !ok || value == "" {
|
||||
return 0, fmt.Errorf("invalid taskrun subject %q", subject)
|
||||
}
|
||||
taskID, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || taskID <= 0 || SubjectForTask(taskID) != subject {
|
||||
return 0, fmt.Errorf("invalid taskrun subject %q", subject)
|
||||
}
|
||||
return taskID, nil
|
||||
}
|
||||
|
||||
// SubscribeTasks selects a dedicated task subject when a boot ID is present,
|
||||
// otherwise the shared worker queue. Wire decoding and inbox replies remain here.
|
||||
func (t *Transport) SubscribeTasks(ctx context.Context, taskID int64, dedicated bool, handler TaskHandler, log *slog.Logger) (Subscription, error) {
|
||||
callback := func(msg *natsio.Msg) { t.handleTask(ctx, msg, taskID, dedicated, handler, log) }
|
||||
subscribe := t.subscribe
|
||||
if subscribe == nil {
|
||||
subscribe = func(subject string, handler natsio.MsgHandler) (sdkSubscription, error) {
|
||||
return t.conn.Subscribe(subject, handler)
|
||||
}
|
||||
}
|
||||
queueSubscribe := t.queueSubscribe
|
||||
if queueSubscribe == nil {
|
||||
queueSubscribe = func(subject, queue string, handler natsio.MsgHandler) (sdkSubscription, error) {
|
||||
return t.conn.QueueSubscribe(subject, queue, handler)
|
||||
}
|
||||
}
|
||||
flush := t.flush
|
||||
if flush == nil {
|
||||
flush = t.conn.FlushTimeout
|
||||
}
|
||||
|
||||
var (
|
||||
sub sdkSubscription
|
||||
err error
|
||||
)
|
||||
if dedicated {
|
||||
log.Info("taskrun: dedicated per-task subscription", "task", taskID)
|
||||
sub, err = subscribe(SubjectForTask(taskID), callback)
|
||||
} else {
|
||||
log.Info("taskrun: shared queue-group subscription (no .git/task.json found)")
|
||||
sub, err = queueSubscribe(taskRunSubjectWildcard, taskRunQueueGroup, callback)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := flush(taskSubscriptionFlushTimeout); err != nil {
|
||||
if cleanupErr := sub.Unsubscribe(); cleanupErr != nil {
|
||||
log.Warn("task subscription cleanup failed after flush failure", "err", cleanupErr)
|
||||
}
|
||||
return nil, fmt.Errorf("flush task subscription: %w", err)
|
||||
}
|
||||
return subscription{sub: sub}, nil
|
||||
}
|
||||
|
||||
func (t *Transport) handleTask(
|
||||
ctx context.Context,
|
||||
msg *natsio.Msg,
|
||||
bootTaskID int64,
|
||||
dedicated bool,
|
||||
handler TaskHandler,
|
||||
log *slog.Logger,
|
||||
) {
|
||||
var request taskrun.Request
|
||||
if err := json.Unmarshal(msg.Data, &request); err != nil {
|
||||
log.Error("taskrun decode failed", "err", err)
|
||||
t.respondTask(msg, nil, fmt.Errorf("decode taskrun request: %w", err), log)
|
||||
return
|
||||
}
|
||||
if err := validateTaskRequest(msg.Subject, request, bootTaskID, dedicated); err != nil {
|
||||
log.Error("taskrun validation failed", "subject", msg.Subject, "err", err)
|
||||
t.respondTask(msg, nil, fmt.Errorf("validate taskrun request: %w", err), log)
|
||||
return
|
||||
}
|
||||
response, err := handler(ctx, request)
|
||||
t.respondTask(msg, response, err, log)
|
||||
}
|
||||
|
||||
func validateTaskRequest(subject string, request taskrun.Request, bootTaskID int64, dedicated bool) error {
|
||||
subjectTaskID, err := taskIDFromSubject(subject)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if request.Task.ID != subjectTaskID {
|
||||
return fmt.Errorf("task ID %d does not match subject task ID %d", request.Task.ID, subjectTaskID)
|
||||
}
|
||||
if dedicated && subjectTaskID != bootTaskID {
|
||||
return fmt.Errorf("task ID %d does not match dedicated boot task ID %d", subjectTaskID, bootTaskID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*Transport) respondTask(msg *natsio.Msg, response *taskrun.Response, runErr error, log *slog.Logger) {
|
||||
if response == nil {
|
||||
response = &taskrun.Response{}
|
||||
}
|
||||
if runErr != nil {
|
||||
response.Error = runErr.Error()
|
||||
}
|
||||
data, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
log.Error("taskrun encode response failed", "err", err)
|
||||
return
|
||||
}
|
||||
if err := msg.Respond(data); err != nil {
|
||||
log.Error("taskrun respond failed", "err", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
natstest "github.com/nats-io/nats-server/v2/test"
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
"github.com/samcharles93/archie-core/internal/forgerpc"
|
||||
busnats "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/storerpc"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"github.com/samcharles93/archie-core/internal/worktreerpc"
|
||||
)
|
||||
|
||||
func testTransport(t *testing.T) (*Transport, *natsio.Conn) {
|
||||
t.Helper()
|
||||
srv := natstest.RunRandClientPortServer()
|
||||
t.Cleanup(srv.Shutdown)
|
||||
conn, err := natsio.Connect(srv.ClientURL())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(conn.Close)
|
||||
return &Transport{conn: conn}, conn
|
||||
}
|
||||
|
||||
func TestTaskRunSubjectOwnsCanonicalNATSTopology(t *testing.T) {
|
||||
if got := SubjectForTask(42); got != "archie.taskrun.42" {
|
||||
t.Fatalf("SubjectForTask(42) = %q", got)
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
subject string
|
||||
wantID int64
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "canonical", subject: "archie.taskrun.42", wantID: 42},
|
||||
{name: "missing prefix", subject: "taskrun.42", wantErr: true},
|
||||
{name: "missing ID", subject: "archie.taskrun.", wantErr: true},
|
||||
{name: "nondecimal", subject: "archie.taskrun.any", wantErr: true},
|
||||
{name: "zero", subject: "archie.taskrun.0", wantErr: true},
|
||||
{name: "negative", subject: "archie.taskrun.-1", wantErr: true},
|
||||
{name: "noncanonical leading zero", subject: "archie.taskrun.042", wantErr: true},
|
||||
{name: "extra token", subject: "archie.taskrun.42.extra", wantErr: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := taskIDFromSubject(test.subject)
|
||||
if test.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("taskIDFromSubject(%q) = %d, want error", test.subject, got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || got != test.wantID {
|
||||
t.Fatalf("taskIDFromSubject(%q) = (%d, %v), want (%d, nil)", test.subject, got, err, test.wantID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscribeTasksPreservesDedicatedAndSharedSubjects(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
taskID int64
|
||||
dedicated bool
|
||||
subject string
|
||||
requestID int64
|
||||
}{
|
||||
{name: "dedicated", taskID: 42, dedicated: true, subject: SubjectForTask(42), requestID: 42},
|
||||
{name: "shared queue", subject: SubjectForTask(7), requestID: 7},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
transport, conn := testTransport(t)
|
||||
calls := 0
|
||||
subscription, err := transport.SubscribeTasks(t.Context(), test.taskID, test.dedicated, func(_ context.Context, request taskrun.Request) (*taskrun.Response, error) {
|
||||
calls++
|
||||
if request.Task.ID != test.requestID {
|
||||
t.Fatalf("task ID = %d, want %d", request.Task.ID, test.requestID)
|
||||
}
|
||||
return &taskrun.Response{Status: "done"}, nil
|
||||
}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = subscription.Close() })
|
||||
|
||||
payload, err := json.Marshal(taskrun.Request{Task: &store.Task{ID: test.requestID}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
message, err := conn.Request(test.subject, payload, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response taskrun.Response
|
||||
if err := json.Unmarshal(message.Data, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 || response.Status != "done" {
|
||||
t.Fatalf("handler/response = (%d, %q), want (1, done)", calls, response.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscribeTasksOwnsWireErrors(t *testing.T) {
|
||||
transport, conn := testTransport(t)
|
||||
handlerCalls := 0
|
||||
subscription, err := transport.SubscribeTasks(t.Context(), 9, true, func(context.Context, taskrun.Request) (*taskrun.Response, error) {
|
||||
handlerCalls++
|
||||
return nil, errors.New("run failed")
|
||||
}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = subscription.Close() })
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
payload []byte
|
||||
want string
|
||||
wantHandlerCalls int
|
||||
}{
|
||||
{name: "decode", payload: []byte("not json"), want: "decode taskrun request:"},
|
||||
{name: "missing task", payload: []byte(`{}`), want: "validate taskrun request: task is required"},
|
||||
{name: "null task", payload: []byte(`{"task":null}`), want: "validate taskrun request: task is required"},
|
||||
{name: "nonpositive task ID", payload: []byte(`{"task":{"id":0}}`), want: "validate taskrun request: task ID must be positive, got 0"},
|
||||
{name: "payload subject mismatch", payload: []byte(`{"task":{"id":8}}`), want: "validate taskrun request: task ID 8 does not match subject task ID 9"},
|
||||
{name: "handler", payload: []byte(`{"task":{"id":9}}`), want: "run failed", wantHandlerCalls: 1},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
before := handlerCalls
|
||||
message, err := conn.Request(SubjectForTask(9), test.payload, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response taskrun.Response
|
||||
if err := json.Unmarshal(message.Data, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Error == "" || !strings.Contains(response.Error, test.want) {
|
||||
t.Fatalf("response error = %q, want containing %q", response.Error, test.want)
|
||||
}
|
||||
if got := handlerCalls - before; got != test.wantHandlerCalls {
|
||||
t.Fatalf("handler calls = %d, want %d", got, test.wantHandlerCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleTaskRejectsSubjectCorrelationErrors(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
subject string
|
||||
bootTaskID int64
|
||||
dedicated bool
|
||||
requestID int64
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "malformed subject",
|
||||
subject: "archie.taskrun.invalid",
|
||||
requestID: 7,
|
||||
want: `validate taskrun request: invalid taskrun subject "archie.taskrun.invalid"`,
|
||||
},
|
||||
{
|
||||
name: "dedicated boot mismatch",
|
||||
subject: SubjectForTask(9),
|
||||
bootTaskID: 42,
|
||||
dedicated: true,
|
||||
requestID: 9,
|
||||
want: "validate taskrun request: task ID 9 does not match dedicated boot task ID 42",
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
transport, conn := testTransport(t)
|
||||
handlerCalls := 0
|
||||
subscription, err := conn.Subscribe(test.subject, func(message *natsio.Msg) {
|
||||
transport.handleTask(t.Context(), message, test.bootTaskID, test.dedicated, func(context.Context, taskrun.Request) (*taskrun.Response, error) {
|
||||
handlerCalls++
|
||||
return &taskrun.Response{Status: "unexpected"}, nil
|
||||
}, slog.New(slog.DiscardHandler))
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = subscription.Unsubscribe() })
|
||||
if err := conn.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(taskrun.Request{Task: &store.Task{ID: test.requestID}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
message, err := conn.Request(test.subject, payload, time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response taskrun.Response
|
||||
if err := json.Unmarshal(message.Data, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Error != test.want {
|
||||
t.Fatalf("response error = %q, want %q", response.Error, test.want)
|
||||
}
|
||||
if handlerCalls != 0 {
|
||||
t.Fatalf("handler calls = %d, want 0", handlerCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type recordingSDKSubscription struct {
|
||||
unsubscribeCalls int
|
||||
unsubscribeErr error
|
||||
}
|
||||
|
||||
func (s *recordingSDKSubscription) Unsubscribe() error {
|
||||
s.unsubscribeCalls++
|
||||
return s.unsubscribeErr
|
||||
}
|
||||
|
||||
func TestSubscribeTasksReportsSetupFailuresAndCleansUpFlushFailure(t *testing.T) {
|
||||
subscribeErr := errors.New("subscribe failed")
|
||||
queueErr := errors.New("queue subscribe failed")
|
||||
flushErr := errors.New("flush failed")
|
||||
cleanupErr := errors.New("unsubscribe failed")
|
||||
tests := []struct {
|
||||
name string
|
||||
dedicated bool
|
||||
subscribeErr error
|
||||
queueErr error
|
||||
flushErr error
|
||||
cleanupErr error
|
||||
wantErr error
|
||||
wantUnsubscribes int
|
||||
wantCleanupLog bool
|
||||
}{
|
||||
{name: "direct subscribe", dedicated: true, subscribeErr: subscribeErr, wantErr: subscribeErr},
|
||||
{name: "queue subscribe", queueErr: queueErr, wantErr: queueErr},
|
||||
{name: "flush cleanup succeeds", dedicated: true, flushErr: flushErr, wantErr: flushErr, wantUnsubscribes: 1},
|
||||
{name: "flush cleanup fails", dedicated: true, flushErr: flushErr, cleanupErr: cleanupErr, wantErr: flushErr, wantUnsubscribes: 1, wantCleanupLog: true},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
sub := &recordingSDKSubscription{unsubscribeErr: test.cleanupErr}
|
||||
transport := &Transport{
|
||||
subscribe: func(string, natsio.MsgHandler) (sdkSubscription, error) {
|
||||
return sub, test.subscribeErr
|
||||
},
|
||||
queueSubscribe: func(string, string, natsio.MsgHandler) (sdkSubscription, error) {
|
||||
return sub, test.queueErr
|
||||
},
|
||||
flush: func(timeout time.Duration) error {
|
||||
if timeout != taskSubscriptionFlushTimeout {
|
||||
t.Fatalf("flush timeout = %s, want %s", timeout, taskSubscriptionFlushTimeout)
|
||||
}
|
||||
return test.flushErr
|
||||
},
|
||||
}
|
||||
var output bytes.Buffer
|
||||
_, err := transport.SubscribeTasks(t.Context(), 42, test.dedicated, func(context.Context, taskrun.Request) (*taskrun.Response, error) {
|
||||
t.Fatal("handler called")
|
||||
return nil, nil
|
||||
}, slog.New(slog.NewTextHandler(&output, nil)))
|
||||
if !errors.Is(err, test.wantErr) {
|
||||
t.Fatalf("error = %v, want %v", err, test.wantErr)
|
||||
}
|
||||
if sub.unsubscribeCalls != test.wantUnsubscribes {
|
||||
t.Fatalf("unsubscribe calls = %d, want %d", sub.unsubscribeCalls, test.wantUnsubscribes)
|
||||
}
|
||||
if got := strings.Contains(output.String(), "task subscription cleanup failed after flush failure"); got != test.wantCleanupLog {
|
||||
t.Fatalf("cleanup warning logged = %v, want %v; output %q", got, test.wantCleanupLog, output.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectOwnsWorkerTopology(t *testing.T) {
|
||||
connectErr := errors.New("stop after config capture")
|
||||
var got busnats.Config
|
||||
_, err := connect(t.Context(), Config{
|
||||
URL: "nats://worker.test:4222",
|
||||
Token: "secret",
|
||||
ConsumerName: "agent-worker",
|
||||
}, slog.New(slog.DiscardHandler), func(_ context.Context, config busnats.Config, _ *slog.Logger) (*busnats.Client, error) {
|
||||
got = config
|
||||
return nil, connectErr
|
||||
})
|
||||
if !errors.Is(err, connectErr) {
|
||||
t.Fatalf("connect error = %v, want %v", err, connectErr)
|
||||
}
|
||||
if got.URL != "nats://worker.test:4222" || got.Token != "secret" || got.ConsumerName != "agent-worker" {
|
||||
t.Fatalf("deployment config = %#v", got)
|
||||
}
|
||||
wantSubjects := []string{workintake.SubjectTaskWildcard, agentexec.SubjectAgentWildcard}
|
||||
if !reflect.DeepEqual(got.Subjects, wantSubjects) {
|
||||
t.Fatalf("subjects = %v, want %v", got.Subjects, wantSubjects)
|
||||
}
|
||||
if got.FilterSubject != agentexec.SubjectAgentWildcard || got.PollTimeout != stagePollTimeout || got.AckWait != stageAckWait {
|
||||
t.Fatalf("topology config = %#v, want filter=%q poll=%s ack=%s", got, agentexec.SubjectAgentWildcard, stagePollTimeout, stageAckWait)
|
||||
}
|
||||
}
|
||||
|
||||
type rawStageMessage struct {
|
||||
data []byte
|
||||
subject string
|
||||
reply string
|
||||
replyErr error
|
||||
ackErr error
|
||||
nakErr error
|
||||
ackCalls int
|
||||
nakCalls int
|
||||
}
|
||||
|
||||
func (m *rawStageMessage) Data() []byte { return m.data }
|
||||
func (m *rawStageMessage) Subject() string { return m.subject }
|
||||
func (m *rawStageMessage) ReplyAddress() (string, error) { return m.reply, m.replyErr }
|
||||
func (m *rawStageMessage) Ack() error { m.ackCalls++; return m.ackErr }
|
||||
func (m *rawStageMessage) Nak() error { m.nakCalls++; return m.nakErr }
|
||||
|
||||
func TestStageMessageOwnsDecodeReplyAndAcknowledgement(t *testing.T) {
|
||||
replyErr := errors.New("no reply")
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
wire *rawStageMessage
|
||||
wantErr string
|
||||
}{
|
||||
{name: "decode", wire: &rawStageMessage{data: []byte("not json"), subject: "archie.agent.bad"}, wantErr: "decode request:"},
|
||||
{name: "reply", wire: &rawStageMessage{data: []byte(`{"task_id":7}`), subject: "archie.agent.no-reply", replyErr: replyErr}, wantErr: "stage request on archie.agent.no-reply:"},
|
||||
{name: "typed request", wire: &rawStageMessage{data: []byte(`{"task_id":7,"stage":"test"}`), reply: "_INBOX.7"}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
message := newStageMessage(test.wire, func(context.Context, string, []byte) error { return nil })
|
||||
request, err := message.Request()
|
||||
if test.wantErr != "" {
|
||||
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
|
||||
t.Fatalf("Request error = %v, want containing %q", err, test.wantErr)
|
||||
}
|
||||
} else if err != nil || request.TaskID != 7 || request.Stage != "test" {
|
||||
t.Fatalf("Request = (%#v, %v), want typed task 7/test", request, err)
|
||||
}
|
||||
if err := message.Ack(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := message.Nak(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if test.wire.ackCalls != 1 || test.wire.nakCalls != 1 {
|
||||
t.Fatalf("ack/nak calls = (%d,%d), want (1,1)", test.wire.ackCalls, test.wire.nakCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageMessageDelegatesAcknowledgementErrors(t *testing.T) {
|
||||
ackErr := errors.New("ack failed")
|
||||
nakErr := errors.New("nak failed")
|
||||
wire := &rawStageMessage{data: []byte(`{"task_id":7}`), reply: "_INBOX.7", ackErr: ackErr, nakErr: nakErr}
|
||||
message := newStageMessage(wire, func(context.Context, string, []byte) error { return nil })
|
||||
if err := message.Ack(); !errors.Is(err, ackErr) {
|
||||
t.Fatalf("Ack error = %v, want %v", err, ackErr)
|
||||
}
|
||||
if err := message.Nak(); !errors.Is(err, nakErr) {
|
||||
t.Fatalf("Nak error = %v, want %v", err, nakErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStageMessageOwnsResponseEncodingAndInboxDelivery(t *testing.T) {
|
||||
encodeErr := errors.New("encode failed")
|
||||
respondErr := errors.New("respond failed")
|
||||
response := &agentexec.AgentResponseEnvelope{Result: agentexec.Result{Status: agentexec.StatusPassed}}
|
||||
|
||||
wire := &rawStageMessage{data: []byte(`{"task_id":7}`), reply: "_INBOX.7"}
|
||||
message := newStageMessage(wire, func(_ context.Context, reply string, data []byte) error {
|
||||
if reply != "_INBOX.7" || !strings.Contains(string(data), `"status":"passed"`) {
|
||||
t.Fatalf("reply/data = (%q,%s)", reply, data)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err := message.Respond(t.Context(), response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
concrete, ok := message.(*stageMessage)
|
||||
if !ok {
|
||||
t.Fatalf("message type = %T, want *stageMessage", message)
|
||||
}
|
||||
concrete.encode = func(any) ([]byte, error) { return nil, encodeErr }
|
||||
if err := concrete.Respond(t.Context(), response); !errors.Is(err, encodeErr) || !strings.Contains(err.Error(), "encode response") {
|
||||
t.Fatalf("encode error = %v", err)
|
||||
}
|
||||
concrete.encode = json.Marshal
|
||||
concrete.respond = func(context.Context, string, []byte) error { return respondErr }
|
||||
if err := concrete.Respond(t.Context(), response); !errors.Is(err, respondErr) || !strings.Contains(err.Error(), "publish response") {
|
||||
t.Fatalf("respond error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRPCFactoriesPreserveIdentityAndTimeout(t *testing.T) {
|
||||
transport, _ := testTransport(t)
|
||||
timeout := 60 * time.Second
|
||||
forgeClient, ok := transport.Forger("identity-a", timeout).(*forgerpc.Client)
|
||||
if !ok || forgeClient.Identity != "identity-a" || forgeClient.Timeout != timeout {
|
||||
t.Fatalf("forge client = %#v", forgeClient)
|
||||
}
|
||||
storeClient, ok := transport.Store(timeout).(*storerpc.Client)
|
||||
if !ok || storeClient.Timeout != timeout {
|
||||
t.Fatalf("store client = %#v", storeClient)
|
||||
}
|
||||
treeClient, ok := transport.Trees("identity-a", timeout).(*worktreerpc.Client)
|
||||
if !ok || treeClient.Identity != "identity-a" || treeClient.Timeout != timeout {
|
||||
t.Fatalf("tree client = %#v", treeClient)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransportFromBusClassifiesUnavailableCoreConnection(t *testing.T) {
|
||||
transport, err := transportFromBus(&busnats.Client{})
|
||||
if transport != nil {
|
||||
t.Fatalf("transport = %#v, want nil", transport)
|
||||
}
|
||||
if !errors.Is(err, ErrCoreConnectionUnavailable) {
|
||||
t.Fatalf("error = %v, want ErrCoreConnectionUnavailable", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectOwnsJetStreamAndCoreConnection(t *testing.T) {
|
||||
srv := natstest.RunRandClientPortServer()
|
||||
t.Cleanup(srv.Shutdown)
|
||||
if err := srv.EnableJetStream(&server.JetStreamConfig{StoreDir: t.TempDir()}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
transport, err := Connect(t.Context(), Config{
|
||||
URL: srv.ClientURL(),
|
||||
ConsumerName: "worker-test",
|
||||
}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
transport.Close()
|
||||
if _, err := transport.FetchStage(t.Context()); err == nil {
|
||||
t.Fatal("FetchStage after Close returned nil error")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user