feat(eda): mappings per event type, match counts, several bindings per source

A mapping belongs to an event type and is checked against its inferred
schema on save. Each event a mapping resolves is counted once in
mapping_matches (migration 0008), read back as match_count and
last_matched_at. Bindings carry an optional CEL filter over the mapping's
parameters, checked on save. The per-source unique indexes are dropped:
every armed binding whose mapping matches the capture's event type and
whose filter admits it dispatches once, claimed in the per-binding ledger
before its task is enqueued. The State Store gains RecordMappingMatch and
the new mapping and binding fields.
This commit is contained in:
sam committed 2026-09-24 14:42:58 +10:00
1 parent d8d7c5a1f2
commit fec0ea1f4e
35 files changed
+1900 -737

No files matched your search

+42 -33
View File
@@ -29,11 +29,12 @@ import (
// satisfies the same surface as *edastore.Store, so the cutover wave can swap
// one for the other behind storecontract without touching the consumers.
var (
_ storecontract.CaptureStore = (*EDA)(nil)
_ storecontract.MappingStore = (*EDA)(nil)
_ storecontract.BindingStore = (*EDA)(nil)
_ storecontract.BindingDispatcher = (*EDA)(nil)
_ storecontract.PlaybookDispatcher = (*EDA)(nil)
_ storecontract.CaptureStore = (*EDA)(nil)
_ storecontract.MappingStore = (*EDA)(nil)
_ storecontract.BindingStore = (*EDA)(nil)
_ storecontract.BindingDispatcher = (*EDA)(nil)
_ storecontract.MappingMatchRecorder = (*EDA)(nil)
_ storecontract.PlaybookDispatcher = (*EDA)(nil)
)
// EDA is the PostgreSQL-backed EDA persistence.
@@ -151,8 +152,8 @@ func (s *EDA) ListCaptures(ctx context.Context, limit int) ([]storecontract.Capt
}
// ListUndispatchedCaptures returns recent identified captures for the given
// sources that no binding has dispatched yet. An unidentified capture is
// never returned, so it never dispatches.
// sources that some armed binding for their event type has not dispatched yet.
// An unidentified capture is never returned, so it never dispatches.
func (s *EDA) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]storecontract.CapturedEvent, error) {
if len(sources) == 0 || limit <= 0 {
return nil, nil
@@ -181,20 +182,27 @@ func marshalMappingFields(fields []mapping.Field) (string, error) {
return string(encoded), nil
}
func mappingValue(r postgresdb.Mapping) (mapping.Mapping, error) {
func mappingValue(r postgresdb.Mapping, matches int64, lastMatched time.Time) (mapping.Mapping, error) {
var fields []mapping.Field
if raw := r.Fields; raw != "" {
if err := json.Unmarshal([]byte(raw), &fields); err != nil {
return mapping.Mapping{}, fmt.Errorf("edastore: decode mapping fields: %w", err)
}
}
// The query reports the epoch for a mapping that never matched.
if matches == 0 {
lastMatched = time.Time{}
}
return mapping.Mapping{
ID: r.ID,
Name: r.Name,
SourceHint: r.SourceHint,
Fields: fields,
CreatedAt: r.CreatedAt,
UpdatedAt: r.UpdatedAt,
ID: r.ID,
Name: r.Name,
SourceHint: r.SourceHint,
EventTypeID: r.EventType,
Fields: fields,
MatchCount: matches,
LastMatchedAt: lastMatched,
CreatedAt: r.CreatedAt,
UpdatedAt: r.UpdatedAt,
}, nil
}
@@ -208,6 +216,7 @@ func (s *EDA) InsertMapping(ctx context.Context, m mapping.Mapping) (string, err
ID: id,
Name: m.Name,
SourceHint: m.SourceHint,
EventType: m.EventTypeID,
Fields: encoded,
}); err != nil {
return "", fmt.Errorf("edastore: insert mapping: %w", err)
@@ -226,7 +235,7 @@ func (s *EDA) GetMapping(ctx context.Context, id string) (*mapping.Mapping, erro
if err != nil {
return nil, err
}
m, err := mappingValue(r)
m, err := mappingValue(r.Mapping, r.MatchCount, r.LastMatchedAt)
if err != nil {
return nil, err
}
@@ -240,7 +249,7 @@ func (s *EDA) ListMappings(ctx context.Context) ([]mapping.Mapping, error) {
}
out := make([]mapping.Mapping, 0, len(rows))
for _, r := range rows {
m, err := mappingValue(r)
m, err := mappingValue(r.Mapping, r.MatchCount, r.LastMatchedAt)
if err != nil {
return nil, err
}
@@ -258,6 +267,7 @@ func (s *EDA) UpdateMapping(ctx context.Context, m mapping.Mapping) error {
ID: m.ID,
Name: m.Name,
SourceHint: m.SourceHint,
EventType: m.EventTypeID,
Fields: encoded,
})
if err != nil {
@@ -282,6 +292,16 @@ func (s *EDA) DeleteMapping(ctx context.Context, id string) error {
return nil
}
// RecordMappingMatch counts one event a mapping resolved. Recording the same
// (mapping, capture) again is a no-op, so the count rises once per event no
// matter how many bindings share the mapping.
func (s *EDA) RecordMappingMatch(ctx context.Context, mappingID, captureID string) error {
if err := s.q.InsertMappingMatch(ctx, postgresdb.InsertMappingMatchParams{Mapping: mappingID, Capture: captureID}); err != nil {
return fmt.Errorf("edastore: record mapping match: %w", err)
}
return nil
}
// --- bindings ---
func (s *EDA) encryptSecret(secret string) (string, error) {
@@ -301,6 +321,7 @@ func (s *EDA) bindingValue(r postgresdb.Binding) (binding.Binding, error) {
Name: r.Name,
Matcher: binding.Matcher{Source: r.Source},
MappingID: r.Mapping,
Filter: r.Filter,
Workflow: r.Workflow,
Owner: r.Owner,
Repo: r.Repo,
@@ -320,10 +341,8 @@ func (s *EDA) bindingValue(r postgresdb.Binding) (binding.Binding, error) {
return b, nil
}
// InsertBinding stores a new binding as pending_approval. "One binding per
// source" is a schema constraint (idx_bindings_source), so a concurrent
// second insert for the same source is refused by the database and surfaced
// here as ErrBindingOverlap.
// InsertBinding stores a new binding as pending_approval. Any number of
// bindings may share a source.
func (s *EDA) InsertBinding(ctx context.Context, b binding.Binding) (string, error) {
secret := b.Secret
if secret != "" {
@@ -339,15 +358,13 @@ func (s *EDA) InsertBinding(ctx context.Context, b binding.Binding) (string, err
Name: b.Name,
Source: b.Matcher.Source,
Mapping: b.MappingID,
Filter: b.Filter,
Workflow: b.Workflow,
Owner: b.Owner,
Repo: b.Repo,
Status: string(binding.StatusPendingApproval),
Secret: secret,
})
if isUniqueViolation(err) {
return "", storecontract.ErrBindingOverlap
}
if err != nil {
return "", fmt.Errorf("edastore: insert binding: %w", err)
}
@@ -423,15 +440,13 @@ func (s *EDA) UpdateBinding(ctx context.Context, b binding.Binding) error {
Name: b.Name,
Source: b.Matcher.Source,
Mapping: b.MappingID,
Filter: b.Filter,
Workflow: b.Workflow,
Owner: b.Owner,
Repo: b.Repo,
Status: string(binding.StatusPendingApproval),
Secret: secret,
})
if isUniqueViolation(err) {
return storecontract.ErrBindingOverlap
}
if err != nil {
return err
}
@@ -454,10 +469,7 @@ func (s *EDA) DeleteBinding(ctx context.Context, id string) error {
return nil
}
// ApproveBinding is the only transition that arms a binding. "One armed
// binding per source" is a partial unique constraint (idx_bindings_armed_source),
// so a concurrent approval of a sibling binding on the same source is refused
// by the database and surfaced here as ErrBindingOverlap.
// ApproveBinding is the only transition that arms a binding.
func (s *EDA) ApproveBinding(ctx context.Context, id string) error {
r, err := s.q.GetBinding(ctx, id)
if errors.Is(err, pgx.ErrNoRows) {
@@ -470,9 +482,6 @@ func (s *EDA) ApproveBinding(ctx context.Context, id string) error {
return storecontract.ErrBindingTransition
}
n, err := s.q.SetBindingArmed(ctx, id)
if isUniqueViolation(err) {
return storecontract.ErrBindingOverlap
}
if err != nil {
return err
}
@@ -0,0 +1,166 @@
package postgres
import (
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// eventTypeFixture saves a type on source matching events whose "kind" equals kind.
func eventTypeFixture(t *testing.T, s *EDA, source, kind string) string {
t.Helper()
id, err := s.InsertEventType(t.Context(), eventtype.EventType{
Source: source, Name: kind,
Rule: eventtype.Rule{Payload: []eventtype.PayloadCondition{{Path: "kind", Op: eventtype.OpEquals, Value: kind}}},
})
if err != nil {
t.Fatalf("InsertEventType() error = %v", err)
}
return id
}
func armedBinding(t *testing.T, s *EDA, source, mappingID string) string {
t.Helper()
id, err := s.InsertBinding(t.Context(), binding.Binding{
Name: "n", Matcher: binding.Matcher{Source: source}, MappingID: mappingID, Workflow: "implement",
})
if err != nil {
t.Fatalf("InsertBinding() error = %v", err)
}
if err := s.ApproveBinding(t.Context(), id); err != nil {
t.Fatalf("ApproveBinding() error = %v", err)
}
return id
}
func captureOf(t *testing.T, s *EDA, source, body string) string {
t.Helper()
id, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: source, Body: body}, 0, 0)
if err != nil {
t.Fatalf("InsertCapture() error = %v", err)
}
return id
}
func undispatchedIDs(t *testing.T, s *EDA, source string) map[string]bool {
t.Helper()
list, err := s.ListUndispatchedCaptures(t.Context(), []string{source}, 10)
if err != nil {
t.Fatalf("ListUndispatchedCaptures() error = %v", err)
}
out := map[string]bool{}
for _, c := range list {
out[c.ID] = true
}
return out
}
func TestSeveralArmedBindingsShareASource(t *testing.T) {
s := edaFor(t)
a := armedBinding(t, s, "github", "")
b := armedBinding(t, s, "github", "")
armed, err := s.ArmedBindingsForSource(t.Context(), "github")
if err != nil {
t.Fatalf("ArmedBindingsForSource() error = %v", err)
}
got := map[string]bool{}
for _, x := range armed {
got[x.ID] = true
}
if !got[a] || !got[b] || len(armed) != 2 {
t.Fatalf("armed = %v, want both %s and %s", got, a, b)
}
}
func TestMappingAndBindingRoundTripEventTypeAndFilter(t *testing.T) {
s := edaFor(t)
typeID := eventTypeFixture(t, s, "github", "push")
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: typeID})
if err != nil {
t.Fatalf("InsertMapping() error = %v", err)
}
m, err := s.GetMapping(t.Context(), mid)
if err != nil || m.EventTypeID != typeID {
t.Fatalf("GetMapping() event type = %q (err %v), want %q", m.EventTypeID, err, typeID)
}
bid, err := s.InsertBinding(t.Context(), binding.Binding{
Name: "n", Matcher: binding.Matcher{Source: "github"}, MappingID: mid, Workflow: "implement",
Filter: `kind == "push"`,
})
if err != nil {
t.Fatalf("InsertBinding() error = %v", err)
}
b, err := s.GetBinding(t.Context(), bid)
if err != nil || b.Filter != `kind == "push"` {
t.Fatalf("GetBinding() filter = %q (err %v)", b.Filter, err)
}
b.Filter = ""
if err := s.UpdateBinding(t.Context(), *b); err != nil {
t.Fatalf("UpdateBinding() error = %v", err)
}
if b, _ = s.GetBinding(t.Context(), bid); b.Filter != "" {
t.Fatalf("filter after clearing = %q, want empty", b.Filter)
}
}
func TestMappingMatchCountRisesOncePerEvent(t *testing.T) {
s := edaFor(t)
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m"})
if err != nil {
t.Fatalf("InsertMapping() error = %v", err)
}
before := time.Now().Add(-time.Minute)
for _, capture := range []string{"c1", "c2", "c1"} {
if err := s.RecordMappingMatch(t.Context(), mid, capture); err != nil {
t.Fatalf("RecordMappingMatch(%s) error = %v", capture, err)
}
}
list, err := s.ListMappings(t.Context())
if err != nil || len(list) != 1 {
t.Fatalf("ListMappings() = %d (err %v)", len(list), err)
}
if list[0].MatchCount != 2 {
t.Errorf("MatchCount = %d, want 2 (one per distinct event)", list[0].MatchCount)
}
if !list[0].LastMatchedAt.After(before) {
t.Errorf("LastMatchedAt = %v, want a recent time", list[0].LastMatchedAt)
}
got, _ := s.GetMapping(t.Context(), mid)
if got.MatchCount != 2 {
t.Errorf("GetMapping MatchCount = %d, want 2", got.MatchCount)
}
}
// A capture stays undispatched until every armed binding for its event type
// has dispatched it; a binding for another event type does not hold it.
func TestUndispatchedIsPerBinding(t *testing.T) {
s := edaFor(t)
push := eventTypeFixture(t, s, "github", "push")
issue := eventTypeFixture(t, s, "github", "issue")
pushMap, _ := s.InsertMapping(t.Context(), mapping.Mapping{Name: "p", EventTypeID: push})
issueMap, _ := s.InsertMapping(t.Context(), mapping.Mapping{Name: "i", EventTypeID: issue})
a := armedBinding(t, s, "github", pushMap)
b := armedBinding(t, s, "github", pushMap)
c := armedBinding(t, s, "github", issueMap)
capture := captureOf(t, s, "github", `{"kind":"push"}`)
if !undispatchedIDs(t, s, "github")[capture] {
t.Fatal("new push capture not listed")
}
if err := s.RecordDispatch(t.Context(), a, 1, capture, 1); err != nil {
t.Fatalf("RecordDispatch(a) error = %v", err)
}
if !undispatchedIDs(t, s, "github")[capture] {
t.Fatal("capture dropped after one of two push bindings dispatched it")
}
if err := s.RecordDispatch(t.Context(), b, 1, capture, 2); err != nil {
t.Fatalf("RecordDispatch(b) error = %v", err)
}
if undispatchedIDs(t, s, "github")[capture] {
t.Fatalf("capture still listed after both push bindings dispatched it (issue binding %s must not hold it)", c)
}
}
@@ -5,6 +5,7 @@ import (
"testing"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
@@ -142,6 +143,11 @@ func TestPastedTypeIdentifiesLaterCaptures(t *testing.T) {
t.Errorf("unmatched capture event type = %q, want unidentified", byBody[`{"ref":"main"}`])
}
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: id})
if err != nil {
t.Fatalf("InsertMapping() error = %v", err)
}
armedBinding(t, s, "gh", mid)
undispatched, err := s.ListUndispatchedCaptures(t.Context(), []string{"gh"}, 10)
if err != nil {
t.Fatalf("ListUndispatchedCaptures() error = %v", err)
@@ -9,7 +9,6 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/events"
@@ -92,42 +91,6 @@ func TestPlaybookDispatchIsIdempotent(t *testing.T) {
}
}
// Hazard 3: "one binding per source" is a schema constraint, so concurrent
// inserts for one source produce exactly one success and one ErrBindingOverlap
// rather than two bindings that a single SQLite writer would have serialised.
func TestConcurrentInsertBindingSameSource(t *testing.T) {
s := edaFor(t)
type result struct{ err error }
start := make(chan struct{})
results := make(chan result, 2)
for range 2 {
go func() {
<-start
_, err := s.InsertBinding(t.Context(), binding.Binding{
Name: "n", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement",
})
results <- result{err: err}
}()
}
close(start)
var succeeded, overlapped int
for range 2 {
outcome := <-results
switch {
case outcome.err == nil:
succeeded++
case errors.Is(outcome.err, storecontract.ErrBindingOverlap):
overlapped++
default:
t.Fatalf("concurrent InsertBinding error = %v", outcome.err)
}
}
if succeeded != 1 || overlapped != 1 {
t.Fatalf("concurrent inserts = %d succeeded, %d overlapped; want 1 each", succeeded, overlapped)
}
}
// Hazard 1: UpdateBinding with an empty secret must leave the stored envelope
// untouched, so an edit form that does not echo the secret cannot blank an
// armed binding's HMAC key.
@@ -219,13 +182,9 @@ func TestBindingLifecycle(t *testing.T) {
}
}
// A capture round-trips its payload verbatim, and a dispatched capture drops
// out of the undispatched listing.
func TestCaptureRoundTripAndUndispatched(t *testing.T) {
// A capture round-trips its payload verbatim.
func TestCaptureRoundTrip(t *testing.T) {
s := edaFor(t)
if _, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "sentry", Name: "any"}); err != nil {
t.Fatalf("InsertEventType() error = %v", err)
}
body := `{"action":"created"}`
if _, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{
Source: "sentry", Body: body, Headers: `{"X-Hook":"1"}`, ContentType: "application/json",
@@ -239,19 +198,6 @@ func TestCaptureRoundTripAndUndispatched(t *testing.T) {
if list[0].Body != body {
t.Errorf("Body round-trip = %q, want %q", list[0].Body, body)
}
undispatched, err := s.ListUndispatchedCaptures(t.Context(), []string{"sentry"}, 10)
if err != nil || len(undispatched) != 1 {
t.Fatalf("ListUndispatchedCaptures() = %d (err %v), want 1", len(undispatched), err)
}
// Dispatch it; the capture must no longer be undispatched.
if err := s.RecordDispatch(t.Context(), "b1", 1, list[0].ID, 42); err != nil {
t.Fatalf("RecordDispatch() error = %v", err)
}
undispatched, err = s.ListUndispatchedCaptures(t.Context(), []string{"sentry"}, 10)
if err != nil || len(undispatched) != 0 {
t.Fatalf("ListUndispatchedCaptures() after dispatch = %d (err %v), want 0", len(undispatched), err)
}
}
func TestMappingCRUD(t *testing.T) {
@@ -0,0 +1,34 @@
-- Mappings per event type, match counts and several bindings per source
-- (docs/prds/event-automation.md, "Mappings" and "Bindings").
--
-- mappings.event_type is the event type a mapping belongs to; like
-- captures.event_type it is plain text, not a foreign key. A binding applies
-- to its mapping's event type, so any number of bindings may share a source
-- and the two per-source unique indexes are dropped.
--
-- mapping_matches holds one row per (mapping, capture) the mapping resolved;
-- a mapping's matched-event count and last match are read from it.
-- bindings.filter is an optional CEL expression over the mapping's parameters.
-- +goose Up
ALTER TABLE mappings ADD COLUMN event_type text NOT NULL DEFAULT '';
ALTER TABLE bindings ADD COLUMN filter text NOT NULL DEFAULT '';
DROP INDEX idx_bindings_source;
DROP INDEX idx_bindings_armed_source;
CREATE TABLE mapping_matches (
mapping text NOT NULL,
capture text NOT NULL,
matched_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (mapping, capture)
);
-- +goose Down
DROP TABLE mapping_matches;
CREATE UNIQUE INDEX idx_bindings_armed_source ON bindings (source) WHERE status = 'armed';
CREATE UNIQUE INDEX idx_bindings_source ON bindings (source);
ALTER TABLE bindings DROP COLUMN filter;
ALTER TABLE mappings DROP COLUMN event_type;
@@ -11,7 +11,7 @@ import (
)
const armedBindingsForSource = `-- name: ArmedBindingsForSource :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at, filter
FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC
`
@@ -37,6 +37,7 @@ func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
&i.Filter,
); err != nil {
return nil, err
}
@@ -147,7 +148,7 @@ func (q *Queries) EventTypesForSource(ctx context.Context, source string) ([]Eve
}
const getBinding = `-- name: GetBinding :one
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at, filter
FROM bindings WHERE id = $1
`
@@ -167,6 +168,7 @@ func (q *Queries) GetBinding(ctx context.Context, id string) (Binding, error) {
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
&i.Filter,
)
return i, err
}
@@ -192,27 +194,38 @@ func (q *Queries) GetEventType(ctx context.Context, id string) (EventType, error
}
const getMapping = `-- name: GetMapping :one
SELECT id, name, source_hint, fields, created_at, updated_at
SELECT mappings.id, mappings.name, mappings.source_hint, mappings.fields, mappings.created_at, mappings.updated_at, mappings.event_type,
(SELECT count(*) FROM mapping_matches mm WHERE mm.mapping = mappings.id)::bigint AS match_count,
COALESCE((SELECT max(mm.matched_at) FROM mapping_matches mm WHERE mm.mapping = mappings.id), 'epoch')::timestamptz AS last_matched_at
FROM mappings WHERE id = $1
`
func (q *Queries) GetMapping(ctx context.Context, id string) (Mapping, error) {
type GetMappingRow struct {
Mapping Mapping
MatchCount int64
LastMatchedAt time.Time
}
func (q *Queries) GetMapping(ctx context.Context, id string) (GetMappingRow, error) {
row := q.db.QueryRow(ctx, getMapping, id)
var i Mapping
var i GetMappingRow
err := row.Scan(
&i.ID,
&i.Name,
&i.SourceHint,
&i.Fields,
&i.CreatedAt,
&i.UpdatedAt,
&i.Mapping.ID,
&i.Mapping.Name,
&i.Mapping.SourceHint,
&i.Mapping.Fields,
&i.Mapping.CreatedAt,
&i.Mapping.UpdatedAt,
&i.Mapping.EventType,
&i.MatchCount,
&i.LastMatchedAt,
)
return i, err
}
const insertBinding = `-- name: InsertBinding :exec
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status, secret)
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8, $9)
INSERT INTO bindings (id, name, source, mapping, filter, workflow, owner, repo, version, status, secret)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9, $10)
`
type InsertBindingParams struct {
@@ -220,6 +233,7 @@ type InsertBindingParams struct {
Name string
Source string
Mapping string
Filter string
Workflow string
Owner string
Repo string
@@ -233,6 +247,7 @@ func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) er
arg.Name,
arg.Source,
arg.Mapping,
arg.Filter,
arg.Workflow,
arg.Owner,
arg.Repo,
@@ -323,14 +338,15 @@ func (q *Queries) InsertEventType(ctx context.Context, arg InsertEventTypeParams
}
const insertMapping = `-- name: InsertMapping :exec
INSERT INTO mappings (id, name, source_hint, fields)
VALUES ($1, $2, $3, $4)
INSERT INTO mappings (id, name, source_hint, event_type, fields)
VALUES ($1, $2, $3, $4, $5)
`
type InsertMappingParams struct {
ID string
Name string
SourceHint string
EventType string
Fields string
}
@@ -339,11 +355,27 @@ func (q *Queries) InsertMapping(ctx context.Context, arg InsertMappingParams) er
arg.ID,
arg.Name,
arg.SourceHint,
arg.EventType,
arg.Fields,
)
return err
}
const insertMappingMatch = `-- name: InsertMappingMatch :exec
INSERT INTO mapping_matches (mapping, capture) VALUES ($1, $2)
ON CONFLICT DO NOTHING
`
type InsertMappingMatchParams struct {
Mapping string
Capture string
}
func (q *Queries) InsertMappingMatch(ctx context.Context, arg InsertMappingMatchParams) error {
_, err := q.db.Exec(ctx, insertMappingMatch, arg.Mapping, arg.Capture)
return err
}
const insertPlaybookDispatch = `-- name: InsertPlaybookDispatch :exec
INSERT INTO playbook_dispatches (playbook_id, playbook_version, event_id, action_id)
VALUES ($1, $2, $3, $4)
@@ -395,7 +427,7 @@ func (q *Queries) InsertToolCall(ctx context.Context, arg InsertToolCallParams)
}
const listBindings = `-- name: ListBindings :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at, filter
FROM bindings ORDER BY created_at DESC
`
@@ -421,6 +453,7 @@ func (q *Queries) ListBindings(ctx context.Context) ([]Binding, error) {
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
&i.Filter,
); err != nil {
return nil, err
}
@@ -503,26 +536,37 @@ func (q *Queries) ListEventTypes(ctx context.Context) ([]EventType, error) {
}
const listMappings = `-- name: ListMappings :many
SELECT id, name, source_hint, fields, created_at, updated_at
SELECT mappings.id, mappings.name, mappings.source_hint, mappings.fields, mappings.created_at, mappings.updated_at, mappings.event_type,
(SELECT count(*) FROM mapping_matches mm WHERE mm.mapping = mappings.id)::bigint AS match_count,
COALESCE((SELECT max(mm.matched_at) FROM mapping_matches mm WHERE mm.mapping = mappings.id), 'epoch')::timestamptz AS last_matched_at
FROM mappings ORDER BY created_at DESC
`
func (q *Queries) ListMappings(ctx context.Context) ([]Mapping, error) {
type ListMappingsRow struct {
Mapping Mapping
MatchCount int64
LastMatchedAt time.Time
}
func (q *Queries) ListMappings(ctx context.Context) ([]ListMappingsRow, error) {
rows, err := q.db.Query(ctx, listMappings)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Mapping
var items []ListMappingsRow
for rows.Next() {
var i Mapping
var i ListMappingsRow
if err := rows.Scan(
&i.ID,
&i.Name,
&i.SourceHint,
&i.Fields,
&i.CreatedAt,
&i.UpdatedAt,
&i.Mapping.ID,
&i.Mapping.Name,
&i.Mapping.SourceHint,
&i.Mapping.Fields,
&i.Mapping.CreatedAt,
&i.Mapping.UpdatedAt,
&i.Mapping.EventType,
&i.MatchCount,
&i.LastMatchedAt,
); err != nil {
return nil, err
}
@@ -535,13 +579,16 @@ func (q *Queries) ListMappings(ctx context.Context) ([]Mapping, error) {
}
const listUndispatchedCaptures = `-- name: ListUndispatchedCaptures :many
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type
FROM captures
WHERE source = ANY($1::text[])
-- An unidentified capture is never dispatched.
AND event_type <> ''
AND id NOT IN (SELECT capture FROM binding_dispatches)
ORDER BY received_at DESC
SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.event_type
FROM captures c
WHERE c.source = ANY($1::text[])
AND c.event_type <> ''
AND EXISTS (
SELECT 1 FROM bindings b JOIN mappings m ON m.id = b.mapping
WHERE b.source = c.source AND b.status = 'armed' AND m.event_type = c.event_type
AND NOT EXISTS (SELECT 1 FROM binding_dispatches d WHERE d.binding = b.id AND d.capture = c.id)
)
ORDER BY c.received_at DESC
LIMIT $2
`
@@ -550,6 +597,9 @@ type ListUndispatchedCapturesParams struct {
EntryLimit int32
}
// A capture is undispatched while some armed binding on its source, whose
// mapping belongs to the capture's event type, has not dispatched it. An
// unidentified capture has no event type, so it is never listed.
func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispatchedCapturesParams) ([]Capture, error) {
rows, err := q.db.Query(ctx, listUndispatchedCaptures, arg.Sources, arg.EntryLimit)
if err != nil {
@@ -648,9 +698,9 @@ func (q *Queries) TaskToolCalls(ctx context.Context, taskID int64) ([]TaskToolCa
const updateBinding = `-- name: UpdateBinding :execrows
UPDATE bindings
SET name = $2, source = $3, mapping = $4, workflow = $5, owner = $6, repo = $7,
version = version + 1, status = $8,
secret = CASE WHEN $9::text = '' THEN secret ELSE $9 END,
SET name = $2, source = $3, mapping = $4, filter = $5, workflow = $6, owner = $7, repo = $8,
version = version + 1, status = $9,
secret = CASE WHEN $10::text = '' THEN secret ELSE $10 END,
updated_at = now()
WHERE id = $1
`
@@ -660,6 +710,7 @@ type UpdateBindingParams struct {
Name string
Source string
Mapping string
Filter string
Workflow string
Owner string
Repo string
@@ -676,6 +727,7 @@ func (q *Queries) UpdateBinding(ctx context.Context, arg UpdateBindingParams) (i
arg.Name,
arg.Source,
arg.Mapping,
arg.Filter,
arg.Workflow,
arg.Owner,
arg.Repo,
@@ -708,7 +760,7 @@ func (q *Queries) UpdateEventType(ctx context.Context, arg UpdateEventTypeParams
const updateMapping = `-- name: UpdateMapping :execrows
UPDATE mappings
SET name = $2, source_hint = $3, fields = $4, updated_at = now()
SET name = $2, source_hint = $3, event_type = $4, fields = $5, updated_at = now()
WHERE id = $1
`
@@ -716,6 +768,7 @@ type UpdateMappingParams struct {
ID string
Name string
SourceHint string
EventType string
Fields string
}
@@ -724,6 +777,7 @@ func (q *Queries) UpdateMapping(ctx context.Context, arg UpdateMappingParams) (i
arg.ID,
arg.Name,
arg.SourceHint,
arg.EventType,
arg.Fields,
)
if err != nil {
@@ -29,6 +29,7 @@ type Binding struct {
Secret string
CreatedAt time.Time
UpdatedAt time.Time
Filter string
}
type BindingDispatch struct {
@@ -144,6 +145,13 @@ type Mapping struct {
Fields string
CreatedAt time.Time
UpdatedAt time.Time
EventType string
}
type MappingMatch struct {
Mapping string
Capture string
MatchedAt time.Time
}
type Message struct {
@@ -11,13 +11,19 @@ ORDER BY received_at DESC
LIMIT $1;
-- name: ListUndispatchedCaptures :many
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type
FROM captures
WHERE source = ANY(@sources::text[])
-- An unidentified capture is never dispatched.
AND event_type <> ''
AND id NOT IN (SELECT capture FROM binding_dispatches)
ORDER BY received_at DESC
-- A capture is undispatched while some armed binding on its source, whose
-- mapping belongs to the capture's event type, has not dispatched it. An
-- unidentified capture has no event type, so it is never listed.
SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.event_type
FROM captures c
WHERE c.source = ANY(@sources::text[])
AND c.event_type <> ''
AND EXISTS (
SELECT 1 FROM bindings b JOIN mappings m ON m.id = b.mapping
WHERE b.source = c.source AND b.status = 'armed' AND m.event_type = c.event_type
AND NOT EXISTS (SELECT 1 FROM binding_dispatches d WHERE d.binding = b.id AND d.capture = c.id)
)
ORDER BY c.received_at DESC
LIMIT @entry_limit;
-- name: DeleteCapturesOlderThan :exec
@@ -29,39 +35,47 @@ DELETE FROM captures WHERE id NOT IN (
);
-- name: InsertMapping :exec
INSERT INTO mappings (id, name, source_hint, fields)
VALUES ($1, $2, $3, $4);
INSERT INTO mappings (id, name, source_hint, event_type, fields)
VALUES ($1, $2, $3, $4, $5);
-- name: GetMapping :one
SELECT id, name, source_hint, fields, created_at, updated_at
SELECT sqlc.embed(mappings),
(SELECT count(*) FROM mapping_matches mm WHERE mm.mapping = mappings.id)::bigint AS match_count,
COALESCE((SELECT max(mm.matched_at) FROM mapping_matches mm WHERE mm.mapping = mappings.id), 'epoch')::timestamptz AS last_matched_at
FROM mappings WHERE id = $1;
-- name: ListMappings :many
SELECT id, name, source_hint, fields, created_at, updated_at
SELECT sqlc.embed(mappings),
(SELECT count(*) FROM mapping_matches mm WHERE mm.mapping = mappings.id)::bigint AS match_count,
COALESCE((SELECT max(mm.matched_at) FROM mapping_matches mm WHERE mm.mapping = mappings.id), 'epoch')::timestamptz AS last_matched_at
FROM mappings ORDER BY created_at DESC;
-- name: UpdateMapping :execrows
UPDATE mappings
SET name = $2, source_hint = $3, fields = $4, updated_at = now()
SET name = $2, source_hint = $3, event_type = $4, fields = $5, updated_at = now()
WHERE id = $1;
-- name: InsertMappingMatch :exec
INSERT INTO mapping_matches (mapping, capture) VALUES ($1, $2)
ON CONFLICT DO NOTHING;
-- name: DeleteMapping :execrows
DELETE FROM mappings WHERE id = $1;
-- name: InsertBinding :exec
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status, secret)
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8, $9);
INSERT INTO bindings (id, name, source, mapping, filter, workflow, owner, repo, version, status, secret)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9, $10);
-- name: GetBinding :one
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at, filter
FROM bindings WHERE id = $1;
-- name: ListBindings :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at, filter
FROM bindings ORDER BY created_at DESC;
-- name: ArmedBindingsForSource :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at, filter
FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC;
-- name: UpdateBinding :execrows
@@ -69,8 +83,8 @@ FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC;
-- untouched so an edit form that does not echo the secret cannot blank an
-- armed binding's HMAC key.
UPDATE bindings
SET name = $2, source = $3, mapping = $4, workflow = $5, owner = $6, repo = $7,
version = version + 1, status = $8,
SET name = $2, source = $3, mapping = $4, filter = $5, workflow = $6, owner = $7, repo = $8,
version = version + 1, status = $9,
secret = CASE WHEN sqlc.arg(secret)::text = '' THEN secret ELSE sqlc.arg(secret) END,
updated_at = now()
WHERE id = $1;