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") // 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 } // Captures returns the events whose source kept their headers and payload, // newest first. func (s *Store) Captures(ctx context.Context, orgID string, limit int) ([]Event, error) { var out []Event if err := s.db.SelectContext(ctx, &out, ` SELECT id, org_id, source, 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 ORDER BY received_at DESC, id LIMIT $2`, orgID, 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"` Source string `db:"source"` 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 organisation's event types, by source and name. func (s *Store) EventTypes(ctx context.Context, orgID string) ([]EventType, error) { var out []EventType if err := s.db.SelectContext(ctx, &out, ` SELECT id, org_id, source, name, rule, schema, created_at, updated_at FROM events.event_types WHERE org_id = $1 ORDER BY source, name`, orgID); 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, source string) ([]EventType, error) { var out []EventType if err := s.db.SelectContext(ctx, &out, ` SELECT id, org_id, source, name, rule, schema, created_at, updated_at FROM events.event_types WHERE org_id = $1 AND source = $2 ORDER BY name`, orgID, source); 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, 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, name, rule, schema) VALUES (:id, :org_id, :source, :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"` SourceHint string `db:"source_hint"` 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_hint, 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_hint, event_type_id, fields) VALUES (:id, :org_id, :name, :source_hint, :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_hint = :source_hint, 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, name, 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 name = $2`, orgID, name, value) if err != nil { return fmt.Errorf("save source: %w", err) } if n, err := res.RowsAffected(); err != nil || n == 0 { return ErrNotFound } return nil } // SetDisplayName labels a source. func (s *Store) SetDisplayName(ctx context.Context, orgID, name, display string) error { return s.setSource(ctx, orgID, name, "display_name", display) } // SetDeliveryHeader names the header a sender repeats on a delivery's retries. func (s *Store) SetDeliveryHeader(ctx context.Context, orgID, name, header string) error { return s.setSource(ctx, orgID, name, "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, name string, capture bool) error { return s.setSource(ctx, orgID, name, "capture", capture) } // SetSecret replaces a source's sealed signing secret. func (s *Store) SetSecret(ctx context.Context, orgID, name string, sealed []byte) error { return s.setSource(ctx, orgID, name, "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, name string, 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 name = $2`, orgID, name, 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, name string) (bool, error) { res, err := s.db.ExecContext(ctx, ` UPDATE events.sources SET unsigned_approved = true, updated_at = now() WHERE org_id = $1 AND name = $2 AND verification = 'none' AND NOT unsigned_approved`, orgID, name) 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, name string) 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 = $2`, orgID, name); 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 = $2`, orgID, name); 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 name = $2`, orgID, name) 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, source string) (int, error) { var n int if err := s.db.GetContext(ctx, &n, ` SELECT count(*) FROM events.triggers WHERE org_id = $1 AND source = $2 AND mapping_id IS NOT NULL`, orgID, source); 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 one run a trigger started for an event. type Dispatch struct { EventID uuid.UUID `db:"event_id"` RunID uuid.UUID `db:"run_id"` CreatedAt time.Time `db:"created_at"` } // DispatchesOf returns the runs a trigger started, 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.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 }