447 lines
15 KiB
Go
447 lines
15 KiB
Go
// 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 source whose connector holds its own connection
|
|
// (a chat long poll) streams its events instead, resuming from a stored
|
|
// cursor. A dispatcher then claims each new event, settles an approval it
|
|
// answers, links a resolve to what it resolves, and starts a run for every
|
|
// trigger it matches.
|
|
package events
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"database/sql"
|
|
"encoding/hex"
|
|
"encoding/json/jsontext"
|
|
json "encoding/json/v2"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"regexp"
|
|
"strconv"
|
|
"sync"
|
|
"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)
|
|
}
|
|
|
|
// Answers settles the approval requests answer events name.
|
|
type Answers interface {
|
|
Settle(ctx context.Context, id uuid.UUID, by, via string, approved bool) (bool, error)
|
|
}
|
|
|
|
// answerType is the event a channel emits when a person answers an approval
|
|
// request.
|
|
const answerType = "approval.answer"
|
|
|
|
// listenRetry is how long a listener waits after its stream breaks.
|
|
const listenRetry = 5 * time.Second
|
|
|
|
// Module hears events for one organisation.
|
|
type Module struct {
|
|
orgID string
|
|
store *store.Store
|
|
connectors Connectors
|
|
runs Runs
|
|
answers Answers
|
|
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, a Answers) *Module {
|
|
return &Module{orgID: orgID, store: store.New(db), connectors: c, runs: r, answers: a, 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 listens to every listening source and dispatches stored events until
|
|
// ctx ends.
|
|
func (m *Module) Work(ctx context.Context) {
|
|
var listeners sync.WaitGroup
|
|
defer listeners.Wait()
|
|
listening := map[string]bool{}
|
|
nextCheck, nextTick := time.Time{}, time.Time{}
|
|
for ctx.Err() == nil {
|
|
if now := time.Now(); now.After(nextTick) {
|
|
if err := m.tick(ctx, now); err != nil && ctx.Err() == nil {
|
|
m.log.ErrorContext(ctx, "fire schedules", "error", err)
|
|
}
|
|
nextTick = now.Add(scheduleCheck)
|
|
}
|
|
if time.Now().After(nextCheck) {
|
|
m.startListeners(ctx, &listeners, listening)
|
|
nextCheck = time.Now().Add(listenRetry)
|
|
}
|
|
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):
|
|
}
|
|
}
|
|
}
|
|
|
|
// startListeners starts one listener for each source whose connector listens
|
|
// and has none yet. A listener lives until ctx ends.
|
|
func (m *Module) startListeners(ctx context.Context, wg *sync.WaitGroup, listening map[string]bool) {
|
|
sources, err := m.store.Sources(ctx, m.orgID)
|
|
if err != nil {
|
|
m.log.ErrorContext(ctx, "list sources", "error", err)
|
|
return
|
|
}
|
|
for _, src := range sources {
|
|
conn, ok := m.connectors.Get(src.Connector)
|
|
if listening[src.Name] || !ok || !conn.Listens() {
|
|
continue
|
|
}
|
|
listening[src.Name] = true
|
|
wg.Go(func() { m.listen(ctx, src) })
|
|
}
|
|
}
|
|
|
|
// listen streams one source's events, storing each batch before its cursor,
|
|
// so a restart fetches again anything not yet stored and dedupe drops what
|
|
// was. A broken stream is opened again from the stored cursor.
|
|
func (m *Module) listen(ctx context.Context, src store.Source) {
|
|
cursor := src.Cursor
|
|
for ctx.Err() == nil {
|
|
conn, ok := m.connectors.Get(src.Connector)
|
|
var err error
|
|
if !ok {
|
|
err = fmt.Errorf("connector %q isn't running", src.Connector)
|
|
} else {
|
|
err = conn.Listen(ctx, cursor, func(events []connectors.Event, next string) error {
|
|
if _, _, err := m.save(ctx, src.Name, events); err != nil {
|
|
return err
|
|
}
|
|
if err := m.store.SetCursor(ctx, m.orgID, src.Name, next); err != nil {
|
|
return err
|
|
}
|
|
cursor = next
|
|
return nil
|
|
})
|
|
}
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
m.log.WarnContext(ctx, "listening stopped", "source", src.Name, "error", err)
|
|
select {
|
|
case <-ctx.Done():
|
|
case <-time.After(listenRetry):
|
|
}
|
|
}
|
|
}
|
|
|
|
// answer settles the approval request an answer event names. An answer that
|
|
// can't settle it is logged and done with: the request's own record already
|
|
// says why.
|
|
func (m *Module) answer(ctx context.Context, e store.Event) error {
|
|
var a struct {
|
|
RequestID uuid.UUID `json:"request_id"`
|
|
Approved bool `json:"approved"`
|
|
By string `json:"by"`
|
|
ByName string `json:"by_name"`
|
|
}
|
|
if err := json.Unmarshal(e.Fields, &a); err != nil {
|
|
m.log.WarnContext(ctx, "unreadable approval answer", "event", e.ID, "error", err)
|
|
return nil
|
|
}
|
|
by := a.By
|
|
if a.ByName != "" {
|
|
by = a.ByName + " (" + a.By + ")"
|
|
}
|
|
settled, err := m.answers.Settle(ctx, a.RequestID, by, e.Source, a.Approved)
|
|
if err != nil {
|
|
return fmt.Errorf("settle approval %s: %w", a.RequestID, err)
|
|
}
|
|
if !settled {
|
|
m.log.InfoContext(ctx, "approval answer changed nothing", "event", e.ID, "request", a.RequestID)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// 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()
|
|
if e.Type == answerType {
|
|
return false, m.answer(ctx, e)
|
|
}
|
|
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
|
|
}
|
|
|
|
// Origin returns the event and trigger that started a run.
|
|
func (m *Module) Origin(ctx context.Context, runID uuid.UUID) (runs.Origin, bool, error) {
|
|
o, ok, err := m.store.OriginOf(ctx, m.orgID, runID)
|
|
if err != nil || !ok {
|
|
return runs.Origin{}, ok, err
|
|
}
|
|
return runs.Origin{
|
|
EventID: o.EventID, Source: o.Source, Type: o.Type, Fields: o.Fields,
|
|
ReceivedAt: o.ReceivedAt, Trigger: o.Trigger, Filter: o.Filter,
|
|
}, true, nil
|
|
}
|
|
|
|
func runInput(e store.Event) jsontext.Value {
|
|
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 jsontext.Value("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"`
|
|
// Every makes the trigger fire on an interval ("1h") instead of on
|
|
// events; source and event_type are then fixed to the schedule's own.
|
|
Every string `json:"every"`
|
|
}
|
|
|
|
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
|
|
}
|
|
var every sql.NullInt64
|
|
if req.Every != "" {
|
|
d, err := time.ParseDuration(req.Every)
|
|
if err != nil || d < minInterval || d%time.Second != 0 {
|
|
httpjson.Error(w, http.StatusBadRequest, "every is a whole number of seconds of at least one minute, such as 1h")
|
|
return
|
|
}
|
|
every = sql.NullInt64{Int64: int64(d / time.Second), Valid: true}
|
|
req.Source, req.EventType = scheduleSource, scheduleType
|
|
// Every schedule's ticks share a source and type, so the filter keeps
|
|
// this trigger to its own.
|
|
req.Filter = map[string]string{"trigger": name}
|
|
}
|
|
if !validName.MatchString(name) || req.Source == "" || req.EventType == "" || req.Workflow == "" {
|
|
httpjson.Error(w, http.StatusBadRequest, "a trigger needs a lowercase name, a workflow, and either a source and event type or an every interval")
|
|
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, ScheduleEverySeconds: every,
|
|
}); 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
|
|
}
|
|
out := make([]eventView, 0, len(events))
|
|
for _, e := range events {
|
|
out = append(out, viewOf(e))
|
|
}
|
|
httpjson.Write(w, http.StatusOK, out)
|
|
}
|
|
|
|
// eventView is an event as the API returns it.
|
|
type eventView struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Source string `json:"source"`
|
|
Type string `json:"type"`
|
|
Fields jsontext.Value `json:"fields"`
|
|
LinkedTo *uuid.UUID `json:"linked_to,omitempty"`
|
|
OccurredAt *time.Time `json:"occurred_at,omitempty"`
|
|
ReceivedAt time.Time `json:"received_at"`
|
|
Matched bool `json:"matched"`
|
|
DispatchedAt *time.Time `json:"dispatched_at,omitempty"`
|
|
}
|
|
|
|
func viewOf(e store.Event) eventView {
|
|
v := eventView{
|
|
ID: e.ID, Source: e.Source, Type: e.Type, Fields: e.Fields, LinkedTo: e.LinkedTo,
|
|
ReceivedAt: e.ReceivedAt, Matched: e.Matched,
|
|
}
|
|
if e.OccurredAt.Valid {
|
|
v.OccurredAt = &e.OccurredAt.Time
|
|
}
|
|
if e.DispatchedAt.Valid {
|
|
v.DispatchedAt = &e.DispatchedAt.Time
|
|
}
|
|
return v
|
|
}
|
|
|
|
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
|
|
}
|