Files

570 lines
24 KiB
Go

// Package store holds the events module's SQL: sources, the events table that
// is Archie's one stream, triggers and the record of which run each trigger
// started.
package store
import (
"context"
"database/sql"
"encoding/json/jsontext"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// ErrNotFound means the named row doesn't exist.
var ErrNotFound = errors.New("not found")
// Verification schemes for a source's deliveries.
const (
Token = "token"
HMAC = "hmac"
None = "none"
)
// Scopes a source can be owned by.
const (
ScopeOrg = "org"
ScopePerson = "person"
)
// Source is a place events come from, read by one connector. It is owned by a
// scope: the organisation, or one person acting in it. Everything stored about
// it refers to ID, so the label and the webhook path can change.
type Source struct {
ID uuid.UUID `db:"id"`
Scope string `db:"scope"`
OrgID string `db:"org_id"`
// PersonID is the owning person of a person source, null for an
// organisation's.
PersonID sql.NullString `db:"person_id"`
// Label is the name people see, unique within the scope.
Label string `db:"label"`
// Connector is the connector's immutable package identifier, never renamed
// and never given to a different package.
Connector string `db:"connector"`
TokenSHA256 string `db:"token_sha256"`
// Verification is the scheme that deliveries must pass: Token, HMAC or None.
Verification string `db:"verification"`
// HMACHeader names the header that carries the signature, HMACPrefix is
// the text before its hex digest, and HMACSecretSealed is the sealed
// shared secret.
HMACHeader string `db:"hmac_header"`
HMACPrefix string `db:"hmac_prefix"`
HMACSecretSealed []byte `db:"hmac_secret_sealed"`
// Cursor is where a listening source resumes.
Cursor string `db:"cursor"`
// KeyFields are the paths its events are grouped by; none means the default.
KeyFields jsontext.Value `db:"key_fields"`
// DeliveryHeader names the header a sender repeats on every retry of one
// delivery.
DeliveryHeader string `db:"delivery_header"`
// UnsignedApproved says a person accepted that a None source does no
// verification. A None source refuses deliveries until then.
UnsignedApproved bool `db:"unsigned_approved"`
// Capture says the source keeps each delivery's headers and raw payload.
Capture bool `db:"capture"`
}
// VisibleTo reports whether the person may see and use the source: an
// organisation's source belongs to every member, a person's only to that person.
func (s Source) VisibleTo(person string) bool {
return !s.PersonID.Valid || s.PersonID.String == person
}
// Event is one stored event.
type Event struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
// SourceID is null for a schedule tick, and for an event whose source was
// deleted.
SourceID uuid.NullUUID `db:"source_id"`
DeclaredEventType string `db:"declared_event_type"`
SourceEventID string `db:"source_event_id"`
LinkKey sql.NullString `db:"link_key"`
LinkedTo *uuid.UUID `db:"linked_to"`
Fields jsontext.Value `db:"fields"`
// Body is the payload as it arrived: the webhook body, or the batch a
// listening connector streamed. It is what an audit reads when the
// parsed fields leave a question open.
Body []byte `db:"body"`
OccurredAt sql.NullTime `db:"occurred_at"`
ReceivedAt time.Time `db:"received_at"`
Matched bool `db:"matched"`
DispatchedAt sql.NullTime `db:"dispatched_at"`
// Own marks the echo of a delivery Archie sent, and OriginRunID is the run
// that sent it. An own event has no group.
Own bool `db:"own"`
OriginRunID uuid.NullUUID `db:"origin_run_id"`
GroupKey sql.NullString `db:"group_key"`
// Scan into []byte to preserve SQL NULL for events with no group.
GroupFilter []byte `db:"group_filter"`
// Verification is how the delivery was verified: Signed (an HMAC
// signature), TokenVerified (a bearer token) or Unsigned (an approved
// source that checks nothing). It is empty for an event that arrived
// through a connector's own stream.
Verification string `db:"verification"`
// Headers are the request's headers without credentials, and RemoteAddr is
// the sender's address. Headers is null when the source keeps no payloads.
Headers []byte `db:"headers"`
RemoteAddr string `db:"remote_addr"`
EventTypeID uuid.NullUUID `db:"event_type_id"`
}
// How an event's delivery was verified.
const (
Signed = "signed"
TokenVerified = "token"
Unsigned = "unsigned"
)
// Trigger starts a workflow for events of one type from one source whose
// fields match its filter.
type Trigger struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
// Name is the trigger's label, unique among the organisation's live
// triggers.
Name string `db:"name"`
// SourceID is null for a scheduled trigger, which has no source.
SourceID uuid.NullUUID `db:"source_id"`
DeclaredEventType string `db:"declared_event_type"`
Filter jsontext.Value `db:"filter"`
WorkflowID uuid.UUID `db:"workflow_id"`
Enabled bool `db:"enabled"`
// ScheduleEverySeconds is the interval a scheduled trigger fires on; it
// is null for a trigger that fires on events.
ScheduleEverySeconds sql.NullInt64 `db:"schedule_every_s"`
// ScheduleSince is when the schedule began or last changed.
ScheduleSince sql.NullTime `db:"schedule_since"`
// Approved says a person accepted the trigger; it fires only once approved
// and enabled. EventTypeID restricts it to events identified as that type,
// MappingID reads the event's payload for the run.
Approved bool `db:"approved"`
EventTypeID uuid.NullUUID `db:"event_type_id"`
MappingID uuid.NullUUID `db:"mapping_id"`
}
const triggerColumns = `id, org_id, name, source_id, declared_event_type, filter, workflow_id, enabled, approved,
event_type_id, mapping_id, schedule_every_s, schedule_since`
// Store is the events module's Postgres store.
type Store struct {
db *sqlx.DB
}
// New returns a store on db.
func New(db *sqlx.DB) *Store { return &Store{db: db} }
const sourceColumns = `id, scope, org_id, person_id, label, connector, token_sha256, verification,
hmac_header, hmac_prefix, hmac_secret_sealed, cursor, key_fields, delivery_header, unsigned_approved, capture`
// Source returns one source of the organisation, whoever owns it. Callers that
// act for a person check Source.VisibleTo.
func (s *Store) Source(ctx context.Context, orgID string, id uuid.UUID) (Source, error) {
var src Source
err := s.db.GetContext(ctx, &src, `SELECT `+sourceColumns+` FROM events.sources WHERE org_id = $1 AND id = $2`, orgID, id)
if errors.Is(err, sql.ErrNoRows) {
return Source{}, ErrNotFound
}
if err != nil {
return Source{}, fmt.Errorf("read source: %w", err)
}
return src, nil
}
// SourceByPath resolves a previously issued webhook alias.
func (s *Store) SourceByPath(ctx context.Context, orgID, path string) (Source, error) {
var src Source
err := s.db.GetContext(ctx, &src, `SELECT `+sourceColumns+` FROM events.sources WHERE org_id = $1 AND webhook_path = $2`, orgID, path)
if errors.Is(err, sql.ErrNoRows) {
return Source{}, ErrNotFound
}
if err != nil {
return Source{}, fmt.Errorf("read source: %w", err)
}
return src, nil
}
// Sources returns every source of the organisation, for the work that runs on
// behalf of no person.
func (s *Store) Sources(ctx context.Context, orgID string) ([]Source, error) {
var out []Source
if err := s.db.SelectContext(ctx, &out, `SELECT `+sourceColumns+` FROM events.sources WHERE org_id = $1 ORDER BY label`, orgID); err != nil {
return nil, fmt.Errorf("list sources: %w", err)
}
return out, nil
}
// SourcesFor returns the organisation's sources the person may see: the
// organisation's own and the person's.
func (s *Store) SourcesFor(ctx context.Context, orgID, person string) ([]Source, error) {
var out []Source
if err := s.db.SelectContext(ctx, &out, `
SELECT `+sourceColumns+` FROM events.sources
WHERE org_id = $1 AND (person_id IS NULL OR person_id = $2) ORDER BY label`, orgID, person); err != nil {
return nil, fmt.Errorf("list sources: %w", err)
}
return out, nil
}
// SetCursor records where a listening source resumes.
func (s *Store) SetCursor(ctx context.Context, orgID string, id uuid.UUID, cursor string) error {
if _, err := s.db.ExecContext(ctx, `
UPDATE events.sources SET cursor = $3, updated_at = now() WHERE org_id = $1 AND id = $2`,
orgID, id, cursor); err != nil {
return fmt.Errorf("save cursor: %w", err)
}
return nil
}
// InsertSource stores a new source. It returns ErrLabelTaken when the label is in use.
func (s *Store) InsertSource(ctx context.Context, src Source) error {
if _, err := s.db.NamedExecContext(ctx, `
INSERT INTO events.sources (id, scope, org_id, person_id, label, connector, token_sha256,
verification, hmac_header, hmac_prefix, hmac_secret_sealed)
VALUES (:id, :scope, :org_id, :person_id, :label, :connector, :token_sha256,
:verification, :hmac_header, :hmac_prefix, :hmac_secret_sealed)`, src); err != nil {
return fmt.Errorf("save source: %w", classifySource(err))
}
return nil
}
// UpdateSource replaces a source's connector and verification. Verification
// that is none stays approved only if it already was and was none before, so
// only ApproveUnsigned approves an unsigned source.
func (s *Store) UpdateSource(ctx context.Context, src Source) error {
res, err := s.db.NamedExecContext(ctx, `
UPDATE events.sources
SET connector = :connector, token_sha256 = :token_sha256,
verification = :verification, hmac_header = :hmac_header,
hmac_prefix = :hmac_prefix, hmac_secret_sealed = :hmac_secret_sealed,
unsigned_approved = :verification = 'none' AND verification = 'none' AND unsigned_approved,
updated_at = now()
WHERE org_id = :org_id AND id = :id`, src)
if err != nil {
return fmt.Errorf("save source: %w", classifySource(err))
}
if n, err := res.RowsAffected(); err != nil || n == 0 {
return ErrNotFound
}
return nil
}
// Insert stores an event unless its source already delivered the same source
// event id, or a schedule already stored the same slot. It reports whether the
// event was new.
func (s *Store) Insert(ctx context.Context, e Event) (bool, error) {
res, err := s.db.NamedExecContext(ctx, `
INSERT INTO events.events (id, org_id, source_id, declared_event_type, source_event_id, link_key, fields, body,
occurred_at, own, origin_run_id, group_key, group_filter, verification, headers,
remote_addr, event_type_id)
VALUES (:id, :org_id, :source_id, :declared_event_type, :source_event_id, :link_key, :fields, :body,
:occurred_at, :own, :origin_run_id, :group_key, :group_filter, :verification, :headers,
:remote_addr, :event_type_id)
ON CONFLICT DO NOTHING`, e)
if err != nil {
return false, fmt.Errorf("store event: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return false, fmt.Errorf("store event: %w", err)
}
return n == 1, nil
}
// Dispatch claims the oldest undispatched event and hands it to fn inside one
// transaction. fn's matched result and the dispatched mark commit together,
// so an event is dispatched once even with several workers. It reports
// whether there was an event to dispatch.
func (s *Store) Dispatch(ctx context.Context, fn func(tx *sqlx.Tx, e Event) (matched bool, err error)) (bool, error) {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return false, fmt.Errorf("begin dispatch: %w", err)
}
defer func() { _ = tx.Rollback() }()
var e Event
err = tx.GetContext(ctx, &e, `
SELECT id, org_id, source_id, declared_event_type, source_event_id, link_key, linked_to, fields, body,
occurred_at, received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter,
event_type_id
FROM events.events WHERE dispatched_at IS NULL
ORDER BY received_at FOR UPDATE SKIP LOCKED LIMIT 1`)
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("claim event: %w", err)
}
matched, err := fn(tx, e)
if err != nil {
return true, err
}
if _, err := tx.ExecContext(ctx, `
UPDATE events.events SET dispatched_at = now(), matched = $2 WHERE id = $1`, e.ID, matched); err != nil {
return true, fmt.Errorf("mark dispatched: %w", err)
}
if err := tx.Commit(); err != nil {
return true, fmt.Errorf("commit dispatch: %w", err)
}
return true, nil
}
// Link points e at the earliest event its source delivered before it with the
// same link key, and reports whether it found one. Only an earlier event
// counts: a firing alert must not link to the resolve that follows it.
func Link(ctx context.Context, tx *sqlx.Tx, e Event) (bool, error) {
if !e.LinkKey.Valid {
return false, nil
}
const earlier = `org_id = $2 AND source_id = $3 AND link_key = $4 AND id <> $1
AND (received_at, id) < ($5, $1)`
res, err := tx.ExecContext(ctx, `
UPDATE events.events SET linked_to = (
SELECT id FROM events.events WHERE `+earlier+`
ORDER BY received_at, id LIMIT 1)
WHERE id = $1 AND EXISTS (SELECT 1 FROM events.events WHERE `+earlier+`)`,
e.ID, e.OrgID, e.SourceID, e.LinkKey.String, e.ReceivedAt)
if err != nil {
return false, fmt.Errorf("link event: %w", err)
}
n, err := res.RowsAffected()
return n == 1, err
}
// SetEventPayload replaces the stored fields and body of e inside tx.
func SetEventPayload(ctx context.Context, tx *sqlx.Tx, e Event) error {
if _, err := tx.ExecContext(ctx, `
UPDATE events.events SET fields = $2, body = $3 WHERE id = $1`, e.ID, e.Fields, e.Body); err != nil {
return fmt.Errorf("redact event payload: %w", err)
}
return nil
}
// Triggers returns the armed triggers that fire for one source and declared
// event type, and for the custom type the event was identified as, if any. A
// schedule tick has no source and matches the triggers that have none.
func Triggers(ctx context.Context, tx *sqlx.Tx, orgID string, sourceID uuid.NullUUID, declaredEventType string, typeID uuid.NullUUID) ([]Trigger, error) {
var out []Trigger
if err := tx.SelectContext(ctx, &out, `
SELECT `+triggerColumns+`
FROM events.triggers
WHERE org_id = $1 AND deleted_at IS NULL AND source_id IS NOT DISTINCT FROM $2
AND (declared_event_type = $3 OR declared_event_type = '')
AND enabled AND approved AND (event_type_id IS NULL OR event_type_id = $4)
ORDER BY name`,
orgID, sourceID, declaredEventType, typeID); err != nil {
return nil, fmt.Errorf("read triggers: %w", err)
}
return out, nil
}
// Dispatch outcomes. A trigger that matched an event either started a run, or
// started none because the event failed its mapping, access policy denied the
// start, or the workflow is disabled.
const (
OutcomeStarted = "started"
OutcomeFailed = "failed"
OutcomeDenied = "denied"
OutcomeDisabled = "disabled"
)
// RecordDispatch records that a trigger started run for an event. It replaces
// an earlier outcome of the same event by the same trigger that started no run.
func RecordDispatch(ctx context.Context, tx *sqlx.Tx, eventID, triggerID, runID uuid.UUID) error {
if _, err := tx.ExecContext(ctx, `
INSERT INTO events.dispatches (event_id, trigger_id, run_id) VALUES ($1, $2, $3)
ON CONFLICT (event_id, trigger_id) DO UPDATE
SET run_id = EXCLUDED.run_id, outcome = 'started', reason = NULL, created_at = now()
WHERE events.dispatches.outcome <> 'started'`, eventID, triggerID, runID); err != nil {
return fmt.Errorf("record dispatch: %w", err)
}
return nil
}
// RecordNoRun records that a trigger matched an event but started no run,
// with the outcome and the reason as a JSON document. A started run already
// recorded for the pair is kept.
func RecordNoRun(ctx context.Context, tx *sqlx.Tx, eventID, triggerID uuid.UUID, outcome string, reason jsontext.Value) error {
if _, err := tx.ExecContext(ctx, `
INSERT INTO events.dispatches (event_id, trigger_id, outcome, reason) VALUES ($1, $2, $3, $4)
ON CONFLICT (event_id, trigger_id) DO UPDATE
SET outcome = EXCLUDED.outcome, reason = EXCLUDED.reason, created_at = now()
WHERE events.dispatches.outcome <> 'started'`, eventID, triggerID, outcome, []byte(reason)); err != nil {
return fmt.Errorf("record dispatch outcome: %w", err)
}
return nil
}
// UpsertTrigger creates the trigger t.ID names, or replaces it. It returns
// ErrExists when a live trigger already has the name, and ErrNotFound when the
// trigger was deleted.
func (s *Store) UpsertTrigger(ctx context.Context, t Trigger) error {
res, err := s.db.NamedExecContext(ctx, `
INSERT INTO events.triggers (id, org_id, name, source_id, declared_event_type, filter, workflow_id, enabled,
approved, event_type_id, mapping_id, schedule_every_s, schedule_since)
VALUES (:id, :org_id, :name, :source_id, :declared_event_type, :filter, :workflow_id, :enabled,
:approved, :event_type_id, :mapping_id,
CAST(:schedule_every_s AS integer), CASE WHEN CAST(:schedule_every_s AS integer) IS NULL THEN NULL ELSE now() END)
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name, source_id = EXCLUDED.source_id, declared_event_type = EXCLUDED.declared_event_type,
filter = EXCLUDED.filter, workflow_id = EXCLUDED.workflow_id, enabled = EXCLUDED.enabled,
approved = EXCLUDED.approved, event_type_id = EXCLUDED.event_type_id, mapping_id = EXCLUDED.mapping_id,
schedule_since = CASE
WHEN EXCLUDED.schedule_every_s IS NULL THEN NULL
WHEN events.triggers.schedule_every_s IS NOT DISTINCT FROM EXCLUDED.schedule_every_s
THEN events.triggers.schedule_since
ELSE now() END,
schedule_every_s = EXCLUDED.schedule_every_s, updated_at = now()
WHERE events.triggers.org_id = EXCLUDED.org_id AND events.triggers.deleted_at IS NULL`, t)
if err != nil {
return fmt.Errorf("save trigger: %w", classify(err))
}
if n, err := res.RowsAffected(); err != nil || n == 0 {
return ErrNotFound
}
return nil
}
// ScheduledTriggers returns the enabled triggers that fire on an interval.
func (s *Store) ScheduledTriggers(ctx context.Context, orgID string) ([]Trigger, error) {
var out []Trigger
if err := s.db.SelectContext(ctx, &out, `
SELECT `+triggerColumns+`
FROM events.triggers
WHERE org_id = $1 AND deleted_at IS NULL AND enabled AND approved AND schedule_every_s IS NOT NULL
ORDER BY name`, orgID); err != nil {
return nil, fmt.Errorf("read schedules: %w", err)
}
return out, nil
}
// EventFilter narrows the events a list returns. A zero field doesn't filter,
// and Matched distinguishes events a trigger started a run for from the rest.
type EventFilter struct {
SourceID uuid.NullUUID
DeclaredEventType string
Matched *bool
Limit int
}
// visibleSource holds for a row whose source the person in $2 may see: it has
// none, or the source is the organisation's or that person's.
const visibleSource = `(source_id IS NULL OR EXISTS (
SELECT 1 FROM events.sources vs WHERE vs.id = source_id AND (vs.person_id IS NULL OR vs.person_id = $2)))`
// Recent returns the newest events of an organisation that match filter and
// come from sources the person may see.
func (s *Store) Recent(ctx context.Context, orgID, person string, f EventFilter) ([]Event, error) {
var out []Event
if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, source_id, declared_event_type, source_event_id, link_key, linked_to, fields,
occurred_at, received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter
FROM events.events
WHERE org_id = $1 AND `+visibleSource+`
AND ($3::uuid IS NULL OR source_id = $3)
AND ($4 = '' OR declared_event_type = $4)
AND ($5::boolean IS NULL OR matched = $5)
ORDER BY received_at DESC LIMIT $6`, orgID, person, f.SourceID, f.DeclaredEventType, f.Matched, f.Limit); err != nil {
return nil, fmt.Errorf("list events: %w", err)
}
return out, nil
}
// Event returns one event with the payload it arrived in, if it comes from a
// source the person may see.
func (s *Store) Event(ctx context.Context, orgID, person string, id uuid.UUID) (Event, error) {
var e Event
err := s.db.GetContext(ctx, &e, `
SELECT id, org_id, source_id, declared_event_type, source_event_id, link_key, linked_to, fields, body,
occurred_at, received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter,
verification, headers, remote_addr, event_type_id
FROM events.events WHERE org_id = $1 AND `+visibleSource+` AND id = $3`, orgID, person, id)
if errors.Is(err, sql.ErrNoRows) {
return Event{}, ErrNotFound
}
if err != nil {
return Event{}, fmt.Errorf("read event: %w", err)
}
return e, nil
}
// TriggerRun is the outcome of a trigger for an event: the run it started, or
// the reason no run started.
type TriggerRun struct {
TriggerID uuid.UUID `db:"trigger_id"`
Trigger string `db:"trigger"`
RunID uuid.NullUUID `db:"run_id"`
Outcome string `db:"outcome"`
Reason jsontext.Value `db:"reason"`
}
// RunsForEvent returns the dispatches of every trigger for an event.
func (s *Store) RunsForEvent(ctx context.Context, orgID string, id uuid.UUID) ([]TriggerRun, error) {
var out []TriggerRun
if err := s.db.SelectContext(ctx, &out, `
SELECT d.trigger_id, t.name AS trigger, d.run_id, d.outcome, d.reason FROM events.dispatches d
JOIN events.events e ON e.id = d.event_id
JOIN events.triggers t ON t.id = d.trigger_id
WHERE e.org_id = $1 AND d.event_id = $2 ORDER BY t.name, d.trigger_id`, orgID, id); err != nil {
return nil, fmt.Errorf("read event runs: %w", err)
}
return out, nil
}
// AllTriggers returns every live trigger of the organisation, enabled or not.
func (s *Store) AllTriggers(ctx context.Context, orgID string) ([]Trigger, error) {
var out []Trigger
if err := s.db.SelectContext(ctx, &out, `
SELECT `+triggerColumns+`
FROM events.triggers WHERE org_id = $1 AND deleted_at IS NULL ORDER BY name`, orgID); err != nil {
return nil, fmt.Errorf("list triggers: %w", err)
}
return out, nil
}
// Origin is the event and trigger that started a run. TriggerID is null for a
// replay, whose trigger isn't saved.
type Origin struct {
EventID uuid.UUID `db:"event_id"`
SourceID uuid.NullUUID `db:"source_id"`
Source string `db:"source"`
DeclaredEventType string `db:"declared_event_type"`
Fields jsontext.Value `db:"fields"`
ReceivedAt time.Time `db:"received_at"`
TriggerID uuid.NullUUID `db:"trigger_id"`
Trigger string `db:"trigger"`
Filter jsontext.Value `db:"filter"`
}
// OriginOf returns what started a run; ok is false when no trigger did.
func (s *Store) OriginOf(ctx context.Context, orgID string, runID uuid.UUID) (Origin, bool, error) {
var o Origin
err := s.db.GetContext(ctx, &o, `
WITH o AS (
SELECT d.event_id, t.id AS trigger_id, t.name AS trigger, t.filter
FROM events.dispatches d JOIN events.triggers t ON t.id = d.trigger_id
WHERE d.run_id = $2
UNION ALL
SELECT r.event_id, NULL::uuid, r.label, '{}'::jsonb FROM events.replays r WHERE r.run_id = $2
)
SELECT e.id AS event_id, e.source_id,
COALESCE(src.label, CASE WHEN e.declared_event_type = 'schedule.tick' THEN 'schedule' ELSE '' END) AS source,
e.declared_event_type, e.fields, e.received_at, o.trigger_id, o.trigger, o.filter
FROM o
JOIN events.events e ON e.id = o.event_id
LEFT JOIN events.sources src ON src.id = e.source_id
WHERE e.org_id = $1
LIMIT 1`, orgID, runID)
if errors.Is(err, sql.ErrNoRows) {
return Origin{}, false, nil
}
if err != nil {
return Origin{}, false, fmt.Errorf("read run origin: %w", err)
}
return o, true, nil
}