feat: Forge RPC proxy for archie-agent (archie-core-5zh.2)
Add internal/forgerpc: core NATS request/reply for the four forge.Forge methods workflow stages call mid-run (Comment, CloseIssue, CreatePR, SetStateLabel). archied stays the sole holder of forge API tokens. All other Forge methods are daemon-only poll/reconcile-loop calls and don't need proxying (confirmed by grep across internal/workflow). Groundwork for archie-core-5zh — not yet wired into daemon.go or workflow.TaskContext.
This commit is contained in:
1 parent
c9d0f015ca
commit
65eda765ab
4 files changed
+485
-1
No files matched your search
@@ -3,3 +3,4 @@
|
||||
{"id":"int-dd2e5e0351a12ea84b50ad3e3c3c42e3","kind":"field_change","created_at":"2026-07-23T21:46:52.85072403Z","actor":"Sam Catlow","issue_id":"archie-core-g1l","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added config.Repo.AllowConcurrent (allow_concurrent toml key) and threaded it through taskDispatcher so opted-in repos skip the default FIFO same-repo serialization while still respecting containers.max_concurrency. Worktrees are already keyed per issue number, so no on-disk collision. Race-tested dispatcher coverage added."}}
|
||||
{"id":"int-a6f23a24a14200e58047cb705b026703","kind":"field_change","created_at":"2026-07-23T21:49:40.094050867Z","actor":"Sam Catlow","issue_id":"archie-core-l1q","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Completed JetStream task dispatch and NATS agent request/reply, including token_env authentication for archied and canonical NATS_URL/NATS_TOKEN propagation to container workers; anonymous local mode remains supported and race-tested."}}
|
||||
{"id":"int-4b10e52acc74cd691919159a77b36f6d","kind":"field_change","created_at":"2026-07-23T21:58:50.804043554Z","actor":"Sam Catlow","issue_id":"archie-core-5zh.1","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added internal/storerpc: core-NATS request/reply RPC so archie-agent can call Store.Update/Transition without direct DB access. archied's Store stays the sole owner; store.Task gained json tags to cross the wire. Not yet wired into daemon.go or workflow.TaskContext — that's archie-core-5zh.4's job once all three RPC proxies exist."}}
|
||||
{"id":"int-b4c080744419b9e5838f016f0f7e3d2f","kind":"field_change","created_at":"2026-07-23T22:02:41.482197412Z","actor":"Sam Catlow","issue_id":"archie-core-5zh.2","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Added internal/forgerpc: core-NATS request/reply RPC for the four forge.Forge methods workflow stages actually call mid-run (Comment, CloseIssue, CreatePR, SetStateLabel). Confirmed via grep that all other Forge methods (AssignedIssues, IssuesWithLabel, React, RepliesAfter, PRState, CreateIssue, AcceptInvitations, VerifyPush) are daemon-only poll/reconcile-loop calls, never invoked from a workflow stage, so nothing else needs proxying. archied stays the sole holder of forge API tokens. Not yet wired into daemon.go or workflow.TaskContext — deferred to archie-core-5zh.4."}}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{"_type":"issue","id":"archie-core-u64","title":"Daemon: process multiple tasks concurrently (max_concurrency enforcement)","description":"Daemon currently processes one task at a time (docs/prds/archie-core-v2-architecture.md Phase 2). This is the core blocker between current state and any multi-agent scaling mode — needed before container max_concurrency or same-repo concurrency can matter. Wire the daemon's dispatch loop to run N tasks in parallel, respecting a configurable max_concurrency.","design":"internal/container/pool.go already enforces max_concurrency for container lifecycle — reuse that limit/pattern in the daemon's task dispatch rather than inventing a second concurrency control.","acceptance_criteria":"Daemon dispatch loop runs multiple tasks concurrently up to a configured max_concurrency limit; single-task-at-a-time behavior is gone.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T19:36:31Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:37:42Z","started_at":"2026-07-23T21:29:41Z","closed_at":"2026-07-23T21:37:42Z","close_reason":"Implemented concurrent SQLite and NATS task dispatch using containers.max_concurrency, with default same-repo serialization and race-tested dispatcher coverage.","dependency_count":0,"dependent_count":2,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-5zh.2","title":"Forge RPC proxy: archie-agent → archied for forge API calls","description":"Phase 1 groundwork for archie-core-5zh. Stages call Forge.SetStateLabel/Comment/CreatePR/CloseIssue/CreateIssue/React/RepliesAfter mid-workflow. Forge holds live API tokens (Gitea/GitHub) that must stay daemon-side per the PRD's 'daemon never runs untrusted code, owns all secrets' boundary. Once workflow.Run moves into archie-agent, these calls need to become NATS request/reply RPCs to the daemon rather than shipping forge credentials into the agent container.","acceptance_criteria":"archie-agent can invoke the forge.Forge interface methods used by workflow stages over NATS; archied executes them against the real forge client and replies; no forge API tokens are present in the agent container.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-23T21:55:44Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:55:44Z","dependencies":[{"issue_id":"archie-core-5zh.2","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T07:55:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-5zh.2","title":"Forge RPC proxy: archie-agent → archied for forge API calls","description":"Phase 1 groundwork for archie-core-5zh. Stages call Forge.SetStateLabel/Comment/CreatePR/CloseIssue/CreateIssue/React/RepliesAfter mid-workflow. Forge holds live API tokens (Gitea/GitHub) that must stay daemon-side per the PRD's 'daemon never runs untrusted code, owns all secrets' boundary. Once workflow.Run moves into archie-agent, these calls need to become NATS request/reply RPCs to the daemon rather than shipping forge credentials into the agent container.","acceptance_criteria":"archie-agent can invoke the forge.Forge interface methods used by workflow stages over NATS; archied executes them against the real forge client and replies; no forge API tokens are present in the agent container.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T21:55:44Z","created_by":"Sam Catlow","updated_at":"2026-07-23T22:02:41Z","started_at":"2026-07-23T22:00:46Z","closed_at":"2026-07-23T22:02:41Z","close_reason":"Added internal/forgerpc: core-NATS request/reply RPC for the four forge.Forge methods workflow stages actually call mid-run (Comment, CloseIssue, CreatePR, SetStateLabel). Confirmed via grep that all other Forge methods (AssignedIssues, IssuesWithLabel, React, RepliesAfter, PRState, CreateIssue, AcceptInvitations, VerifyPush) are daemon-only poll/reconcile-loop calls, never invoked from a workflow stage, so nothing else needs proxying. archied stays the sole holder of forge API tokens. Not yet wired into daemon.go or workflow.TaskContext — deferred to archie-core-5zh.4.","dependencies":[{"issue_id":"archie-core-5zh.2","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T07:55:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-5zh.3","title":"Worktree push RPC proxy: archie-agent → archied for git push","description":"Phase 1 groundwork for archie-core-5zh. worktree.Manager.Push needs the forge HTTPS push token (held daemon-side, used via an askpass helper). Trees.Prepare/CommitAll/Diff/ChangedFiles/ChangedLines are local git operations against the already-mounted worktree and can run agent-side unchanged (containers already bind-mount /data/worktree) — only Push needs to be proxied back to the daemon, which holds the credential.","acceptance_criteria":"archie-agent can request a git push over NATS; archied performs the authenticated push using its held token and replies with success/failure; the push token is never sent to or stored in the agent container.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-23T21:55:44Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:55:44Z","dependencies":[{"issue_id":"archie-core-5zh.3","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T07:55:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-5zh.4","title":"Move workflow.Route/workflow.Run stage loop into archie-agent","description":"Final step of archie-core-5zh, depends on the Store/Forge/push RPC proxies existing. Move workflow.Route + workflow.Run's stage-loop execution from internal/daemon/daemon.go's process() into cmd/archie-agent, using the RPC proxies for Store/Forge/push and reimplementing CustomStages discovery (wfeval.Discover) agent-side against the already-mounted worktree. daemon.process() keeps worktree prepare + container acquire/release, then hands off the whole task to archie-agent in one NATS round trip instead of one round trip per stage.","acceptance_criteria":"workflow.Route and workflow.Run execute inside archie-agent, not archied, when agent.mode=nats; archie-agent handles a full task (not a single stage) per invocation; inprocess/subprocess modes keep working unchanged.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-23T21:55:44Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:55:44Z","dependencies":[{"issue_id":"archie-core-5zh.4","depends_on_id":"archie-core-5zh.1","type":"blocks","created_at":"2026-07-24T07:55:48Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-5zh.4","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T07:55:44Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-5zh.4","depends_on_id":"archie-core-5zh.3","type":"blocks","created_at":"2026-07-24T07:55:49Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-5zh.4","depends_on_id":"archie-core-5zh.2","type":"blocks","created_at":"2026-07-24T07:55:49Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":3,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-5zh.1","title":"Store RPC proxy: archie-agent → archied for task state mutations","description":"Phase 1 groundwork for archie-core-5zh. workflow.Run calls tc.Store.Update every stage and tc.Store.Transition on terminal outcomes — Store wraps a direct SQLite *sql.DB handle that only the daemon owns. Once workflow.Run moves into archie-agent, these calls need to become NATS request/reply RPCs to the daemon (the sole DB owner), reusing the existing AgentRequestMessage/reply-inbox plumbing pattern (internal/agentexec/nats.go) rather than giving the agent container direct DB access.","acceptance_criteria":"archie-agent can call Store.Update and Store.Transition equivalents over NATS; archied executes them against SQLite and replies; no direct DB access from the agent container.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T21:55:43Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:58:51Z","started_at":"2026-07-23T21:55:58Z","closed_at":"2026-07-23T21:58:51Z","close_reason":"Added internal/storerpc: core-NATS request/reply RPC so archie-agent can call Store.Update/Transition without direct DB access. archied's Store stays the sole owner; store.Task gained json tags to cross the wire. Not yet wired into daemon.go or workflow.TaskContext — that's archie-core-5zh.4's job once all three RPC proxies exist.","dependencies":[{"issue_id":"archie-core-5zh.1","depends_on_id":"archie-core-5zh","type":"parent-child","created_at":"2026-07-24T07:55:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
// Package forgerpc lets archie-agent call the four forge.Forge methods
|
||||
// workflow stages invoke mid-run (Comment, CloseIssue, CreatePR,
|
||||
// SetStateLabel) over core NATS request/reply, instead of the agent
|
||||
// container holding a live forge API token. archied remains the sole
|
||||
// holder of forge credentials and the sole caller of forge.Forge.
|
||||
//
|
||||
// Only these four methods are proxied — the rest of forge.Forge (issue
|
||||
// polling, invitations, reactions, PR-state reconciliation) is used
|
||||
// exclusively by the daemon's own poll/reconcile loops, never from inside
|
||||
// a workflow stage, so there's nothing for archie-agent to call.
|
||||
package forgerpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
)
|
||||
|
||||
const (
|
||||
SubjectComment = "archie.forge.comment"
|
||||
SubjectCloseIssue = "archie.forge.close_issue"
|
||||
SubjectCreatePR = "archie.forge.create_pr"
|
||||
SubjectSetStateLabel = "archie.forge.set_state_label"
|
||||
)
|
||||
|
||||
type CommentRequest struct {
|
||||
Owner, Repo string
|
||||
Number int
|
||||
Body string
|
||||
}
|
||||
|
||||
type CommentResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type CloseIssueRequest struct {
|
||||
Owner, Repo string
|
||||
Number int
|
||||
Comment string
|
||||
}
|
||||
|
||||
type CreatePRRequest struct {
|
||||
Owner, Repo, Title, Head, Base, Body string
|
||||
}
|
||||
|
||||
type CreatePRResponse struct {
|
||||
Number int `json:"number"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type SetStateLabelRequest struct {
|
||||
Owner, Repo string
|
||||
Number int
|
||||
Label string
|
||||
KnownLabels []string
|
||||
}
|
||||
|
||||
// Response is a bare success/error envelope for calls with no return value.
|
||||
type Response struct {
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Server proxies forgerpc requests to a real forge.Forge implementation.
|
||||
type Server struct {
|
||||
Forge forge.Forge
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
// Register subscribes all four handlers on nc. The returned func
|
||||
// unsubscribes all of them.
|
||||
func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) {
|
||||
type registration struct {
|
||||
subject string
|
||||
handler nats.MsgHandler
|
||||
}
|
||||
regs := []registration{
|
||||
{SubjectComment, s.handleComment},
|
||||
{SubjectCloseIssue, s.handleCloseIssue},
|
||||
{SubjectCreatePR, s.handleCreatePR},
|
||||
{SubjectSetStateLabel, s.handleSetStateLabel},
|
||||
}
|
||||
|
||||
var subs []*nats.Subscription
|
||||
for _, r := range regs {
|
||||
sub, err := nc.Subscribe(r.subject, r.handler)
|
||||
if err != nil {
|
||||
for _, s := range subs {
|
||||
s.Unsubscribe()
|
||||
}
|
||||
return nil, fmt.Errorf("subscribe %s: %w", r.subject, err)
|
||||
}
|
||||
subs = append(subs, sub)
|
||||
}
|
||||
return func() {
|
||||
for _, s := range subs {
|
||||
s.Unsubscribe()
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Server) handleComment(msg *nats.Msg) {
|
||||
var req CommentRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, CommentResponse{Error: fmt.Sprintf("decode comment request: %v", err)})
|
||||
return
|
||||
}
|
||||
id, err := s.Forge.Comment(context.Background(), req.Owner, req.Repo, req.Number, req.Body)
|
||||
resp := CommentResponse{ID: id}
|
||||
if err != nil {
|
||||
resp.Error = err.Error()
|
||||
}
|
||||
s.respond(msg, resp)
|
||||
}
|
||||
|
||||
func (s *Server) handleCloseIssue(msg *nats.Msg) {
|
||||
var req CloseIssueRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, Response{Error: fmt.Sprintf("decode close_issue request: %v", err)})
|
||||
return
|
||||
}
|
||||
err := s.Forge.CloseIssue(context.Background(), req.Owner, req.Repo, req.Number, req.Comment)
|
||||
s.respond(msg, errResponse(err))
|
||||
}
|
||||
|
||||
func (s *Server) handleCreatePR(msg *nats.Msg) {
|
||||
var req CreatePRRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, CreatePRResponse{Error: fmt.Sprintf("decode create_pr request: %v", err)})
|
||||
return
|
||||
}
|
||||
num, err := s.Forge.CreatePR(context.Background(), req.Owner, req.Repo, req.Title, req.Head, req.Base, req.Body)
|
||||
resp := CreatePRResponse{Number: num}
|
||||
if err != nil {
|
||||
resp.Error = err.Error()
|
||||
}
|
||||
s.respond(msg, resp)
|
||||
}
|
||||
|
||||
func (s *Server) handleSetStateLabel(msg *nats.Msg) {
|
||||
var req SetStateLabelRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, Response{Error: fmt.Sprintf("decode set_state_label request: %v", err)})
|
||||
return
|
||||
}
|
||||
// SetStateLabel has no error return in forge.Forge — nothing to propagate.
|
||||
s.Forge.SetStateLabel(context.Background(), req.Owner, req.Repo, req.Number, req.Label, req.KnownLabels)
|
||||
s.respond(msg, Response{})
|
||||
}
|
||||
|
||||
func errResponse(err error) Response {
|
||||
if err == nil {
|
||||
return Response{}
|
||||
}
|
||||
return Response{Error: err.Error()}
|
||||
}
|
||||
|
||||
func (s *Server) respond(msg *nats.Msg, v any) {
|
||||
data, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
if s.Log != nil {
|
||||
s.Log.Error("forgerpc: encode response failed", "err", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := msg.Respond(data); err != nil && s.Log != nil {
|
||||
s.Log.Error("forgerpc: respond failed", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Client calls the forgerpc Server from archie-agent's process. It
|
||||
// implements the four proxied forge.Forge methods with matching
|
||||
// signatures so it can be used as a drop-in for workflow stages.
|
||||
type Client struct {
|
||||
Conn *nats.Conn
|
||||
// Timeout bounds each call when ctx has no deadline of its own.
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func (c *Client) Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error) {
|
||||
data, err := json.Marshal(CommentRequest{Owner: owner, Repo: repo, Number: number, Body: body})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("encode comment request: %w", err)
|
||||
}
|
||||
reply, err := c.call(ctx, SubjectComment, data)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var resp CommentResponse
|
||||
if err := json.Unmarshal(reply, &resp); err != nil {
|
||||
return 0, fmt.Errorf("forgerpc %s: decode response: %w", SubjectComment, err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return 0, errors.New(resp.Error)
|
||||
}
|
||||
return resp.ID, nil
|
||||
}
|
||||
|
||||
func (c *Client) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error {
|
||||
data, err := json.Marshal(CloseIssueRequest{Owner: owner, Repo: repo, Number: number, Comment: comment})
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode close_issue request: %w", err)
|
||||
}
|
||||
return c.callErr(ctx, SubjectCloseIssue, data)
|
||||
}
|
||||
|
||||
func (c *Client) CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error) {
|
||||
data, err := json.Marshal(CreatePRRequest{Owner: owner, Repo: repo, Title: title, Head: head, Base: base, Body: body})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("encode create_pr request: %w", err)
|
||||
}
|
||||
reply, err := c.call(ctx, SubjectCreatePR, data)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var resp CreatePRResponse
|
||||
if err := json.Unmarshal(reply, &resp); err != nil {
|
||||
return 0, fmt.Errorf("forgerpc %s: decode response: %w", SubjectCreatePR, err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return 0, errors.New(resp.Error)
|
||||
}
|
||||
return resp.Number, nil
|
||||
}
|
||||
|
||||
// SetStateLabel matches forge.Forge's signature (no error return). RPC or
|
||||
// server-side failures are logged by the server; the daemon still owns
|
||||
// SetStateLabel's fire-and-forget semantics.
|
||||
func (c *Client) SetStateLabel(ctx context.Context, owner, repo string, number int, label string, knownLabels []string) {
|
||||
data, err := json.Marshal(SetStateLabelRequest{Owner: owner, Repo: repo, Number: number, Label: label, KnownLabels: knownLabels})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = c.callErr(ctx, SubjectSetStateLabel, data)
|
||||
}
|
||||
|
||||
func (c *Client) callErr(ctx context.Context, subject string, data []byte) error {
|
||||
reply, err := c.call(ctx, subject, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var resp Response
|
||||
if err := json.Unmarshal(reply, &resp); err != nil {
|
||||
return fmt.Errorf("forgerpc %s: decode response: %w", subject, err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return errors.New(resp.Error)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) call(ctx context.Context, subject string, data []byte) ([]byte, error) {
|
||||
if _, hasDeadline := ctx.Deadline(); !hasDeadline && c.Timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, c.Timeout)
|
||||
defer cancel()
|
||||
}
|
||||
reply, err := c.Conn.RequestWithContext(ctx, subject, data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("forgerpc %s: %w", subject, err)
|
||||
}
|
||||
return reply.Data, nil
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package forgerpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
natssrv "github.com/nats-io/nats-server/v2/test"
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
)
|
||||
|
||||
func startEmbedded(t *testing.T) *server.Server {
|
||||
t.Helper()
|
||||
srv := natssrv.RunRandClientPortServer()
|
||||
t.Cleanup(srv.Shutdown)
|
||||
return srv
|
||||
}
|
||||
|
||||
func connect(t *testing.T, url string) *nats.Conn {
|
||||
t.Helper()
|
||||
nc, err := nats.Connect(url)
|
||||
if err != nil {
|
||||
t.Fatalf("nats connect: %v", err)
|
||||
}
|
||||
t.Cleanup(nc.Close)
|
||||
return nc
|
||||
}
|
||||
|
||||
// fakeForge implements forge.Forge, recording calls to the four methods
|
||||
// workflow stages invoke mid-run. Every other method panics if called —
|
||||
// this RPC layer must never proxy them.
|
||||
type fakeForge struct {
|
||||
comments []commentCall
|
||||
closes []closeCall
|
||||
prs []prCall
|
||||
stateLabels []stateLabelCall
|
||||
|
||||
commentErr error
|
||||
closeErr error
|
||||
prErr error
|
||||
}
|
||||
|
||||
type commentCall struct {
|
||||
owner, repo string
|
||||
number int
|
||||
body string
|
||||
}
|
||||
type closeCall struct {
|
||||
owner, repo string
|
||||
number int
|
||||
comment string
|
||||
}
|
||||
type prCall struct {
|
||||
owner, repo, title, head, base, body string
|
||||
}
|
||||
type stateLabelCall struct {
|
||||
owner, repo string
|
||||
number int
|
||||
label string
|
||||
knownLabels []string
|
||||
}
|
||||
|
||||
func (f *fakeForge) Comment(_ context.Context, owner, repo string, number int, body string) (int64, error) {
|
||||
f.comments = append(f.comments, commentCall{owner, repo, number, body})
|
||||
if f.commentErr != nil {
|
||||
return 0, f.commentErr
|
||||
}
|
||||
return 99, nil
|
||||
}
|
||||
|
||||
func (f *fakeForge) CloseIssue(_ context.Context, owner, repo string, number int, comment string) error {
|
||||
f.closes = append(f.closes, closeCall{owner, repo, number, comment})
|
||||
return f.closeErr
|
||||
}
|
||||
|
||||
func (f *fakeForge) CreatePR(_ context.Context, owner, repo, title, head, base, body string) (int, error) {
|
||||
f.prs = append(f.prs, prCall{owner, repo, title, head, base, body})
|
||||
if f.prErr != nil {
|
||||
return 0, f.prErr
|
||||
}
|
||||
return 7, nil
|
||||
}
|
||||
|
||||
func (f *fakeForge) SetStateLabel(_ context.Context, owner, repo string, number int, label string, knownLabels []string) {
|
||||
f.stateLabels = append(f.stateLabels, stateLabelCall{owner, repo, number, label, knownLabels})
|
||||
}
|
||||
|
||||
func (f *fakeForge) AcceptInvitations(context.Context) error { panic("unexpected call") }
|
||||
func (f *fakeForge) AssignedIssues(context.Context, string, string, string) ([]forge.Issue, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
func (f *fakeForge) IssuesWithLabel(context.Context, string, string, string) ([]forge.Issue, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
func (f *fakeForge) RepliesAfter(context.Context, string, string, int, int64, string) ([]forge.Reply, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
func (f *fakeForge) PRState(context.Context, string, string, int) (string, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
func (f *fakeForge) CreateIssue(context.Context, string, string, string, string, []string) (int, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
func (f *fakeForge) React(context.Context, string, string, int, string) error { panic("unexpected call") }
|
||||
func (f *fakeForge) VerifyPush(context.Context, string, string) error { panic("unexpected call") }
|
||||
|
||||
func newTestServer(t *testing.T) (*fakeForge, *Client) {
|
||||
t.Helper()
|
||||
fg := &fakeForge{}
|
||||
srv := startEmbedded(t)
|
||||
url := srv.ClientURL()
|
||||
|
||||
serverConn := connect(t, url)
|
||||
rpcServer := &Server{Forge: fg, Log: slog.New(slog.DiscardHandler)}
|
||||
unsub, err := rpcServer.Register(serverConn)
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
t.Cleanup(unsub)
|
||||
|
||||
clientConn := connect(t, url)
|
||||
client := &Client{Conn: clientConn, Timeout: 2 * time.Second}
|
||||
return fg, client
|
||||
}
|
||||
|
||||
func TestClientCommentPersistsViaServer(t *testing.T) {
|
||||
fg, client := newTestServer(t)
|
||||
|
||||
id, err := client.Comment(context.Background(), "sam", "archie", 1, "hello")
|
||||
if err != nil {
|
||||
t.Fatalf("Comment: %v", err)
|
||||
}
|
||||
if id != 99 {
|
||||
t.Fatalf("expected comment id 99, got %d", id)
|
||||
}
|
||||
if len(fg.comments) != 1 || fg.comments[0] != (commentCall{"sam", "archie", 1, "hello"}) {
|
||||
t.Fatalf("comment did not reach server, got %+v", fg.comments)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientCloseIssuePersistsViaServer(t *testing.T) {
|
||||
fg, client := newTestServer(t)
|
||||
|
||||
if err := client.CloseIssue(context.Background(), "sam", "archie", 2, "done"); err != nil {
|
||||
t.Fatalf("CloseIssue: %v", err)
|
||||
}
|
||||
if len(fg.closes) != 1 || fg.closes[0] != (closeCall{"sam", "archie", 2, "done"}) {
|
||||
t.Fatalf("close did not reach server, got %+v", fg.closes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientCreatePRPersistsViaServer(t *testing.T) {
|
||||
fg, client := newTestServer(t)
|
||||
|
||||
num, err := client.CreatePR(context.Background(), "sam", "archie", "title", "head", "main", "body")
|
||||
if err != nil {
|
||||
t.Fatalf("CreatePR: %v", err)
|
||||
}
|
||||
if num != 7 {
|
||||
t.Fatalf("expected PR number 7, got %d", num)
|
||||
}
|
||||
if len(fg.prs) != 1 || fg.prs[0] != (prCall{"sam", "archie", "title", "head", "main", "body"}) {
|
||||
t.Fatalf("PR did not reach server, got %+v", fg.prs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientSetStateLabelPersistsViaServer(t *testing.T) {
|
||||
fg, client := newTestServer(t)
|
||||
|
||||
client.SetStateLabel(context.Background(), "sam", "archie", 3, "archie:working", []string{"archie:queued", "archie:working"})
|
||||
|
||||
if len(fg.stateLabels) != 1 {
|
||||
t.Fatalf("expected 1 state label call, got %d", len(fg.stateLabels))
|
||||
}
|
||||
got := fg.stateLabels[0]
|
||||
if got.owner != "sam" || got.repo != "archie" || got.number != 3 || got.label != "archie:working" {
|
||||
t.Fatalf("state label call mismatch: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientPropagatesServerError(t *testing.T) {
|
||||
fg := &fakeForge{commentErr: errors.New("forge unavailable")}
|
||||
srv := startEmbedded(t)
|
||||
url := srv.ClientURL()
|
||||
|
||||
rpcServer := &Server{Forge: fg, Log: slog.New(slog.DiscardHandler)}
|
||||
unsub, err := rpcServer.Register(connect(t, url))
|
||||
if err != nil {
|
||||
t.Fatalf("register: %v", err)
|
||||
}
|
||||
t.Cleanup(unsub)
|
||||
|
||||
client := &Client{Conn: connect(t, url), Timeout: 2 * time.Second}
|
||||
_, err = client.Comment(context.Background(), "sam", "archie", 1, "hello")
|
||||
if err == nil {
|
||||
t.Fatal("expected Comment to propagate the server-side error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientCommentTimesOutWithNoResponder(t *testing.T) {
|
||||
srv := startEmbedded(t)
|
||||
client := &Client{Conn: connect(t, srv.ClientURL()), Timeout: 100 * time.Millisecond}
|
||||
|
||||
_, err := client.Comment(context.Background(), "sam", "archie", 1, "hello")
|
||||
if err == nil {
|
||||
t.Fatal("expected Comment to time out with no server registered")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user