Files
archie/internal/infrastructure/edastore/schema_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

195 lines
7.3 KiB
Go

package edastore_test
import (
"errors"
"path/filepath"
"testing"
"github.com/pocketbase/pocketbase/core"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
)
func newStore(t *testing.T) *edastore.Store {
t.Helper()
dir := t.TempDir()
st, err := edastore.Open(edastore.Config{
DBPath: filepath.Join(dir, "eda.sqlite"),
DataDir: filepath.Join(dir, "pb_data"),
})
if err != nil {
t.Fatalf("edastore.Open() error = %v", err)
}
t.Cleanup(func() { _ = st.Close() })
return st
}
// TestCollectionsAreCreated pins that every EDA collection exists and is a
// base collection, not a view: unlike the read-only operator surface, these
// are the authoritative tables and the admin UI is expected to edit them.
func TestCollectionsAreCreated(t *testing.T) {
st := newStore(t)
for _, name := range edastore.Collections() {
c, err := st.App().FindCollectionByNameOrId(name)
if err != nil {
t.Fatalf("collection %q missing: %v", name, err)
}
if c.IsView() {
t.Errorf("collection %q is a view; EDA tables are authoritative and must be writable", name)
}
}
}
// TestBindingDispatchIsIdempotent pins the at-most-once ledger. The SQLite
// implementation got this from INSERT OR IGNORE on a composite primary key
// (bindings.go:365); here it must come from a unique index, so a duplicate is
// refused by the schema rather than by the caller remembering to ignore it.
func TestBindingDispatchIsIdempotent(t *testing.T) {
st := newStore(t)
if err := st.RecordDispatch(t.Context(), "b1", 1, "c1", 42); err != nil {
t.Fatalf("first RecordDispatch() error = %v", err)
}
// A replay of the same (binding, capture) must be refused, not run again.
err := st.RecordDispatch(t.Context(), "b1", 1, "c1", 99)
if !errors.Is(err, storecontract.ErrAlreadyDispatched) {
t.Errorf("second RecordDispatch() error = %v, want ErrAlreadyDispatched: (binding, capture) is an at-most-once ledger", err)
}
}
// TestPlaybookDispatchIsIdempotent pins the same at-most-once rule on the
// four-part playbook key (playbook, version, event, action).
func TestPlaybookDispatchIsIdempotent(t *testing.T) {
st := newStore(t)
if err := st.RecordPlaybookDispatch(t.Context(), "p1", "v1", "e1", "a1"); err != nil {
t.Fatalf("first RecordPlaybookDispatch() error = %v", err)
}
err := st.RecordPlaybookDispatch(t.Context(), "p1", "v1", "e1", "a1")
if !errors.Is(err, storecontract.ErrAlreadyDispatched) {
t.Errorf("second RecordPlaybookDispatch() error = %v, want ErrAlreadyDispatched", err)
}
}
// TestBindingStartsAsDraft pins the approval gate from the epic's acceptance
// criteria: "A binding cannot go live without explicit human approval." A
// binding created without a status must not default to anything live.
func TestBindingStartsAsDraft(t *testing.T) {
st := newStore(t)
id, err := st.InsertBinding(t.Context(), binding.Binding{
Name: "n", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement",
})
if err != nil {
t.Fatalf("InsertBinding() error = %v", err)
}
b, err := st.GetBinding(t.Context(), id)
if err != nil {
t.Fatalf("GetBinding() error = %v", err)
}
if b.Status != binding.StatusDraft {
t.Errorf("new binding status = %q, want %q: a binding must not be live before approval", b.Status, binding.StatusDraft)
}
}
// TestApproveRejectsUnknownBinding pins the sentinel the gRPC layer maps.
func TestApproveRejectsUnknownBinding(t *testing.T) {
st := newStore(t)
if err := st.ApproveBinding(t.Context(), "nosuchbinding"); !errors.Is(err, storecontract.ErrBindingNotFound) {
t.Errorf("ApproveBinding(unknown) error = %v, want ErrBindingNotFound", err)
}
}
// TestCaptureRoundTripsPayload pins the epic's core requirement: an event
// arrives with a payload nobody has modelled yet and must be readable back
// verbatim so an operator can map fields against it.
func TestCaptureRoundTripsPayload(t *testing.T) {
st := newStore(t)
body := `{"action":"created","issue":{"number":7,"title":"it broke"}}`
if _, err := st.InsertCapture(t.Context(), storecontract.CapturedEvent{
Source: "sentry", Body: body, Headers: `{"X-Hook":"1"}`, ContentType: "application/json",
}, 0, 0); err != nil {
t.Fatalf("InsertCapture() error = %v", err)
}
list, err := st.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures() error = %v", err)
}
if len(list) != 1 {
t.Fatalf("ListCaptures() returned %d captures, want 1", len(list))
}
got := list[0]
if got.Body != body {
t.Errorf("Body round-trip = %q, want %q: the raw payload is what field mapping is designed against", got.Body, body)
}
}
var _ = core.Collection{}
// TestBindingLifecycleIsThreeStates pins draft -> pending_approval -> armed.
// The states are the domain's, not this package's: collapsing them (as an
// earlier version of this store did) removes the review step while still
// looking like an approval gate, which is the worst of both.
func TestBindingLifecycleIsThreeStates(t *testing.T) {
st := newStore(t)
id, err := st.InsertBinding(t.Context(), binding.Binding{
Name: "n", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement",
})
if err != nil {
t.Fatalf("InsertBinding() error = %v", err)
}
// A draft cannot skip review.
if err := st.ApproveBinding(t.Context(), id); !errors.Is(err, storecontract.ErrBindingTransition) {
t.Fatalf("ApproveBinding(draft) error = %v, want ErrBindingTransition: draft must not skip review", err)
}
// Editing sends it to pending_approval.
if err := st.UpdateBinding(t.Context(), binding.Binding{
ID: id, Name: "n2", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement",
}); err != nil {
t.Fatalf("UpdateBinding() error = %v", err)
}
b, err := st.GetBinding(t.Context(), id)
if err != nil {
t.Fatalf("GetBinding() error = %v", err)
}
if b.Status != binding.StatusPendingApproval {
t.Fatalf("status after edit = %q, want %q", b.Status, binding.StatusPendingApproval)
}
// Approval arms it, and only from pending_approval.
if err := st.ApproveBinding(t.Context(), id); err != nil {
t.Fatalf("ApproveBinding(pending_approval) error = %v", err)
}
if b, err = st.GetBinding(t.Context(), id); err != nil || b.Status != binding.StatusArmed {
t.Fatalf("status after approve = %q (err %v), want %q", b.Status, err, binding.StatusArmed)
}
if err := st.ApproveBinding(t.Context(), id); !errors.Is(err, storecontract.ErrBindingTransition) {
t.Errorf("re-approving an armed binding = %v, want ErrBindingTransition", err)
}
// Only armed bindings dispatch.
armed, err := st.ArmedBindingsForSource(t.Context(), "sentry")
if err != nil || len(armed) != 1 {
t.Fatalf("ArmedBindingsForSource() = %d bindings (err %v), want 1", len(armed), err)
}
}
// TestOneBindingPerSource pins the overlap guard: a second binding on a
// source that already has one is refused, so a capture can never match two.
func TestOneBindingPerSource(t *testing.T) {
st := newStore(t)
mk := func() error {
_, err := st.InsertBinding(t.Context(), binding.Binding{
Name: "n", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement",
})
return err
}
if err := mk(); err != nil {
t.Fatalf("first InsertBinding() error = %v", err)
}
if err := mk(); !errors.Is(err, storecontract.ErrBindingOverlap) {
t.Errorf("second InsertBinding() error = %v, want ErrBindingOverlap", err)
}
}