Files
archie/internal/webui/remote_store_test.go
T
sam ed1557c12e feat(edastore)!: move event capture and bindings onto PocketBase collections
The event-capture tables (captures, mappings, bindings, binding_dispatches,
playbook_dispatches) now live in PocketBase-owned collections and their ids
are opaque record ids rather than autoincrement integers. The task lifecycle
stays on SQLite: tasks/transitions/events carry FIFO claim ordering, id-cursor
pagination and the task-grant map, none of which gain anything from being
hand-editable. binding_dispatches.task_id is the single seam and stays an
integer addressing that store.

BREAKING: CapturedEvent.Id, Mapping.Id, Binding.Id and Binding.MappingId are
strings on the wire, as are the ids in the capture/mapping/binding requests.
RecordDispatchRequest.task_id is deliberately unchanged.

What the collections buy, beyond storage: a payload nobody has modelled yet is
inspectable, a mapping is editable at runtime, and a binding's relation to its
mapping is enforced. The old schema declared no FOREIGN KEY on that link, so a
dangling mapping_id was previously possible and is now refused.

Behaviour preserved deliberately, each recovered from the SQLite version
rather than reimplemented from memory:
  - draft -> pending_approval -> armed, with approval only from
    pending_approval and an edit always returning a binding for re-approval
  - one binding per source, guarded on insert, update and approve
  - an empty secret on update keeps the stored one, so an edit form that does
    not echo it back cannot silently disarm a binding
  - ErrMappingNotFound / ErrBindingNotFound on a missing delete target
  - sentinels are re-exported from storecontract, never redefined: staterpc
    matches on exact canonical message to rehydrate them, so a second
    definition would break errors.Is across the wire invisibly

Two implementation notes worth keeping:
  - at-most-once dispatch is now a unique index rather than INSERT OR IGNORE.
    Only the unique-violation maps to ErrAlreadyDispatched; any other save
    error is returned, because treating them all as "already recorded" would
    turn the ledger into a silent at-least-once dispatcher.
  - captures store received_at themselves at nanosecond precision in a
    fixed-width layout. PocketBase autodates are millisecond and record ids
    are random, so same-millisecond captures would otherwise order
    arbitrarily; the old store got insertion order free from autoincrement.
  - ListUndispatchedCaptures is raw SQL: the anti-join is a subquery and
    PocketBase's filter DSL is not SQL. A read fires no hooks either way.

Adds tool_calls, which had no persistence at all: tool calls only ever reached
the on-disk task log, readable as text but never queryable or watchable.
Nothing writes it yet.

The binding secret cipher moves with the bindings it protects.
2026-09-23 02:19:28 +10:00

170 lines
6.1 KiB
Go

package webui
// Remote-contract coverage for the dashboard data paths. The production UI
// process (archie-ui, and the daemon's webui) serves task, capture, mapping
// and binding routes against a *staterpc.Client — the remote read contract —
// not a concrete *store.Store. Every other webui test feeds a local store
// directly, so none of them prove the handlers work once the data crosses the
// gRPC wire. These do: they stand up a real SQLite store behind
// staterpc.RegisterServer, dial it, and assert the handlers serve correctly.
import (
"context"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"google.golang.org/grpc"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/store"
)
// newRemoteTestServer serves a real SQLite store behind a gRPC listener and
// returns a webui.Server whose store fields are all the remote *staterpc.Client.
// This is the composition the UI Service uses; it exercises the full
// round-trip (handler -> narrow interface -> client -> wire -> server -> store)
// rather than a fake.
func newRemoteTestServer(t *testing.T) *Server {
t.Helper()
st, err := store.Open(t.Context(), t.TempDir()+"/remote.db")
if err != nil {
t.Fatalf("open temp store: %v", err)
}
t.Cleanup(func() { _ = st.Close() })
listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
server := grpc.NewServer()
// Two stores, as in the real composition: the task store serves the task
// surfaces, the event-capture store serves captures/mappings/bindings.
// Leaving one nil makes ListMappings/ListBindings fail closed with
// err*Unavailable, which is also the real wiring.
eda := edastore.OpenTest(t)
staterpc.RegisterServer(server, staterpc.Deps{
Tasks: st,
Captures: eda,
Mappings: eda,
Bindings: eda,
BindingDispatcher: eda,
BindingTaskCreator: st,
Log: slog.New(slog.DiscardHandler),
})
go func() { _ = server.Serve(listener) }()
t.Cleanup(server.Stop)
client, closeConn, err := staterpc.Dial(listener.Addr().String(), "")
if err != nil {
t.Fatalf("dial state store: %v", err)
}
t.Cleanup(closeConn)
return &Server{
Store: client,
Captures: client,
Mappings: client,
Bindings: client,
Log: slog.New(slog.DiscardHandler),
CaptureMaxEvents: 10,
}
}
func TestRemoteEndpointFamiliesServeOverReadContracts(t *testing.T) {
srv := newRemoteTestServer(t)
ctx := context.Background()
t.Run("summary", func(t *testing.T) {
rr := httptest.NewRecorder()
srv.handleSummary(rr, httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/summary", nil))
if rr.Code != http.StatusOK {
t.Fatalf("GET /api/summary = %d, body %s", rr.Code, rr.Body.String())
}
})
t.Run("tasks_and_timeline", func(t *testing.T) {
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "remote task", "", "", ""); err != nil {
t.Fatalf("enqueue: %v", err)
}
task, err := srv.Store.ClaimNext(ctx)
if err != nil || task == nil {
t.Fatalf("claim (%v, %v)", task, err)
}
if err := srv.Store.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusWaitingHuman, "needs info"); err != nil {
t.Fatalf("transition: %v", err)
}
rr := httptest.NewRecorder()
srv.handleTasks(rr, httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks", nil))
if rr.Code != http.StatusOK {
t.Fatalf("GET /api/tasks = %d, body %s", rr.Code, rr.Body.String())
}
if !strings.Contains(rr.Body.String(), "remote task") {
t.Fatalf("task not in response: %s", rr.Body.String())
}
// The {id} route reads the task's events over the wire. handleTask
// reads r.PathValue("id"), which only the mux populates, so this goes
// through Server.Handler() rather than a direct handler call — the
// realistic path and the one that exercises routing too.
handler := srv.Handler()
rr2 := httptest.NewRecorder()
handler.ServeHTTP(rr2, httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks/"+strconv.FormatInt(task.ID, 10), nil))
if rr2.Code != http.StatusOK {
t.Fatalf("GET /api/tasks/{id} = %d, body %s", rr2.Code, rr2.Body.String())
}
})
t.Run("mappings", func(t *testing.T) {
rr := httptest.NewRecorder()
srv.handleMappingsList(rr, httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/mappings", nil))
if rr.Code != http.StatusOK {
t.Fatalf("GET /api/mappings = %d, body %s", rr.Code, rr.Body.String())
}
})
t.Run("bindings", func(t *testing.T) {
rr := httptest.NewRecorder()
srv.handleBindingsList(rr, httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/bindings", nil))
if rr.Code != http.StatusOK {
t.Fatalf("GET /api/bindings = %d, body %s", rr.Code, rr.Body.String())
}
})
}
// TestRemoteLogAndHealthDegrade covers the two paths with no State Store
// contract: logs (in-process feed, nil in a remote composition) report
// disabled, and health consults the local registry (nil here) rather than a
// concrete store. Both are deliberate degradation, not gaps to fill by
// inventing a contract.
func TestRemoteLogAndHealthDegrade(t *testing.T) {
srv := newRemoteTestServer(t)
ctx := context.Background()
t.Run("logs_disabled", func(t *testing.T) {
rr := httptest.NewRecorder()
srv.handleLogs(rr, httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/logs", nil))
if rr.Code != http.StatusOK {
t.Fatalf("GET /api/logs = %d, body %s", rr.Code, rr.Body.String())
}
if !strings.Contains(rr.Body.String(), "disabled") {
t.Fatalf("expected logs to report disabled, got %s", rr.Body.String())
}
})
t.Run("health_without_registry", func(t *testing.T) {
rr := httptest.NewRecorder()
srv.handleHealthDetailed(rr, httptest.NewRequestWithContext(ctx, http.MethodGet, "/health/detailed", nil))
if rr.Code != http.StatusOK && rr.Code != http.StatusServiceUnavailable {
t.Fatalf("GET /health/detailed = %d, body %s", rr.Code, rr.Body.String())
}
})
}