refactor(scripts): drop the SQLite task-database backup from the installer and watchdog
The pre-update PostgreSQL snapshot is the only backup; the watchdog restores binaries and never the database.
This commit is contained in:
42 files changed
+14
-6999
No files matched your search
File renamed without changes.
File renamed without changes.
@@ -1,190 +0,0 @@
|
||||
package edastore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// capturedAtLayout is fixed-width UTC with nanosecond precision, so string
|
||||
// comparison is time comparison. time.RFC3339Nano trims trailing zeros, which
|
||||
// would break that.
|
||||
const capturedAtLayout = "2006-01-02T15:04:05.000000000Z"
|
||||
|
||||
// This store is the implementation of every event-capture contract. The task
|
||||
// lifecycle contracts stay on the SQLite store; the two meet only at
|
||||
// binding_dispatches.task_id.
|
||||
var (
|
||||
_ storecontract.CaptureStore = (*Store)(nil)
|
||||
_ storecontract.MappingStore = (*Store)(nil)
|
||||
_ storecontract.BindingStore = (*Store)(nil)
|
||||
_ storecontract.BindingDispatcher = (*Store)(nil)
|
||||
_ storecontract.PlaybookDispatcher = (*Store)(nil)
|
||||
)
|
||||
|
||||
func (s *Store) record(collection, id string) (*core.Record, error) {
|
||||
r, err := s.app.FindRecordById(collection, id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return r, err
|
||||
}
|
||||
|
||||
// InsertCapture stores one inbound event verbatim. Redaction happens upstream
|
||||
// in webhookguard; this persists exactly what it is given, because field
|
||||
// mapping is designed against the payload as received.
|
||||
//
|
||||
// retention and maxEvents are accepted for contract compatibility and applied
|
||||
// as a prune after the insert.
|
||||
func (s *Store) InsertCapture(ctx context.Context, c storecontract.CapturedEvent, retention time.Duration, maxEvents int) (string, error) {
|
||||
collection, err := s.app.FindCollectionByNameOrId(CollCaptures)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
r := core.NewRecord(collection)
|
||||
r.Set("source", c.Source)
|
||||
r.Set("remote_addr", c.RemoteAddr)
|
||||
r.Set("content_type", c.ContentType)
|
||||
r.Set("headers", c.Headers)
|
||||
r.Set("body", c.Body)
|
||||
r.Set("authenticated", c.Authenticated)
|
||||
received := c.ReceivedAt
|
||||
if received.IsZero() {
|
||||
received = time.Now()
|
||||
}
|
||||
r.Set("received_at", received.UTC().Format(capturedAtLayout))
|
||||
if err := s.app.Save(r); err != nil {
|
||||
return "", fmt.Errorf("edastore: insert capture: %w", err)
|
||||
}
|
||||
if err := s.pruneCaptures(ctx, retention, maxEvents); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return r.Id, nil
|
||||
}
|
||||
|
||||
// pruneCaptures enforces the retention window and count cap. A capture exists
|
||||
// to be mapped against while it is recent; keeping every event forever would
|
||||
// make an unauthenticated intake surface a disk-growth vector.
|
||||
func (s *Store) pruneCaptures(_ context.Context, retention time.Duration, maxEvents int) error {
|
||||
if retention > 0 {
|
||||
cutoff := time.Now().Add(-retention).UTC().Format(time.RFC3339)
|
||||
if _, err := s.app.DB().NewQuery(
|
||||
"DELETE FROM " + CollCaptures + " WHERE received_at < {:cutoff}").
|
||||
Bind(map[string]any{"cutoff": cutoff}).Execute(); err != nil {
|
||||
return fmt.Errorf("edastore: prune captures by age: %w", err)
|
||||
}
|
||||
}
|
||||
if maxEvents > 0 {
|
||||
if _, err := s.app.DB().NewQuery(
|
||||
"DELETE FROM " + CollCaptures + " WHERE id NOT IN (SELECT id FROM " + CollCaptures +
|
||||
" ORDER BY received_at DESC LIMIT {:keep})").
|
||||
Bind(map[string]any{"keep": maxEvents}).Execute(); err != nil {
|
||||
return fmt.Errorf("edastore: prune captures by count: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseCapturedAt reads the stored timestamp, tolerating the RFC3339 form a
|
||||
// caller-supplied value may carry.
|
||||
func parseCapturedAt(raw string) time.Time {
|
||||
for _, layout := range []string{capturedAtLayout, time.RFC3339Nano, time.RFC3339} {
|
||||
if t, err := time.Parse(layout, raw); err == nil {
|
||||
return t
|
||||
}
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
func captureValue(r *core.Record) storecontract.CapturedEvent {
|
||||
return storecontract.CapturedEvent{
|
||||
ID: r.Id,
|
||||
ReceivedAt: parseCapturedAt(r.GetString("received_at")),
|
||||
Source: r.GetString("source"),
|
||||
RemoteAddr: r.GetString("remote_addr"),
|
||||
ContentType: r.GetString("content_type"),
|
||||
Headers: r.GetString("headers"),
|
||||
Body: r.GetString("body"),
|
||||
Authenticated: r.GetBool("authenticated"),
|
||||
}
|
||||
}
|
||||
|
||||
// ListCaptures returns the newest captures first.
|
||||
func (s *Store) ListCaptures(_ context.Context, limit int) ([]storecontract.CapturedEvent, error) {
|
||||
records, err := s.app.FindRecordsByFilter(CollCaptures, "", "-received_at", limit, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("edastore: list captures: %w", err)
|
||||
}
|
||||
out := make([]storecontract.CapturedEvent, 0, len(records))
|
||||
for _, r := range records {
|
||||
out = append(out, captureValue(r))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListUndispatchedCaptures returns recent captures for the given sources that
|
||||
// no binding has dispatched yet.
|
||||
//
|
||||
// This is raw SQL rather than a record filter: the anti-join against the
|
||||
// dispatch ledger is a subquery, and PocketBase's filter DSL is not SQL (it
|
||||
// has no IN (SELECT ...) form). A read fires no hooks either way, so nothing
|
||||
// is lost by dropping to the query builder here.
|
||||
func (s *Store) ListUndispatchedCaptures(_ context.Context, sources []string, limit int) ([]storecontract.CapturedEvent, error) {
|
||||
if len(sources) == 0 || limit <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
placeholders := make([]string, 0, len(sources))
|
||||
params := dbx.Params{"limit": limit}
|
||||
for i, src := range sources {
|
||||
key := fmt.Sprintf("s%d", i)
|
||||
placeholders = append(placeholders, "{:"+key+"}")
|
||||
params[key] = src
|
||||
}
|
||||
query := "SELECT id, received_at, source, remote_addr, content_type, headers, body, authenticated FROM " +
|
||||
CollCaptures + " WHERE source IN (" + strings.Join(placeholders, ",") +
|
||||
") AND id NOT IN (SELECT capture FROM " + CollBindingDispatches + ") ORDER BY received_at DESC LIMIT {:limit}"
|
||||
|
||||
var rows []captureRow
|
||||
if err := s.app.DB().NewQuery(query).Bind(params).All(&rows); err != nil {
|
||||
return nil, fmt.Errorf("edastore: list undispatched captures: %w", err)
|
||||
}
|
||||
out := make([]storecontract.CapturedEvent, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, r.value())
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// captureRow is the raw-SQL shape of a capture, used only where a record
|
||||
// filter cannot express the query.
|
||||
type captureRow struct {
|
||||
ID string `db:"id"`
|
||||
ReceivedAt string `db:"received_at"`
|
||||
Source string `db:"source"`
|
||||
RemoteAddr string `db:"remote_addr"`
|
||||
ContentType string `db:"content_type"`
|
||||
Headers string `db:"headers"`
|
||||
Body string `db:"body"`
|
||||
Authenticated bool `db:"authenticated"`
|
||||
}
|
||||
|
||||
func (r captureRow) value() storecontract.CapturedEvent {
|
||||
return storecontract.CapturedEvent{
|
||||
ID: r.ID,
|
||||
ReceivedAt: parseCapturedAt(r.ReceivedAt),
|
||||
Source: r.Source,
|
||||
RemoteAddr: r.RemoteAddr,
|
||||
ContentType: r.ContentType,
|
||||
Headers: r.Headers,
|
||||
Body: r.Body,
|
||||
Authenticated: r.Authenticated,
|
||||
}
|
||||
}
|
||||
@@ -1,393 +0,0 @@
|
||||
package edastore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// --- mappings ---
|
||||
|
||||
func mappingValue(r *core.Record) (mapping.Mapping, error) {
|
||||
var fields []mapping.Field
|
||||
if raw := r.GetString("fields"); raw != "" {
|
||||
if err := json.Unmarshal([]byte(raw), &fields); err != nil {
|
||||
return mapping.Mapping{}, fmt.Errorf("edastore: decode mapping fields: %w", err)
|
||||
}
|
||||
}
|
||||
return mapping.Mapping{
|
||||
ID: r.Id,
|
||||
Name: r.GetString("name"),
|
||||
SourceHint: r.GetString("source_hint"),
|
||||
Fields: fields,
|
||||
CreatedAt: r.GetDateTime("created_at").Time(),
|
||||
UpdatedAt: r.GetDateTime("updated_at").Time(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Store) applyMapping(r *core.Record, m mapping.Mapping) error {
|
||||
encoded, err := json.Marshal(m.Fields)
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: encode mapping fields: %w", err)
|
||||
}
|
||||
r.Set("name", m.Name)
|
||||
r.Set("source_hint", m.SourceHint)
|
||||
r.Set("fields", string(encoded))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) InsertMapping(_ context.Context, m mapping.Mapping) (string, error) {
|
||||
collection, err := s.app.FindCollectionByNameOrId(CollMappings)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
r := core.NewRecord(collection)
|
||||
if err := s.applyMapping(r, m); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := s.app.Save(r); err != nil {
|
||||
return "", fmt.Errorf("edastore: insert mapping: %w", err)
|
||||
}
|
||||
s.notifyWrite(events.KindMappingChanged, "mapping", "create", r.Id)
|
||||
return r.Id, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetMapping(_ context.Context, id string) (*mapping.Mapping, error) {
|
||||
r, err := s.record(CollMappings, id)
|
||||
if err != nil || r == nil {
|
||||
return nil, err
|
||||
}
|
||||
m, err := mappingValue(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListMappings(_ context.Context) ([]mapping.Mapping, error) {
|
||||
records, err := s.app.FindRecordsByFilter(CollMappings, "", "-created_at", 0, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("edastore: list mappings: %w", err)
|
||||
}
|
||||
out := make([]mapping.Mapping, 0, len(records))
|
||||
for _, r := range records {
|
||||
m, err := mappingValue(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Store) UpdateMapping(_ context.Context, m mapping.Mapping) error {
|
||||
r, err := s.record(CollMappings, m.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r == nil {
|
||||
return ErrMappingNotFound
|
||||
}
|
||||
if err := s.applyMapping(r, m); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.app.Save(r); err != nil {
|
||||
return err
|
||||
}
|
||||
s.notifyWrite(events.KindMappingChanged, "mapping", "update", m.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) DeleteMapping(_ context.Context, id string) error {
|
||||
r, err := s.record(CollMappings, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r == nil {
|
||||
return ErrMappingNotFound
|
||||
}
|
||||
if err := s.app.Delete(r); err != nil {
|
||||
return err
|
||||
}
|
||||
s.notifyWrite(events.KindMappingChanged, "mapping", "delete", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- bindings ---
|
||||
|
||||
func (s *Store) bindingValue(r *core.Record) (binding.Binding, error) {
|
||||
b := binding.Binding{
|
||||
ID: r.Id,
|
||||
Name: r.GetString("name"),
|
||||
Matcher: binding.Matcher{Source: r.GetString("source")},
|
||||
MappingID: r.GetString("mapping"),
|
||||
Workflow: r.GetString("workflow"),
|
||||
Owner: r.GetString("owner"),
|
||||
Repo: r.GetString("repo"),
|
||||
Version: r.GetInt("version"),
|
||||
Status: binding.Status(r.GetString("status")),
|
||||
Secret: r.GetString("secret"),
|
||||
CreatedAt: r.GetDateTime("created_at").Time(),
|
||||
UpdatedAt: r.GetDateTime("updated_at").Time(),
|
||||
}
|
||||
if s.cipher != nil && b.Secret != "" {
|
||||
plain, err := s.cipher.Decrypt(b.Secret)
|
||||
if err != nil {
|
||||
return binding.Binding{}, fmt.Errorf("edastore: decrypt binding secret: %w", err)
|
||||
}
|
||||
b.Secret = plain
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (s *Store) applyBinding(r *core.Record, b binding.Binding) error {
|
||||
r.Set("name", b.Name)
|
||||
r.Set("source", b.Matcher.Source)
|
||||
r.Set("mapping", b.MappingID)
|
||||
r.Set("workflow", b.Workflow)
|
||||
r.Set("owner", b.Owner)
|
||||
r.Set("repo", b.Repo)
|
||||
// An empty secret means "keep the stored one". An edit form that does not
|
||||
// echo the secret back must not silently disarm the binding by erasing it.
|
||||
if b.Secret == "" {
|
||||
return nil
|
||||
}
|
||||
secret := b.Secret
|
||||
if s.cipher != nil {
|
||||
encrypted, err := s.cipher.Encrypt(secret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: encrypt binding secret: %w", err)
|
||||
}
|
||||
secret = encrypted
|
||||
}
|
||||
r.Set("secret", secret)
|
||||
return nil
|
||||
}
|
||||
|
||||
// InsertBinding stores a new binding as a draft. The caller's status is
|
||||
// ignored on purpose: a binding cannot go live without explicit approval, so
|
||||
// ApproveBinding is the only path to armed.
|
||||
//
|
||||
// A source may carry at most one binding, so an insert against a source that
|
||||
// already has one is refused rather than creating an ambiguous second matcher.
|
||||
func (s *Store) InsertBinding(ctx context.Context, b binding.Binding) (string, error) {
|
||||
existing, err := s.bindingsByFilter("source = {:source}", map[string]any{"source": b.Matcher.Source})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(existing) > 0 {
|
||||
return "", ErrBindingOverlap
|
||||
}
|
||||
collection, err := s.app.FindCollectionByNameOrId(CollBindings)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
r := core.NewRecord(collection)
|
||||
if err := s.applyBinding(r, b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
r.Set("version", 1)
|
||||
r.Set("status", string(binding.StatusPendingApproval))
|
||||
if err := s.app.Save(r); err != nil {
|
||||
return "", fmt.Errorf("edastore: insert binding: %w", err)
|
||||
}
|
||||
_ = ctx
|
||||
s.notifyWrite(events.KindBindingChanged, "binding", "create", r.Id)
|
||||
return r.Id, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetBinding(_ context.Context, id string) (*binding.Binding, error) {
|
||||
r, err := s.record(CollBindings, id)
|
||||
if err != nil || r == nil {
|
||||
return nil, err
|
||||
}
|
||||
b, err := s.bindingValue(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &b, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListBindings(_ context.Context) ([]binding.Binding, error) {
|
||||
return s.bindingsByFilter("", nil)
|
||||
}
|
||||
|
||||
// ArmedBindingsForSource returns the armed bindings a source can dispatch. A
|
||||
// draft or pending_approval binding is never returned: that is the gate.
|
||||
func (s *Store) ArmedBindingsForSource(_ context.Context, source string) ([]binding.Binding, error) {
|
||||
return s.bindingsByFilter("source = {:source} && status = {:status}",
|
||||
map[string]any{"source": source, "status": string(binding.StatusArmed)})
|
||||
}
|
||||
|
||||
func (s *Store) bindingsByFilter(filter string, params map[string]any) ([]binding.Binding, error) {
|
||||
var records []*core.Record
|
||||
var err error
|
||||
if params == nil {
|
||||
records, err = s.app.FindRecordsByFilter(CollBindings, filter, "-created_at", 0, 0)
|
||||
} else {
|
||||
records, err = s.app.FindRecordsByFilter(CollBindings, filter, "-created_at", 0, 0, params)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("edastore: list bindings: %w", err)
|
||||
}
|
||||
out := make([]binding.Binding, 0, len(records))
|
||||
for _, r := range records {
|
||||
b, err := s.bindingValue(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, b)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// UpdateBinding rewrites a binding's editable fields, bumps its version, and
|
||||
// sends it back to pending_approval. An edit always requires re-approval: an
|
||||
// armed binding whose matcher or workflow changed is a different binding, and
|
||||
// re-arming it silently would defeat the gate.
|
||||
func (s *Store) UpdateBinding(_ context.Context, b binding.Binding) error {
|
||||
r, err := s.record(CollBindings, b.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r == nil {
|
||||
return ErrBindingNotFound
|
||||
}
|
||||
others, err := s.bindingsByFilter("source = {:source} && id != {:id}",
|
||||
map[string]any{"source": b.Matcher.Source, "id": b.ID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(others) > 0 {
|
||||
return ErrBindingOverlap
|
||||
}
|
||||
if err := s.applyBinding(r, b); err != nil {
|
||||
return err
|
||||
}
|
||||
r.Set("status", string(binding.StatusPendingApproval))
|
||||
r.Set("version", r.GetInt("version")+1)
|
||||
if err := s.app.Save(r); err != nil {
|
||||
return err
|
||||
}
|
||||
s.notifyWrite(events.KindBindingChanged, "binding", "update", b.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) DeleteBinding(_ context.Context, id string) error {
|
||||
r, err := s.record(CollBindings, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r == nil {
|
||||
return ErrBindingNotFound
|
||||
}
|
||||
if err := s.app.Delete(r); err != nil {
|
||||
return err
|
||||
}
|
||||
s.notifyWrite(events.KindBindingChanged, "binding", "delete", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApproveBinding is the only transition that arms a binding. It moves
|
||||
// pending_approval to armed; any other current state is refused, so a draft
|
||||
// cannot skip review and an armed binding cannot be re-approved.
|
||||
//
|
||||
// A source may have only one armed binding, so approval is refused when
|
||||
// another binding on the same source is already armed. Without that guard,
|
||||
// one capture could match two armed matchers and dispatch twice.
|
||||
func (s *Store) ApproveBinding(_ context.Context, id string) error {
|
||||
r, err := s.record(CollBindings, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r == nil {
|
||||
return ErrBindingNotFound
|
||||
}
|
||||
armed, err := s.bindingsByFilter("source = {:source} && status = {:status} && id != {:id}",
|
||||
map[string]any{"source": r.GetString("source"), "status": string(binding.StatusArmed), "id": id})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(armed) > 0 {
|
||||
return ErrBindingOverlap
|
||||
}
|
||||
if r.GetString("status") != string(binding.StatusPendingApproval) {
|
||||
return ErrBindingTransition
|
||||
}
|
||||
r.Set("status", string(binding.StatusArmed))
|
||||
if err := s.app.Save(r); err != nil {
|
||||
return err
|
||||
}
|
||||
s.notifyWrite(events.KindBindingChanged, "binding", "approve", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- dispatch ledgers ---
|
||||
|
||||
// RecordDispatch writes one at-most-once binding dispatch. Uniqueness is the
|
||||
// collection's index, so a replay is refused by the schema; the caller sees
|
||||
// ErrAlreadyDispatched rather than a silent second run.
|
||||
func (s *Store) RecordDispatch(_ context.Context, bindingID string, bindingVersion int64, captureID string, taskID int64) error {
|
||||
collection, err := s.app.FindCollectionByNameOrId(CollBindingDispatches)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r := core.NewRecord(collection)
|
||||
r.Set("binding", bindingID)
|
||||
r.Set("binding_version", bindingVersion)
|
||||
r.Set("capture", captureID)
|
||||
r.Set("task_id", taskID)
|
||||
return ledgerWrite(s.app.Save(r), "edastore: record dispatch")
|
||||
}
|
||||
|
||||
func (s *Store) RecordPlaybookDispatch(_ context.Context, playbookID, playbookVersion, eventID, actionID string) error {
|
||||
collection, err := s.app.FindCollectionByNameOrId(CollPlaybookDispatches)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r := core.NewRecord(collection)
|
||||
r.Set("playbook_id", playbookID)
|
||||
r.Set("playbook_version", playbookVersion)
|
||||
r.Set("event_id", eventID)
|
||||
r.Set("action_id", actionID)
|
||||
return ledgerWrite(s.app.Save(r), "edastore: record playbook dispatch")
|
||||
}
|
||||
|
||||
func (s *Store) DeletePlaybookDispatches(_ context.Context, playbookID string) error {
|
||||
_, err := s.app.DB().NewQuery(
|
||||
"DELETE FROM " + CollPlaybookDispatches + " WHERE playbook_id = {:id}").
|
||||
Bind(map[string]any{"id": playbookID}).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: delete playbook dispatches: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ledgerWrite turns the unique-index refusal into ErrAlreadyDispatched and
|
||||
// leaves every other failure alone. Treating all errors as "already recorded"
|
||||
// would turn an at-most-once ledger into a silent at-least-once dispatcher.
|
||||
func ledgerWrite(err error, what string) error {
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case isUniqueViolation(err):
|
||||
return ErrAlreadyDispatched
|
||||
default:
|
||||
return fmt.Errorf("%s: %w", what, err)
|
||||
}
|
||||
}
|
||||
|
||||
// isUniqueViolation reports whether err is the unique-index refusal.
|
||||
// PocketBase surfaces it as a validation failure rather than a typed error,
|
||||
// so the message is what there is to match on.
|
||||
func isUniqueViolation(err error) bool {
|
||||
text := strings.ToLower(err.Error())
|
||||
return strings.Contains(text, "unique") || strings.Contains(text, "already exists")
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
// Package edastore persists the event-capture and playbook-binding tables on
|
||||
// PocketBase-owned collections.
|
||||
//
|
||||
// These are the tables behind the event-capture epic: an inbound webhook is
|
||||
// captured whether or not anything understands it yet, an operator inspects
|
||||
// the real payload, maps fields against it, and binds a matcher and mapping
|
||||
// to a workflow. That loop wants a runtime-editable store with a live view of
|
||||
// arriving payloads, which is what PocketBase collections give directly.
|
||||
//
|
||||
// These collections are authoritative and writable: the admin UI editing a binding
|
||||
// IS the feature, not a hazard. The task lifecycle tables stay on SQLite --
|
||||
// they carry ordering, cursor and task-grant semantics that gain nothing from
|
||||
// being hand-editable. binding_dispatches.task reaches them by plain id, which
|
||||
// is the single seam between the two stores.
|
||||
//
|
||||
// Idempotency here is schema-enforced. The SQLite implementation relied on
|
||||
// INSERT OR IGNORE against a composite primary key; a unique index does the
|
||||
// same job without every caller having to remember the pattern.
|
||||
package edastore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
_ "modernc.org/sqlite"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// Collection names. They are unprefixed because this store owns its database;
|
||||
// nothing else writes these tables.
|
||||
const (
|
||||
CollCaptures = "captures"
|
||||
CollMappings = "mappings"
|
||||
CollBindings = "bindings"
|
||||
CollBindingDispatches = "binding_dispatches"
|
||||
CollPlaybookDispatches = "playbook_dispatches"
|
||||
CollToolCalls = "tool_calls"
|
||||
)
|
||||
|
||||
// Sentinels are re-exported from the contract rather than redefined. Their
|
||||
// exact message strings are the wire contract: staterpc matches on (code,
|
||||
// canonical message) to rehydrate them on the client, so a second definition
|
||||
// with different text would break errors.Is across the gRPC boundary without
|
||||
// changing anything visible.
|
||||
var (
|
||||
ErrBindingNotFound = storecontract.ErrBindingNotFound
|
||||
ErrBindingOverlap = storecontract.ErrBindingOverlap
|
||||
ErrBindingTransition = storecontract.ErrBindingTransition
|
||||
ErrAlreadyDispatched = storecontract.ErrAlreadyDispatched
|
||||
ErrMappingNotFound = storecontract.ErrMappingNotFound
|
||||
)
|
||||
|
||||
// ErrCaptureNotFound reports a capture that is absent or aged out.
|
||||
var ErrCaptureNotFound = errors.New("edastore: capture not found")
|
||||
|
||||
// Collections returns every collection this store owns.
|
||||
func Collections() []string {
|
||||
return []string{
|
||||
CollCaptures, CollMappings, CollBindings,
|
||||
CollBindingDispatches, CollPlaybookDispatches, CollToolCalls,
|
||||
}
|
||||
}
|
||||
|
||||
// Config describes one store.
|
||||
type Config struct {
|
||||
// Cipher encrypts binding secrets at rest. Nil keeps them plaintext,
|
||||
// which is the behaviour that predates the option.
|
||||
Cipher BindingCipher
|
||||
// Notify receives one event per successful write on the bindings and
|
||||
// mappings tables, so an operator edit surfaces on the dashboard's
|
||||
// activity stream exactly like capture arrival does. Nil keeps writes
|
||||
// silent, which is the behaviour that predates the option and what
|
||||
// every existing constructor gets.
|
||||
Notify func(events.Event)
|
||||
// DBPath is the SQLite file PocketBase owns for these collections.
|
||||
DBPath string
|
||||
// DataDir holds PocketBase's auxiliary database and settings.
|
||||
DataDir string
|
||||
}
|
||||
|
||||
// Store is the PocketBase-backed EDA persistence.
|
||||
type Store struct {
|
||||
app *pocketbase.PocketBase
|
||||
cipher BindingCipher
|
||||
notify func(events.Event)
|
||||
}
|
||||
|
||||
// Open bootstraps the store and ensures its collections exist.
|
||||
func Open(cfg Config) (*Store, error) {
|
||||
if cfg.DBPath == "" || cfg.DataDir == "" {
|
||||
return nil, errors.New("edastore: DBPath and DataDir are required")
|
||||
}
|
||||
app := pocketbase.NewWithConfig(pocketbase.Config{
|
||||
DefaultDataDir: cfg.DataDir,
|
||||
HideStartBanner: true,
|
||||
DBConnect: func(requested string) (*dbx.DB, error) {
|
||||
if isDataDB(requested) {
|
||||
requested = cfg.DBPath
|
||||
}
|
||||
return dbx.Open("sqlite", requested+"?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)")
|
||||
},
|
||||
})
|
||||
if err := app.Bootstrap(); err != nil {
|
||||
return nil, fmt.Errorf("edastore: bootstrap: %w", err)
|
||||
}
|
||||
if err := app.RunAllMigrations(); err != nil {
|
||||
return nil, fmt.Errorf("edastore: migrations: %w", err)
|
||||
}
|
||||
if err := removeDefaultAuthCollection(app); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ensureCollections(app); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Store{app: app, cipher: cfg.Cipher, notify: cfg.Notify}, nil
|
||||
}
|
||||
|
||||
// App exposes the PocketBase application so one process can serve this store
|
||||
// and its admin UI from a single bootstrap.
|
||||
func (s *Store) App() core.App { return s.app }
|
||||
|
||||
// Close releases the store's database connections.
|
||||
func (s *Store) Close() error { return s.app.ClearBootstrap() }
|
||||
@@ -1,26 +0,0 @@
|
||||
package edastore
|
||||
|
||||
import "github.com/samcharles93/archie-core/internal/events"
|
||||
|
||||
// notifyWrite announces one successful write on the bindings or mappings
|
||||
// tables. It rides the same activity-event path capture arrival uses: the
|
||||
// State Store's event insert feeds the webui pump, which broadcasts to every
|
||||
// connected browser, so an operator edit is visible without a manual
|
||||
// refresh. The data carries the record id and action; the row itself stays
|
||||
// the only source of the full record, and consumers refetch through the
|
||||
// authenticated API -- the event is an invalidation signal, not a payload.
|
||||
//
|
||||
// A nil notifier is a silent no-op: stores composed without one (tests,
|
||||
// tooling) keep working unchanged, mirroring the nil Publish on
|
||||
// captureintake.Receiver.
|
||||
func (s *Store) notifyWrite(kind, subject, action, id string) {
|
||||
if s.notify == nil {
|
||||
return
|
||||
}
|
||||
past := map[string]string{"create": "created", "update": "updated", "approve": "approved", "delete": "deleted"}[action]
|
||||
s.notify(events.Event{
|
||||
Kind: kind,
|
||||
Detail: subject + " " + past,
|
||||
Data: map[string]any{"id": id, "action": action},
|
||||
})
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
package edastore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// recordingNotifier collects every event the store emits so a test can
|
||||
// assert on the exact sequence, mirroring captureintake's recordingPublisher.
|
||||
type recordingNotifier struct {
|
||||
got []events.Event
|
||||
}
|
||||
|
||||
func (r *recordingNotifier) notify(e events.Event) { r.got = append(r.got, e) }
|
||||
|
||||
func (r *recordingNotifier) reset() { r.got = nil }
|
||||
|
||||
// notifiedStore is an OpenTest store with the notifier wired, the way
|
||||
// composition does it through Config.Notify.
|
||||
func notifiedStore(t *testing.T) (*Store, *recordingNotifier) {
|
||||
t.Helper()
|
||||
s := OpenTest(t)
|
||||
n := &recordingNotifier{}
|
||||
s.notify = n.notify
|
||||
return s, n
|
||||
}
|
||||
|
||||
func TestWriteMethodsNotifyOnSuccess(t *testing.T) {
|
||||
b := func(source string) binding.Binding {
|
||||
return binding.Binding{
|
||||
Name: "webhook to workflow",
|
||||
Matcher: binding.Matcher{Source: source},
|
||||
Workflow: "triage",
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("InsertBinding", func(t *testing.T) {
|
||||
s, n := notifiedStore(t)
|
||||
id, err := s.InsertBinding(t.Context(), b("src-insert"))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
if len(n.got) != 1 {
|
||||
t.Fatalf("InsertBinding notified %d times, want 1: %+v", len(n.got), n.got)
|
||||
}
|
||||
assertEditEvent(t, n.got[0], events.KindBindingChanged, "create", id)
|
||||
})
|
||||
|
||||
t.Run("UpdateBinding", func(t *testing.T) {
|
||||
s, n := notifiedStore(t)
|
||||
id := insertBinding(t, s, bindingInput{Name: "before", Source: "src-update", Workflow: "triage"})
|
||||
n.reset()
|
||||
bb := b("src-update")
|
||||
bb.ID = id
|
||||
bb.Workflow = "escalate"
|
||||
if err := s.UpdateBinding(t.Context(), bb); err != nil {
|
||||
t.Fatalf("UpdateBinding() error = %v", err)
|
||||
}
|
||||
if len(n.got) != 1 {
|
||||
t.Fatalf("UpdateBinding notified %d times, want 1: %+v", len(n.got), n.got)
|
||||
}
|
||||
assertEditEvent(t, n.got[0], events.KindBindingChanged, "update", id)
|
||||
})
|
||||
|
||||
t.Run("ApproveBinding", func(t *testing.T) {
|
||||
s, n := notifiedStore(t)
|
||||
id := insertBinding(t, s, bindingInput{Name: "draft", Source: "src-approve", Workflow: "triage"})
|
||||
bb := b("src-approve")
|
||||
bb.ID = id
|
||||
// Approval requires pending_approval; the edit transition also fires.
|
||||
if err := s.UpdateBinding(t.Context(), bb); err != nil {
|
||||
t.Fatalf("UpdateBinding() error = %v", err)
|
||||
}
|
||||
n.reset()
|
||||
if err := s.ApproveBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("ApproveBinding() error = %v", err)
|
||||
}
|
||||
if len(n.got) != 1 {
|
||||
t.Fatalf("ApproveBinding notified %d times, want 1: %+v", len(n.got), n.got)
|
||||
}
|
||||
assertEditEvent(t, n.got[0], events.KindBindingChanged, "approve", id)
|
||||
})
|
||||
|
||||
t.Run("DeleteBinding", func(t *testing.T) {
|
||||
s, n := notifiedStore(t)
|
||||
id := insertBinding(t, s, bindingInput{Name: "doomed", Source: "src-delete", Workflow: "triage"})
|
||||
n.reset()
|
||||
if err := s.DeleteBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("DeleteBinding() error = %v", err)
|
||||
}
|
||||
if len(n.got) != 1 {
|
||||
t.Fatalf("DeleteBinding notified %d times, want 1: %+v", len(n.got), n.got)
|
||||
}
|
||||
assertEditEvent(t, n.got[0], events.KindBindingChanged, "delete", id)
|
||||
})
|
||||
|
||||
t.Run("InsertMapping", func(t *testing.T) {
|
||||
s, n := notifiedStore(t)
|
||||
id, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "payload-map"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
if len(n.got) != 1 {
|
||||
t.Fatalf("InsertMapping notified %d times, want 1: %+v", len(n.got), n.got)
|
||||
}
|
||||
assertEditEvent(t, n.got[0], events.KindMappingChanged, "create", id)
|
||||
})
|
||||
|
||||
t.Run("UpdateMapping", func(t *testing.T) {
|
||||
s, n := notifiedStore(t)
|
||||
id, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "payload-map"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
n.reset()
|
||||
m, err := s.GetMapping(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetMapping() error = %v", err)
|
||||
}
|
||||
m.Name = "renamed"
|
||||
if err := s.UpdateMapping(t.Context(), *m); err != nil {
|
||||
t.Fatalf("UpdateMapping() error = %v", err)
|
||||
}
|
||||
if len(n.got) != 1 {
|
||||
t.Fatalf("UpdateMapping notified %d times, want 1: %+v", len(n.got), n.got)
|
||||
}
|
||||
assertEditEvent(t, n.got[0], events.KindMappingChanged, "update", id)
|
||||
})
|
||||
|
||||
t.Run("DeleteMapping", func(t *testing.T) {
|
||||
s, n := notifiedStore(t)
|
||||
id, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "doomed"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
n.reset()
|
||||
if err := s.DeleteMapping(t.Context(), id); err != nil {
|
||||
t.Fatalf("DeleteMapping() error = %v", err)
|
||||
}
|
||||
if len(n.got) != 1 {
|
||||
t.Fatalf("DeleteMapping notified %d times, want 1: %+v", len(n.got), n.got)
|
||||
}
|
||||
assertEditEvent(t, n.got[0], events.KindMappingChanged, "delete", id)
|
||||
})
|
||||
}
|
||||
|
||||
func assertEditEvent(t *testing.T, e events.Event, kind, action, id string) {
|
||||
t.Helper()
|
||||
if e.Kind != kind {
|
||||
t.Errorf("event kind = %q, want %q", e.Kind, kind)
|
||||
}
|
||||
if e.Detail == "" {
|
||||
t.Errorf("event detail is empty")
|
||||
}
|
||||
if got := e.Data["id"]; got != id {
|
||||
t.Errorf("event data id = %v, want %q", got, id)
|
||||
}
|
||||
if got := e.Data["action"]; got != action {
|
||||
t.Errorf("event data action = %v, want %q", got, action)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedWritesNotifyNothing(t *testing.T) {
|
||||
s, n := notifiedStore(t)
|
||||
|
||||
// Seed one binding and one mapping, then clear the seed-time events.
|
||||
seedID := insertBinding(t, s, bindingInput{Name: "seed", Source: "src-seed", Workflow: "triage"})
|
||||
if err := s.ApproveBinding(t.Context(), seedID); err != nil {
|
||||
t.Fatalf("ApproveBinding(seed) error = %v", err)
|
||||
}
|
||||
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "seed-map"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
n.reset()
|
||||
|
||||
t.Run("UpdateBinding nonexistent", func(t *testing.T) {
|
||||
bb := binding.Binding{ID: "missing", Matcher: binding.Matcher{Source: "src-other"}}
|
||||
if err := s.UpdateBinding(t.Context(), bb); !errors.Is(err, ErrBindingNotFound) {
|
||||
t.Fatalf("UpdateBinding() error = %v, want ErrBindingNotFound", err)
|
||||
}
|
||||
})
|
||||
t.Run("ApproveBinding refuses an armed binding", func(t *testing.T) {
|
||||
if err := s.ApproveBinding(t.Context(), seedID); !errors.Is(err, ErrBindingTransition) {
|
||||
t.Fatalf("ApproveBinding() error = %v, want ErrBindingTransition", err)
|
||||
}
|
||||
})
|
||||
t.Run("InsertBinding overlaps source", func(t *testing.T) {
|
||||
if _, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Matcher: binding.Matcher{Source: "src-seed"},
|
||||
}); !errors.Is(err, ErrBindingOverlap) {
|
||||
t.Fatalf("InsertBinding() error = %v, want ErrBindingOverlap", err)
|
||||
}
|
||||
})
|
||||
t.Run("DeleteBinding nonexistent", func(t *testing.T) {
|
||||
if err := s.DeleteBinding(t.Context(), "missing"); !errors.Is(err, ErrBindingNotFound) {
|
||||
t.Fatalf("DeleteBinding() error = %v, want ErrBindingNotFound", err)
|
||||
}
|
||||
})
|
||||
t.Run("UpdateMapping nonexistent", func(t *testing.T) {
|
||||
if err := s.UpdateMapping(t.Context(), mapping.Mapping{ID: "missing"}); !errors.Is(err, ErrMappingNotFound) {
|
||||
t.Fatalf("UpdateMapping() error = %v, want ErrMappingNotFound", err)
|
||||
}
|
||||
})
|
||||
t.Run("DeleteMapping nonexistent", func(t *testing.T) {
|
||||
if err := s.DeleteMapping(t.Context(), "missing"); !errors.Is(err, ErrMappingNotFound) {
|
||||
t.Fatalf("DeleteMapping() error = %v, want ErrMappingNotFound", err)
|
||||
}
|
||||
})
|
||||
_ = mid
|
||||
|
||||
if len(n.got) != 0 {
|
||||
t.Fatalf("failed writes notified %d times: %+v", len(n.got), n.got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNilNotifierIsNoOp pins that a store composed without a notifier keeps
|
||||
// every write path working: the existing constructors and tests never set
|
||||
// one, so a nil-dereference there would break them all.
|
||||
func TestNilNotifierIsNoOp(t *testing.T) {
|
||||
s := OpenTest(t)
|
||||
id, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "nil-safe",
|
||||
Matcher: binding.Matcher{Source: "src-nil"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding with nil notifier: error = %v", err)
|
||||
}
|
||||
bb, err := s.GetBinding(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding() error = %v", err)
|
||||
}
|
||||
bb.Workflow = "escalate"
|
||||
if err := s.UpdateBinding(t.Context(), *bb); err != nil {
|
||||
t.Fatalf("UpdateBinding() error = %v", err)
|
||||
}
|
||||
if err := s.ApproveBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("ApproveBinding() error = %v", err)
|
||||
}
|
||||
if err := s.DeleteBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("DeleteBinding() error = %v", err)
|
||||
}
|
||||
if _, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m"}); err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenHonoursConfigNotify pins the composition surface: the wire-in sets
|
||||
// Config.Notify, not the unexported field.
|
||||
func TestOpenHonoursConfigNotify(t *testing.T) {
|
||||
n := &recordingNotifier{}
|
||||
dir := t.TempDir()
|
||||
s, err := Open(Config{
|
||||
DBPath: t.TempDir() + "/eda.sqlite",
|
||||
DataDir: dir,
|
||||
Notify: n.notify,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Open() error = %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
|
||||
if _, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "wired"}); err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
if len(n.got) != 1 {
|
||||
t.Fatalf("store built from Config.Notify notified %d times, want 1: %+v", len(n.got), n.got)
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package edastore
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// OpenTest builds a throwaway store for tests, closed when the test ends.
|
||||
// It mirrors store.OpenTest so a test that needs both stores wires them the
|
||||
// same way.
|
||||
func OpenTest(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
s, err := Open(Config{
|
||||
DBPath: filepath.Join(dir, "eda.sqlite"),
|
||||
DataDir: filepath.Join(dir, "pb_data"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("edastore.OpenTest: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return s
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
package edastore
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
)
|
||||
|
||||
// isDataDB reports whether PocketBase is asking for its main database, as
|
||||
// opposed to the auxiliary one it keeps for logs and settings.
|
||||
func isDataDB(path string) bool { return filepath.Base(path) == "data.db" }
|
||||
|
||||
// removeDefaultAuthCollection deletes the open-signup "users" collection
|
||||
// PocketBase creates on first bootstrap. This store has no end users, and its
|
||||
// createRule is open, so leaving it would accept unauthenticated writes.
|
||||
func removeDefaultAuthCollection(app core.App) error {
|
||||
c, err := app.FindCollectionByNameOrId("users")
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
return nil
|
||||
case err != nil:
|
||||
return fmt.Errorf("edastore: look up default users collection: %w", err)
|
||||
}
|
||||
if err := app.Delete(c); err != nil {
|
||||
return fmt.Errorf("edastore: remove default users collection: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureCollections creates each collection once and is safe to re-run: the
|
||||
// store bootstraps on every process start.
|
||||
func ensureCollections(app core.App) error {
|
||||
for _, build := range []func(core.App) error{
|
||||
ensureCaptures, ensureMappings, ensureBindings,
|
||||
ensureBindingDispatches, ensurePlaybookDispatches, ensureToolCalls,
|
||||
} {
|
||||
if err := build(app); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// collection returns the named collection, or a new base collection when it
|
||||
// does not exist yet. A lookup that failed for any other reason is an error:
|
||||
// creating a second collection over a live one on a transient failure would be
|
||||
// a schema change made for the wrong reason.
|
||||
func collection(app core.App, name string) (*core.Collection, bool, error) {
|
||||
c, err := app.FindCollectionByNameOrId(name)
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
return core.NewBaseCollection(name), true, nil
|
||||
case err != nil:
|
||||
return nil, false, fmt.Errorf("edastore: look up collection %q: %w", name, err)
|
||||
}
|
||||
return c, false, nil
|
||||
}
|
||||
|
||||
func ensureCaptures(app core.App) error {
|
||||
c, fresh, err := collection(app, CollCaptures)
|
||||
if err != nil || !fresh {
|
||||
return err
|
||||
}
|
||||
c.Fields.Add(
|
||||
&core.TextField{Name: "source", Required: true},
|
||||
&core.TextField{Name: "remote_addr"},
|
||||
&core.TextField{Name: "content_type"},
|
||||
// Headers and body are stored verbatim. Field mapping is designed
|
||||
// against the real payload, so nothing here may be normalised away.
|
||||
&core.JSONField{Name: "headers", MaxSize: 1 << 20},
|
||||
&core.TextField{Name: "body", Max: 1 << 20},
|
||||
&core.BoolField{Name: "authenticated"},
|
||||
// received_at is written by the store, not an autodate field, because
|
||||
// it is also the sort key. PocketBase autodates are millisecond
|
||||
// precision and record ids are random, so two captures arriving in
|
||||
// the same millisecond would order arbitrarily -- the old store got
|
||||
// insertion order free from an autoincrement id. capturedAtLayout is
|
||||
// fixed-width so lexicographic order is chronological order.
|
||||
&core.TextField{Name: "received_at"},
|
||||
)
|
||||
c.AddIndex("idx_captures_source", false, "source, received_at", "")
|
||||
return save(app, c)
|
||||
}
|
||||
|
||||
func ensureMappings(app core.App) error {
|
||||
c, fresh, err := collection(app, CollMappings)
|
||||
if err != nil || !fresh {
|
||||
return err
|
||||
}
|
||||
c.Fields.Add(
|
||||
&core.TextField{Name: "name", Required: true},
|
||||
&core.TextField{Name: "source_hint"},
|
||||
&core.JSONField{Name: "fields", MaxSize: 1 << 18},
|
||||
&core.AutodateField{Name: "created_at", OnCreate: true},
|
||||
&core.AutodateField{Name: "updated_at", OnCreate: true, OnUpdate: true},
|
||||
)
|
||||
return save(app, c)
|
||||
}
|
||||
|
||||
func ensureBindings(app core.App) error {
|
||||
c, fresh, err := collection(app, CollBindings)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !fresh {
|
||||
return promoteDraftBindings(app)
|
||||
}
|
||||
mappings, err := app.FindCollectionByNameOrId(CollMappings)
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: bindings need mappings: %w", err)
|
||||
}
|
||||
c.Fields.Add(
|
||||
&core.TextField{Name: "name", Required: true},
|
||||
&core.TextField{Name: "source", Required: true},
|
||||
&core.RelationField{Name: "mapping", CollectionId: mappings.Id, MaxSelect: 1},
|
||||
&core.TextField{Name: "workflow"},
|
||||
&core.TextField{Name: "owner"},
|
||||
&core.TextField{Name: "repo"},
|
||||
&core.NumberField{Name: "version"},
|
||||
// status is the domain's lifecycle, not a local vocabulary:
|
||||
// pending_approval -> armed. Only ApproveBinding reaches armed,
|
||||
// which is the epic's approval gate.
|
||||
&core.SelectField{Name: "status", MaxSelect: 1, Values: []string{
|
||||
string(binding.StatusPendingApproval),
|
||||
string(binding.StatusArmed),
|
||||
}},
|
||||
&core.TextField{Name: "secret"},
|
||||
&core.AutodateField{Name: "created_at", OnCreate: true},
|
||||
&core.AutodateField{Name: "updated_at", OnCreate: true, OnUpdate: true},
|
||||
)
|
||||
c.AddIndex("idx_bindings_source_status", false, "source, status", "")
|
||||
return save(app, c)
|
||||
}
|
||||
|
||||
// promoteDraftBindings moves bindings an earlier version stored as "draft",
|
||||
// a state nothing could leave without an unrelated edit, to
|
||||
// pending_approval so they can be approved. It is a no-op once none remain.
|
||||
func promoteDraftBindings(app core.App) error {
|
||||
_, err := app.DB().NewQuery("UPDATE " + CollBindings + " SET status = {:pending} WHERE status = 'draft'").
|
||||
Bind(map[string]any{"pending": string(binding.StatusPendingApproval)}).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: promote draft bindings: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ensureBindingDispatches(app core.App) error {
|
||||
c, fresh, err := collection(app, CollBindingDispatches)
|
||||
if err != nil || !fresh {
|
||||
return err
|
||||
}
|
||||
c.Fields.Add(
|
||||
&core.TextField{Name: "binding", Required: true},
|
||||
&core.NumberField{Name: "binding_version"},
|
||||
&core.TextField{Name: "capture", Required: true},
|
||||
// task_id is the seam to the SQLite-owned task tables. It stays a
|
||||
// plain integer id rather than a relation precisely because the task
|
||||
// lifecycle is not migrating.
|
||||
&core.NumberField{Name: "task_id"},
|
||||
&core.AutodateField{Name: "dispatched_at", OnCreate: true},
|
||||
)
|
||||
// At-most-once, enforced by the schema rather than by every caller
|
||||
// remembering INSERT OR IGNORE.
|
||||
c.AddIndex("idx_binding_dispatch_once", true, "binding, capture", "")
|
||||
return save(app, c)
|
||||
}
|
||||
|
||||
func ensurePlaybookDispatches(app core.App) error {
|
||||
c, fresh, err := collection(app, CollPlaybookDispatches)
|
||||
if err != nil || !fresh {
|
||||
return err
|
||||
}
|
||||
c.Fields.Add(
|
||||
&core.TextField{Name: "playbook_id", Required: true},
|
||||
&core.TextField{Name: "playbook_version", Required: true},
|
||||
&core.TextField{Name: "event_id", Required: true},
|
||||
&core.TextField{Name: "action_id", Required: true},
|
||||
&core.AutodateField{Name: "dispatched_at", OnCreate: true},
|
||||
)
|
||||
c.AddIndex("idx_playbook_dispatch_once", true,
|
||||
"playbook_id, playbook_version, event_id, action_id", "")
|
||||
return save(app, c)
|
||||
}
|
||||
|
||||
// ensureToolCalls adds persistence that did not exist before. Tool calls were
|
||||
// only ever written to the on-disk task log (internal/logging), so they could
|
||||
// be read back as text but never queried, filtered or watched. As a collection
|
||||
// they become all three.
|
||||
func ensureToolCalls(app core.App) error {
|
||||
c, fresh, err := collection(app, CollToolCalls)
|
||||
if err != nil || !fresh {
|
||||
return err
|
||||
}
|
||||
c.Fields.Add(
|
||||
&core.NumberField{Name: "task_id"},
|
||||
&core.NumberField{Name: "attempt"},
|
||||
&core.TextField{Name: "tool", Required: true},
|
||||
&core.JSONField{Name: "args", MaxSize: 1 << 18},
|
||||
&core.JSONField{Name: "result", MaxSize: 1 << 18},
|
||||
&core.TextField{Name: "error"},
|
||||
&core.NumberField{Name: "duration_ms"},
|
||||
&core.AutodateField{Name: "called_at", OnCreate: true},
|
||||
)
|
||||
c.AddIndex("idx_tool_calls_task", false, "task_id, attempt", "")
|
||||
return save(app, c)
|
||||
}
|
||||
|
||||
func save(app core.App, c *core.Collection) error {
|
||||
if err := app.Save(c); err != nil {
|
||||
return fmt.Errorf("edastore: create collection %q: %w", c.Name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBindingStartsPendingApproval pins the approval gate from the epic's
|
||||
// acceptance criteria: "A binding cannot go live without explicit human
|
||||
// approval." A new binding awaits that approval and is not live.
|
||||
func TestBindingStartsPendingApproval(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.StatusPendingApproval {
|
||||
t.Errorf("new binding status = %q, want %q: a binding must not be live before approval", b.Status, binding.StatusPendingApproval)
|
||||
}
|
||||
}
|
||||
|
||||
// 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 TestBindingLifecycle(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)
|
||||
}
|
||||
|
||||
// It is created awaiting review.
|
||||
b, err := st.GetBinding(t.Context(), id)
|
||||
if err != nil || b.Status != binding.StatusPendingApproval {
|
||||
t.Fatalf("status after insert = %q (err %v), want %q", b.Status, err, 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)
|
||||
}
|
||||
}
|
||||
|
||||
// A binding stored as "draft" by an earlier version could never be approved.
|
||||
// Opening the store moves it to pending_approval, so it can be.
|
||||
func TestOpenMovesLegacyDraftBindingsToPendingApproval(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := edastore.Config{DBPath: filepath.Join(dir, "eda.sqlite"), DataDir: filepath.Join(dir, "pb_data")}
|
||||
st, err := edastore.Open(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, err := st.InsertBinding(t.Context(), binding.Binding{Name: "n", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.App().DB().NewQuery("UPDATE bindings SET status = 'draft' WHERE id = {:id}").Bind(map[string]any{"id": id}).Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = st.Close()
|
||||
|
||||
st, err = edastore.Open(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
if err := st.ApproveBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("ApproveBinding(legacy draft) = %v, want it approvable after reopen", err)
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package edastore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
)
|
||||
|
||||
// bindingInput is the small shape the cipher tests need, kept separate from
|
||||
// binding.Binding so a domain field addition does not churn every test.
|
||||
type bindingInput struct {
|
||||
Name string
|
||||
Source string
|
||||
Workflow string
|
||||
Secret string
|
||||
}
|
||||
|
||||
func insertBinding(t *testing.T, s *Store, in bindingInput) string {
|
||||
t.Helper()
|
||||
id, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: in.Name,
|
||||
Matcher: binding.Matcher{Source: in.Source},
|
||||
Workflow: in.Workflow,
|
||||
Secret: in.Secret,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
package edastore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
)
|
||||
|
||||
// ToolCall is one completed tool invocation during an agent stage run, as the
|
||||
// tool_call event projection stores it. The projection adapts the event to the
|
||||
// existing collection (schema.go): a tool's output summary goes in result, a
|
||||
// failure's detail in error. The args and duration_ms fields the schema also
|
||||
// carries are left unwritten -- the tool_call event reports neither -- and a
|
||||
// future producer that has them can start filling them without a schema
|
||||
// change.
|
||||
type ToolCall struct {
|
||||
ID string
|
||||
TaskID int64
|
||||
Attempt int
|
||||
Tool string
|
||||
Result string
|
||||
Error string
|
||||
CalledAt time.Time
|
||||
}
|
||||
|
||||
// InsertToolCall appends one row to the tool_calls collection. There is no
|
||||
// idempotency here, deliberately: the collection is an append-only transcript
|
||||
// and the schema carries no unique index (the SQLite predecessor had none --
|
||||
// tool calls lived only in the on-disk task log), so one event is one row.
|
||||
//
|
||||
// The notify hook stays silent, matching the task-dispatch tables rather than
|
||||
// the operator-editable ones: tool calls are high-frequency telemetry, not
|
||||
// dashboard activity.
|
||||
func (s *Store) InsertToolCall(_ context.Context, tc ToolCall) error {
|
||||
collection, err := s.app.FindCollectionByNameOrId(CollToolCalls)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r := core.NewRecord(collection)
|
||||
r.Set("task_id", tc.TaskID)
|
||||
r.Set("attempt", tc.Attempt)
|
||||
r.Set("tool", tc.Tool)
|
||||
if tc.Result != "" {
|
||||
r.Set("result", tc.Result)
|
||||
}
|
||||
if tc.Error != "" {
|
||||
r.Set("error", tc.Error)
|
||||
}
|
||||
if !tc.CalledAt.IsZero() {
|
||||
// called_at is an autodate field, but an explicitly set date is kept:
|
||||
// the row carries the time the tool call happened, not the time it
|
||||
// was projected.
|
||||
r.Set("called_at", tc.CalledAt)
|
||||
}
|
||||
if err := s.app.Save(r); err != nil {
|
||||
return fmt.Errorf("edastore: insert tool call: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TaskToolCalls returns one task's tool calls in call order.
|
||||
func (s *Store) TaskToolCalls(_ context.Context, taskID int64) ([]ToolCall, error) {
|
||||
records, err := s.app.FindRecordsByFilter(CollToolCalls, "task_id = {:task}", "+called_at", 0, 0,
|
||||
map[string]any{"task": taskID})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("edastore: list tool calls: %w", err)
|
||||
}
|
||||
out := make([]ToolCall, 0, len(records))
|
||||
for _, r := range records {
|
||||
out = append(out, ToolCall{
|
||||
ID: r.Id,
|
||||
TaskID: r.GetInt64("task_id"),
|
||||
Attempt: r.GetInt("attempt"),
|
||||
Tool: r.GetString("tool"),
|
||||
Result: jsonTextToString(r.GetString("result")),
|
||||
Error: r.GetString("error"),
|
||||
CalledAt: r.GetDateTime("called_at").Time(),
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// jsonTextToString unwraps the JSON string a JSONField stores a plain text
|
||||
// summary under, and falls back to the raw text for anything that is not a
|
||||
// JSON string (e.g. an object a future producer stored directly).
|
||||
func jsonTextToString(raw string) string {
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
var decoded string
|
||||
if err := json.Unmarshal([]byte(raw), &decoded); err != nil {
|
||||
return raw
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
package edastore_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
)
|
||||
|
||||
func insertToolCall(t *testing.T, s *edastore.Store, tc edastore.ToolCall) {
|
||||
t.Helper()
|
||||
if err := s.InsertToolCall(t.Context(), tc); err != nil {
|
||||
t.Fatalf("InsertToolCall() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInsertToolCallRoundTrip pins the write/read pair on the tool_calls
|
||||
// collection: a row written with the fields the tool_call projection provides
|
||||
// reads back unchanged, and the read filters on task_id so one task's calls
|
||||
// never surface in another's.
|
||||
func TestInsertToolCallRoundTrip(t *testing.T) {
|
||||
s := newStore(t)
|
||||
at := time.Date(2026, 9, 23, 1, 2, 3, 0, time.UTC)
|
||||
|
||||
insertToolCall(t, s, edastore.ToolCall{
|
||||
TaskID: 42,
|
||||
Attempt: 2,
|
||||
Tool: "shell",
|
||||
Result: "all checks passed",
|
||||
CalledAt: at,
|
||||
})
|
||||
insertToolCall(t, s, edastore.ToolCall{
|
||||
TaskID: 42,
|
||||
Attempt: 2,
|
||||
Tool: "read_file",
|
||||
Error: "no such file",
|
||||
CalledAt: at.Add(time.Second),
|
||||
})
|
||||
// A different task's call must not leak into the read below.
|
||||
insertToolCall(t, s, edastore.ToolCall{
|
||||
TaskID: 7,
|
||||
Attempt: 1,
|
||||
Tool: "shell",
|
||||
Result: "other task's call",
|
||||
CalledAt: at.Add(2 * time.Second),
|
||||
})
|
||||
|
||||
got, err := s.TaskToolCalls(t.Context(), 42)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskToolCalls() error = %v", err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("TaskToolCalls() returned %d rows for task 42, want 2: %+v", len(got), got)
|
||||
}
|
||||
|
||||
first, second := got[0], got[1]
|
||||
// Chronological order: the earlier call first.
|
||||
if first.Tool != "shell" || second.Tool != "read_file" {
|
||||
t.Errorf("order = [%q, %q], want [shell, read_file] by called_at", first.Tool, second.Tool)
|
||||
}
|
||||
if first.TaskID != 42 || first.Attempt != 2 {
|
||||
t.Errorf("first row task/attempt = %d/%d, want 42/2", first.TaskID, first.Attempt)
|
||||
}
|
||||
if first.Result != "all checks passed" {
|
||||
t.Errorf("first row result = %q, want the stored summary without JSON quoting", first.Result)
|
||||
}
|
||||
if first.Error != "" {
|
||||
t.Errorf("first row error = %q, want empty: a succeeded call is not an error", first.Error)
|
||||
}
|
||||
if second.Error != "no such file" {
|
||||
t.Errorf("second row error = %q, want the stored failure detail", second.Error)
|
||||
}
|
||||
if second.Result != "" {
|
||||
t.Errorf("second row result = %q, want empty: a failed call has no result", second.Result)
|
||||
}
|
||||
if first.CalledAt.IsZero() {
|
||||
t.Error("first row called_at is zero; the call time must round-trip")
|
||||
}
|
||||
}
|
||||
|
||||
// TestInsertToolCallIsAnAppendOnlyTranscript pins that the collection is one
|
||||
// row per tool call, not an upsert: repeated calls with the same (task,
|
||||
// attempt, tool) are distinct transcript entries. There is no unique index and
|
||||
// there must not be one -- the SQLite predecessor had none (tool calls lived
|
||||
// only in the on-disk task log), so the schema's non-unique (task_id, attempt)
|
||||
// index stays the only one.
|
||||
func TestInsertToolCallIsAnAppendOnlyTranscript(t *testing.T) {
|
||||
s := newStore(t)
|
||||
at := time.Date(2026, 9, 23, 1, 2, 3, 0, time.UTC)
|
||||
row := edastore.ToolCall{TaskID: 42, Attempt: 3, Tool: "shell", Result: "ok", CalledAt: at}
|
||||
|
||||
insertToolCall(t, s, row)
|
||||
insertToolCall(t, s, row)
|
||||
|
||||
got, err := s.TaskToolCalls(t.Context(), 42)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskToolCalls() error = %v", err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("TaskToolCalls() returned %d rows, want 2: the transcript is append-only, not a dedup ledger", len(got))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user