feat(events): hear Alertmanager through its connector: verified intake, dedupe, links, triggers that start runs (#1980, #1978)
This commit is contained in:
12 files changed
+1025
-13
No files matched your search
@@ -0,0 +1,86 @@
|
||||
// Package store holds the connectors module's SQL: the accepted connector
|
||||
// specs the host starts at boot.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// Accepted is one connector an operator accepted, with the authority it
|
||||
// declared.
|
||||
type Accepted struct {
|
||||
OrgID string `db:"org_id"`
|
||||
Name string `db:"name"`
|
||||
Path string `db:"path"`
|
||||
SHA256 string `db:"sha256"`
|
||||
Egress Strings `db:"egress"`
|
||||
Env Strings `db:"env"`
|
||||
Settings json.RawMessage `db:"settings"`
|
||||
}
|
||||
|
||||
// Store is the connectors 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} }
|
||||
|
||||
// List returns an organisation's accepted connectors.
|
||||
func (s *Store) List(ctx context.Context, orgID string) ([]Accepted, error) {
|
||||
var out []Accepted
|
||||
if err := s.db.SelectContext(ctx, &out, `
|
||||
SELECT org_id, name, path, sha256, egress, env, settings
|
||||
FROM connectors.accepted WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
|
||||
return nil, fmt.Errorf("list connectors: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Upsert records an accepted connector, replacing an earlier acceptance.
|
||||
func (s *Store) Upsert(ctx context.Context, a Accepted) error {
|
||||
if _, err := s.db.NamedExecContext(ctx, `
|
||||
INSERT INTO connectors.accepted (org_id, name, path, sha256, egress, env, settings)
|
||||
VALUES (:org_id, :name, :path, :sha256, :egress, :env, :settings)
|
||||
ON CONFLICT (org_id, name) DO UPDATE
|
||||
SET path = EXCLUDED.path, sha256 = EXCLUDED.sha256, egress = EXCLUDED.egress,
|
||||
env = EXCLUDED.env, settings = EXCLUDED.settings, updated_at = now()`, a); err != nil {
|
||||
return fmt.Errorf("accept connector: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Strings is a string list stored as a JSON array. Value has a value receiver
|
||||
// so database/sql finds it on a struct field; Scan needs a pointer.
|
||||
type Strings []string //nolint:recvcheck // database/sql's Valuer and Scanner idiom
|
||||
|
||||
// Value encodes the list as JSON.
|
||||
func (s Strings) Value() (driver.Value, error) {
|
||||
if s == nil {
|
||||
return []byte("[]"), nil
|
||||
}
|
||||
return json.Marshal([]string(s))
|
||||
}
|
||||
|
||||
// Scan decodes a JSON array.
|
||||
func (s *Strings) Scan(src any) error {
|
||||
var raw []byte
|
||||
switch v := src.(type) {
|
||||
case []byte:
|
||||
raw = v
|
||||
case string:
|
||||
raw = []byte(v)
|
||||
case nil:
|
||||
*s = nil
|
||||
return nil
|
||||
default:
|
||||
return errors.New("strings: unsupported column type")
|
||||
}
|
||||
return json.Unmarshal(raw, (*[]string)(s))
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package connectors
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
|
||||
)
|
||||
|
||||
// validName is the shape of a connector name: it appears in logs and URLs.
|
||||
var validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`)
|
||||
|
||||
// Module runs an organisation's accepted connectors and serves their
|
||||
// administration.
|
||||
type Module struct {
|
||||
orgID string
|
||||
host *Host
|
||||
store *store.Store
|
||||
log *slog.Logger
|
||||
|
||||
mu sync.RWMutex
|
||||
running map[string]*Connector
|
||||
failed map[string]string
|
||||
}
|
||||
|
||||
// NewModule returns the connectors module for orgID.
|
||||
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string) *Module {
|
||||
return &Module{
|
||||
orgID: orgID, host: NewHost(log), store: store.New(db), log: log,
|
||||
running: map[string]*Connector{}, failed: map[string]string{},
|
||||
}
|
||||
}
|
||||
|
||||
// Start launches every accepted connector. A connector that fails to start is
|
||||
// reported by Ready and logged; the others still run.
|
||||
func (m *Module) Start(ctx context.Context) error {
|
||||
accepted, err := m.store.List(ctx, m.orgID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, a := range accepted {
|
||||
// A failure is recorded for Ready and logged; the rest still start.
|
||||
_ = m.launch(ctx, a)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get returns the running connector named name.
|
||||
func (m *Module) Get(name string) (*Connector, bool) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
c, ok := m.running[name]
|
||||
return c, ok
|
||||
}
|
||||
|
||||
// Ready reports connectors that failed to start or whose process has exited.
|
||||
func (m *Module) Ready(context.Context) error {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
var problems []string
|
||||
for name, reason := range m.failed {
|
||||
problems = append(problems, name+": "+reason)
|
||||
}
|
||||
for name := range m.running {
|
||||
if !m.host.Alive(name) {
|
||||
problems = append(problems, name+": process exited")
|
||||
}
|
||||
}
|
||||
if len(problems) == 0 {
|
||||
return nil
|
||||
}
|
||||
sort.Strings(problems)
|
||||
return errors.New(strings.Join(problems, "; "))
|
||||
}
|
||||
|
||||
// Close stops every connector.
|
||||
func (m *Module) Close() { m.host.Close() }
|
||||
|
||||
// Routes adds the admin routes, each wrapped in guard.
|
||||
func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) {
|
||||
mux.Handle("PUT /api/connectors/{name}", guard(http.HandlerFunc(m.accept)))
|
||||
}
|
||||
|
||||
type acceptRequest struct {
|
||||
Path string `json:"path"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Egress []string `json:"egress"`
|
||||
Env []string `json:"env"`
|
||||
Settings map[string]string `json:"settings"`
|
||||
}
|
||||
|
||||
func (m *Module) accept(w http.ResponseWriter, r *http.Request) {
|
||||
name := r.PathValue("name")
|
||||
var req acceptRequest
|
||||
if err := httpjson.Read(r, &req); err != nil {
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if !validName.MatchString(name) || req.Path == "" || req.SHA256 == "" {
|
||||
httpjson.Error(w, http.StatusBadRequest, "a connector needs a lowercase name, a path and a sha256")
|
||||
return
|
||||
}
|
||||
settings, err := json.Marshal(req.Settings)
|
||||
if err != nil {
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
a := store.Accepted{
|
||||
OrgID: m.orgID, Name: name, Path: req.Path, SHA256: req.SHA256,
|
||||
Egress: req.Egress, Env: req.Env, Settings: settings,
|
||||
}
|
||||
if err := m.store.Upsert(r.Context(), a); err != nil {
|
||||
httpjson.Error(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if err := m.launch(context.WithoutCancel(r.Context()), a); err != nil {
|
||||
httpjson.Error(w, http.StatusUnprocessableEntity, err.Error())
|
||||
return
|
||||
}
|
||||
httpjson.Write(w, http.StatusOK, map[string]string{"name": name, "state": "running"})
|
||||
}
|
||||
|
||||
// launch starts or restarts one accepted connector and records the outcome.
|
||||
func (m *Module) launch(ctx context.Context, a store.Accepted) error {
|
||||
var settings map[string]string
|
||||
if len(a.Settings) > 0 {
|
||||
if err := json.Unmarshal(a.Settings, &settings); err != nil {
|
||||
return m.fail(ctx, a.Name, fmt.Errorf("settings: %w", err))
|
||||
}
|
||||
}
|
||||
c, err := m.host.Start(ctx, Spec{
|
||||
Name: a.Name, Path: a.Path, SHA256: a.SHA256,
|
||||
Env: a.Env, Egress: a.Egress, Settings: settings,
|
||||
})
|
||||
if err != nil {
|
||||
return m.fail(ctx, a.Name, err)
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.running[a.Name] = c
|
||||
delete(m.failed, a.Name)
|
||||
m.mu.Unlock()
|
||||
m.log.InfoContext(ctx, "connector started", "connector", a.Name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Module) fail(ctx context.Context, name string, err error) error {
|
||||
m.mu.Lock()
|
||||
delete(m.running, name)
|
||||
m.failed[name] = err.Error()
|
||||
m.mu.Unlock()
|
||||
m.log.ErrorContext(ctx, "connector failed to start", "connector", name, "error", err)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
// Package events is how Archie hears: sources deliver payloads, a connector
|
||||
// turns each verified payload into typed events, and every event is stored
|
||||
// before it is acknowledged. A dispatcher then claims each new event, links a
|
||||
// resolve to what it resolves, and starts a run for every trigger it matches.
|
||||
package events
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/events/internal/match"
|
||||
"github.com/samcharles93/archie-core/modules/events/internal/store"
|
||||
"github.com/samcharles93/archie-core/modules/runs"
|
||||
)
|
||||
|
||||
var validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`)
|
||||
|
||||
// Connectors finds the running connector a source reads with.
|
||||
type Connectors interface {
|
||||
Get(name string) (*connectors.Connector, bool)
|
||||
}
|
||||
|
||||
// Runs starts runs for matched triggers.
|
||||
type Runs interface {
|
||||
Start(ctx context.Context, req runs.StartRequest) (uuid.UUID, error)
|
||||
}
|
||||
|
||||
// Module hears events for one organisation.
|
||||
type Module struct {
|
||||
orgID string
|
||||
store *store.Store
|
||||
connectors Connectors
|
||||
runs Runs
|
||||
log *slog.Logger
|
||||
poll time.Duration
|
||||
}
|
||||
|
||||
// NewModule returns the events module for orgID.
|
||||
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, c Connectors, r Runs) *Module {
|
||||
return &Module{orgID: orgID, store: store.New(db), connectors: c, runs: r, log: log, poll: time.Second}
|
||||
}
|
||||
|
||||
// Routes adds the webhook intake and the guarded admin routes.
|
||||
func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) {
|
||||
mux.HandleFunc("POST /hooks/{source}", m.intake)
|
||||
mux.Handle("PUT /api/sources/{name}", guard(http.HandlerFunc(m.putSource)))
|
||||
mux.Handle("PUT /api/triggers/{name}", guard(http.HandlerFunc(m.putTrigger)))
|
||||
mux.Handle("GET /api/events", guard(http.HandlerFunc(m.recent)))
|
||||
}
|
||||
|
||||
// intake verifies the source's token before reading the body, has the
|
||||
// source's connector parse it, and stores each event before answering. A
|
||||
// re-delivered event is a constraint conflict, counted as a duplicate.
|
||||
func (m *Module) intake(w http.ResponseWriter, r *http.Request) {
|
||||
src, err := m.store.Source(r.Context(), m.orgID, r.PathValue("source"))
|
||||
if errors.Is(err, store.ErrNotFound) || (err == nil && !httpjson.TokenMatches(httpjson.Bearer(r), src.TokenSHA256)) {
|
||||
// Unknown source and wrong token answer alike, so neither is probed.
|
||||
httpjson.Error(w, http.StatusUnauthorized, "unknown source or wrong token")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
httpjson.Error(w, http.StatusServiceUnavailable, "events store unavailable")
|
||||
return
|
||||
}
|
||||
conn, ok := m.connectors.Get(src.Connector)
|
||||
if !ok {
|
||||
httpjson.Error(w, http.StatusServiceUnavailable, "connector "+src.Connector+" isn't running")
|
||||
return
|
||||
}
|
||||
body, err := httpjson.Body(r)
|
||||
if err != nil {
|
||||
httpjson.Error(w, http.StatusRequestEntityTooLarge, err.Error())
|
||||
return
|
||||
}
|
||||
parsed, err := conn.Parse(r.Context(), body, map[string]string{"Content-Type": r.Header.Get("Content-Type")})
|
||||
if err != nil {
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
stored, duplicates, err := m.save(r.Context(), src.Name, parsed)
|
||||
if err != nil {
|
||||
httpjson.Error(w, http.StatusServiceUnavailable, err.Error())
|
||||
return
|
||||
}
|
||||
httpjson.Write(w, http.StatusAccepted, map[string]int{"stored": stored, "duplicates": duplicates})
|
||||
}
|
||||
|
||||
func (m *Module) save(ctx context.Context, source string, parsed []connectors.Event) (stored, duplicates int, err error) {
|
||||
for _, e := range parsed {
|
||||
row := store.Event{
|
||||
ID: uuid.New(), OrgID: m.orgID, Source: source, Type: e.Type, SourceEventID: e.SourceEventID,
|
||||
Fields: e.Fields,
|
||||
}
|
||||
row.LinkKey.String, row.LinkKey.Valid = e.LinkKey, e.LinkKey != ""
|
||||
row.OccurredAt.Time, row.OccurredAt.Valid = e.OccurredAt, !e.OccurredAt.IsZero()
|
||||
isNew, err := m.store.Insert(ctx, row)
|
||||
if err != nil {
|
||||
return stored, duplicates, err
|
||||
}
|
||||
if isNew {
|
||||
stored++
|
||||
} else {
|
||||
duplicates++
|
||||
}
|
||||
}
|
||||
return stored, duplicates, nil
|
||||
}
|
||||
|
||||
// Work dispatches stored events until ctx ends.
|
||||
func (m *Module) Work(ctx context.Context) {
|
||||
for ctx.Err() == nil {
|
||||
found, err := m.store.Dispatch(ctx, m.dispatch)
|
||||
if err != nil {
|
||||
m.log.ErrorContext(ctx, "dispatch event", "error", err)
|
||||
}
|
||||
if found && err == nil {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(m.poll):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dispatch links a resolve to the event it resolves and starts no work for
|
||||
// it. Any other event starts one run per matching trigger, keyed so a retried
|
||||
// dispatch never starts a second run.
|
||||
func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) {
|
||||
ctx := context.Background()
|
||||
linked, err := store.Link(ctx, tx, e)
|
||||
if err != nil || linked {
|
||||
return false, err
|
||||
}
|
||||
triggers, err := store.Triggers(ctx, tx, e.OrgID, e.Source, e.Type)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
matched := false
|
||||
for _, t := range triggers {
|
||||
var filter map[string]string
|
||||
if err := json.Unmarshal(t.Filter, &filter); err != nil {
|
||||
return false, fmt.Errorf("trigger %q filter: %w", t.Name, err)
|
||||
}
|
||||
if !match.Fields(e.Fields, filter) {
|
||||
continue
|
||||
}
|
||||
runID, err := m.runs.Start(ctx, runs.StartRequest{
|
||||
OrgID: e.OrgID, Workflow: t.Workflow, Key: e.ID.String() + ":" + t.Name, Input: runInput(e),
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("start run for trigger %q: %w", t.Name, err)
|
||||
}
|
||||
if err := store.RecordDispatch(ctx, tx, e.ID, t.Name, runID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
m.log.InfoContext(ctx, "trigger started run", "event", e.ID, "trigger", t.Name, "run", runID)
|
||||
matched = true
|
||||
}
|
||||
return matched, nil
|
||||
}
|
||||
|
||||
func runInput(e store.Event) json.RawMessage {
|
||||
input, err := json.Marshal(map[string]any{"event": map[string]any{
|
||||
"id": e.ID, "source": e.Source, "type": e.Type, "fields": e.Fields, "occurred_at": e.OccurredAt.Time,
|
||||
}})
|
||||
if err != nil {
|
||||
return json.RawMessage("null")
|
||||
}
|
||||
return input
|
||||
}
|
||||
|
||||
type sourceRequest struct {
|
||||
Connector string `json:"connector"`
|
||||
}
|
||||
|
||||
// putSource creates a source or rotates its token. The token is returned once
|
||||
// and stored only as its hash.
|
||||
func (m *Module) putSource(w http.ResponseWriter, r *http.Request) {
|
||||
name := r.PathValue("name")
|
||||
var req sourceRequest
|
||||
if err := httpjson.Read(r, &req); err != nil {
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if !validName.MatchString(name) || !validName.MatchString(req.Connector) {
|
||||
httpjson.Error(w, http.StatusBadRequest, "a source needs a lowercase name and a connector")
|
||||
return
|
||||
}
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
httpjson.Error(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
if err := m.store.UpsertSource(r.Context(), store.Source{
|
||||
OrgID: m.orgID, Name: name, Connector: req.Connector, TokenSHA256: httpjson.TokenHash(token),
|
||||
}); err != nil {
|
||||
httpjson.Error(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
httpjson.Write(w, http.StatusOK, map[string]string{"source": name, "token": token, "url": "/hooks/" + name})
|
||||
}
|
||||
|
||||
type triggerRequest struct {
|
||||
Source string `json:"source"`
|
||||
EventType string `json:"event_type"`
|
||||
Filter map[string]string `json:"filter"`
|
||||
Workflow string `json:"workflow"`
|
||||
Disabled bool `json:"disabled"`
|
||||
}
|
||||
|
||||
func (m *Module) putTrigger(w http.ResponseWriter, r *http.Request) {
|
||||
name := r.PathValue("name")
|
||||
var req triggerRequest
|
||||
if err := httpjson.Read(r, &req); err != nil {
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if !validName.MatchString(name) || req.Source == "" || req.EventType == "" || req.Workflow == "" {
|
||||
httpjson.Error(w, http.StatusBadRequest, "a trigger needs a lowercase name, a source, an event type and a workflow")
|
||||
return
|
||||
}
|
||||
filter, err := json.Marshal(req.Filter)
|
||||
if err != nil {
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if err := m.store.UpsertTrigger(r.Context(), store.Trigger{
|
||||
OrgID: m.orgID, Name: name, Source: req.Source, EventType: req.EventType,
|
||||
Filter: filter, Workflow: req.Workflow, Enabled: !req.Disabled,
|
||||
}); err != nil {
|
||||
httpjson.Error(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
httpjson.Write(w, http.StatusOK, map[string]string{"trigger": name})
|
||||
}
|
||||
|
||||
func (m *Module) recent(w http.ResponseWriter, r *http.Request) {
|
||||
limit := 50
|
||||
if n, err := strconv.Atoi(r.URL.Query().Get("limit")); err == nil && n > 0 && n <= 500 {
|
||||
limit = n
|
||||
}
|
||||
events, err := m.store.Recent(r.Context(), m.orgID, limit)
|
||||
if err != nil {
|
||||
httpjson.Error(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
httpjson.Write(w, http.StatusOK, events)
|
||||
}
|
||||
|
||||
func newToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("generate token: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Package match decides whether an event's fields satisfy a trigger's filter.
|
||||
package match
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Fields reports whether every filter entry equals the event field at its
|
||||
// dotted path ("labels.alertname"). An empty filter matches every event.
|
||||
func Fields(fields json.RawMessage, filter map[string]string) bool {
|
||||
if len(filter) == 0 {
|
||||
return true
|
||||
}
|
||||
var doc any
|
||||
if err := json.Unmarshal(fields, &doc); err != nil {
|
||||
return false
|
||||
}
|
||||
for path, want := range filter {
|
||||
got, ok := lookup(doc, strings.Split(path, "."))
|
||||
if !ok || got != want {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func lookup(doc any, path []string) (string, bool) {
|
||||
for _, key := range path {
|
||||
obj, ok := doc.(map[string]any)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
if doc, ok = obj[key]; !ok {
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
switch v := doc.(type) {
|
||||
case string:
|
||||
return v, true
|
||||
case float64, bool:
|
||||
return fmt.Sprint(v), true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
// 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"
|
||||
"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")
|
||||
|
||||
// Source is a named place events come from, read by one connector.
|
||||
type Source struct {
|
||||
OrgID string `db:"org_id"`
|
||||
Name string `db:"name"`
|
||||
Connector string `db:"connector"`
|
||||
TokenSHA256 string `db:"token_sha256"`
|
||||
}
|
||||
|
||||
// Event is one stored event.
|
||||
type Event struct {
|
||||
ID uuid.UUID `db:"id"`
|
||||
OrgID string `db:"org_id"`
|
||||
Source string `db:"source"`
|
||||
Type string `db:"type"`
|
||||
SourceEventID string `db:"source_event_id"`
|
||||
LinkKey sql.NullString `db:"link_key"`
|
||||
LinkedTo *uuid.UUID `db:"linked_to"`
|
||||
Fields json.RawMessage `db:"fields"`
|
||||
OccurredAt sql.NullTime `db:"occurred_at"`
|
||||
ReceivedAt time.Time `db:"received_at"`
|
||||
Matched bool `db:"matched"`
|
||||
DispatchedAt sql.NullTime `db:"dispatched_at"`
|
||||
}
|
||||
|
||||
// Trigger starts a workflow for events of one type from one source whose
|
||||
// fields match its filter.
|
||||
type Trigger struct {
|
||||
OrgID string `db:"org_id"`
|
||||
Name string `db:"name"`
|
||||
Source string `db:"source"`
|
||||
EventType string `db:"event_type"`
|
||||
Filter json.RawMessage `db:"filter"`
|
||||
Workflow string `db:"workflow"`
|
||||
Enabled bool `db:"enabled"`
|
||||
}
|
||||
|
||||
// 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} }
|
||||
|
||||
// Source returns the named source.
|
||||
func (s *Store) Source(ctx context.Context, orgID, name string) (Source, error) {
|
||||
var src Source
|
||||
err := s.db.GetContext(ctx, &src, `
|
||||
SELECT org_id, name, connector, token_sha256 FROM events.sources
|
||||
WHERE org_id = $1 AND name = $2`, orgID, name)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Source{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return Source{}, fmt.Errorf("read source: %w", err)
|
||||
}
|
||||
return src, nil
|
||||
}
|
||||
|
||||
// UpsertSource creates a source or replaces its connector and token.
|
||||
func (s *Store) UpsertSource(ctx context.Context, src Source) error {
|
||||
if _, err := s.db.NamedExecContext(ctx, `
|
||||
INSERT INTO events.sources (org_id, name, connector, token_sha256)
|
||||
VALUES (:org_id, :name, :connector, :token_sha256)
|
||||
ON CONFLICT (org_id, name) DO UPDATE
|
||||
SET connector = EXCLUDED.connector, token_sha256 = EXCLUDED.token_sha256, updated_at = now()`, src); err != nil {
|
||||
return fmt.Errorf("save source: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Insert stores an event unless its source already delivered the same source
|
||||
// event id. 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, type, source_event_id, link_key, fields, occurred_at)
|
||||
VALUES (:id, :org_id, :source, :type, :source_event_id, :link_key, :fields, :occurred_at)
|
||||
ON CONFLICT (org_id, source, source_event_id) 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, type, source_event_id, link_key, linked_to, fields, occurred_at,
|
||||
received_at, matched, dispatched_at
|
||||
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 = $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.Source, e.LinkKey.String, e.ReceivedAt)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("link event: %w", err)
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
return n == 1, err
|
||||
}
|
||||
|
||||
// Triggers returns the enabled triggers for one source and event type.
|
||||
func Triggers(ctx context.Context, tx *sqlx.Tx, orgID, source, eventType string) ([]Trigger, error) {
|
||||
var out []Trigger
|
||||
if err := tx.SelectContext(ctx, &out, `
|
||||
SELECT org_id, name, source, event_type, filter, workflow, enabled FROM events.triggers
|
||||
WHERE org_id = $1 AND source = $2 AND event_type = $3 AND enabled ORDER BY name`,
|
||||
orgID, source, eventType); err != nil {
|
||||
return nil, fmt.Errorf("read triggers: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// RecordDispatch notes that trigger started run for an event.
|
||||
func RecordDispatch(ctx context.Context, tx *sqlx.Tx, eventID uuid.UUID, trigger string, runID uuid.UUID) error {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO events.dispatches (event_id, trigger, run_id) VALUES ($1, $2, $3)
|
||||
ON CONFLICT (event_id, trigger) DO NOTHING`, eventID, trigger, runID); err != nil {
|
||||
return fmt.Errorf("record dispatch: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpsertTrigger creates or replaces a trigger.
|
||||
func (s *Store) UpsertTrigger(ctx context.Context, t Trigger) error {
|
||||
if _, err := s.db.NamedExecContext(ctx, `
|
||||
INSERT INTO events.triggers (org_id, name, source, event_type, filter, workflow, enabled)
|
||||
VALUES (:org_id, :name, :source, :event_type, :filter, :workflow, :enabled)
|
||||
ON CONFLICT (org_id, name) DO UPDATE
|
||||
SET source = EXCLUDED.source, event_type = EXCLUDED.event_type, filter = EXCLUDED.filter,
|
||||
workflow = EXCLUDED.workflow, enabled = EXCLUDED.enabled, updated_at = now()`, t); err != nil {
|
||||
return fmt.Errorf("save trigger: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Recent returns an organisation's newest events.
|
||||
func (s *Store) Recent(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, link_key, linked_to, fields, occurred_at,
|
||||
received_at, matched, dispatched_at
|
||||
FROM events.events WHERE org_id = $1 ORDER BY received_at DESC LIMIT $2`, orgID, limit); err != nil {
|
||||
return nil, fmt.Errorf("list events: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
Reference in new issue
Block a user