A source is keyed by a uuid, owned by the organisation or one person, and labelled within that scope. The webhook path is a separate unique column, so renaming either leaves stored events, event types, triggers, groups, mappings and drafts alone. Delivery policies, sealed secrets and group keys use the id.
449 lines
17 KiB
Go
449 lines
17 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json/jsontext"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jmoiron/sqlx"
|
|
)
|
|
|
|
// ErrInUse means other rows still refer to the row being deleted.
|
|
var ErrInUse = errors.New("in use")
|
|
|
|
// ErrExists means a row with that name already exists.
|
|
var ErrExists = errors.New("already exists")
|
|
|
|
// ErrLabelTaken and ErrPathTaken mean another source of the same scope has the
|
|
// label, or another source has the webhook path.
|
|
var (
|
|
ErrLabelTaken = errors.New("a source with that label already exists")
|
|
ErrPathTaken = errors.New("a source with that webhook path already exists")
|
|
)
|
|
|
|
// Postgres reports a delete blocked by ON DELETE RESTRICT as 23001 and a
|
|
// reference to a missing row as 23503.
|
|
const (
|
|
restrictViolation = "23001"
|
|
foreignKeyViolation = "23503"
|
|
uniqueViolation = "23505"
|
|
)
|
|
|
|
// classify turns the constraint errors callers act on into the sentinels
|
|
// above.
|
|
func classify(err error) error {
|
|
if pqErr, ok := errors.AsType[*pgconn.PgError](err); ok {
|
|
switch pqErr.Code {
|
|
case restrictViolation, foreignKeyViolation:
|
|
return fmt.Errorf("%w: %s", ErrInUse, pqErr.Detail)
|
|
case uniqueViolation:
|
|
return ErrExists
|
|
}
|
|
}
|
|
return err
|
|
}
|
|
|
|
// classifySource turns a unique violation on a source's label or webhook path
|
|
// into its sentinel.
|
|
func classifySource(err error) error {
|
|
if pqErr, ok := errors.AsType[*pgconn.PgError](err); ok && pqErr.Code == uniqueViolation {
|
|
if pqErr.ConstraintName == "sources_webhook_path_key" {
|
|
return ErrPathTaken
|
|
}
|
|
return ErrLabelTaken
|
|
}
|
|
return err
|
|
}
|
|
|
|
// Captures returns the events whose source kept their headers and payload,
|
|
// newest first, for the sources the person may see.
|
|
func (s *Store) Captures(ctx context.Context, orgID, person string, limit int) ([]Event, error) {
|
|
var out []Event
|
|
if err := s.db.SelectContext(ctx, &out, `
|
|
SELECT id, org_id, source_id, type, source_event_id, fields, body, headers, remote_addr, verification,
|
|
event_type_id, received_at, occurred_at
|
|
FROM events.events
|
|
WHERE org_id = $1 AND headers IS NOT NULL AND `+visibleSource+`
|
|
ORDER BY received_at DESC, id LIMIT $3`, orgID, person, limit); err != nil {
|
|
return nil, fmt.Errorf("list captures: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// EventType is a person's name for one kind of event on a source.
|
|
type EventType struct {
|
|
ID uuid.UUID `db:"id"`
|
|
OrgID string `db:"org_id"`
|
|
SourceID uuid.UUID `db:"source_id"`
|
|
Name string `db:"name"`
|
|
Rule jsontext.Value `db:"rule"`
|
|
Schema jsontext.Value `db:"schema"`
|
|
CreatedAt time.Time `db:"created_at"`
|
|
UpdatedAt time.Time `db:"updated_at"`
|
|
}
|
|
|
|
// EventTypes returns the event types of the sources the person may see, by
|
|
// source and name.
|
|
func (s *Store) EventTypes(ctx context.Context, orgID, person string) ([]EventType, error) {
|
|
var out []EventType
|
|
if err := s.db.SelectContext(ctx, &out, `
|
|
SELECT id, org_id, source_id, name, rule, schema, created_at, updated_at
|
|
FROM events.event_types WHERE org_id = $1 AND `+visibleSource+` ORDER BY source_id, name`, orgID, person); err != nil {
|
|
return nil, fmt.Errorf("list event types: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// EventTypesOf returns the event types of one source.
|
|
func (s *Store) EventTypesOf(ctx context.Context, orgID string, sourceID uuid.UUID) ([]EventType, error) {
|
|
var out []EventType
|
|
if err := s.db.SelectContext(ctx, &out, `
|
|
SELECT id, org_id, source_id, name, rule, schema, created_at, updated_at
|
|
FROM events.event_types WHERE org_id = $1 AND source_id = $2 ORDER BY name`, orgID, sourceID); err != nil {
|
|
return nil, fmt.Errorf("list event types of source: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// EventType returns one event type.
|
|
func (s *Store) EventType(ctx context.Context, orgID string, id uuid.UUID) (EventType, error) {
|
|
var t EventType
|
|
err := s.db.GetContext(ctx, &t, `
|
|
SELECT id, org_id, source_id, name, rule, schema, created_at, updated_at
|
|
FROM events.event_types WHERE org_id = $1 AND id = $2`, orgID, id)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return EventType{}, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return EventType{}, fmt.Errorf("read event type: %w", err)
|
|
}
|
|
return t, nil
|
|
}
|
|
|
|
// InsertEventType stores a new event type.
|
|
func (s *Store) InsertEventType(ctx context.Context, t EventType) error {
|
|
if _, err := s.db.NamedExecContext(ctx, `
|
|
INSERT INTO events.event_types (id, org_id, source_id, name, rule, schema)
|
|
VALUES (:id, :org_id, :source_id, :name, :rule, :schema)`, t); err != nil {
|
|
return fmt.Errorf("save event type: %w", classify(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UpdateEventType changes an event type's name and rule. Its source and
|
|
// schema are fixed.
|
|
func (s *Store) UpdateEventType(ctx context.Context, orgID string, id uuid.UUID, name string, rule jsontext.Value) error {
|
|
res, err := s.db.ExecContext(ctx, `
|
|
UPDATE events.event_types SET name = $3, rule = $4, updated_at = now()
|
|
WHERE org_id = $1 AND id = $2`, orgID, id, name, rule)
|
|
if err != nil {
|
|
return fmt.Errorf("save event type: %w", classify(err))
|
|
}
|
|
if n, err := res.RowsAffected(); err != nil || n == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DeleteEventType removes an event type. Events identified as it become
|
|
// unidentified; a mapping or trigger that uses it blocks the delete.
|
|
func (s *Store) DeleteEventType(ctx context.Context, orgID string, id uuid.UUID) error {
|
|
res, err := s.db.ExecContext(ctx, `DELETE FROM events.event_types WHERE org_id = $1 AND id = $2`, orgID, id)
|
|
if err != nil {
|
|
return fmt.Errorf("delete event type: %w", classify(err))
|
|
}
|
|
if n, err := res.RowsAffected(); err != nil || n == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Mapping names the payload paths a workflow reads from one event type.
|
|
type Mapping struct {
|
|
ID uuid.UUID `db:"id"`
|
|
OrgID string `db:"org_id"`
|
|
Name string `db:"name"`
|
|
SourceID uuid.NullUUID `db:"source_id"`
|
|
EventTypeID uuid.UUID `db:"event_type_id"`
|
|
Fields jsontext.Value `db:"fields"`
|
|
MatchCount int64 `db:"match_count"`
|
|
LastMatchedAt sql.NullTime `db:"last_matched_at"`
|
|
CreatedAt time.Time `db:"created_at"`
|
|
UpdatedAt time.Time `db:"updated_at"`
|
|
}
|
|
|
|
const mappingColumns = `id, org_id, name, source_id, event_type_id, fields, match_count, last_matched_at, created_at, updated_at`
|
|
|
|
// Mappings returns the organisation's mappings, by name.
|
|
func (s *Store) Mappings(ctx context.Context, orgID string) ([]Mapping, error) {
|
|
var out []Mapping
|
|
if err := s.db.SelectContext(ctx, &out, `SELECT `+mappingColumns+` FROM events.mappings WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
|
|
return nil, fmt.Errorf("list mappings: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// Mapping returns one mapping.
|
|
func (s *Store) Mapping(ctx context.Context, orgID string, id uuid.UUID) (Mapping, error) {
|
|
var m Mapping
|
|
err := s.db.GetContext(ctx, &m, `SELECT `+mappingColumns+` FROM events.mappings WHERE org_id = $1 AND id = $2`, orgID, id)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return Mapping{}, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return Mapping{}, fmt.Errorf("read mapping: %w", err)
|
|
}
|
|
return m, nil
|
|
}
|
|
|
|
// MappingIn reads a mapping inside a dispatch transaction.
|
|
func MappingIn(ctx context.Context, tx *sqlx.Tx, orgID string, id uuid.UUID) (Mapping, error) {
|
|
var m Mapping
|
|
if err := tx.GetContext(ctx, &m, `SELECT `+mappingColumns+` FROM events.mappings WHERE org_id = $1 AND id = $2`, orgID, id); err != nil {
|
|
return Mapping{}, fmt.Errorf("read mapping: %w", err)
|
|
}
|
|
return m, nil
|
|
}
|
|
|
|
// InsertMapping stores a new mapping.
|
|
func (s *Store) InsertMapping(ctx context.Context, m Mapping) error {
|
|
if _, err := s.db.NamedExecContext(ctx, `
|
|
INSERT INTO events.mappings (id, org_id, name, source_id, event_type_id, fields)
|
|
VALUES (:id, :org_id, :name, :source_id, :event_type_id, :fields)`, m); err != nil {
|
|
return fmt.Errorf("save mapping: %w", classify(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UpdateMapping replaces a mapping's name, event type and fields. Its match
|
|
// count is kept.
|
|
func (s *Store) UpdateMapping(ctx context.Context, m Mapping) error {
|
|
res, err := s.db.NamedExecContext(ctx, `
|
|
UPDATE events.mappings SET name = :name, source_id = :source_id, event_type_id = :event_type_id,
|
|
fields = :fields, updated_at = now()
|
|
WHERE org_id = :org_id AND id = :id`, m)
|
|
if err != nil {
|
|
return fmt.Errorf("save mapping: %w", classify(err))
|
|
}
|
|
if n, err := res.RowsAffected(); err != nil || n == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DeleteMapping removes a mapping that no trigger uses.
|
|
func (s *Store) DeleteMapping(ctx context.Context, orgID string, id uuid.UUID) error {
|
|
res, err := s.db.ExecContext(ctx, `DELETE FROM events.mappings WHERE org_id = $1 AND id = $2`, orgID, id)
|
|
if err != nil {
|
|
return fmt.Errorf("delete mapping: %w", classify(err))
|
|
}
|
|
if n, err := res.RowsAffected(); err != nil || n == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// CountMatch notes that a mapping read an event a trigger started a run for.
|
|
func CountMatch(ctx context.Context, tx *sqlx.Tx, id uuid.UUID) error {
|
|
if _, err := tx.ExecContext(ctx, `
|
|
UPDATE events.mappings SET match_count = match_count + 1, last_matched_at = now() WHERE id = $1`, id); err != nil {
|
|
return fmt.Errorf("count mapping match: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SetEventType records which event type an event was identified as.
|
|
func (s *Store) SetEventType(ctx context.Context, id, typeID uuid.UUID) error {
|
|
if _, err := s.db.ExecContext(ctx, `UPDATE events.events SET event_type_id = $2 WHERE id = $1`, id, typeID); err != nil {
|
|
return fmt.Errorf("identify event: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SetSourceColumn changes one of a source's single-value settings. column is
|
|
// always a constant of this package.
|
|
func (s *Store) setSource(ctx context.Context, orgID string, id uuid.UUID, column string, value any) error {
|
|
res, err := s.db.ExecContext(ctx, `
|
|
UPDATE events.sources SET `+column+` = $3, updated_at = now() WHERE org_id = $1 AND id = $2`,
|
|
orgID, id, value)
|
|
if err != nil {
|
|
return fmt.Errorf("save source: %w", classifySource(err))
|
|
}
|
|
if n, err := res.RowsAffected(); err != nil || n == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SetLabel renames a source. The label is unique within the source's scope.
|
|
func (s *Store) SetLabel(ctx context.Context, orgID string, id uuid.UUID, label string) error {
|
|
return s.setSource(ctx, orgID, id, "label", label)
|
|
}
|
|
|
|
// SetWebhookPath moves the address a source receives deliveries at. Stored
|
|
// events, event types and triggers refer to the source by id and are unaffected.
|
|
func (s *Store) SetWebhookPath(ctx context.Context, orgID string, id uuid.UUID, path string) error {
|
|
return s.setSource(ctx, orgID, id, "webhook_path", path)
|
|
}
|
|
|
|
// SetDeliveryHeader names the header a sender repeats on a delivery's retries.
|
|
func (s *Store) SetDeliveryHeader(ctx context.Context, orgID string, id uuid.UUID, header string) error {
|
|
return s.setSource(ctx, orgID, id, "delivery_header", header)
|
|
}
|
|
|
|
// SetCapture turns the keeping of a source's headers and payloads on or off.
|
|
func (s *Store) SetCapture(ctx context.Context, orgID string, id uuid.UUID, capture bool) error {
|
|
return s.setSource(ctx, orgID, id, "capture", capture)
|
|
}
|
|
|
|
// SetSecret replaces a source's sealed signing secret.
|
|
func (s *Store) SetSecret(ctx context.Context, orgID string, id uuid.UUID, sealed []byte) error {
|
|
return s.setSource(ctx, orgID, id, "hmac_secret_sealed", sealed)
|
|
}
|
|
|
|
// SetSigning switches a source between an HMAC signature and no verification.
|
|
// Turning signing off leaves the source unapproved, so it refuses deliveries
|
|
// until a person approves it; the signature header and secret are kept so
|
|
// signing can be required again.
|
|
func (s *Store) SetSigning(ctx context.Context, orgID string, id uuid.UUID, signed bool) error {
|
|
verification := None
|
|
if signed {
|
|
verification = HMAC
|
|
}
|
|
res, err := s.db.ExecContext(ctx, `
|
|
UPDATE events.sources SET verification = $3, unsigned_approved = false, updated_at = now()
|
|
WHERE org_id = $1 AND id = $2`, orgID, id, verification)
|
|
if err != nil {
|
|
return fmt.Errorf("save source: %w", err)
|
|
}
|
|
if n, err := res.RowsAffected(); err != nil || n == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ApproveUnsigned accepts that a source with no verification takes
|
|
// deliveries. It reports false when the source isn't waiting for approval.
|
|
func (s *Store) ApproveUnsigned(ctx context.Context, orgID string, id uuid.UUID) (bool, error) {
|
|
res, err := s.db.ExecContext(ctx, `
|
|
UPDATE events.sources SET unsigned_approved = true, updated_at = now()
|
|
WHERE org_id = $1 AND id = $2 AND verification = 'none' AND NOT unsigned_approved`, orgID, id)
|
|
if err != nil {
|
|
return false, fmt.Errorf("approve source: %w", err)
|
|
}
|
|
n, err := res.RowsAffected()
|
|
return n == 1, err
|
|
}
|
|
|
|
// DeleteSource removes a source and its event types. A trigger or a mapping
|
|
// that still uses it blocks the delete; stored events and their dispatch
|
|
// history stay.
|
|
func (s *Store) DeleteSource(ctx context.Context, orgID string, id uuid.UUID) error {
|
|
tx, err := s.db.BeginTxx(ctx, nil)
|
|
if err != nil {
|
|
return fmt.Errorf("begin delete source: %w", err)
|
|
}
|
|
defer func() { _ = tx.Rollback() }()
|
|
var triggers int
|
|
if err := tx.GetContext(ctx, &triggers, `SELECT count(*) FROM events.triggers WHERE org_id = $1 AND source_id = $2`, orgID, id); err != nil {
|
|
return fmt.Errorf("check triggers of source: %w", err)
|
|
}
|
|
if triggers > 0 {
|
|
return fmt.Errorf("%w: %d trigger(s) use it", ErrInUse, triggers)
|
|
}
|
|
if _, err := tx.ExecContext(ctx, `DELETE FROM events.event_types WHERE org_id = $1 AND source_id = $2`, orgID, id); err != nil {
|
|
return fmt.Errorf("delete event types of source: %w", classify(err))
|
|
}
|
|
res, err := tx.ExecContext(ctx, `DELETE FROM events.sources WHERE org_id = $1 AND id = $2`, orgID, id)
|
|
if err != nil {
|
|
return fmt.Errorf("delete source: %w", err)
|
|
}
|
|
if n, err := res.RowsAffected(); err != nil || n == 0 {
|
|
return ErrNotFound
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
return fmt.Errorf("commit delete source: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// MappedTriggers counts the triggers of a source that read events with a
|
|
// mapping, which needs the stored payload.
|
|
func (s *Store) MappedTriggers(ctx context.Context, orgID string, sourceID uuid.UUID) (int, error) {
|
|
var n int
|
|
if err := s.db.GetContext(ctx, &n, `
|
|
SELECT count(*) FROM events.triggers WHERE org_id = $1 AND source_id = $2 AND mapping_id IS NOT NULL`, orgID, sourceID); err != nil {
|
|
return 0, fmt.Errorf("count mapped triggers: %w", err)
|
|
}
|
|
return n, nil
|
|
}
|
|
|
|
// SetTriggerState changes whether a trigger is approved and enabled, and
|
|
// reports whether it exists.
|
|
func (s *Store) SetTriggerState(ctx context.Context, orgID, name string, approved, enabled bool) (bool, error) {
|
|
res, err := s.db.ExecContext(ctx, `
|
|
UPDATE events.triggers SET approved = $3, enabled = $4, updated_at = now()
|
|
WHERE org_id = $1 AND name = $2`, orgID, name, approved, enabled)
|
|
if err != nil {
|
|
return false, fmt.Errorf("save trigger: %w", err)
|
|
}
|
|
n, err := res.RowsAffected()
|
|
return n == 1, err
|
|
}
|
|
|
|
// Trigger returns one trigger.
|
|
func (s *Store) Trigger(ctx context.Context, orgID, name string) (Trigger, error) {
|
|
var t Trigger
|
|
err := s.db.GetContext(ctx, &t, `
|
|
SELECT org_id, name, source, event_type, filter, workflow, enabled, approved, event_type_id, mapping_id,
|
|
schedule_every_s, schedule_since
|
|
FROM events.triggers WHERE org_id = $1 AND name = $2`, orgID, name)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return Trigger{}, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return Trigger{}, fmt.Errorf("read trigger: %w", err)
|
|
}
|
|
return t, nil
|
|
}
|
|
|
|
// DeleteTrigger removes a trigger. Runs it already started and their dispatch
|
|
// records stay.
|
|
func (s *Store) DeleteTrigger(ctx context.Context, orgID, name string) error {
|
|
res, err := s.db.ExecContext(ctx, `DELETE FROM events.triggers WHERE org_id = $1 AND name = $2`, orgID, name)
|
|
if err != nil {
|
|
return fmt.Errorf("delete trigger: %w", err)
|
|
}
|
|
if n, err := res.RowsAffected(); err != nil || n == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Dispatch is the outcome of a trigger for an event: the run it started, or
|
|
// the reason no run started.
|
|
type Dispatch struct {
|
|
EventID uuid.UUID `db:"event_id"`
|
|
RunID uuid.NullUUID `db:"run_id"`
|
|
Outcome string `db:"outcome"`
|
|
Reason jsontext.Value `db:"reason"`
|
|
CreatedAt time.Time `db:"created_at"`
|
|
}
|
|
|
|
// DispatchesOf returns a trigger's dispatches, newest first.
|
|
func (s *Store) DispatchesOf(ctx context.Context, orgID, trigger string, limit int) ([]Dispatch, error) {
|
|
var out []Dispatch
|
|
if err := s.db.SelectContext(ctx, &out, `
|
|
SELECT d.event_id, d.run_id, d.outcome, d.reason, d.created_at FROM events.dispatches d
|
|
JOIN events.events e ON e.id = d.event_id
|
|
WHERE e.org_id = $1 AND d.trigger = $2 ORDER BY d.created_at DESC LIMIT $3`, orgID, trigger, limit); err != nil {
|
|
return nil, fmt.Errorf("list dispatches: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|