feat(connectors,deliveries,events): channels are connectors that deliver and listen; messages retry from their rows, and answers arrive as events (archie #1984, #1985)

This commit is contained in:
sam committed 2026-11-16 04:22:52 +11:00
1 parent 3a700cddfa
commit 7903a0e225
13 files changed
+975 -128

No files matched your search

+12 -4
View File
@@ -182,11 +182,19 @@ func (m *Module) Answer(ctx context.Context, id uuid.UUID, by, via string, appro
return requestOf(row, judgement.Decision{}), nil
}
// Settle answers a request on one of the channels that carries it, which is
// what a Telegram tap calls. It reports only whether the answer was taken.
func (m *Module) Settle(ctx context.Context, id uuid.UUID, by, via string, approved bool) error {
// Settle answers a request from an answer a channel delivered as an event. An
// answer that can't settle it, because it was already answered, has expired
// or names no request, reports false rather than an error: retrying the event
// would never change that.
func (m *Module) Settle(ctx context.Context, id uuid.UUID, by, via string, approved bool) (bool, error) {
_, err := m.Answer(ctx, id, by, via, approved)
return err
switch {
case err == nil:
return true, nil
case errors.Is(err, ErrAnswered), errors.Is(err, ErrExpired), errors.Is(err, ErrNotFound):
return false, nil
}
return false, err
}
// Expire settles a request whose deadline passed, so the trail shows why it
+80 -12
View File
@@ -127,11 +127,15 @@ type Tool interface {
// Connector is a running connector and what it declared.
type Connector struct {
name string
client pb.ConnectorServiceClient
events map[string]*jsonschema.Resolved
actions map[string]action
lookups map[string]lookup
name string
client pb.ConnectorServiceClient
eventTypes map[string]*jsonschema.Resolved
actions map[string]action
lookups map[string]lookup
// deliveries are the messages and records it sends, never offered to an
// agent.
deliveries map[string]*jsonschema.Resolved
listens bool
}
// open configures a connector and reads its declaration.
@@ -148,9 +152,11 @@ func open(ctx context.Context, name string, client pb.ConnectorServiceClient, se
}
c := &Connector{
name: name, client: client,
events: map[string]*jsonschema.Resolved{},
actions: map[string]action{},
lookups: map[string]lookup{},
eventTypes: map[string]*jsonschema.Resolved{},
actions: map[string]action{},
lookups: map[string]lookup{},
deliveries: map[string]*jsonschema.Resolved{},
listens: desc.GetListens(),
}
return c, c.load(desc)
}
@@ -161,7 +167,7 @@ func (c *Connector) load(desc *pb.DescribeResponse) error {
if err != nil {
return fmt.Errorf("connector %q: event %q: %w", c.name, e.GetName(), err)
}
c.events[e.GetName()] = s
c.eventTypes[e.GetName()] = s
}
for _, a := range desc.GetActions() {
s, err := compile(a.GetInputSchema())
@@ -180,9 +186,66 @@ func (c *Connector) load(desc *pb.DescribeResponse) error {
}
c.lookups[l.GetName()] = lookup{input: s, description: l.GetDescription(), schema: schemaOrEmpty(l.GetInputSchema())}
}
for _, d := range desc.GetDeliveries() {
s, err := compile(d.GetInputSchema())
if err != nil {
return fmt.Errorf("connector %q: delivery %q: %w", c.name, d.GetName(), err)
}
c.deliveries[d.GetName()] = s
}
return nil
}
// Delivers reports whether the connector sends the named delivery.
func (c *Connector) Delivers(name string) bool {
_, ok := c.deliveries[name]
return ok
}
// Deliver sends one delivery, checked against its declared schema, and
// returns what the service called it.
func (c *Connector) Deliver(ctx context.Context, name string, input jsontext.Value, key string) (string, error) {
schema, ok := c.deliveries[name]
if !ok {
return "", fmt.Errorf("connector %q: delivery %q: %w", c.name, name, ErrUnknownName)
}
if err := validate(schema, input); err != nil {
return "", fmt.Errorf("connector %q: delivery %q: %w", c.name, name, err)
}
resp, err := c.client.Deliver(ctx, &pb.DeliverRequest{Delivery: name, Input: input, IdempotencyKey: key})
if err != nil {
return "", fmt.Errorf("connector %q: deliver %q: %w", c.name, name, err)
}
return resp.GetExternalId(), nil
}
// Listens reports whether the connector holds its own connection to a source
// and streams its events.
func (c *Connector) Listens() bool { return c.listens }
// Listen streams the connector's events from cursor on, handing each batch
// and the cursor after it to store. It returns when ctx ends, the stream
// breaks, or store fails; the caller listens again from its last cursor.
func (c *Connector) Listen(ctx context.Context, cursor string, store func(events []Event, cursor string) error) error {
stream, err := c.client.Listen(ctx, &pb.ListenRequest{Cursor: cursor})
if err != nil {
return fmt.Errorf("connector %q: listen: %w", c.name, err)
}
for {
resp, err := stream.Recv()
if err != nil {
return fmt.Errorf("connector %q: listen: %w", c.name, err)
}
events, err := c.events(resp.GetEvents())
if err != nil {
return err
}
if err := store(events, resp.GetCursor()); err != nil {
return err
}
}
}
// Declarations lists the connector's lookups and actions in name order.
func (c *Connector) Declarations() []Declaration {
out := make([]Declaration, 0, len(c.lookups)+len(c.actions))
@@ -211,9 +274,14 @@ func (c *Connector) Parse(ctx context.Context, body []byte, headers map[string]s
if err != nil {
return nil, fmt.Errorf("connector %q: parse: %w", c.name, err)
}
events := make([]Event, 0, len(resp.GetEvents()))
for _, e := range resp.GetEvents() {
schema, ok := c.events[e.GetType()]
return c.events(resp.GetEvents())
}
// events checks each wire event against its declared schema.
func (c *Connector) events(wire []*pb.Event) ([]Event, error) {
events := make([]Event, 0, len(wire))
for _, e := range wire {
schema, ok := c.eventTypes[e.GetType()]
if !ok {
return nil, fmt.Errorf("connector %q: event type %q: %w", c.name, e.GetType(), ErrUnknownName)
}
+14
View File
@@ -121,6 +121,20 @@ func (m *Module) Tool(name string) (Tool, bool) {
return s, ok
}
// Delivering lists the running connectors that send the named delivery, in
// name order: the channels a message goes out on.
func (m *Module) Delivering(delivery string) []*Connector {
m.mu.RLock()
defer m.mu.RUnlock()
var out []*Connector
for _, name := range slices.Sorted(maps.Keys(m.running)) {
if c := m.running[name]; c.Delivers(delivery) {
out = append(out, c)
}
}
return out
}
// Declarations lists every running connector's lookups and actions and every
// MCP server's declared tools, ordered by name and then by tool name.
func (m *Module) Declarations() []Declaration {
+94 -10
View File
@@ -2,12 +2,15 @@
// channel. It holds no approval state: approvals own the request and its
// answer, and use deliveries to carry them. The composer, the chat box in the
// dashboard, is the first channel: its messages are rows a client reads from a
// cursor, with a live stream that only says when to read.
// cursor, with a live stream that only says when to read. Every accepted
// connector that delivers messages is another: each gets its own row, retried
// until the connector confirms it.
package deliveries
import (
"context"
"database/sql"
json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
@@ -20,6 +23,7 @@ import (
"github.com/samcharles93/archie-core/internal/platform/httpjson"
"github.com/samcharles93/archie-core/internal/platform/hub"
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/deliveries/internal/store"
)
@@ -28,6 +32,9 @@ const (
topicComposer = "composer"
pageSize = 100
heartbeat = 25 * time.Second
// deliveryMessage is the delivery a connector declares to carry messages.
deliveryMessage = "message"
maxBackoff = 10 * time.Minute
)
// The kinds of message a channel carries.
@@ -77,18 +84,26 @@ type Message struct {
CreatedAt time.Time `json:"created_at"`
}
// Channels are the running connectors a message can go out on.
type Channels interface {
Delivering(delivery string) []*connectors.Connector
Get(name string) (*connectors.Connector, bool)
}
// Module delivers one organisation's notifications.
type Module struct {
orgID string
store *store.Store
hub *hub.Hub
log *slog.Logger
orgID string
store *store.Store
hub *hub.Hub
channels Channels
log *slog.Logger
poll time.Duration
}
// NewModule returns the deliveries module for orgID, announcing new messages
// on h.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, h *hub.Hub) *Module {
return &Module{orgID: orgID, store: store.New(db), hub: h, log: log}
// on h and sending them on every connector in channels that delivers them.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, h *hub.Hub, channels Channels) *Module {
return &Module{orgID: orgID, store: store.New(db), hub: h, channels: channels, log: log, poll: time.Second}
}
// Notify delivers n on every channel. Delivering the same key again changes
@@ -126,9 +141,10 @@ func (m *Module) Told(ctx context.Context, a ApprovalRequest, answer string) err
})
}
// send writes msg to every channel and wakes the composer's readers.
// send writes msg to the composer, which wakes its readers, and queues it for
// every connector that delivers messages. Work sends the queued rows.
func (m *Module) send(ctx context.Context, msg store.Message) error {
msg.OrgID, msg.Channel = m.orgID, channelComposer
msg.OrgID, msg.Channel, msg.Sent = m.orgID, channelComposer, true
seq, created, err := m.store.Insert(ctx, msg)
if err != nil {
return err
@@ -136,9 +152,77 @@ func (m *Module) send(ctx context.Context, msg store.Message) error {
if created {
m.hub.Publish(hub.Note{Topic: topicComposer, Seq: seq})
}
for _, c := range m.channels.Delivering(deliveryMessage) {
// Each channel keeps its own row, so each carries its own id.
row := msg
row.ID, row.Channel, row.Sent = uuid.New(), c.Name(), false
if _, _, err := m.store.Insert(ctx, row); err != nil {
return err
}
}
return nil
}
// Work sends queued messages to their connectors until ctx ends. A failed send
// is tried again after a backoff that grows to maxBackoff, never dropped.
func (m *Module) Work(ctx context.Context) {
for ctx.Err() == nil {
msg, found, err := m.store.Claim(ctx, backoff)
if err != nil {
m.log.ErrorContext(ctx, "claim delivery", "error", err)
}
if found {
m.deliver(ctx, msg)
continue
}
select {
case <-ctx.Done():
case <-time.After(m.poll):
}
}
}
func (m *Module) deliver(ctx context.Context, msg store.Message) {
external, err := m.sendTo(ctx, msg)
if err != nil {
m.log.WarnContext(ctx, "delivery failed", "channel", msg.Channel, "message", msg.ID, "attempt", msg.Attempts, "error", err)
if err := m.store.Failed(ctx, msg.Seq, err.Error()); err != nil {
m.log.ErrorContext(ctx, "record failed delivery", "error", err)
}
return
}
if err := m.store.Sent(ctx, msg.Seq, external); err != nil {
m.log.ErrorContext(ctx, "record delivery", "error", err)
}
}
func (m *Module) sendTo(ctx context.Context, msg store.Message) (string, error) {
c, ok := m.channels.Get(msg.Channel)
if !ok {
return "", fmt.Errorf("connector %q isn't running", msg.Channel)
}
input := map[string]string{"title": msg.Title}
if msg.Body != "" {
input["body"] = msg.Body
}
if msg.Kind == KindApprovalRequest && msg.RequestID.Valid {
input["approval_request_id"] = msg.RequestID.UUID.String()
}
raw, err := json.Marshal(input)
if err != nil {
return "", err
}
return c.Deliver(ctx, deliveryMessage, raw, msg.Key)
}
// backoff is how long to wait after the attempts so far before the next.
func backoff(attempts int) time.Duration {
if attempts >= 10 {
return maxBackoff
}
return min(time.Duration(1<<attempts)*time.Second, maxBackoff)
}
// Routes adds the composer API to mux behind guard.
func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) {
mux.Handle("GET /api/composer/messages", guard(http.HandlerFunc(m.messages)))
+60 -3
View File
@@ -29,6 +29,10 @@ type Message struct {
RequestID uuid.NullUUID `db:"request_id"`
ExpiresAt sql.NullTime `db:"expires_at"`
CreatedAt time.Time `db:"created_at"`
// Sent is set on a message its channel has confirmed; the composer's are
// sent when they are stored.
Sent bool `db:"-"`
Attempts int `db:"attempts"`
}
// Store is the deliveries module's Postgres store.
@@ -44,10 +48,10 @@ func New(db *sqlx.DB) *Store { return &Store{db: db} }
func (s *Store) Insert(ctx context.Context, m Message) (int64, bool, error) {
var seq int64
err := s.db.GetContext(ctx, &seq, `
INSERT INTO deliveries.messages (id, org_id, channel, kind, run_id, title, body, key, request_id, expires_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
INSERT INTO deliveries.messages (id, org_id, channel, kind, run_id, title, body, key, request_id, expires_at, sent_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, CASE WHEN $11 THEN now() END)
ON CONFLICT (org_id, channel, key) DO NOTHING
RETURNING seq`, m.ID, m.OrgID, m.Channel, m.Kind, m.RunID, m.Title, m.Body, m.Key, m.RequestID, m.ExpiresAt)
RETURNING seq`, m.ID, m.OrgID, m.Channel, m.Kind, m.RunID, m.Title, m.Body, m.Key, m.RequestID, m.ExpiresAt, m.Sent)
if errors.Is(err, sql.ErrNoRows) {
err = s.db.GetContext(ctx, &seq, `
SELECT seq FROM deliveries.messages WHERE org_id = $1 AND channel = $2 AND key = $3`,
@@ -88,3 +92,56 @@ func (s *Store) Latest(ctx context.Context, orgID, channel string, limit int) ([
}
return out, nil
}
// Claim takes the oldest message a channel hasn't confirmed whose next attempt
// is due, and pushes that attempt out by backoff first: the push is the lease,
// so a crash mid-delivery retries after it rather than never.
func (s *Store) Claim(ctx context.Context, backoff func(attempts int) time.Duration) (Message, bool, error) {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return Message{}, false, err
}
defer func() { _ = tx.Rollback() }()
var m Message
err = tx.GetContext(ctx, &m, `
SELECT seq, id, org_id, channel, kind, run_id, title, body, key, request_id, expires_at, created_at, attempts
FROM deliveries.messages
WHERE sent_at IS NULL AND next_attempt_at <= now()
ORDER BY seq LIMIT 1 FOR UPDATE SKIP LOCKED`)
if errors.Is(err, sql.ErrNoRows) {
return Message{}, false, nil
}
if err != nil {
return Message{}, false, fmt.Errorf("claim message: %w", err)
}
m.Attempts++
if _, err := tx.ExecContext(ctx, `
UPDATE deliveries.messages SET attempts = $2, next_attempt_at = now() + make_interval(secs => $3) WHERE seq = $1`,
m.Seq, m.Attempts, backoff(m.Attempts).Seconds()); err != nil {
return Message{}, false, fmt.Errorf("lease message: %w", err)
}
if err := tx.Commit(); err != nil {
return Message{}, false, fmt.Errorf("lease message: %w", err)
}
return m, true, nil
}
// Sent records that a channel confirmed a message.
func (s *Store) Sent(ctx context.Context, seq int64, externalID string) error {
if _, err := s.db.ExecContext(ctx, `
UPDATE deliveries.messages SET sent_at = now(), external_id = $2, last_error = NULL WHERE seq = $1`,
seq, externalID); err != nil {
return fmt.Errorf("mark message sent: %w", err)
}
return nil
}
// Failed records why an attempt failed; the lease already set when it is
// tried again.
func (s *Store) Failed(ctx context.Context, seq int64, reason string) error {
if _, err := s.db.ExecContext(ctx, `
UPDATE deliveries.messages SET last_error = $2 WHERE seq = $1`, seq, reason); err != nil {
return fmt.Errorf("record failed delivery: %w", err)
}
return nil
}
+113 -5
View File
@@ -1,7 +1,10 @@
// 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.
// 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 (
@@ -16,6 +19,7 @@ import (
"net/http"
"regexp"
"strconv"
"sync"
"time"
"github.com/google/uuid"
@@ -40,19 +44,32 @@ 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) *Module {
return &Module{orgID: orgID, store: store.New(db), connectors: c, runs: r, log: log, poll: time.Second}
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.
@@ -121,9 +138,18 @@ func (m *Module) save(ctx context.Context, source string, parsed []connectors.Ev
return stored, duplicates, nil
}
// Work dispatches stored events until ctx ends.
// 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 := time.Time{}
for ctx.Err() == nil {
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)
@@ -138,11 +164,93 @@ func (m *Module) Work(ctx context.Context) {
}
}
// 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
+23
View File
@@ -24,6 +24,8 @@ type Source struct {
Name string `db:"name"`
Connector string `db:"connector"`
TokenSHA256 string `db:"token_sha256"`
// Cursor is where a listening source resumes.
Cursor string `db:"cursor"`
}
// Event is one stored event.
@@ -77,6 +79,27 @@ func (s *Store) Source(ctx context.Context, orgID, name string) (Source, error)
return src, nil
}
// Sources returns every source of the organisation.
func (s *Store) Sources(ctx context.Context, orgID string) ([]Source, error) {
var out []Source
if err := s.db.SelectContext(ctx, &out, `
SELECT org_id, name, connector, token_sha256, cursor FROM events.sources
WHERE org_id = $1 ORDER BY name`, orgID); 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, name, cursor string) error {
if _, err := s.db.ExecContext(ctx, `
UPDATE events.sources SET cursor = $3, updated_at = now() WHERE org_id = $1 AND name = $2`,
orgID, name, cursor); err != nil {
return fmt.Errorf("save cursor: %w", err)
}
return 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, `