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.
205 lines
7.1 KiB
Go
205 lines
7.1 KiB
Go
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 || !fresh {
|
|
return err
|
|
}
|
|
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 three-state lifecycle, not a local
|
|
// vocabulary: draft -> pending_approval -> armed. Only
|
|
// ApproveBinding reaches armed, which is the epic's approval gate.
|
|
&core.SelectField{Name: "status", MaxSelect: 1, Values: []string{
|
|
string(binding.StatusDraft),
|
|
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)
|
|
}
|
|
|
|
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
|
|
}
|