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.
122 lines
4.4 KiB
Go
122 lines
4.4 KiB
Go
// 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.
|
|
//
|
|
// Unlike the read-only surface in internal/infrastructure/stateadmin, 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"
|
|
)
|
|
|
|
// 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
|
|
// 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
|
|
}
|
|
|
|
// 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}, 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() }
|