Merge branch 'worktree-agent-a62864fcfbdb43f5a' into pg/foundation

This commit is contained in:
sam committed 2026-09-24 19:34:44 +10:00
commit a377da6678
52 files changed
+2156 -785

No files matched your search

+14 -9
View File
@@ -21,7 +21,8 @@ machine** governing whether it is live.
type Binding struct {
ID, Name // identity
Matcher // { Source string } -- the webhook path segment, e.g. "sentry"
MappingID // which Mapping resolves payload fields
MappingID // which Mapping resolves payload fields; its event type is the binding's
Filter // optional CEL over the mapping's parameters
Workflow // registered workflow name to dispatch to
Version // bumped on every edit
Status // pending_approval | armed
@@ -34,19 +35,23 @@ them from the dashboard while the daemon runs, without a restart.
### Matching
`Matcher.Source` is the only predicate today: the path segment a sender
POSTs to (e.g. a webhook hitting `.../sentry` matches bindings with
`Matcher.Source == "sentry"`). The storage column is plain `TEXT`, so adding
predicates later is non-breaking -- extend `Matcher`, don't invent a second
matcher shape.
A binding applies to a capture when the capture arrived on `Matcher.Source`,
was identified as the event type its mapping belongs to, and passes its
`Filter` (`binding.CompileFilter`, checked against the mapping's parameters on
save). Any number of bindings may share a source; each dispatches a capture at
most once, claimed in `binding_dispatches` keyed by (binding, capture) before
its task is enqueued. An event signed with any armed binding's secret on the
source is authenticated.
### Mapping
`mapping.Resolve(fields, payload)` walks a captured JSON payload against a
list of typed `Field`s (name, JSON path, expected type), returning resolved
values plus a `[]Failure` for anything that didn't parse or type-match. This
is schema-by-example in practice: a mapping is authored by pointing at a
real captured payload in the dashboard, not by guessing a schema in advance.
values plus a `[]Failure` for anything that didn't parse or type-match. A
mapping belongs to an event type, and `mapping.CheckSchema` refuses a field
whose path or type the type's inferred schema lacks. Each capture a mapping
resolves at dispatch is counted once in `mapping_matches`, read back as
`MatchCount` and `LastMatchedAt`.
### Versioning
+1 -1
View File
@@ -22,7 +22,7 @@
"url": "/dev/architecture/bindings/",
"title": "Playbook bindings: model and threat model",
"section": "Architecture",
"body": "# Playbook bindings: model and threat model\n\n**Status:** Approved foundation (documents shipped code: `archie-core-t2db.1`\nthrough `.5`, `.7`, `.9`-`.15`)\n**Date:** 2026-09-03\n\nThis document covers the binding model and the intake threat model portion\nof `archie-core-t2db.6`. It does not cover the task-lifecycle provenance rule\n(`messaging-and-work-intake.md`'s \"Intake provenance\") or the operator\nwalkthrough -- that walkthrough remains an open piece of the same ticket.\n\n## What a binding is\n\nA `binding` (`internal/domain/binding.Binding`) ties four things together:\na **matcher** (which captured events it applies to), a **mapping**\n(`internal/domain/mapping.Mapping`, how fields are pulled out of a payload),\na **workflow** (which registered workflow runs on a match), and a **state\nmachine** governing whether it is live.\n\n```go\ntype Binding struct {\n ID, Name // identity\n Matcher // { Source string } -- the webhook path segment, e.g. \"sentry\"\n MappingID // which Mapping resolves payload fields\n Workflow // registered workflow name to dispatch to\n Version // bumped on every edit\n Status // pending_approval | armed\n Secret // HMAC-SHA256 shared secret, encrypted at rest, never returned by GET\n}\n```\n\nBindings live in the store (SQLite), not `config.toml` -- operators author\nthem from the dashboard while the daemon runs, without a restart.\n\n### Matching\n\n`Matcher.Source` is the only predicate today: the path segment a sender\nPOSTs to (e.g. a webhook hitting `.../sentry` matches bindings with\n`Matcher.Source == \"sentry\"`). The storage column is plain `TEXT`, so adding\npredicates later is non-breaking -- extend `Matcher`, don't invent a second\nmatcher shape.\n\n### Mapping\n\n`mapping.Resolve(fields, payload)` walks a captured JSON payload against a\nlist of typed `Field`s (name, JSON path, expected type), returning resolved\nvalues plus a `[]Failure` for anything that didn't parse or type-match. This\nis schema-by-example in practice: a mapping is authored by pointing at a\nreal captured payload in the dashboard, not by guessing a schema in advance.\n\n### Versioning\n\n`Version` increments on every `UpdateBinding` call. This exists so an\neditor's later change can never silently rewrite the historical provenance\nof a task that already fired -- a dispatched task's binding reference is\npinned to the version that was armed when it fired, not \"whatever the\nbinding currently says.\"\n\n### State machine\n\n```\ncreate ---\u003e pending_approval ---\u003e armed\n ^ |\n +----------------+\n (any edit to an armed binding drops it back to pending_approval)\n```\n\nA binding is created `pending_approval`, so the operator who creates one can\napprove it immediately. Bindings stored as `draft` by an earlier version are\nmoved to `pending_approval` when the EDA store opens.\n\nModeled directly on Telegram's existing `dangerousAction`/`pendingApproval`\nflow (`internal/channels/telegram/dangerous.go`, `approval.go`) -- not a new\napproval mechanism invented for this feature. **Only `armed` evaluates\nagainst incoming events** (`binding.Matches`, `internal/domain/binding/\nbinding.go`); a `pending_approval` binding is inert. An edit to\nan already-armed binding cannot bypass approval by silent mutation -- it\ndrops back to `pending_approval` and requires an explicit `Approve` call to\nre-arm.\n\n## The threat model\n\nThis is a public, unauthenticated-by-default intake surface whose output is\nan agent with a repo, a worktree, and tool access. The design brief\n(`archie-core-t2db.5`, `docs/prds/webhook-intake-security.md`) named five\nnon-negotiables; each is verified below against the actual shipped code,\nnot the design intent.\n\n### 1. Per-source authentication\n\nReuses `internal/channels/webhook`'s existing HMAC-SHA256 scheme --\ncapture accepts unsigned events (visible in the dashboard, marked\nunauthenticated), but **only authenticated events can ever match a\nbinding**. `binding.Matches`' doc comment states this plainly: \"an\nunauthenticated event can never trigger a binding, no matter how well it\nwould otherwise match.\" Enforced structurally at two points, not just\nconvention:\n\n- `captured_events.authenticated` is a real column (`internal/store/\n captures.go`), set at capture time.\n- `dispatchBindings` (`internal/daemon/daemon.go:479`) walks **authenticated\n captures whose source has at least one armed binding** -- an\n unauthenticated capture is never even considered for dispatch.\n\n### 2. Human approval before a binding goes live\n\nCovered by the state machine above. Nothing self-arms: `pending_approval -\u003e\narmed` requires an explicit `Approve` call, and any edit to an armed\nbinding reverts it.\n\n### 3. Rate and volume limits per source\n\nCapture writes are bounded independentlyLine truncated
"body": "# Playbook bindings: model and threat model\n\n**Status:** Approved foundation (documents shipped code: `archie-core-t2db.1`\nthrough `.5`, `.7`, `.9`-`.15`)\n**Date:** 2026-09-03\n\nThis document covers the binding model and the intake threat model portion\nof `archie-core-t2db.6`. It does not cover the task-lifecycle provenance rule\n(`messaging-and-work-intake.md`'s \"Intake provenance\") or the operator\nwalkthrough -- that walkthrough remains an open piece of the same ticket.\n\n## What a binding is\n\nA `binding` (`internal/domain/binding.Binding`) ties four things together:\na **matcher** (which captured events it applies to), a **mapping**\n(`internal/domain/mapping.Mapping`, how fields are pulled out of a payload),\na **workflow** (which registered workflow runs on a match), and a **state\nmachine** governing whether it is live.\n\n```go\ntype Binding struct {\n ID, Name // identity\n Matcher // { Source string } -- the webhook path segment, e.g. \"sentry\"\n MappingID // which Mapping resolves payload fields; its event type is the binding's\n Filter // optional CEL over the mapping's parameters\n Workflow // registered workflow name to dispatch to\n Version // bumped on every edit\n Status // pending_approval | armed\n Secret // HMAC-SHA256 shared secret, encrypted at rest, never returned by GET\n}\n```\n\nBindings live in the store (SQLite), not `config.toml` -- operators author\nthem from the dashboard while the daemon runs, without a restart.\n\n### Matching\n\nA binding applies to a capture when the capture arrived on `Matcher.Source`,\nwas identified as the event type its mapping belongs to, and passes its\n`Filter` (`binding.CompileFilter`, checked against the mapping's parameters on\nsave). Any number of bindings may share a source; each dispatches a capture at\nmost once, claimed in `binding_dispatches` keyed by (binding, capture) before\nits task is enqueued. An event signed with any armed binding's secret on the\nsource is authenticated.\n\n### Mapping\n\n`mapping.Resolve(fields, payload)` walks a captured JSON payload against a\nlist of typed `Field`s (name, JSON path, expected type), returning resolved\nvalues plus a `[]Failure` for anything that didn't parse or type-match. A\nmapping belongs to an event type, and `mapping.CheckSchema` refuses a field\nwhose path or type the type's inferred schema lacks. Each capture a mapping\nresolves at dispatch is counted once in `mapping_matches`, read back as\n`MatchCount` and `LastMatchedAt`.\n\n### Versioning\n\n`Version` increments on every `UpdateBinding` call. This exists so an\neditor's later change can never silently rewrite the historical provenance\nof a task that already fired -- a dispatched task's binding reference is\npinned to the version that was armed when it fired, not \"whatever the\nbinding currently says.\"\n\n### State machine\n\n```\ncreate ---\u003e pending_approval ---\u003e armed\n ^ |\n +----------------+\n (any edit to an armed binding drops it back to pending_approval)\n```\n\nA binding is created `pending_approval`, so the operator who creates one can\napprove it immediately. Bindings stored as `draft` by an earlier version are\nmoved to `pending_approval` when the EDA store opens.\n\nModeled directly on Telegram's existing `dangerousAction`/`pendingApproval`\nflow (`internal/channels/telegram/dangerous.go`, `approval.go`) -- not a new\napproval mechanism invented for this feature. **Only `armed` evaluates\nagainst incoming events** (`binding.Matches`, `internal/domain/binding/\nbinding.go`); a `pending_approval` binding is inert. An edit to\nan already-armed binding cannot bypass approval by silent mutation -- it\ndrops back to `pending_approval` and requires an explicit `Approve` call to\nre-arm.\n\n## The threat model\n\nThis is a public, unauthenticated-by-default intake surface whose output is\nan agent with a repo, a worktree, and tool access. The design brief\n(`archie-core-t2db.5`, `docs/prds/webhook-intake-security.md`) named five\nnon-negotiables; each is verified below against the actual shipped code,\nnot the design intent.\n\n### 1. Per-source authentication\n\nReuses `internal/channels/webhook`'s existing HMAC-SHA256 scheme --\ncapture accepts unsigned events (visible in the dashboard, marked\nunauthenticated), but **only authenticated events can ever match a\nbinding**. `binding.Matches`' doc comment states this plainly: \"an\nunauthenticated event can never trigger a binding, no matter how well it\nwould otherwise match.\" Enforced structurally at two points, not just\nconvention:\n\n- `captured_events.authenticated` is a real column (`internal/store/\n captures.go`), set at capture time.\n- `dispatchBindings` (`internal/daemon/daemon.go:479`) walks **authenticated\n captures whose source has at least one armed bindingLine truncated
},
{
"url": "/dev/architecture/configuration/",
+3
View File
@@ -1349,6 +1349,9 @@ func (b *boot) buildDaemon() {
if bd, ok := b.stateStore.(storecontract.BindingDispatcher); ok {
b.d.BindingDispatcher = bd
}
if mm, ok := b.stateStore.(storecontract.MappingMatchRecorder); ok {
b.d.MappingMatches = mm
}
if btc, ok := b.stateStore.(storecontract.BindingTaskCreator); ok {
b.d.BindingTaskCreator = btc
}
+1
View File
@@ -256,6 +256,7 @@ func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
deps.PlaybookDispatcher = b.eda
deps.EventTypes = b.eda
deps.Sources = b.eda
deps.MappingMatches = b.eda
}
// tool_call events project into the tool_calls collection on the same
// event-capture store: this process legitimately owns both, so the
+2 -1
View File
@@ -8,11 +8,12 @@ import (
// eventCaptureStore is every surface the State Store serves from the
// event-capture tables, plus the tool_call projection it writes through.
type eventCaptureStore interface {
type eventCaptureStore interface { //nolint:interfacebloat // composite of the store contracts the event-capture tables serve
storecontract.CaptureStore
storecontract.MappingStore
storecontract.BindingStore
storecontract.BindingDispatcher
storecontract.MappingMatchRecorder
storecontract.PlaybookDispatcher
storecontract.EventTypeStore
storecontract.SourceStore
File diff suppressed because it is too large. Load diff
@@ -73,6 +73,7 @@ const (
StateStoreService_ListMappings_FullMethodName = "/state.v1.StateStoreService/ListMappings"
StateStoreService_UpdateMapping_FullMethodName = "/state.v1.StateStoreService/UpdateMapping"
StateStoreService_DeleteMapping_FullMethodName = "/state.v1.StateStoreService/DeleteMapping"
StateStoreService_RecordMappingMatch_FullMethodName = "/state.v1.StateStoreService/RecordMappingMatch"
StateStoreService_InsertEventType_FullMethodName = "/state.v1.StateStoreService/InsertEventType"
StateStoreService_UpdateEventType_FullMethodName = "/state.v1.StateStoreService/UpdateEventType"
StateStoreService_DeleteEventType_FullMethodName = "/state.v1.StateStoreService/DeleteEventType"
@@ -206,6 +207,9 @@ type StateStoreServiceClient interface {
ListMappings(ctx context.Context, in *ListMappingsRequest, opts ...grpc.CallOption) (*ListMappingsResponse, error)
UpdateMapping(ctx context.Context, in *UpdateMappingRequest, opts ...grpc.CallOption) (*UpdateMappingResponse, error)
DeleteMapping(ctx context.Context, in *DeleteMappingRequest, opts ...grpc.CallOption) (*DeleteMappingResponse, error)
// RecordMappingMatch counts one event a mapping resolved; the same
// (mapping, capture) twice counts once.
RecordMappingMatch(ctx context.Context, in *RecordMappingMatchRequest, opts ...grpc.CallOption) (*RecordMappingMatchResponse, error)
// EventType (docs/prds/event-automation.md, "Event types"). Insert and
// Update refuse an overlapping or malformed type.
InsertEventType(ctx context.Context, in *InsertEventTypeRequest, opts ...grpc.CallOption) (*InsertEventTypeResponse, error)
@@ -811,6 +815,16 @@ func (c *stateStoreServiceClient) DeleteMapping(ctx context.Context, in *DeleteM
return out, nil
}
func (c *stateStoreServiceClient) RecordMappingMatch(ctx context.Context, in *RecordMappingMatchRequest, opts ...grpc.CallOption) (*RecordMappingMatchResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RecordMappingMatchResponse)
err := c.cc.Invoke(ctx, StateStoreService_RecordMappingMatch_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) InsertEventType(ctx context.Context, in *InsertEventTypeRequest, opts ...grpc.CallOption) (*InsertEventTypeResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(InsertEventTypeResponse)
@@ -1150,6 +1164,9 @@ type StateStoreServiceServer interface {
ListMappings(context.Context, *ListMappingsRequest) (*ListMappingsResponse, error)
UpdateMapping(context.Context, *UpdateMappingRequest) (*UpdateMappingResponse, error)
DeleteMapping(context.Context, *DeleteMappingRequest) (*DeleteMappingResponse, error)
// RecordMappingMatch counts one event a mapping resolved; the same
// (mapping, capture) twice counts once.
RecordMappingMatch(context.Context, *RecordMappingMatchRequest) (*RecordMappingMatchResponse, error)
// EventType (docs/prds/event-automation.md, "Event types"). Insert and
// Update refuse an overlapping or malformed type.
InsertEventType(context.Context, *InsertEventTypeRequest) (*InsertEventTypeResponse, error)
@@ -1358,6 +1375,9 @@ func (UnimplementedStateStoreServiceServer) UpdateMapping(context.Context, *Upda
func (UnimplementedStateStoreServiceServer) DeleteMapping(context.Context, *DeleteMappingRequest) (*DeleteMappingResponse, error) {
return nil, status.Error(codes.Unimplemented, "method DeleteMapping not implemented")
}
func (UnimplementedStateStoreServiceServer) RecordMappingMatch(context.Context, *RecordMappingMatchRequest) (*RecordMappingMatchResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RecordMappingMatch not implemented")
}
func (UnimplementedStateStoreServiceServer) InsertEventType(context.Context, *InsertEventTypeRequest) (*InsertEventTypeResponse, error) {
return nil, status.Error(codes.Unimplemented, "method InsertEventType not implemented")
}
@@ -2403,6 +2423,24 @@ func _StateStoreService_DeleteMapping_Handler(srv interface{}, ctx context.Conte
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_RecordMappingMatch_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RecordMappingMatchRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).RecordMappingMatch(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_RecordMappingMatch_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).RecordMappingMatch(ctx, req.(*RecordMappingMatchRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_InsertEventType_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(InsertEventTypeRequest)
if err := dec(in); err != nil {
@@ -3007,6 +3045,10 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
MethodName: "DeleteMapping",
Handler: _StateStoreService_DeleteMapping_Handler,
},
{
MethodName: "RecordMappingMatch",
Handler: _StateStoreService_RecordMappingMatch_Handler,
},
{
MethodName: "InsertEventType",
Handler: _StateStoreService_InsertEventType_Handler,
+65 -57
View File
@@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"log/slog"
"maps"
"os"
"strings"
"sync"
@@ -120,6 +121,9 @@ type Daemon struct {
// BindingStore to keep the CRUD interface under the interfacebloat
// limit. Optional: nil disables the dispatch loop.
BindingDispatcher storecontract.BindingDispatcher
// MappingMatches counts each event a mapping resolved at dispatch.
// Optional: nil leaves match counts unrecorded.
MappingMatches storecontract.MappingMatchRecorder
// BindingTaskCreator enqueues a task triggered by a binding. Split
// off TaskLifecycle so the lifecycle surface stays narrow and the
// dispatch loop does not acquire the full task-creation contract.
@@ -611,30 +615,18 @@ func (d *Daemon) cleanupExpiredStorage(ctx context.Context) {
// single cycle's worst-case latency on a backlog.
const bindingDispatchBatchLimit = 100
// dispatchBindings walks dispatchable captures whose source has at
// least one armed binding, evaluates each binding's matcher against
// the capture, resolves fields through the binding's mapping, and
// enqueues a task per matched (binding, capture) pair.
// dispatchBindings walks identified captures on sources with an armed
// binding and offers each capture to every armed binding on its source.
// Each binding dispatches it at most once (dispatchOneBinding).
//
// The binding_dispatches ledger is the at-most-once guarantee across
// cycles and daemon restarts: RecordDispatch returns
// storecontract.ErrAlreadyDispatched on a duplicate (binding_id, capture_id)
// pair, and dispatchOneBinding treats that as a normal "another cycle
// raced us" outcome rather than an error.
//
// Nil Bindings, BindingDispatcher or BindingTaskCreator disables the
// loop (legacy behaviour: daemons built before t2db.4 Phase E had no
// playbook bindings, and each field's own doc comment promises this
// degrade-not-panic contract independently).
// Nil Bindings, BindingDispatcher or BindingTaskCreator disables the loop.
func (d *Daemon) dispatchBindings(ctx context.Context) {
if d.Bindings == nil || d.BindingDispatcher == nil || d.BindingTaskCreator == nil {
return
}
// Gather armed sources first so the captures query filters down to
// only relevant rows -- the table-level view over captured_events
// is otherwise unbounded, and a backlog of unrelated sources
// should never be scanned on a cycle.
// only relevant rows.
bindings, err := d.Bindings.ListBindings(ctx)
if err != nil {
d.Log.Warn("list bindings failed", "error", err)
@@ -670,45 +662,54 @@ func (d *Daemon) dispatchBindings(ctx context.Context) {
}
}
// dispatchOneBinding handles a single (binding, capture) match: resolve
// fields through the binding's mapping, enqueue a task, and record the
// dispatch in the dedup ledger. Each step degrades independently --
// a mapping lookup failure logs and returns, a required-field
// resolution failure records a binding_dispatch_failure event and
// returns without enqueueing, an enqueue failure logs and returns, and
// a RecordDispatch returning ErrAlreadyDispatched is treated as a
// benign race winner (another cycle already created the task).
//
// Owner/repo resolution currently falls back to the single configured
// repo (when exactly one is configured); binding.Owner/Repo is a
// follow-up so multi-repo deployments don't have to live with the
// ambiguity.
func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c storecontract.CapturedEvent) {
// bindingMapping returns b's mapping, or nil after logging why it is
// unavailable.
func (d *Daemon) bindingMapping(ctx context.Context, b binding.Binding) *mapping.Mapping {
if d.Mappings == nil {
d.Log.Warn("binding dispatch: mapping store unavailable", "binding", b.ID)
return
return nil
}
m, err := d.Mappings.GetMapping(ctx, b.MappingID)
if err != nil {
d.Log.Warn("binding dispatch: get mapping", "binding", b.ID, "mapping", b.MappingID, "error", err)
return
return nil
}
if m == nil {
d.Log.Warn("binding dispatch: mapping missing", "binding", b.ID, "mapping", b.MappingID)
}
return m
}
// dispatchOneBinding offers one capture to one binding. The binding applies
// when its mapping belongs to the capture's event type. The mapping resolves
// the payload (a required-field failure records binding_dispatch_failure and
// stops), counts the match, and the binding's filter must admit the resolved
// parameters. The dispatch is then claimed in the binding_dispatches ledger
// before the task is enqueued: a capture stays listed until every binding for
// its event type has dispatched it, so the claim is what stops a binding that
// already fired from firing again on a later cycle. A failed enqueue after the
// claim loses that dispatch, which is the at-most-once side of the trade.
func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c storecontract.CapturedEvent) {
m := d.bindingMapping(ctx, b)
if m == nil || m.EventTypeID != c.EventType {
return
}
values, failures := mapping.Resolve(m.Fields, []byte(c.Body))
if hasBlockingFailure(m.Fields, failures) {
_, _ = d.Store.InsertEvent(ctx, events.Event{
Kind: "binding_dispatch_failure",
Detail: fmt.Sprintf("binding %q (capture %q): required field failed", b.ID, c.ID),
Data: map[string]any{
"binding_id": b.ID,
"binding_version": b.Version,
"capture_id": c.ID,
"failures": failures,
},
})
d.recordDispatchFailure(ctx, b, c, "required field failed", map[string]any{"failures": failures})
return
}
if d.MappingMatches != nil {
if err := d.MappingMatches.RecordMappingMatch(ctx, m.ID, c.ID); err != nil {
d.Log.Warn("binding dispatch: record mapping match", "mapping", m.ID, "capture", c.ID, "error", err)
}
}
filter, err := binding.CompileFilter(b.Filter, m.Fields)
if err != nil {
d.recordDispatchFailure(ctx, b, c, "filter does not compile", map[string]any{"error": err.Error()})
return
}
if admitted, _ := filter.Admits(values); !admitted {
return
}
@@ -716,27 +717,19 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st
if !ok {
return // resolveBindingRepo already logged a warning
}
if err := d.BindingDispatcher.RecordDispatch(ctx, b.ID, int64(b.Version), c.ID, 0); err != nil {
if !errors.Is(err, storecontract.ErrAlreadyDispatched) {
d.Log.Warn("binding dispatch: record", "binding", b.ID, "capture", c.ID, "error", err)
}
return
}
title := fmt.Sprintf("binding %s/%d from %s", b.Name, b.Version, c.Source)
body := renderBindingBody(values, c)
task, err := d.BindingTaskCreator.EnqueueBindingTask(ctx, owner, repo, title, body, b.Workflow, "", b.ID, b.Version)
if err != nil {
d.Log.Warn("binding dispatch: enqueue", "binding", b.ID, "capture", c.ID, "error", err)
return
}
if err := d.BindingDispatcher.RecordDispatch(ctx, b.ID, int64(b.Version), c.ID, task.ID); err != nil {
if errors.Is(err, storecontract.ErrAlreadyDispatched) {
// Another cycle or daemon instance raced us and already
// recorded the dispatch. The duplicate task remains
// queued (delete-on-races is its own can of worms),
// but the ledger prevents the same (binding, capture)
// pair from ever being dispatched again.
return
}
d.Log.Warn("binding dispatch: record", "binding", b.ID, "capture", c.ID, "error", err)
return
}
if c.Unsigned {
if _, err := d.Store.InsertEvent(ctx, events.Event{
TaskID: task.ID,
@@ -749,6 +742,21 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st
}
}
// recordDispatchFailure records why a binding did not dispatch a capture.
func (d *Daemon) recordDispatchFailure(ctx context.Context, b binding.Binding, c storecontract.CapturedEvent, reason string, extra map[string]any) {
data := map[string]any{
"binding_id": b.ID,
"binding_version": b.Version,
"capture_id": c.ID,
}
maps.Copy(data, extra)
_, _ = d.Store.InsertEvent(ctx, events.Event{
Kind: "binding_dispatch_failure",
Detail: fmt.Sprintf("binding %q (capture %q): %s", b.ID, c.ID, reason),
Data: data,
})
}
// hasBlockingFailure reports whether any of the failures belongs to a
// required field. The mapping package reports failures only by field
// name and reason -- the Field's Required flag is on the Field
+8 -15
View File
@@ -51,7 +51,7 @@ func TestDispatchBindingsCreatesTaskFromArmedCapture(t *testing.T) {
t.Errorf("task.Status = %q, want %q", got.Status, workflow.StatusQueued)
}
assertDispatchRecorded(t, s, bindingID, got.ID)
assertDispatchRecorded(t, s, bindingID)
}
// TestDispatchBindingsUsesBindingRepoPinWithMultipleConfiguredRepos is the
@@ -81,7 +81,7 @@ func TestDispatchBindingsUsesBindingRepoPinWithMultipleConfiguredRepos(t *testin
if tasks[0].Owner != "acme" || tasks[0].Repo != "widget" {
t.Fatalf("task owner/repo = %s/%s, want acme/widget (the binding's own pin, not a guess)", tasks[0].Owner, tasks[0].Repo)
}
assertDispatchRecorded(t, s, bindingID, tasks[0].ID)
assertDispatchRecorded(t, s, bindingID)
}
// TestDispatchBindingsRefusesUnpinnedBindingWithMultipleConfiguredRepos
@@ -411,23 +411,16 @@ func newDispatchDaemonWithRepos(t *testing.T, s *dispatchStores, repos []config.
}
}
// assertDispatchRecorded reads the dedup ledger directly: the
// (binding, capture) unique index is what guarantees no double
// dispatch. Going through the SQL table rather than the public
// BindingStore surface keeps the assertion focused on the contract
// Phase E actually writes to, not on a ListDispatches helper that
// may not exist.
func assertDispatchRecorded(t *testing.T, s *dispatchStores, bindingID string, taskID int64) {
// assertDispatchRecorded reads the dedup ledger directly: the (binding,
// capture) unique index is what guarantees no double dispatch. The dispatch
// is claimed before its task exists, so the row carries no task id.
func assertDispatchRecorded(t *testing.T, s *dispatchStores, bindingID string) {
t.Helper()
var gotBindingID string
var gotTaskID int64
if err := s.EdaStore.App().DB().NewQuery(
"SELECT binding, task_id FROM binding_dispatches WHERE binding = {:binding}").
"SELECT binding FROM binding_dispatches WHERE binding = {:binding}").
Bind(map[string]any{"binding": bindingID}).
Row(&gotBindingID, &gotTaskID); err != nil {
Row(&gotBindingID); err != nil {
t.Fatalf("binding_dispatches row missing: %v", err)
}
if gotBindingID != bindingID || gotTaskID != taskID {
t.Fatalf("binding_dispatches row = (%q, %d), want (%q, %d)", gotBindingID, gotTaskID, bindingID, taskID)
}
}
@@ -0,0 +1,176 @@
package daemon
import (
"context"
"log/slog"
"path/filepath"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/store"
)
// fakeEDA serves bindings, mappings and one capture from memory, and records
// dispatches and mapping matches the way the store's unique keys do.
type fakeEDA struct {
bindings []binding.Binding
mappings map[string]mapping.Mapping
captures []storecontract.CapturedEvent
dispatched map[[2]string]bool
matches map[[2]string]bool
}
func (f *fakeEDA) InsertMapping(context.Context, mapping.Mapping) (string, error) { return "", nil }
func (f *fakeEDA) GetMapping(_ context.Context, id string) (*mapping.Mapping, error) {
m, ok := f.mappings[id]
if !ok {
return nil, nil
}
return &m, nil
}
func (f *fakeEDA) ListMappings(context.Context) ([]mapping.Mapping, error) { return nil, nil }
func (f *fakeEDA) UpdateMapping(context.Context, mapping.Mapping) error { return nil }
func (f *fakeEDA) DeleteMapping(context.Context, string) error { return nil }
func (f *fakeEDA) InsertBinding(context.Context, binding.Binding) (string, error) { return "", nil }
func (f *fakeEDA) GetBinding(context.Context, string) (*binding.Binding, error) { return nil, nil }
func (f *fakeEDA) ListBindings(context.Context) ([]binding.Binding, error) { return f.bindings, nil }
func (f *fakeEDA) UpdateBinding(context.Context, binding.Binding) error { return nil }
func (f *fakeEDA) DeleteBinding(context.Context, string) error { return nil }
func (f *fakeEDA) ApproveBinding(context.Context, string) error { return nil }
func (f *fakeEDA) ArmedBindingsForSource(_ context.Context, source string) ([]binding.Binding, error) {
var out []binding.Binding
for _, b := range f.bindings {
if b.Status == binding.StatusArmed && b.Matcher.Source == source {
out = append(out, b)
}
}
return out, nil
}
func (f *fakeEDA) RecordDispatch(_ context.Context, bindingID string, _ int64, captureID string, _ int64) error {
key := [2]string{bindingID, captureID}
if f.dispatched[key] {
return storecontract.ErrAlreadyDispatched
}
f.dispatched[key] = true
return nil
}
func (f *fakeEDA) ListUndispatchedCaptures(context.Context, []string, int) ([]storecontract.CapturedEvent, error) {
return f.captures, nil
}
func (f *fakeEDA) RecordMappingMatch(_ context.Context, mappingID, captureID string) error {
f.matches[[2]string{mappingID, captureID}] = true
return nil
}
func armed(id, mappingID, filter string) binding.Binding {
return binding.Binding{
ID: id, Name: id, Matcher: binding.Matcher{Source: "fw"}, MappingID: mappingID,
Filter: filter, Workflow: "implement", Status: binding.StatusArmed, Version: 1,
}
}
func severityMapping(id, eventType string) mapping.Mapping {
return mapping.Mapping{
ID: id, Name: id, EventTypeID: eventType,
Fields: []mapping.Field{{Name: "severity", Path: "severity", Type: mapping.TypeString, Required: true}},
}
}
func TestDispatchPerBindingByEventTypeAndFilter(t *testing.T) {
capture := storecontract.CapturedEvent{
ID: "c1", Source: "fw", EventType: "blocked", Authenticated: true, Body: `{"severity":"high"}`,
}
tests := []struct {
name string
bindings []binding.Binding
mappings []mapping.Mapping
wantTasks []string
wantMatches [][2]string
}{
{
name: "several bindings on one source each dispatch once",
bindings: []binding.Binding{armed("a", "m", ""), armed("b", "m", "")},
mappings: []mapping.Mapping{severityMapping("m", "blocked")},
wantTasks: []string{"a", "b"},
wantMatches: [][2]string{{"m", "c1"}},
},
{
name: "a binding for another event type does not dispatch",
bindings: []binding.Binding{armed("a", "m", "")},
mappings: []mapping.Mapping{severityMapping("m", "allowed")},
},
{
name: "a filter that excludes the event does not dispatch it",
bindings: []binding.Binding{armed("a", "m", `severity == "low"`), armed("b", "m", `severity in ["high", "critical"]`)},
mappings: []mapping.Mapping{severityMapping("m", "blocked")},
wantTasks: []string{"b"},
wantMatches: [][2]string{{"m", "c1"}},
},
{
name: "a filter that does not compile does not dispatch",
bindings: []binding.Binding{armed("a", "m", `nope ==`)},
mappings: []mapping.Mapping{severityMapping("m", "blocked")},
// The mapping still resolved the event.
wantMatches: [][2]string{{"m", "c1"}},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "dispatch.db"))
if err != nil {
t.Fatalf("store.Open: %v", err)
}
t.Cleanup(func() { _ = st.Close() })
eda := &fakeEDA{
bindings: tt.bindings, mappings: map[string]mapping.Mapping{},
captures: []storecontract.CapturedEvent{capture},
dispatched: map[[2]string]bool{}, matches: map[[2]string]bool{},
}
for _, m := range tt.mappings {
eda.mappings[m.ID] = m
}
d := &Daemon{
Cfg: config.NewHolder(config.Config{Repos: []config.Repo{{Owner: "acme", Name: "widget"}}}),
Store: st, Mappings: eda, Bindings: eda, BindingDispatcher: eda, MappingMatches: eda,
BindingTaskCreator: st,
Log: slog.New(slog.DiscardHandler),
}
d.dispatchBindings(t.Context())
d.dispatchBindings(t.Context())
tasks, err := st.Tasks(t.Context(), 10)
if err != nil {
t.Fatalf("Tasks: %v", err)
}
got := map[string]int{}
for _, task := range tasks {
got[task.BindingID]++
}
if len(tasks) != len(tt.wantTasks) {
t.Fatalf("tasks by binding = %v, want one each for %v", got, tt.wantTasks)
}
for _, id := range tt.wantTasks {
if got[id] != 1 {
t.Fatalf("tasks by binding = %v, want one each for %v", got, tt.wantTasks)
}
}
if len(eda.matches) != len(tt.wantMatches) {
t.Fatalf("mapping matches = %v, want %v", eda.matches, tt.wantMatches)
}
for _, key := range tt.wantMatches {
if !eda.matches[key] {
t.Fatalf("mapping matches = %v, want %v", eda.matches, tt.wantMatches)
}
}
})
}
}
+6 -2
View File
@@ -34,7 +34,8 @@ type Matcher struct {
// Binding is the runtime-editable entity that ties a matcher, a payload
// mapping, and a workflow together. Bindings live in the store, not in
// config.toml, so operators can author them from the dashboard while the
// daemon runs.
// daemon runs. Any number of bindings may share a source: each one applies to
// the event type its mapping belongs to.
//
// Version is bumped on every UpdateBinding so a later edit cannot
// silently rewrite the historical provenance of a task that already
@@ -45,7 +46,10 @@ type Binding struct {
Name string `json:"name"`
Matcher Matcher `json:"matcher"`
MappingID string `json:"mapping_id"`
Workflow string `json:"workflow"`
// Filter is an optional CEL expression over the mapping's parameters
// (CompileFilter). An event it excludes is not dispatched.
Filter string `json:"filter,omitempty"`
Workflow string `json:"workflow"`
// Owner and Repo pin a binding to a specific configured repo, so a
// multi-repo deployment can dispatch correctly. Both empty means "no
// pin" -- resolveBindingRepo falls back to the single-configured-repo
+78
View File
@@ -0,0 +1,78 @@
package binding
import (
"fmt"
"strings"
"cel.dev/cel-go/cel"
"github.com/samcharles93/archie-core/internal/domain/eda/expr"
"github.com/samcharles93/archie-core/internal/domain/mapping"
)
// Filter is a compiled binding filter: a CEL expression over the mapping's
// named parameters, each declared as a variable of its field type
// (`severity in ["high", "critical"]`). A nil Filter admits every event.
type Filter struct {
prg cel.Program
}
// CompileFilter checks src against the mapping's fields and compiles it. An
// empty src is no filter. A reference to a parameter the mapping lacks, a type
// error, or a non-boolean result is refused.
func CompileFilter(src string, fields []mapping.Field) (*Filter, error) {
if strings.TrimSpace(src) == "" {
return nil, nil
}
opts := make([]cel.EnvOption, 0, len(fields))
for _, f := range fields {
opts = append(opts, cel.Variable(f.Name, celType(f.Type)))
}
env, err := cel.NewEnv(opts...)
if err != nil {
return nil, fmt.Errorf("binding: filter: %w", err)
}
ast, issues := env.Compile(src)
if issues != nil && issues.Err() != nil {
return nil, fmt.Errorf("binding: filter: %w", issues.Err())
}
if !ast.OutputType().IsExactType(cel.BoolType) {
return nil, fmt.Errorf("binding: filter must be a boolean, not %s", ast.OutputType())
}
prg, err := env.Program(ast, cel.CostLimit(expr.DefaultCostLimit))
if err != nil {
return nil, fmt.Errorf("binding: filter: %w", err)
}
return &Filter{prg: prg}, nil
}
// Admits evaluates the filter over resolved parameter values. An evaluation
// error, such as a parameter that did not resolve, excludes the event.
func (f *Filter) Admits(values map[string]any) (bool, error) {
if f == nil {
return true, nil
}
v, _, err := f.prg.Eval(values)
if err != nil {
return false, fmt.Errorf("binding: filter: %w", err)
}
admitted, _ := v.Value().(bool)
return admitted, nil
}
func celType(t mapping.FieldType) *cel.Type {
switch t {
case mapping.TypeString:
return cel.StringType
case mapping.TypeNumber:
return cel.DoubleType
case mapping.TypeBool:
return cel.BoolType
case mapping.TypeObject:
return cel.MapType(cel.StringType, cel.DynType)
case mapping.TypeArray:
return cel.ListType(cel.DynType)
default:
return cel.DynType
}
}
+59
View File
@@ -0,0 +1,59 @@
package binding
import (
"testing"
"github.com/samcharles93/archie-core/internal/domain/mapping"
)
var filterFields = []mapping.Field{
{Name: "severity", Path: "severity", Type: mapping.TypeString},
{Name: "count", Path: "count", Type: mapping.TypeNumber},
{Name: "urgent", Path: "urgent", Type: mapping.TypeBool},
{Name: "extra", Path: "extra", Type: mapping.TypeAny},
}
func TestCompileFilterRefuses(t *testing.T) {
tests := []struct{ name, src string }{
{"unknown parameter", `sender == "x"`},
{"not boolean", `severity`},
{"type mismatch", `count == "3"`},
{"syntax", `severity in [`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if _, err := CompileFilter(tt.src, filterFields); err == nil {
t.Fatalf("CompileFilter(%q) = nil error, want refusal", tt.src)
}
})
}
}
func TestFilterAdmits(t *testing.T) {
values := map[string]any{"severity": "high", "count": float64(3), "urgent": true, "extra": "x"}
tests := []struct {
name string
src string
values map[string]any
want bool
}{
{"empty filter admits everything", "", values, true},
{"list membership admits", `severity in ["high", "critical"]`, values, true},
{"list membership excludes", `severity in ["critical"]`, values, false},
{"number comparison", `count > 2.0 && urgent`, values, true},
{"dyn parameter", `extra == "x"`, values, true},
{"unresolved parameter excludes", `severity == "high"`, map[string]any{"count": float64(1)}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := CompileFilter(tt.src, filterFields)
if err != nil {
t.Fatalf("CompileFilter: %v", err)
}
got, _ := f.Admits(tt.values)
if got != tt.want {
t.Fatalf("Admits = %v, want %v", got, tt.want)
}
})
}
}
+56 -9
View File
@@ -8,10 +8,13 @@ package mapping
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
)
// FieldType is the expected JSON shape of a mapped field, checked at
@@ -46,16 +49,20 @@ type Field struct {
Required bool `json:"required"`
}
// Mapping is a named, reusable set of field bindings, authored by clicking
// through one example captured event but not pinned to that event or its
// source -- t2db.4's matcher decides which events a binding applies to.
// Mapping is a named set of field bindings belonging to one event type and
// checked against its schema (CheckSchema). Any number of bindings may reuse
// it. MatchCount and LastMatchedAt are read-only: the store counts each
// capture the mapping resolved at dispatch.
type Mapping struct {
ID string `json:"id"`
Name string `json:"name"`
SourceHint string `json:"source_hint"`
Fields []Field `json:"fields"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID string `json:"id"`
Name string `json:"name"`
SourceHint string `json:"source_hint"`
EventTypeID string `json:"event_type_id"`
Fields []Field `json:"fields"`
MatchCount int64 `json:"match_count"`
LastMatchedAt time.Time `json:"last_matched_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// validTypes is the set of FieldType values Validate accepts.
@@ -231,6 +238,46 @@ func walk(node any, path []pathSegment) (value any, found bool) {
return cur, true
}
// ErrSchema marks a mapping whose field paths or types disagree with its
// event type's inferred schema.
var ErrSchema = errors.New("mapping: field does not fit the event type's schema")
// CheckSchema refuses fields whose path the event type's schema lacks, or
// whose declared type differs from the schema's. Array indices match the
// schema's "[]" segment, and a path the example held as null accepts any type.
func CheckSchema(fields []Field, schema map[string]eventtype.ValueType) error {
for _, f := range fields {
got, ok := schema[schemaPath(f.Path)]
if !ok {
return fmt.Errorf("%w: %s: path %q is not in the event type", ErrSchema, f.Name, f.Path)
}
if f.Type != TypeAny && got != eventtype.TypeNull && string(got) != string(f.Type) {
return fmt.Errorf("%w: %s: path %q is %s, not %s", ErrSchema, f.Name, f.Path, got, f.Type)
}
}
return nil
}
// schemaPath rewrites a resolve path ("items[0].id") into the schema's form
// ("items[].id"). A malformed path has no schema form.
func schemaPath(path string) string {
var b strings.Builder
for _, seg := range parsePath(path) {
switch {
case seg.Invalid:
return ""
case seg.Index >= 0:
b.WriteString("[]")
default:
if b.Len() > 0 {
b.WriteByte('.')
}
b.WriteString(seg.Key)
}
}
return b.String()
}
func typeMatches(v any, want FieldType) bool {
if want == TypeAny {
return true
+51
View File
@@ -0,0 +1,51 @@
package mapping_test
import (
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/mapping"
)
func TestCheckSchema(t *testing.T) {
schema := map[string]eventtype.ValueType{
"action": eventtype.TypeString,
"issue": eventtype.TypeObject,
"issue.number": eventtype.TypeNumber,
"labels": eventtype.TypeArray,
"labels[]": eventtype.TypeObject,
"labels[].name": eventtype.TypeString,
"closed_at": eventtype.TypeNull,
"repository.url": eventtype.TypeString,
}
tests := []struct {
name string
fields []mapping.Field
ok bool
}{
{"top level path with matching type", []mapping.Field{{Name: "a", Path: "action", Type: mapping.TypeString}}, true},
{"nested number", []mapping.Field{{Name: "n", Path: "issue.number", Type: mapping.TypeNumber}}, true},
{"indexed array element maps to the [] path", []mapping.Field{{Name: "l", Path: "labels[0].name", Type: mapping.TypeString}}, true},
{"any accepts every schema type", []mapping.Field{{Name: "i", Path: "issue", Type: mapping.TypeAny}}, true},
{"a null example value accepts any declared type", []mapping.Field{{Name: "c", Path: "closed_at", Type: mapping.TypeString}}, true},
{"path the type does not have", []mapping.Field{{Name: "x", Path: "sender.login", Type: mapping.TypeString}}, false},
{"type differs from the schema", []mapping.Field{{Name: "n", Path: "issue.number", Type: mapping.TypeString}}, false},
{"malformed index", []mapping.Field{{Name: "l", Path: "labels[x].name", Type: mapping.TypeString}}, false},
{"one bad field refuses the mapping", []mapping.Field{
{Name: "a", Path: "action", Type: mapping.TypeString},
{Name: "b", Path: "nope", Type: mapping.TypeString},
}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := mapping.CheckSchema(tt.fields, schema)
if tt.ok && err != nil {
t.Fatalf("CheckSchema() = %v, want nil", err)
}
if !tt.ok && !errors.Is(err, mapping.ErrSchema) {
t.Fatalf("CheckSchema() = %v, want ErrSchema", err)
}
})
}
}
@@ -179,6 +179,13 @@ type MappingStore interface {
DeleteMapping(ctx context.Context, id string) error
}
// MappingMatchRecorder counts the events each mapping resolved, which the
// store reports as Mapping.MatchCount and LastMatchedAt. Recording the same
// (mapping, capture) twice counts once.
type MappingMatchRecorder interface {
RecordMappingMatch(ctx context.Context, mappingID, captureID string) error
}
// EventTypeStore persists event types (docs/prds/event-automation.md, "Event
// types"). Insert and Update refuse a type whose rule overlaps another on the
// same source with eventtype.ErrOverlap, and a malformed one with
@@ -234,7 +241,8 @@ type BindingDispatcher interface {
bindingVersion int64,
captureID string,
// taskID addresses the SQLite-owned task tables, which are not
// migrating: it stays an integer on purpose.
// migrating: it stays an integer on purpose. The binding dispatch
// loop claims before it enqueues, so it records 0.
taskID int64,
) error
ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]CapturedEvent, error)
+5 -1
View File
@@ -26,9 +26,13 @@ var droppedColumns = map[string]bool{
// newColumns are target columns added after the legacy stores, with no
// legacy value to carry; an imported row takes the column default. An
// imported capture has no event type, so it stays unidentified and never
// dispatches, and no legacy source could take unsigned events.
// dispatches, and no legacy source could take unsigned events. An imported
// mapping has no event type, so no binding using it dispatches until it is
// given one, and an imported binding has no filter.
var newColumns = map[string]bool{
"captures.event_type": true,
"mappings.event_type": true,
"bindings.filter": true,
"captures.unsigned": true,
}
+42 -33
View File
@@ -29,11 +29,12 @@ import (
// satisfies the same surface as *edastore.Store, so the cutover wave can swap
// one for the other behind storecontract without touching the consumers.
var (
_ storecontract.CaptureStore = (*EDA)(nil)
_ storecontract.MappingStore = (*EDA)(nil)
_ storecontract.BindingStore = (*EDA)(nil)
_ storecontract.BindingDispatcher = (*EDA)(nil)
_ storecontract.PlaybookDispatcher = (*EDA)(nil)
_ storecontract.CaptureStore = (*EDA)(nil)
_ storecontract.MappingStore = (*EDA)(nil)
_ storecontract.BindingStore = (*EDA)(nil)
_ storecontract.BindingDispatcher = (*EDA)(nil)
_ storecontract.MappingMatchRecorder = (*EDA)(nil)
_ storecontract.PlaybookDispatcher = (*EDA)(nil)
)
// EDA is the PostgreSQL-backed EDA persistence.
@@ -153,8 +154,8 @@ func (s *EDA) ListCaptures(ctx context.Context, limit int) ([]storecontract.Capt
}
// ListUndispatchedCaptures returns recent identified captures for the given
// sources that no binding has dispatched yet. An unidentified capture is
// never returned, so it never dispatches.
// sources that some armed binding for their event type has not dispatched yet.
// An unidentified capture is never returned, so it never dispatches.
func (s *EDA) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]storecontract.CapturedEvent, error) {
if len(sources) == 0 || limit <= 0 {
return nil, nil
@@ -183,20 +184,27 @@ func marshalMappingFields(fields []mapping.Field) (string, error) {
return string(encoded), nil
}
func mappingValue(r postgresdb.Mapping) (mapping.Mapping, error) {
func mappingValue(r postgresdb.Mapping, matches int64, lastMatched time.Time) (mapping.Mapping, error) {
var fields []mapping.Field
if raw := r.Fields; raw != "" {
if err := json.Unmarshal([]byte(raw), &fields); err != nil {
return mapping.Mapping{}, fmt.Errorf("edastore: decode mapping fields: %w", err)
}
}
// The query reports the epoch for a mapping that never matched.
if matches == 0 {
lastMatched = time.Time{}
}
return mapping.Mapping{
ID: r.ID,
Name: r.Name,
SourceHint: r.SourceHint,
Fields: fields,
CreatedAt: r.CreatedAt,
UpdatedAt: r.UpdatedAt,
ID: r.ID,
Name: r.Name,
SourceHint: r.SourceHint,
EventTypeID: r.EventType,
Fields: fields,
MatchCount: matches,
LastMatchedAt: lastMatched,
CreatedAt: r.CreatedAt,
UpdatedAt: r.UpdatedAt,
}, nil
}
@@ -210,6 +218,7 @@ func (s *EDA) InsertMapping(ctx context.Context, m mapping.Mapping) (string, err
ID: id,
Name: m.Name,
SourceHint: m.SourceHint,
EventType: m.EventTypeID,
Fields: encoded,
}); err != nil {
return "", fmt.Errorf("edastore: insert mapping: %w", err)
@@ -228,7 +237,7 @@ func (s *EDA) GetMapping(ctx context.Context, id string) (*mapping.Mapping, erro
if err != nil {
return nil, err
}
m, err := mappingValue(r)
m, err := mappingValue(r.Mapping, r.MatchCount, r.LastMatchedAt)
if err != nil {
return nil, err
}
@@ -242,7 +251,7 @@ func (s *EDA) ListMappings(ctx context.Context) ([]mapping.Mapping, error) {
}
out := make([]mapping.Mapping, 0, len(rows))
for _, r := range rows {
m, err := mappingValue(r)
m, err := mappingValue(r.Mapping, r.MatchCount, r.LastMatchedAt)
if err != nil {
return nil, err
}
@@ -260,6 +269,7 @@ func (s *EDA) UpdateMapping(ctx context.Context, m mapping.Mapping) error {
ID: m.ID,
Name: m.Name,
SourceHint: m.SourceHint,
EventType: m.EventTypeID,
Fields: encoded,
})
if err != nil {
@@ -284,6 +294,16 @@ func (s *EDA) DeleteMapping(ctx context.Context, id string) error {
return nil
}
// RecordMappingMatch counts one event a mapping resolved. Recording the same
// (mapping, capture) again is a no-op, so the count rises once per event no
// matter how many bindings share the mapping.
func (s *EDA) RecordMappingMatch(ctx context.Context, mappingID, captureID string) error {
if err := s.q.InsertMappingMatch(ctx, postgresdb.InsertMappingMatchParams{Mapping: mappingID, Capture: captureID}); err != nil {
return fmt.Errorf("edastore: record mapping match: %w", err)
}
return nil
}
// --- bindings ---
// bindingValue takes GetBindingRow; the list queries' rows share its fields
@@ -294,6 +314,7 @@ func bindingValue(r postgresdb.GetBindingRow) binding.Binding {
Name: r.Name,
Matcher: binding.Matcher{Source: r.Source},
MappingID: r.Mapping,
Filter: r.Filter,
Workflow: r.Workflow,
Owner: r.Owner,
Repo: r.Repo,
@@ -304,10 +325,8 @@ func bindingValue(r postgresdb.GetBindingRow) binding.Binding {
}
}
// InsertBinding stores a new binding as pending_approval. "One binding per
// source" is a schema constraint (idx_bindings_source), so a concurrent
// second insert for the same source is refused by the database and surfaced
// here as ErrBindingOverlap.
// InsertBinding stores a new binding as pending_approval. Any number of
// bindings may share a source.
func (s *EDA) InsertBinding(ctx context.Context, b binding.Binding) (string, error) {
id := newRecordID()
err := s.q.InsertBinding(ctx, postgresdb.InsertBindingParams{
@@ -315,14 +334,12 @@ func (s *EDA) InsertBinding(ctx context.Context, b binding.Binding) (string, err
Name: b.Name,
Source: b.Matcher.Source,
Mapping: b.MappingID,
Filter: b.Filter,
Workflow: b.Workflow,
Owner: b.Owner,
Repo: b.Repo,
Status: string(binding.StatusPendingApproval),
})
if isUniqueViolation(err) {
return "", storecontract.ErrBindingOverlap
}
if err != nil {
return "", fmt.Errorf("edastore: insert binding: %w", err)
}
@@ -377,14 +394,12 @@ func (s *EDA) UpdateBinding(ctx context.Context, b binding.Binding) error {
Name: b.Name,
Source: b.Matcher.Source,
Mapping: b.MappingID,
Filter: b.Filter,
Workflow: b.Workflow,
Owner: b.Owner,
Repo: b.Repo,
Status: string(binding.StatusPendingApproval),
})
if isUniqueViolation(err) {
return storecontract.ErrBindingOverlap
}
if err != nil {
return err
}
@@ -407,10 +422,7 @@ func (s *EDA) DeleteBinding(ctx context.Context, id string) error {
return nil
}
// ApproveBinding is the only transition that arms a binding. "One armed
// binding per source" is a partial unique constraint (idx_bindings_armed_source),
// so a concurrent approval of a sibling binding on the same source is refused
// by the database and surfaced here as ErrBindingOverlap.
// ApproveBinding is the only transition that arms a binding.
func (s *EDA) ApproveBinding(ctx context.Context, id string) error {
r, err := s.q.GetBinding(ctx, id)
if errors.Is(err, pgx.ErrNoRows) {
@@ -423,9 +435,6 @@ func (s *EDA) ApproveBinding(ctx context.Context, id string) error {
return storecontract.ErrBindingTransition
}
n, err := s.q.SetBindingArmed(ctx, id)
if isUniqueViolation(err) {
return storecontract.ErrBindingOverlap
}
if err != nil {
return err
}
@@ -0,0 +1,166 @@
package postgres
import (
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// eventTypeFixture saves a type on source matching events whose "kind" equals kind.
func eventTypeFixture(t *testing.T, s *EDA, source, kind string) string {
t.Helper()
id, err := s.InsertEventType(t.Context(), eventtype.EventType{
Source: source, Name: kind,
Rule: eventtype.Rule{Payload: []eventtype.PayloadCondition{{Path: "kind", Op: eventtype.OpEquals, Value: kind}}},
})
if err != nil {
t.Fatalf("InsertEventType() error = %v", err)
}
return id
}
func armedBinding(t *testing.T, s *EDA, source, mappingID string) string {
t.Helper()
id, err := s.InsertBinding(t.Context(), binding.Binding{
Name: "n", Matcher: binding.Matcher{Source: source}, MappingID: mappingID, Workflow: "implement",
})
if err != nil {
t.Fatalf("InsertBinding() error = %v", err)
}
if err := s.ApproveBinding(t.Context(), id); err != nil {
t.Fatalf("ApproveBinding() error = %v", err)
}
return id
}
func captureOf(t *testing.T, s *EDA, source, body string) string {
t.Helper()
id, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: source, Body: body}, 0, 0)
if err != nil {
t.Fatalf("InsertCapture() error = %v", err)
}
return id
}
func undispatchedIDs(t *testing.T, s *EDA, source string) map[string]bool {
t.Helper()
list, err := s.ListUndispatchedCaptures(t.Context(), []string{source}, 10)
if err != nil {
t.Fatalf("ListUndispatchedCaptures() error = %v", err)
}
out := map[string]bool{}
for _, c := range list {
out[c.ID] = true
}
return out
}
func TestSeveralArmedBindingsShareASource(t *testing.T) {
s := edaFor(t)
a := armedBinding(t, s, "github", "")
b := armedBinding(t, s, "github", "")
armed, err := s.ArmedBindingsForSource(t.Context(), "github")
if err != nil {
t.Fatalf("ArmedBindingsForSource() error = %v", err)
}
got := map[string]bool{}
for _, x := range armed {
got[x.ID] = true
}
if !got[a] || !got[b] || len(armed) != 2 {
t.Fatalf("armed = %v, want both %s and %s", got, a, b)
}
}
func TestMappingAndBindingRoundTripEventTypeAndFilter(t *testing.T) {
s := edaFor(t)
typeID := eventTypeFixture(t, s, "github", "push")
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: typeID})
if err != nil {
t.Fatalf("InsertMapping() error = %v", err)
}
m, err := s.GetMapping(t.Context(), mid)
if err != nil || m.EventTypeID != typeID {
t.Fatalf("GetMapping() event type = %q (err %v), want %q", m.EventTypeID, err, typeID)
}
bid, err := s.InsertBinding(t.Context(), binding.Binding{
Name: "n", Matcher: binding.Matcher{Source: "github"}, MappingID: mid, Workflow: "implement",
Filter: `kind == "push"`,
})
if err != nil {
t.Fatalf("InsertBinding() error = %v", err)
}
b, err := s.GetBinding(t.Context(), bid)
if err != nil || b.Filter != `kind == "push"` {
t.Fatalf("GetBinding() filter = %q (err %v)", b.Filter, err)
}
b.Filter = ""
if err := s.UpdateBinding(t.Context(), *b); err != nil {
t.Fatalf("UpdateBinding() error = %v", err)
}
if b, _ = s.GetBinding(t.Context(), bid); b.Filter != "" {
t.Fatalf("filter after clearing = %q, want empty", b.Filter)
}
}
func TestMappingMatchCountRisesOncePerEvent(t *testing.T) {
s := edaFor(t)
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m"})
if err != nil {
t.Fatalf("InsertMapping() error = %v", err)
}
before := time.Now().Add(-time.Minute)
for _, capture := range []string{"c1", "c2", "c1"} {
if err := s.RecordMappingMatch(t.Context(), mid, capture); err != nil {
t.Fatalf("RecordMappingMatch(%s) error = %v", capture, err)
}
}
list, err := s.ListMappings(t.Context())
if err != nil || len(list) != 1 {
t.Fatalf("ListMappings() = %d (err %v)", len(list), err)
}
if list[0].MatchCount != 2 {
t.Errorf("MatchCount = %d, want 2 (one per distinct event)", list[0].MatchCount)
}
if !list[0].LastMatchedAt.After(before) {
t.Errorf("LastMatchedAt = %v, want a recent time", list[0].LastMatchedAt)
}
got, _ := s.GetMapping(t.Context(), mid)
if got.MatchCount != 2 {
t.Errorf("GetMapping MatchCount = %d, want 2", got.MatchCount)
}
}
// A capture stays undispatched until every armed binding for its event type
// has dispatched it; a binding for another event type does not hold it.
func TestUndispatchedIsPerBinding(t *testing.T) {
s := edaFor(t)
push := eventTypeFixture(t, s, "github", "push")
issue := eventTypeFixture(t, s, "github", "issue")
pushMap, _ := s.InsertMapping(t.Context(), mapping.Mapping{Name: "p", EventTypeID: push})
issueMap, _ := s.InsertMapping(t.Context(), mapping.Mapping{Name: "i", EventTypeID: issue})
a := armedBinding(t, s, "github", pushMap)
b := armedBinding(t, s, "github", pushMap)
c := armedBinding(t, s, "github", issueMap)
capture := captureOf(t, s, "github", `{"kind":"push"}`)
if !undispatchedIDs(t, s, "github")[capture] {
t.Fatal("new push capture not listed")
}
if err := s.RecordDispatch(t.Context(), a, 1, capture, 1); err != nil {
t.Fatalf("RecordDispatch(a) error = %v", err)
}
if !undispatchedIDs(t, s, "github")[capture] {
t.Fatal("capture dropped after one of two push bindings dispatched it")
}
if err := s.RecordDispatch(t.Context(), b, 1, capture, 2); err != nil {
t.Fatalf("RecordDispatch(b) error = %v", err)
}
if undispatchedIDs(t, s, "github")[capture] {
t.Fatalf("capture still listed after both push bindings dispatched it (issue binding %s must not hold it)", c)
}
}
@@ -5,6 +5,7 @@ import (
"testing"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
@@ -142,6 +143,11 @@ func TestPastedTypeIdentifiesLaterCaptures(t *testing.T) {
t.Errorf("unmatched capture event type = %q, want unidentified", byBody[`{"ref":"main"}`])
}
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: id})
if err != nil {
t.Fatalf("InsertMapping() error = %v", err)
}
armedBinding(t, s, "gh", mid)
undispatched, err := s.ListUndispatchedCaptures(t.Context(), []string{"gh"}, 10)
if err != nil {
t.Fatalf("ListUndispatchedCaptures() error = %v", err)
@@ -9,7 +9,6 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/events"
@@ -92,42 +91,6 @@ func TestPlaybookDispatchIsIdempotent(t *testing.T) {
}
}
// Hazard 3: "one binding per source" is a schema constraint, so concurrent
// inserts for one source produce exactly one success and one ErrBindingOverlap
// rather than two bindings that a single SQLite writer would have serialised.
func TestConcurrentInsertBindingSameSource(t *testing.T) {
s := edaFor(t)
type result struct{ err error }
start := make(chan struct{})
results := make(chan result, 2)
for range 2 {
go func() {
<-start
_, err := s.InsertBinding(t.Context(), binding.Binding{
Name: "n", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement",
})
results <- result{err: err}
}()
}
close(start)
var succeeded, overlapped int
for range 2 {
outcome := <-results
switch {
case outcome.err == nil:
succeeded++
case errors.Is(outcome.err, storecontract.ErrBindingOverlap):
overlapped++
default:
t.Fatalf("concurrent InsertBinding error = %v", outcome.err)
}
}
if succeeded != 1 || overlapped != 1 {
t.Fatalf("concurrent inserts = %d succeeded, %d overlapped; want 1 each", succeeded, overlapped)
}
}
// The lifecycle gate survives the port: pending_approval -> armed, and only
// from pending_approval.
func TestBindingLifecycle(t *testing.T) {
@@ -146,13 +109,9 @@ func TestBindingLifecycle(t *testing.T) {
}
}
// A capture round-trips its payload verbatim, and a dispatched capture drops
// out of the undispatched listing.
func TestCaptureRoundTripAndUndispatched(t *testing.T) {
// A capture round-trips its payload verbatim.
func TestCaptureRoundTrip(t *testing.T) {
s := edaFor(t)
if _, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "sentry", Name: "any"}); err != nil {
t.Fatalf("InsertEventType() error = %v", err)
}
body := `{"action":"created"}`
if _, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{
Source: "sentry", Body: body, Headers: `{"X-Hook":"1"}`, ContentType: "application/json",
@@ -166,19 +125,6 @@ func TestCaptureRoundTripAndUndispatched(t *testing.T) {
if list[0].Body != body {
t.Errorf("Body round-trip = %q, want %q", list[0].Body, body)
}
undispatched, err := s.ListUndispatchedCaptures(t.Context(), []string{"sentry"}, 10)
if err != nil || len(undispatched) != 1 {
t.Fatalf("ListUndispatchedCaptures() = %d (err %v), want 1", len(undispatched), err)
}
// Dispatch it; the capture must no longer be undispatched.
if err := s.RecordDispatch(t.Context(), "b1", 1, list[0].ID, 42); err != nil {
t.Fatalf("RecordDispatch() error = %v", err)
}
undispatched, err = s.ListUndispatchedCaptures(t.Context(), []string{"sentry"}, 10)
if err != nil || len(undispatched) != 0 {
t.Fatalf("ListUndispatchedCaptures() after dispatch = %d (err %v), want 0", len(undispatched), err)
}
}
func TestMappingCRUD(t *testing.T) {
@@ -0,0 +1,34 @@
-- Mappings per event type, match counts and several bindings per source
-- (docs/prds/event-automation.md, "Mappings" and "Bindings").
--
-- mappings.event_type is the event type a mapping belongs to; like
-- captures.event_type it is plain text, not a foreign key. A binding applies
-- to its mapping's event type, so any number of bindings may share a source
-- and the two per-source unique indexes are dropped.
--
-- mapping_matches holds one row per (mapping, capture) the mapping resolved;
-- a mapping's matched-event count and last match are read from it.
-- bindings.filter is an optional CEL expression over the mapping's parameters.
-- +goose Up
ALTER TABLE mappings ADD COLUMN event_type text NOT NULL DEFAULT '';
ALTER TABLE bindings ADD COLUMN filter text NOT NULL DEFAULT '';
DROP INDEX idx_bindings_source;
DROP INDEX idx_bindings_armed_source;
CREATE TABLE mapping_matches (
mapping text NOT NULL,
capture text NOT NULL,
matched_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (mapping, capture)
);
-- +goose Down
DROP TABLE mapping_matches;
CREATE UNIQUE INDEX idx_bindings_armed_source ON bindings (source) WHERE status = 'armed';
CREATE UNIQUE INDEX idx_bindings_source ON bindings (source);
ALTER TABLE bindings DROP COLUMN filter;
ALTER TABLE mappings DROP COLUMN event_type;
@@ -11,7 +11,7 @@ import (
)
const armedBindingsForSource = `-- name: ArmedBindingsForSource :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter
FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC
`
@@ -27,6 +27,7 @@ type ArmedBindingsForSourceRow struct {
Status string
CreatedAt time.Time
UpdatedAt time.Time
Filter string
}
func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]ArmedBindingsForSourceRow, error) {
@@ -50,6 +51,7 @@ func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
&i.Filter,
); err != nil {
return nil, err
}
@@ -169,7 +171,7 @@ func (q *Queries) EventTypesForSource(ctx context.Context, source string) ([]Eve
}
const getBinding = `-- name: GetBinding :one
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter
FROM bindings WHERE id = $1
`
@@ -185,6 +187,7 @@ type GetBindingRow struct {
Status string
CreatedAt time.Time
UpdatedAt time.Time
Filter string
}
func (q *Queries) GetBinding(ctx context.Context, id string) (GetBindingRow, error) {
@@ -202,6 +205,7 @@ func (q *Queries) GetBinding(ctx context.Context, id string) (GetBindingRow, err
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
&i.Filter,
)
return i, err
}
@@ -227,20 +231,31 @@ func (q *Queries) GetEventType(ctx context.Context, id string) (EventType, error
}
const getMapping = `-- name: GetMapping :one
SELECT id, name, source_hint, fields, created_at, updated_at
SELECT mappings.id, mappings.name, mappings.source_hint, mappings.fields, mappings.created_at, mappings.updated_at, mappings.event_type,
(SELECT count(*) FROM mapping_matches mm WHERE mm.mapping = mappings.id)::bigint AS match_count,
COALESCE((SELECT max(mm.matched_at) FROM mapping_matches mm WHERE mm.mapping = mappings.id), 'epoch')::timestamptz AS last_matched_at
FROM mappings WHERE id = $1
`
func (q *Queries) GetMapping(ctx context.Context, id string) (Mapping, error) {
type GetMappingRow struct {
Mapping Mapping
MatchCount int64
LastMatchedAt time.Time
}
func (q *Queries) GetMapping(ctx context.Context, id string) (GetMappingRow, error) {
row := q.db.QueryRow(ctx, getMapping, id)
var i Mapping
var i GetMappingRow
err := row.Scan(
&i.ID,
&i.Name,
&i.SourceHint,
&i.Fields,
&i.CreatedAt,
&i.UpdatedAt,
&i.Mapping.ID,
&i.Mapping.Name,
&i.Mapping.SourceHint,
&i.Mapping.Fields,
&i.Mapping.CreatedAt,
&i.Mapping.UpdatedAt,
&i.Mapping.EventType,
&i.MatchCount,
&i.LastMatchedAt,
)
return i, err
}
@@ -263,8 +278,8 @@ func (q *Queries) GetSource(ctx context.Context, path string) (Source, error) {
}
const insertBinding = `-- name: InsertBinding :exec
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8)
INSERT INTO bindings (id, name, source, mapping, filter, workflow, owner, repo, version, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9)
`
type InsertBindingParams struct {
@@ -272,6 +287,7 @@ type InsertBindingParams struct {
Name string
Source string
Mapping string
Filter string
Workflow string
Owner string
Repo string
@@ -284,6 +300,7 @@ func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) er
arg.Name,
arg.Source,
arg.Mapping,
arg.Filter,
arg.Workflow,
arg.Owner,
arg.Repo,
@@ -375,14 +392,15 @@ func (q *Queries) InsertEventType(ctx context.Context, arg InsertEventTypeParams
}
const insertMapping = `-- name: InsertMapping :exec
INSERT INTO mappings (id, name, source_hint, fields)
VALUES ($1, $2, $3, $4)
INSERT INTO mappings (id, name, source_hint, event_type, fields)
VALUES ($1, $2, $3, $4, $5)
`
type InsertMappingParams struct {
ID string
Name string
SourceHint string
EventType string
Fields string
}
@@ -391,11 +409,27 @@ func (q *Queries) InsertMapping(ctx context.Context, arg InsertMappingParams) er
arg.ID,
arg.Name,
arg.SourceHint,
arg.EventType,
arg.Fields,
)
return err
}
const insertMappingMatch = `-- name: InsertMappingMatch :exec
INSERT INTO mapping_matches (mapping, capture) VALUES ($1, $2)
ON CONFLICT DO NOTHING
`
type InsertMappingMatchParams struct {
Mapping string
Capture string
}
func (q *Queries) InsertMappingMatch(ctx context.Context, arg InsertMappingMatchParams) error {
_, err := q.db.Exec(ctx, insertMappingMatch, arg.Mapping, arg.Capture)
return err
}
const insertPlaybookDispatch = `-- name: InsertPlaybookDispatch :exec
INSERT INTO playbook_dispatches (playbook_id, playbook_version, event_id, action_id)
VALUES ($1, $2, $3, $4)
@@ -462,7 +496,7 @@ func (q *Queries) InsertToolCall(ctx context.Context, arg InsertToolCallParams)
}
const listBindings = `-- name: ListBindings :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter
FROM bindings ORDER BY created_at DESC
`
@@ -478,6 +512,7 @@ type ListBindingsRow struct {
Status string
CreatedAt time.Time
UpdatedAt time.Time
Filter string
}
func (q *Queries) ListBindings(ctx context.Context) ([]ListBindingsRow, error) {
@@ -501,6 +536,7 @@ func (q *Queries) ListBindings(ctx context.Context) ([]ListBindingsRow, error) {
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
&i.Filter,
); err != nil {
return nil, err
}
@@ -584,26 +620,37 @@ func (q *Queries) ListEventTypes(ctx context.Context) ([]EventType, error) {
}
const listMappings = `-- name: ListMappings :many
SELECT id, name, source_hint, fields, created_at, updated_at
SELECT mappings.id, mappings.name, mappings.source_hint, mappings.fields, mappings.created_at, mappings.updated_at, mappings.event_type,
(SELECT count(*) FROM mapping_matches mm WHERE mm.mapping = mappings.id)::bigint AS match_count,
COALESCE((SELECT max(mm.matched_at) FROM mapping_matches mm WHERE mm.mapping = mappings.id), 'epoch')::timestamptz AS last_matched_at
FROM mappings ORDER BY created_at DESC
`
func (q *Queries) ListMappings(ctx context.Context) ([]Mapping, error) {
type ListMappingsRow struct {
Mapping Mapping
MatchCount int64
LastMatchedAt time.Time
}
func (q *Queries) ListMappings(ctx context.Context) ([]ListMappingsRow, error) {
rows, err := q.db.Query(ctx, listMappings)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Mapping
var items []ListMappingsRow
for rows.Next() {
var i Mapping
var i ListMappingsRow
if err := rows.Scan(
&i.ID,
&i.Name,
&i.SourceHint,
&i.Fields,
&i.CreatedAt,
&i.UpdatedAt,
&i.Mapping.ID,
&i.Mapping.Name,
&i.Mapping.SourceHint,
&i.Mapping.Fields,
&i.Mapping.CreatedAt,
&i.Mapping.UpdatedAt,
&i.Mapping.EventType,
&i.MatchCount,
&i.LastMatchedAt,
); err != nil {
return nil, err
}
@@ -646,13 +693,16 @@ func (q *Queries) ListSources(ctx context.Context) ([]Source, error) {
}
const listUndispatchedCaptures = `-- name: ListUndispatchedCaptures :many
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type
FROM captures
WHERE source = ANY($1::text[])
-- An unidentified capture is never dispatched.
AND event_type <> ''
AND id NOT IN (SELECT capture FROM binding_dispatches)
ORDER BY received_at DESC
SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.unsigned, c.event_type
FROM captures c
WHERE c.source = ANY($1::text[])
AND c.event_type <> ''
AND EXISTS (
SELECT 1 FROM bindings b JOIN mappings m ON m.id = b.mapping
WHERE b.source = c.source AND b.status = 'armed' AND m.event_type = c.event_type
AND NOT EXISTS (SELECT 1 FROM binding_dispatches d WHERE d.binding = b.id AND d.capture = c.id)
)
ORDER BY c.received_at DESC
LIMIT $2
`
@@ -661,6 +711,9 @@ type ListUndispatchedCapturesParams struct {
EntryLimit int32
}
// A capture is undispatched while some armed binding on its source, whose
// mapping belongs to the capture's event type, has not dispatched it. An
// unidentified capture has no event type, so it is never listed.
func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispatchedCapturesParams) ([]Capture, error) {
rows, err := q.db.Query(ctx, listUndispatchedCaptures, arg.Sources, arg.EntryLimit)
if err != nil {
@@ -807,8 +860,8 @@ func (q *Queries) TaskToolCalls(ctx context.Context, taskID int64) ([]TaskToolCa
const updateBinding = `-- name: UpdateBinding :execrows
UPDATE bindings
SET name = $2, source = $3, mapping = $4, workflow = $5, owner = $6, repo = $7,
version = version + 1, status = $8, updated_at = now()
SET name = $2, source = $3, mapping = $4, filter = $5, workflow = $6, owner = $7, repo = $8,
version = version + 1, status = $9, updated_at = now()
WHERE id = $1
`
@@ -817,6 +870,7 @@ type UpdateBindingParams struct {
Name string
Source string
Mapping string
Filter string
Workflow string
Owner string
Repo string
@@ -829,6 +883,7 @@ func (q *Queries) UpdateBinding(ctx context.Context, arg UpdateBindingParams) (i
arg.Name,
arg.Source,
arg.Mapping,
arg.Filter,
arg.Workflow,
arg.Owner,
arg.Repo,
@@ -860,7 +915,7 @@ func (q *Queries) UpdateEventType(ctx context.Context, arg UpdateEventTypeParams
const updateMapping = `-- name: UpdateMapping :execrows
UPDATE mappings
SET name = $2, source_hint = $3, fields = $4, updated_at = now()
SET name = $2, source_hint = $3, event_type = $4, fields = $5, updated_at = now()
WHERE id = $1
`
@@ -868,6 +923,7 @@ type UpdateMappingParams struct {
ID string
Name string
SourceHint string
EventType string
Fields string
}
@@ -876,6 +932,7 @@ func (q *Queries) UpdateMapping(ctx context.Context, arg UpdateMappingParams) (i
arg.ID,
arg.Name,
arg.SourceHint,
arg.EventType,
arg.Fields,
)
if err != nil {
@@ -29,6 +29,7 @@ type Binding struct {
Secret string
CreatedAt time.Time
UpdatedAt time.Time
Filter string
}
type BindingDispatch struct {
@@ -145,6 +146,13 @@ type Mapping struct {
Fields string
CreatedAt time.Time
UpdatedAt time.Time
EventType string
}
type MappingMatch struct {
Mapping string
Capture string
MatchedAt time.Time
}
type Message struct {
@@ -11,13 +11,19 @@ ORDER BY received_at DESC
LIMIT $1;
-- name: ListUndispatchedCaptures :many
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type
FROM captures
WHERE source = ANY(@sources::text[])
-- An unidentified capture is never dispatched.
AND event_type <> ''
AND id NOT IN (SELECT capture FROM binding_dispatches)
ORDER BY received_at DESC
-- A capture is undispatched while some armed binding on its source, whose
-- mapping belongs to the capture's event type, has not dispatched it. An
-- unidentified capture has no event type, so it is never listed.
SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.unsigned, c.event_type
FROM captures c
WHERE c.source = ANY(@sources::text[])
AND c.event_type <> ''
AND EXISTS (
SELECT 1 FROM bindings b JOIN mappings m ON m.id = b.mapping
WHERE b.source = c.source AND b.status = 'armed' AND m.event_type = c.event_type
AND NOT EXISTS (SELECT 1 FROM binding_dispatches d WHERE d.binding = b.id AND d.capture = c.id)
)
ORDER BY c.received_at DESC
LIMIT @entry_limit;
-- name: DeleteCapturesOlderThan :exec
@@ -29,45 +35,53 @@ DELETE FROM captures WHERE id NOT IN (
);
-- name: InsertMapping :exec
INSERT INTO mappings (id, name, source_hint, fields)
VALUES ($1, $2, $3, $4);
INSERT INTO mappings (id, name, source_hint, event_type, fields)
VALUES ($1, $2, $3, $4, $5);
-- name: GetMapping :one
SELECT id, name, source_hint, fields, created_at, updated_at
SELECT sqlc.embed(mappings),
(SELECT count(*) FROM mapping_matches mm WHERE mm.mapping = mappings.id)::bigint AS match_count,
COALESCE((SELECT max(mm.matched_at) FROM mapping_matches mm WHERE mm.mapping = mappings.id), 'epoch')::timestamptz AS last_matched_at
FROM mappings WHERE id = $1;
-- name: ListMappings :many
SELECT id, name, source_hint, fields, created_at, updated_at
SELECT sqlc.embed(mappings),
(SELECT count(*) FROM mapping_matches mm WHERE mm.mapping = mappings.id)::bigint AS match_count,
COALESCE((SELECT max(mm.matched_at) FROM mapping_matches mm WHERE mm.mapping = mappings.id), 'epoch')::timestamptz AS last_matched_at
FROM mappings ORDER BY created_at DESC;
-- name: UpdateMapping :execrows
UPDATE mappings
SET name = $2, source_hint = $3, fields = $4, updated_at = now()
SET name = $2, source_hint = $3, event_type = $4, fields = $5, updated_at = now()
WHERE id = $1;
-- name: InsertMappingMatch :exec
INSERT INTO mapping_matches (mapping, capture) VALUES ($1, $2)
ON CONFLICT DO NOTHING;
-- name: DeleteMapping :execrows
DELETE FROM mappings WHERE id = $1;
-- name: InsertBinding :exec
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8);
INSERT INTO bindings (id, name, source, mapping, filter, workflow, owner, repo, version, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9);
-- name: GetBinding :one
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter
FROM bindings WHERE id = $1;
-- name: ListBindings :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter
FROM bindings ORDER BY created_at DESC;
-- name: ArmedBindingsForSource :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at, filter
FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC;
-- name: UpdateBinding :execrows
UPDATE bindings
SET name = $2, source = $3, mapping = $4, workflow = $5, owner = $6, repo = $7,
version = version + 1, status = $8, updated_at = now()
SET name = $2, source = $3, mapping = $4, filter = $5, workflow = $6, owner = $7, repo = $8,
version = version + 1, status = $9, updated_at = now()
WHERE id = $1;
-- name: SetBindingArmed :execrows
@@ -7,6 +7,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
@@ -104,11 +105,17 @@ func TestSourceSigningAndSecretWrites(t *testing.T) {
func TestCaptureUnsignedRoundTrip(t *testing.T) {
s := edaFor(t)
// Only an identified capture is listed for dispatch; a catch-all type
// identifies every event on the source.
if _, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "fw", Name: "any"}); err != nil {
// Only an identified capture with an armed binding for its type is listed
// for dispatch; a catch-all type identifies every event on the source.
etID, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "fw", Name: "any"})
if err != nil {
t.Fatalf("InsertEventType() error = %v", err)
}
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: etID})
if err != nil {
t.Fatalf("InsertMapping() error = %v", err)
}
armedBinding(t, s, "fw", mid)
if _, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: "fw", Unsigned: true}, 0, 0); err != nil {
t.Fatalf("InsertCapture() error = %v", err)
}
+20 -14
View File
@@ -42,20 +42,21 @@ func (c *Client) ControlPlane() controlpb.ControlPlaneServiceClient { return c.c
func (c *Client) Close() error { return nil }
var (
_ task.Store = (*Client)(nil)
_ storecontract.TaskStore = (*Client)(nil)
_ storecontract.TaskLogStore = (*Client)(nil)
_ storecontract.CaptureStore = (*Client)(nil)
_ storecontract.MappingStore = (*Client)(nil)
_ storecontract.BindingStore = (*Client)(nil)
_ storecontract.SourceStore = (*Client)(nil)
_ storecontract.BindingDispatcher = (*Client)(nil)
_ storecontract.BindingTaskCreator = (*Client)(nil)
_ storecontract.PlaybookDispatcher = (*Client)(nil)
_ storecontract.ConfigSnapshotStore = (*Client)(nil)
_ storecontract.ChannelStatusStore = (*Client)(nil)
_ storecontract.ApplyStatusStore = (*Client)(nil)
_ identity.Repository = (*Client)(nil)
_ task.Store = (*Client)(nil)
_ storecontract.TaskStore = (*Client)(nil)
_ storecontract.TaskLogStore = (*Client)(nil)
_ storecontract.CaptureStore = (*Client)(nil)
_ storecontract.MappingStore = (*Client)(nil)
_ storecontract.BindingStore = (*Client)(nil)
_ storecontract.SourceStore = (*Client)(nil)
_ storecontract.BindingDispatcher = (*Client)(nil)
_ storecontract.MappingMatchRecorder = (*Client)(nil)
_ storecontract.BindingTaskCreator = (*Client)(nil)
_ storecontract.PlaybookDispatcher = (*Client)(nil)
_ storecontract.ConfigSnapshotStore = (*Client)(nil)
_ storecontract.ChannelStatusStore = (*Client)(nil)
_ storecontract.ApplyStatusStore = (*Client)(nil)
_ identity.Repository = (*Client)(nil)
)
// Lifecycle
@@ -417,6 +418,11 @@ func (c *Client) DeleteMapping(ctx context.Context, id string) error {
return unmapError(err)
}
func (c *Client) RecordMappingMatch(ctx context.Context, mappingID, captureID string) error {
_, err := c.client.RecordMappingMatch(ctx, &pb.RecordMappingMatchRequest{MappingId: mappingID, CaptureId: captureID})
return unmapError(err)
}
// Binding
func (c *Client) InsertBinding(ctx context.Context, b binding.Binding) (string, error) {
@@ -0,0 +1,58 @@
package staterpc
import (
"context"
"net"
"reflect"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/test/bufconn"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/mapping"
)
type fakeMappingMatches struct{ mappingID, captureID string }
func (f *fakeMappingMatches) RecordMappingMatch(_ context.Context, mappingID, captureID string) error {
f.mappingID, f.captureID = mappingID, captureID
return nil
}
func TestRecordMappingMatchCrossesTheWire(t *testing.T) {
fake := &fakeMappingMatches{}
listener := bufconn.Listen(1 << 20)
server := grpc.NewServer()
RegisterServer(server, Deps{MappingMatches: fake})
go func() { _ = server.Serve(listener) }()
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
conn, err := grpc.NewClient("passthrough:///state",
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
if err := NewClient(conn).RecordMappingMatch(t.Context(), "m1", "c1"); err != nil {
t.Fatalf("RecordMappingMatch() error = %v", err)
}
if fake.mappingID != "m1" || fake.captureID != "c1" {
t.Fatalf("server received (%q, %q), want (m1, c1)", fake.mappingID, fake.captureID)
}
}
func TestMappingAndBindingCarryEventTypeCountsAndFilter(t *testing.T) {
stamp := time.Date(2026, 9, 24, 9, 0, 0, 0, time.UTC)
m := mapping.Mapping{ID: "m", Name: "n", Fields: []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}}, EventTypeID: "et-1", MatchCount: 7, LastMatchedAt: stamp, CreatedAt: stamp, UpdatedAt: stamp}
if got := mappingValue(mappingProto(m)); !reflect.DeepEqual(got, m) {
t.Fatalf("mapping after round trip = %+v, want %+v", got, m)
}
b := binding.Binding{ID: "b", Filter: `severity == "high"`, CreatedAt: stamp, UpdatedAt: stamp}
if got := bindingValue(bindingProto(b)); got.Filter != b.Filter {
t.Fatalf("binding filter after round trip = %q, want %q", got.Filter, b.Filter)
}
}
+17 -4
View File
@@ -75,10 +75,13 @@ type Deps struct {
// ChannelStatus is the channel runtime state the process hosting the channels
// reports. Optional: nil disables the pair with codes.Unavailable, which is
// the honest answer for a store service no messaging process is writing to.
ChannelStatus storecontract.ChannelStatusStore
ApplyStatus storecontract.ApplyStatusStore
Mappings storecontract.MappingStore
EventTypes storecontract.EventTypeStore
ChannelStatus storecontract.ChannelStatusStore
ApplyStatus storecontract.ApplyStatusStore
Mappings storecontract.MappingStore
EventTypes storecontract.EventTypeStore
// MappingMatches counts the events each mapping resolved. Optional: nil
// answers RecordMappingMatch with codes.Unavailable.
MappingMatches storecontract.MappingMatchRecorder
Bindings storecontract.BindingStore
Sources storecontract.SourceStore
BindingDispatcher storecontract.BindingDispatcher
@@ -572,6 +575,16 @@ func (s *server) DeleteMapping(ctx context.Context, r *pb.DeleteMappingRequest)
return &pb.DeleteMappingResponse{}, nil
}
func (s *server) RecordMappingMatch(ctx context.Context, r *pb.RecordMappingMatchRequest) (*pb.RecordMappingMatchResponse, error) {
if s.deps.MappingMatches == nil {
return nil, status.Error(codes.Unavailable, "mapping match recorder unavailable")
}
if err := s.deps.MappingMatches.RecordMappingMatch(ctx, r.MappingId, r.CaptureId); err != nil {
return nil, s.logErr("RecordMappingMatch", err)
}
return &pb.RecordMappingMatchResponse{}, nil
}
// Binding
func (s *server) binding() (storecontract.BindingStore, error) {
+8 -6
View File
@@ -198,8 +198,9 @@ func mappingFieldValue(f *pb.MappingField) mapping.Field {
func mappingProto(m mapping.Mapping) *pb.Mapping {
return &pb.Mapping{
Id: m.ID, Name: m.Name, SourceHint: m.SourceHint,
Fields: mapValues(m.Fields, mappingFieldProto),
Id: m.ID, Name: m.Name, SourceHint: m.SourceHint, EventTypeId: m.EventTypeID,
Fields: mapValues(m.Fields, mappingFieldProto),
MatchCount: m.MatchCount, LastMatchedAt: timestamp(m.LastMatchedAt),
CreatedAt: timestamp(m.CreatedAt), UpdatedAt: timestamp(m.UpdatedAt),
}
}
@@ -209,8 +210,9 @@ func mappingValue(m *pb.Mapping) mapping.Mapping {
return mapping.Mapping{}
}
return mapping.Mapping{
ID: m.Id, Name: m.Name, SourceHint: m.SourceHint,
Fields: mapValues(m.Fields, mappingFieldValue),
ID: m.Id, Name: m.Name, SourceHint: m.SourceHint, EventTypeID: m.EventTypeId,
Fields: mapValues(m.Fields, mappingFieldValue),
MatchCount: m.MatchCount, LastMatchedAt: timeValue(m.LastMatchedAt),
CreatedAt: timeValue(m.CreatedAt), UpdatedAt: timeValue(m.UpdatedAt),
}
}
@@ -218,7 +220,7 @@ func mappingValue(m *pb.Mapping) mapping.Mapping {
func bindingProto(b binding.Binding) *pb.Binding {
return &pb.Binding{
Id: b.ID, Name: b.Name, Matcher: &pb.BindingMatcher{Source: b.Matcher.Source},
MappingId: b.MappingID, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
MappingId: b.MappingID, Filter: b.Filter, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
Version: int64(b.Version), Status: string(b.Status),
CreatedAt: timestamp(b.CreatedAt), UpdatedAt: timestamp(b.UpdatedAt),
}
@@ -234,7 +236,7 @@ func bindingValue(b *pb.Binding) binding.Binding {
}
return binding.Binding{
ID: b.Id, Name: b.Name, Matcher: binding.Matcher{Source: source},
MappingID: b.MappingId, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
MappingID: b.MappingId, Filter: b.Filter, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
Version: int(b.Version), Status: binding.Status(b.Status),
CreatedAt: timeValue(b.CreatedAt), UpdatedAt: timeValue(b.UpdatedAt),
}
+3 -5
View File
@@ -398,11 +398,9 @@ func (s *Store) EnqueueChatTask(ctx context.Context, owner, repo, title, body, w
// binding_version on the new row in a second statement.
//
// A crash between the two writes leaves the task without provenance
// (binding_id == 0); the binding_dispatches ledger row written by the
// dispatch loop still records the (binding, capture, task) triple, so
// a future repair pass could backfill. This is the same
// best-effort-provenance pattern the rest of the task lifecycle uses
// for fields added after the row's primary insert.
// (binding_id == 0). This is the same best-effort-provenance pattern the
// rest of the task lifecycle uses for fields added after the row's primary
// insert.
func (s *Store) EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity, bindingID string, bindingVersion int) (*workflow.Task, error) {
t, err := s.EnqueueChatTask(ctx, owner, repo, title, body, wf, identity)
if err != nil {
+33 -8
View File
@@ -16,6 +16,7 @@ type bindingRequest struct {
Name string `json:"name"`
Matcher binding.Matcher `json:"matcher"`
MappingID string `json:"mapping_id"`
Filter string `json:"filter"`
Workflow string `json:"workflow"`
// Owner and Repo optionally pin the binding to one configured repo,
// for multi-repo deployments. Both empty is valid (falls back to the
@@ -82,6 +83,7 @@ func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
Name: req.Name,
Matcher: req.Matcher,
MappingID: req.MappingID,
Filter: req.Filter,
Workflow: req.Workflow,
Owner: req.Owner,
Repo: req.Repo,
@@ -91,12 +93,11 @@ func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if !s.checkBindingFilter(w, r, b) {
return
}
id, err := s.Bindings.InsertBinding(r.Context(), b)
if err != nil {
if errors.Is(err, storecontract.ErrBindingOverlap) {
http.Error(w, "binding source overlaps an existing binding", http.StatusConflict)
return
}
s.Log.Error("insert binding", "err", err)
http.Error(w, "create binding failed", http.StatusInternalServerError)
return
@@ -166,6 +167,7 @@ func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) {
Name: req.Name,
Matcher: req.Matcher,
MappingID: req.MappingID,
Filter: req.Filter,
Workflow: req.Workflow,
Owner: req.Owner,
Repo: req.Repo,
@@ -174,12 +176,13 @@ func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if !s.checkBindingFilter(w, r, b) {
return
}
if err := s.Bindings.UpdateBinding(r.Context(), b); err != nil {
switch {
case errors.Is(err, storecontract.ErrBindingNotFound):
http.Error(w, "binding not found", http.StatusNotFound)
case errors.Is(err, storecontract.ErrBindingOverlap):
http.Error(w, "binding source overlaps an existing binding", http.StatusConflict)
default:
s.Log.Error("update binding", "err", err, "id", id)
http.Error(w, "update binding failed", http.StatusInternalServerError)
@@ -239,8 +242,6 @@ func (s *Server) handleBindingApprove(w http.ResponseWriter, r *http.Request) {
http.Error(w, "binding not found", http.StatusNotFound)
case errors.Is(err, storecontract.ErrBindingTransition):
http.Error(w, "binding cannot be approved from its current state", http.StatusConflict)
case errors.Is(err, storecontract.ErrBindingOverlap):
http.Error(w, "binding source overlaps an existing binding", http.StatusConflict)
default:
s.Log.Error("approve binding", "err", err, "id", id)
http.Error(w, "approve binding failed", http.StatusInternalServerError)
@@ -255,3 +256,27 @@ func (s *Server) handleBindingApprove(w http.ResponseWriter, r *http.Request) {
}
writeJSON(w, updated)
}
// checkBindingFilter refuses a binding whose mapping does not exist or whose
// filter does not compile against the mapping's parameters.
func (s *Server) checkBindingFilter(w http.ResponseWriter, r *http.Request, b binding.Binding) bool {
if s.Mappings == nil {
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
return false
}
m, err := s.Mappings.GetMapping(r.Context(), b.MappingID)
if err != nil {
s.Log.Error("get mapping for binding", "err", err, "mapping", b.MappingID)
http.Error(w, "get mapping failed", http.StatusInternalServerError)
return false
}
if m == nil {
http.Error(w, "binding: mapping not found: "+b.MappingID, http.StatusBadRequest)
return false
}
if _, err := binding.CompileFilter(b.Filter, m.Fields); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return false
}
return true
}
+137
View File
@@ -0,0 +1,137 @@
package webui
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"testing"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
// memBindings keeps mappings and bindings in memory with no per-source limit,
// as the Postgres store does.
type memBindings struct {
mappings map[string]mapping.Mapping
bindings map[string]binding.Binding
}
func newMemBindings() *memBindings {
return &memBindings{mappings: map[string]mapping.Mapping{}, bindings: map[string]binding.Binding{}}
}
func (m *memBindings) InsertMapping(_ context.Context, v mapping.Mapping) (string, error) {
v.ID = fmt.Sprintf("m%d", len(m.mappings)+1)
m.mappings[v.ID] = v
return v.ID, nil
}
func (m *memBindings) GetMapping(_ context.Context, id string) (*mapping.Mapping, error) {
v, ok := m.mappings[id]
if !ok {
return nil, nil
}
return &v, nil
}
func (m *memBindings) ListMappings(context.Context) ([]mapping.Mapping, error) { return nil, nil }
func (m *memBindings) UpdateMapping(context.Context, mapping.Mapping) error { return nil }
func (m *memBindings) DeleteMapping(context.Context, string) error { return nil }
func (m *memBindings) InsertBinding(_ context.Context, b binding.Binding) (string, error) {
b.ID = fmt.Sprintf("b%d", len(m.bindings)+1)
m.bindings[b.ID] = b
return b.ID, nil
}
func (m *memBindings) GetBinding(_ context.Context, id string) (*binding.Binding, error) {
v, ok := m.bindings[id]
if !ok {
return nil, nil
}
return &v, nil
}
func (m *memBindings) ListBindings(context.Context) ([]binding.Binding, error) { return nil, nil }
func (m *memBindings) UpdateBinding(_ context.Context, b binding.Binding) error {
if _, ok := m.bindings[b.ID]; !ok {
return storecontract.ErrBindingNotFound
}
m.bindings[b.ID] = b
return nil
}
func (m *memBindings) DeleteBinding(context.Context, string) error { return nil }
func (m *memBindings) ApproveBinding(context.Context, string) error { return nil }
func memBindingServer(t *testing.T) (*Server, string) {
t.Helper()
store := newMemBindings()
mappingID, _ := store.InsertMapping(t.Context(), mapping.Mapping{
Name: "m", EventTypeID: "et-1",
Fields: []mapping.Field{{Name: "title", Path: "issue.title", Type: mapping.TypeString}},
})
return &Server{
Log: slog.New(slog.DiscardHandler),
Mappings: store,
Bindings: store,
ControlPlane: workflowControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"}}}),
}, mappingID
}
// Several bindings may share a source.
func TestHandleBindingCreateAllowsSeveralPerSource(t *testing.T) {
srv, mappingID := memBindingServer(t)
for _, suffix := range []string{"first", "second"} {
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest(suffix, "sentry", mappingID))
if w.Code != http.StatusCreated {
t.Fatalf("%s create status = %d, want %d; body = %s", suffix, w.Code, http.StatusCreated, w.Body.String())
}
}
}
// A binding's filter is checked against its mapping's parameters on save.
func TestHandleBindingFilterIsCheckedAgainstMapping(t *testing.T) {
tests := []struct {
name string
filter string
want int
}{
{"no filter", "", http.StatusCreated},
{"filter on a mapped parameter", `title.startsWith("P1")`, http.StatusCreated},
{"unknown parameter", `severity == "high"`, http.StatusBadRequest},
{"not boolean", `title`, http.StatusBadRequest},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv, mappingID := memBindingServer(t)
req := validBindingRequest("f", "sentry", mappingID)
req["filter"] = tt.filter
w := doJSON(t, srv, http.MethodPost, "/api/bindings", req)
if w.Code != tt.want {
t.Fatalf("create status = %d, want %d; body = %s", w.Code, tt.want, w.Body.String())
}
if w.Code == http.StatusCreated {
var created binding.Binding
_ = json.Unmarshal(w.Body.Bytes(), &created)
if created.Filter != tt.filter {
t.Fatalf("created.Filter = %q, want %q", created.Filter, tt.filter)
}
w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, req)
if w.Code != http.StatusOK {
t.Fatalf("update status = %d; body = %s", w.Code, w.Body.String())
}
}
})
}
}
func TestHandleBindingRejectsUnknownMapping(t *testing.T) {
srv, _ := memBindingServer(t)
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("x", "sentry", "absent"))
if w.Code != http.StatusBadRequest {
t.Fatalf("create status = %d, want %d; body = %s", w.Code, http.StatusBadRequest, w.Body.String())
}
}
-17
View File
@@ -149,23 +149,6 @@ func TestHandleBindingCreateRejectsPartialOwnerRepo(t *testing.T) {
}
}
func TestHandleBindingCreateRejectsOverlap(t *testing.T) {
srv := bindingTestServer(t)
mappingID := seedMapping(t, srv, "m")
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("first", "sentry", mappingID))
if w.Code != http.StatusCreated {
t.Fatalf("first create status = %d, want %d; body = %s", w.Code, http.StatusCreated, w.Body.String())
}
// Overlap because Per bead t2db.4, two bindings may not own the same
// source; the second insert must surface ErrBindingOverlap -> 409.
w = doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("second", "sentry", mappingID))
if w.Code != http.StatusConflict {
t.Fatalf("second create status = %d, want %d; body = %s", w.Code, http.StatusConflict, w.Body.String())
}
}
func TestHandleBindingCreateRejectsMissingWorkflow(t *testing.T) {
srv := bindingTestServer(t)
mappingID := seedMapping(t, srv, "m")
+38 -9
View File
@@ -14,9 +14,40 @@ import (
// PATCH /api/mappings/{id} both accept. ID/CreatedAt/UpdatedAt are
// server-assigned, never taken from the request body.
type mappingRequest struct {
Name string `json:"name"`
SourceHint string `json:"source_hint"`
Fields []mapping.Field `json:"fields"`
Name string `json:"name"`
SourceHint string `json:"source_hint"`
EventTypeID string `json:"event_type_id"`
Fields []mapping.Field `json:"fields"`
}
// validateMapping checks m is well-formed and fits its event type's schema.
// It writes the refusal and returns false when it does not.
func (s *Server) validateMapping(w http.ResponseWriter, r *http.Request, m mapping.Mapping) bool {
if err := m.Validate(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return false
}
if s.EventTypes == nil {
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
return false
}
types, err := s.EventTypes.ListEventTypes(r.Context())
if err != nil {
s.Log.Error("list event types", "err", err)
http.Error(w, "list event types failed", http.StatusInternalServerError)
return false
}
for _, t := range types {
if t.ID == m.EventTypeID {
if err := mapping.CheckSchema(m.Fields, t.Schema); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return false
}
return true
}
}
http.Error(w, "mapping: event type not found: "+m.EventTypeID, http.StatusBadRequest)
return false
}
func (s *Server) handleMappingsList(w http.ResponseWriter, r *http.Request) {
@@ -46,9 +77,8 @@ func (s *Server) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
m := mapping.Mapping{Name: req.Name, SourceHint: req.SourceHint, Fields: req.Fields}
if err := m.Validate(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
m := mapping.Mapping{Name: req.Name, SourceHint: req.SourceHint, EventTypeID: req.EventTypeID, Fields: req.Fields}
if !s.validateMapping(w, r, m) {
return
}
id, err := s.Mappings.InsertMapping(r.Context(), m)
@@ -108,9 +138,8 @@ func (s *Server) handleMappingUpdate(w http.ResponseWriter, r *http.Request) {
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
return
}
m := mapping.Mapping{ID: id, Name: req.Name, SourceHint: req.SourceHint, Fields: req.Fields}
if err := m.Validate(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
m := mapping.Mapping{ID: id, Name: req.Name, SourceHint: req.SourceHint, EventTypeID: req.EventTypeID, Fields: req.Fields}
if !s.validateMapping(w, r, m) {
return
}
if err := s.Mappings.UpdateMapping(r.Context(), m); err != nil {
+82 -18
View File
@@ -9,6 +9,7 @@ import (
"path/filepath"
"testing"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
"github.com/samcharles93/archie-core/internal/store"
@@ -26,10 +27,66 @@ func mappingTestServer(t *testing.T) *Server {
t.Cleanup(func() { _ = s.Close() })
eda := edastore.OpenTest(t)
return &Server{
Store: s,
Log: slog.New(slog.DiscardHandler),
Mappings: eda,
Captures: eda,
Store: s,
Log: slog.New(slog.DiscardHandler),
Mappings: eda,
Captures: eda,
EventTypes: testEventTypes(),
}
}
// testEventTypes holds one event type, et-1, whose schema has every path the
// mapping tests write.
func testEventTypes() *memEventTypes {
return &memEventTypes{types: []eventtype.EventType{{
ID: "et-1", Source: "sentry", Name: "issue",
Schema: map[string]eventtype.ValueType{
"a": eventtype.TypeString, "b": eventtype.TypeBool,
"issue": eventtype.TypeObject, "issue.title": eventtype.TypeString,
},
}}}
}
// A mapping belongs to an event type and is checked against its schema.
func TestHandleMappingSaveChecksEventTypeSchema(t *testing.T) {
tests := []struct {
name string
eventType string
path string
fieldType mapping.FieldType
want int
}{
{"fits the schema", "et-1", "issue.title", mapping.TypeString, http.StatusCreated},
{"no event type", "", "issue.title", mapping.TypeString, http.StatusBadRequest},
{"unknown event type", "et-9", "issue.title", mapping.TypeString, http.StatusBadRequest},
{"path the type does not have", "et-1", "sender.login", mapping.TypeString, http.StatusBadRequest},
{"type differs from the schema", "et-1", "issue.title", mapping.TypeNumber, http.StatusBadRequest},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := mappingTestServer(t)
req := map[string]any{
"name": "m",
"event_type_id": tt.eventType,
"fields": []mapping.Field{{Name: "f", Path: tt.path, Type: tt.fieldType}},
}
if w := doJSON(t, srv, http.MethodPost, "/api/mappings", req); w.Code != tt.want {
t.Fatalf("create status = %d, want %d; body = %s", w.Code, tt.want, w.Body.String())
}
ok := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
"name": "base", "event_type_id": "et-1",
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
})
var created mapping.Mapping
_ = json.Unmarshal(ok.Body.Bytes(), &created)
want := tt.want
if want == http.StatusCreated {
want = http.StatusOK
}
if w := doJSON(t, srv, http.MethodPatch, "/api/mappings/"+created.ID, req); w.Code != want {
t.Fatalf("update status = %d, want %d; body = %s", w.Code, want, w.Body.String())
}
})
}
}
@@ -74,8 +131,9 @@ func doJSONWithHeaders(t *testing.T, srv *Server, method, path string, body any,
func TestHandleMappingCreateAndGet(t *testing.T) {
srv := mappingTestServer(t)
w := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
"name": "sentry issue opened",
"source_hint": "sentry",
"name": "sentry issue opened",
"source_hint": "sentry",
"event_type_id": "et-1",
"fields": []mapping.Field{
{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: true},
},
@@ -124,8 +182,9 @@ func TestHandleMappingsList(t *testing.T) {
srv := mappingTestServer(t)
for range 3 {
doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
"name": "m",
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
"name": "m",
"event_type_id": "et-1",
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
})
}
w := doJSON(t, srv, http.MethodGet, "/api/mappings", nil)
@@ -146,15 +205,17 @@ func TestHandleMappingsList(t *testing.T) {
func TestHandleMappingUpdate(t *testing.T) {
srv := mappingTestServer(t)
w := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
"name": "orig",
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
"name": "orig",
"event_type_id": "et-1",
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
})
var created mapping.Mapping
_ = json.Unmarshal(w.Body.Bytes(), &created)
w = doJSON(t, srv, http.MethodPatch, "/api/mappings/"+created.ID, map[string]any{
"name": "renamed",
"fields": []mapping.Field{{Name: "b", Path: "b", Type: mapping.TypeBool}},
"name": "renamed",
"event_type_id": "et-1",
"fields": []mapping.Field{{Name: "b", Path: "b", Type: mapping.TypeBool}},
})
if w.Code != http.StatusOK {
t.Fatalf("update status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
@@ -171,8 +232,9 @@ func TestHandleMappingUpdate(t *testing.T) {
func TestHandleMappingUpdateMissingReturns404(t *testing.T) {
srv := mappingTestServer(t)
w := doJSON(t, srv, http.MethodPatch, "/api/mappings/999", map[string]any{
"name": "x",
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
"name": "x",
"event_type_id": "et-1",
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
})
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusNotFound, w.Body.String())
@@ -182,8 +244,9 @@ func TestHandleMappingUpdateMissingReturns404(t *testing.T) {
func TestHandleMappingDelete(t *testing.T) {
srv := mappingTestServer(t)
w := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
"name": "m",
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
"name": "m",
"event_type_id": "et-1",
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
})
var created mapping.Mapping
_ = json.Unmarshal(w.Body.Bytes(), &created)
@@ -274,8 +337,9 @@ func TestHandleMappingsUnavailableWhenNotConfigured(t *testing.T) {
func TestHandleMappingMutationsRequireCSRFHeader(t *testing.T) {
srv := mappingTestServer(t)
newMapping := map[string]any{
"name": "sentry issue opened",
"source_hint": "sentry",
"name": "sentry issue opened",
"source_hint": "sentry",
"event_type_id": "et-1",
"fields": []mapping.Field{
{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: true},
},
+14
View File
@@ -119,6 +119,9 @@ service StateStoreService {
rpc ListMappings(ListMappingsRequest) returns (ListMappingsResponse);
rpc UpdateMapping(UpdateMappingRequest) returns (UpdateMappingResponse);
rpc DeleteMapping(DeleteMappingRequest) returns (DeleteMappingResponse);
// RecordMappingMatch counts one event a mapping resolved; the same
// (mapping, capture) twice counts once.
rpc RecordMappingMatch(RecordMappingMatchRequest) returns (RecordMappingMatchResponse);
// EventType (docs/prds/event-automation.md, "Event types"). Insert and
// Update refuse an overlapping or malformed type.
@@ -372,6 +375,10 @@ message Mapping {
repeated MappingField fields = 4;
google.protobuf.Timestamp created_at = 5;
google.protobuf.Timestamp updated_at = 6;
string event_type_id = 7;
// match_count and last_matched_at are read-only: the store counts them.
int64 match_count = 8;
google.protobuf.Timestamp last_matched_at = 9;
}
// BindingMatcher mirrors internal/domain/binding.Matcher.
@@ -394,6 +401,7 @@ message Binding {
string secret = 10 [deprecated = true];
google.protobuf.Timestamp created_at = 11;
google.protobuf.Timestamp updated_at = 12;
string filter = 13;
}
// Source mirrors internal/domain/source.Source.
@@ -744,6 +752,12 @@ message UpdateMappingResponse {}
message DeleteMappingRequest { string id = 1; }
message DeleteMappingResponse {}
message RecordMappingMatchRequest {
string mapping_id = 1;
string capture_id = 2;
}
message RecordMappingMatchResponse {}
message InsertEventTypeRequest { EventType event_type = 1; }
message InsertEventTypeResponse { string id = 1; }
+2 -2
View File
@@ -16,5 +16,5 @@ Defaulting to \`null\`.`),null)}function Mx(e){return Ax(e)&&!Number.isNaN(e)&&e
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:lT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>lT(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=dT(c),u=e+1<n.length?dT(n[e+1]):null;if(l&&u&&fT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=dT(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>lT(e)),rows:r.map(e=>e.map(e=>lT(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:lT(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:lT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
`)}),t}function dT(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function fT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var pT={class:`[overflow-wrap:anywhere]`},mT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},hT={class:`font-mono text-[0.85em]`},gT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},_T={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},vT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},yT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},bT={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},xT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},ST={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},CT={key:8,class:`mb-2.5 last:mb-0`},wT=M({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=W(()=>uT(t.text));return(e,t)=>(I(),L(`div`,pT,[(I(!0),L(F,null,N(n.value,(e,t)=>(I(),L(F,{key:t},[e.kind===`pre`?(I(),L(`pre`,mT,[z(`code`,hT,D(e.code),1)])):e.kind===`table`?(I(),L(`table`,gT,[z(`thead`,null,[z(`tr`,null,[(I(!0),L(F,null,N(e.head,(e,t)=>(I(),L(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[B(sT,{inline:e},null,8,[`inline`])]))),128))])]),z(`tbody`,null,[(I(!0),L(F,null,N(e.rows,(e,t)=>(I(),L(`tr`,{key:t},[(I(!0),L(F,null,N(e,(e,t)=>(I(),L(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[B(sT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(I(),L(`blockquote`,_T,[B(sT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(I(),L(`h1`,vT,[B(sT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(I(),L(`h2`,yT,[B(sT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(I(),L(`h3`,bT,[B(sT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(I(),L(`ul`,xT,[(I(!0),L(F,null,N(e.items,(e,t)=>(I(),L(`li`,{key:t},[B(sT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(I(),L(`ol`,ST,[(I(!0),L(F,null,N(e.items,(e,t)=>(I(),L(`li`,{key:t},[B(sT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(I(),L(`p`,CT,[B(sT,{inline:e.inline},null,8,[`inline`])])):H(``,!0)],64))),128))]))}}),TT={class:`truncate`},ET=M({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ha(`RouterLink`);return I(),R(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:A(()=>[B(k(bd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),z(`span`,TT,D(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),DT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},OT={class:`font-semibold text-foreground`},kT={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},AT=M({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=W(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=W(()=>t.tool.parameters||t.tool.Parameters||``),i=W(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=W(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(I(),R(ET,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(I(),L(`div`,DT,[B(k($d),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),z(`span`,OT,D(n.value),1),r.value?(I(),L(`code`,kT,D(r.value),1)):H(``,!0),z(`span`,{class:E(k(q)(`text-fg-muted`,i.value&&`text-danger`))},D(a.value),3)]))}}),jT={key:0,class:`mb-2 grid gap-0.5 text-xs`},MT={key:2,class:`whitespace-pre-wrap`},NT=M({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(I(),L(`div`,{class:E([`flex`,e.assistant?`justify-start`:`justify-end`])},[z(`div`,{class:E(k(q)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(I(),L(`div`,jT,[(I(!0),L(F,null,N(e.tools,(t,n)=>(I(),R(AT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):H(``,!0),e.assistant?(I(),R(wT,{key:1,text:e.text},null,8,[`text`])):(I(),L(`div`,MT,D(e.text),1)),P(t.$slots,`default`)],2)],2))}}),PT={class:`w-full self-center justify-self-center py-6 text-center`},FT={class:`grid gap-2`},IT=[`onClick`],LT=M({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(I(),L(`div`,PT,[t[0]||=z(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>oA?`${n.slice(0,oA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var cA=[`title`],lA=M({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=W(()=>Pk(n.event)),a=W(()=>sA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=W(()=>n.event.at?TO(n.event.at):`—`);return(e,t)=>(I(),R(k(iA),{class:E(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[fu(uu(o,[`prevent`]),[`enter`]),fu(uu(o,[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-medium`},{default:A(()=>[V(D(n.event.kind||n.event.type||`event`),1)]),_:1}),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(i.value>0?`#${i.value}`:`—`),1)]),_:1}),B(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[z(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},D(a.value.text),9,cA)]),_:1}),B(k(Q),null,{default:A(()=>[V(D(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function uA(e,t){return`${e}:${t??0}`}function dA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=uA(sA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var fA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},pA={class:`max-h-[28rem] overflow-y-auto`},mA=[`aria-expanded`,`aria-label`,`onClick`],hA=[`title`],gA=M({__name:`LiveActivityCard`,setup(e){let t=oE(),{activity:n,streamKind:r,streamState:i}=od(sk()),a=rn(new Set),o=W(()=>dA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return sA(e.representative)}function u(e){return e.representative.at?TO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(I(),R(k(_O),null,{default:A(()=>[B(k(SO),null,{default:A(()=>[B(k(CO),null,{default:A(()=>[...t[0]||=[V(`Live activity`,-1)]]),_:1}),B(k(vO),null,{default:A(()=>[B(k(rO),{variant:k(r)},{default:A(()=>[V(D(k(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),B(k(yO),null,{default:A(()=>[z(`div`,fA,[z(`div`,pA,[B(k(nA),null,{default:A(()=>[B(k(aA),{class:`sticky top-0 z-10 bg-card`},{default:A(()=>[B(k(iA),null,{default:A(()=>[B(k($),null,{default:A(()=>[...t[1]||=[V(`Event`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[2]||=[V(`Task`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[3]||=[V(`Detail`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[4]||=[V(`When`,-1)]]),_:1})]),_:1})]),_:1}),B(k(rA),null,{default:A(()=>[k(n).length?H(``,!0):(I(),R(k(iA),{key:0},{default:A(()=>[B(k(Q),{colspan:`4`},{default:A(()=>[B(k(YD),null,{default:A(()=>[B(k(QD),null,{default:A(()=>[B(k(tO),null,{default:A(()=>[...t[5]||=[V(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),k(n).length?(I(!0),L(F,{key:1},N(o.value,e=>(I(),L(F,{key:e.key},[e.count===1?(I(),R(lA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(I(),L(F,{key:1},[B(k(iA),{class:E(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-medium`},{default:A(()=>[z(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:uu(t=>s(e.key),[`stop`])},[c(e)?(I(),R(k(Sd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(I(),R(k(wd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),V(` `+D(e.label)+` `,1),B(k(rO),{variant:`idle`},{default:A(()=>[V(`×`+D(e.count),1)]),_:2},1024)],8,mA)]),_:2},1024),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),B(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[z(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},D(l(e).text),9,hA)]),_:2},1024),B(k(Q),null,{default:A(()=>[V(D(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(I(!0),L(F,{key:0},N(e.events,(t,n)=>(I(),R(lA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):H(``,!0)],64))],64))),128)):H(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),_A=M({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=aC(t,`class`);return(e,r)=>(I(),R(k(Nx),U({"data-slot":`progress`},k(n),{class:k(q)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:A(()=>[B(k(Px),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ye(`transLine truncated
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim();r&&(t[r]=n.slice(e+1).trim())}return t}function kM(e,t){if(!e.event_type)return{label:`Unidentified`,identified:!1};let n=t.find(t=>t.id===e.event_type);return{label:n?n.name:`Deleted type`,identified:!0}}function AM(e){let t=[...(e.headers||[]).map(e=>`${e.name} = ${e.value}`),...(e.payload||[]).map(e=>e.op===`present`?`${e.path} present`:`${e.path} = ${e.value??``}`)];return t.length?t.join(` · `):`any event`}function jM(e){return{headers:(e.headers||[]).filter(e=>e.name.trim()!==``).map(e=>({name:e.name.trim(),value:e.value})),payload:(e.payload||[]).filter(e=>e.path.trim()!==``).map(e=>e.op===`present`?{path:e.path.trim(),op:e.op}:{path:e.path.trim(),op:e.op,value:e.value??``})}}var MM=O([]),NM=O([]),PM=O(!0),FM=O(null),IM=O(null),LM=O(!1),RM=O(null);async function zM(){try{let e=await J.eventTypes();PM.value=e.enabled!==!1,MM.value=e.event_types||[],NM.value=e.proposals||[],FM.value=null}catch(e){FM.value=e.message||String(e)}}function BM(e){return{headers:(e.headers||[]).map(e=>({...e})),payload:(e.payload||[]).map(e=>({...e}))}}function VM(e){RM.value=null,IM.value=e}function HM(e){let t=XM.value.find(t=>String(t.id)===e.sample_id);VM({mode:`proposal`,id:null,source:e.source,name:``,rule:BM(e.rule),headersText:``,body:t?.body||``,exampleHeaders:e.headers||{}})}function UM(e=``){VM({mode:`paste`,id:null,source:e,name:``,rule:{headers:[],payload:[]},headersText:``,body:``,exampleHeaders:{}})}function WM(e){VM({mode:`edit`,id:e.id,source:e.source,name:e.name,rule:BM(e.rule),headersText:``,body:``,exampleHeaders:{}})}function GM(){IM.value=null}async function KM(){let e=IM.value;if(e){LM.value=!0;try{if(e.mode===`edit`&&e.id)await J.eventTypeUpdate(e.id,{name:e.name,rule:jM(e.rule)});else{let t=e.mode===`paste`?OM(e.headersText):e.exampleHeaders;await J.eventTypeCreate({source:e.source,name:e.name,rule:e.mode===`paste`?void 0:jM(e.rule),example:{headers:t,body:e.body}})}IM.value=null,await zM()}catch(e){RM.value=e.message||String(e)}finally{LM.value=!1}}}var qM=O(null);async function JM(){let e=qM.value;if(qM.value=null,e)try{await J.eventTypeDelete(e.id),await zM()}catch(e){FM.value=e.message||String(e)}}var YM=100,XM=O([]),ZM=O(!0),QM=O(null),$M=O(!0),eN=O(null);async function tN(){try{let e=await J.captures(YM);ZM.value=e.enabled!==!1,XM.value=e.captures||[],QM.value=null}catch(e){QM.value=e.message||String(e)}finally{$M.value=!1}}function nN(e){let t=XM.value.find(t=>t.id===e);return t&&(eN.value=t),!!t}function rN(){XM.value.length&&(eN.value=XM.value[0])}function iN(){ck(`captures`,()=>{tN(),zM()})}var aN={class:`flex flex-col gap-5`},oN=M({__name:`CaptureDetail`,props:{maxHeight:{}},setup(e){let t=e,n=O(null),r=mC(`(max-width: 1099px)`),i=W(()=>r.value||!t.maxHeight?void 0:`${t.maxHeight}px`),a=W(()=>eN.value?_M(eN.value):null),o=W(()=>{let e=eN.value;return e?[TO(e.received_at),e.content_type||`no content type`,e.remote_addr].filter(Boolean).join(` · `):``});return j(eN,()=>{r.value&&n.value?.scrollIntoView({block:`start`,behavior:`smooth`})}),(e,t)=>k(eN)?(I(),L(`div`,{key:0,ref_key:`pane`,ref:n,class:`min-w-0`},[B(k(_O),{class:`flex flex-col`,style:ye(i.value?{maxHeight:i.value}:void 0)},{default:A(()=>[B(k(SO),null,{default:A(()=>[B(k(CO),{class:`flex items-center gap-2 font-mono`},{default:A(()=>[V(D(k(eN).source||`Unknown source`)+` `,1),a.value?(I(),R(k(rO),{key:0,variant:a.value.kind},{default:A(()=>[V(D(a.value.label),1)]),_:1},8,[`variant`])):H(``,!0)]),_:1}),B(k(bO),null,{default:A(()=>[V(D(o.value),1)]),_:1})]),_:1}),B(k(yO),{class:`min-h-0 max-h-[62vh] overflow-y-auto min-[1100px]:max-h-none`},{default:A(()=>[z(`div`,aN,[B(DM,{label:`Payload`,raw:k(eN).body},null,8,[`raw`]),B(DM,{label:`Headers`,raw:k(eN).headers},null,8,[`raw`])])]),_:1})]),_:1},8,[`style`])],512)):H(``,!0)}}),sN=M({__name:`CaptureStatus`,setup(e){let{streamKind:t,streamState:n}=od(sk());return(e,r)=>(I(),R(k(rO),{variant:k(t)},{default:A(()=>[V(D(k(n)),1)]),_:1},8,[`variant`]))}}),cN={class:`flex items-center gap-1`},lN={class:`truncate`},uN=M({__name:`CaptureRow`,props:{capture:{}},setup(e){let t=e,n=W(()=>kM(t.capture,MM.value)),r=W(()=>_M(t.capture)),i=W(()=>eN.value?.id===t.capture.id),a=W(()=>`Show the payload received from ${t.capture.source||`an unknown source`}`);function o(){eN.value=t.capture}return(e,s)=>(I(),R(k(iA),{"data-state":i.value?`selected`:void 0,role:`button`,tabindex:`0`,"aria-current":i.value?`true`:void 0,"aria-label":a.value,class:`cursor-pointer focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring`,onClick:o,onKeydown:[fu(uu(o,[`prevent`]),[`enter`]),fu(uu(o,[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(t.capture.source||`(unknown)`),1)]),_:1}),B(k(Q),{title:t.capture.received_at||``},{default:A(()=>[V(D(k(TO)(t.capture.received_at)),1)]),_:1},8,[`title`]),B(k(Q),null,{default:A(()=>[z(`div`,cN,[B(k(rO),{variant:n.value.identified?`ok`:`warn`,class Line truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>oA?`${n.slice(0,oA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var cA=[`title`],lA=M({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=W(()=>Pk(n.event)),a=W(()=>sA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=W(()=>n.event.at?TO(n.event.at):`—`);return(e,t)=>(I(),R(k(iA),{class:E(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[fu(uu(o,[`prevent`]),[`enter`]),fu(uu(o,[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-medium`},{default:A(()=>[V(D(n.event.kind||n.event.type||`event`),1)]),_:1}),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(i.value>0?`#${i.value}`:`—`),1)]),_:1}),B(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[z(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},D(a.value.text),9,cA)]),_:1}),B(k(Q),null,{default:A(()=>[V(D(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function uA(e,t){return`${e}:${t??0}`}function dA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=uA(sA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var fA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},pA={class:`max-h-[28rem] overflow-y-auto`},mA=[`aria-expanded`,`aria-label`,`onClick`],hA=[`title`],gA=M({__name:`LiveActivityCard`,setup(e){let t=oE(),{activity:n,streamKind:r,streamState:i}=od(sk()),a=rn(new Set),o=W(()=>dA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return sA(e.representative)}function u(e){return e.representative.at?TO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(I(),R(k(_O),null,{default:A(()=>[B(k(SO),null,{default:A(()=>[B(k(CO),null,{default:A(()=>[...t[0]||=[V(`Live activity`,-1)]]),_:1}),B(k(vO),null,{default:A(()=>[B(k(rO),{variant:k(r)},{default:A(()=>[V(D(k(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),B(k(yO),null,{default:A(()=>[z(`div`,fA,[z(`div`,pA,[B(k(nA),null,{default:A(()=>[B(k(aA),{class:`sticky top-0 z-10 bg-card`},{default:A(()=>[B(k(iA),null,{default:A(()=>[B(k($),null,{default:A(()=>[...t[1]||=[V(`Event`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[2]||=[V(`Task`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[3]||=[V(`Detail`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[4]||=[V(`When`,-1)]]),_:1})]),_:1})]),_:1}),B(k(rA),null,{default:A(()=>[k(n).length?H(``,!0):(I(),R(k(iA),{key:0},{default:A(()=>[B(k(Q),{colspan:`4`},{default:A(()=>[B(k(YD),null,{default:A(()=>[B(k(QD),null,{default:A(()=>[B(k(tO),null,{default:A(()=>[...t[5]||=[V(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),k(n).length?(I(!0),L(F,{key:1},N(o.value,e=>(I(),L(F,{key:e.key},[e.count===1?(I(),R(lA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(I(),L(F,{key:1},[B(k(iA),{class:E(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-medium`},{default:A(()=>[z(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:uu(t=>s(e.key),[`stop`])},[c(e)?(I(),R(k(Sd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(I(),R(k(wd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),V(` `+D(e.label)+` `,1),B(k(rO),{variant:`idle`},{default:A(()=>[V(`×`+D(e.count),1)]),_:2},1024)],8,mA)]),_:2},1024),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),B(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[z(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},D(l(e).text),9,hA)]),_:2},1024),B(k(Q),null,{default:A(()=>[V(D(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(I(!0),L(F,{key:0},N(e.events,(t,n)=>(I(),R(lA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):H(``,!0)],64))],64))),128)):H(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),_A=M({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=aC(t,`class`);return(e,r)=>(I(),R(k(Nx),U({"data-slot":`progress`},k(n),{class:k(q)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:A(()=>[B(k(Px),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ye(`transLine truncated
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim();r&&(t[r]=n.slice(e+1).trim())}return t}function Bj(e,t){if(!e.event_type)return{label:`Unidentified`,identified:!1};let n=t.find(t=>t.id===e.event_type);return{label:n?n.name:`Deleted type`,identified:!0}}function Vj(e,t){if(!e)return`No event type`;let n=t.find(t=>t.id===e);return n?`${n.source} / ${n.name}`:`Deleted type`}function Hj(e){let t=[...(e.headers||[]).map(e=>`${e.name} = ${e.value}`),...(e.payload||[]).map(e=>e.op===`present`?`${e.path} present`:`${e.path} = ${e.value??``}`)];return t.length?t.join(` · `):`any event`}function Uj(e){return{headers:(e.headers||[]).filter(e=>e.name.trim()!==``).map(e=>({name:e.name.trim(),value:e.value})),payload:(e.payload||[]).filter(e=>e.path.trim()!==``).map(e=>e.op===`present`?{path:e.path.trim(),op:e.op}:{path:e.path.trim(),op:e.op,value:e.value??``})}}function Wj(e,t){return t?e.filter(e=>e.event_type_id===t):[]}var Gj={pending_approval:`pending approval`,armed:`armed`},Kj={pending_approval:`warn`,armed:`ok`};function qj(e){return e?Gj[e]??e:`unknown`}function Jj(e){return Kj[e??``]??`idle`}function Yj(){return{id:null,name:``,eventTypeId:``,mappingId:``,filter:``,workflow:``,owner:``,repo:``}}function Xj(e,t){let n=t.find(t=>t.id===e.mapping_id);return{id:e.id,name:e.name,eventTypeId:n?.event_type_id||``,mappingId:e.mapping_id||``,filter:e.filter||``,workflow:e.workflow||``,owner:e.owner||``,repo:e.repo||``}}function Zj(e,t){let n=t.find(t=>t.id===e.eventTypeId);return{name:e.name,matcher:{source:n?.source||``},mapping_id:e.mappingId,filter:e.filter.trim(),workflow:e.workflow,owner:e.owner,repo:e.repo}}function Qj(e){return e.owner&&e.repo?`${e.owner}/${e.repo}`:`—`}function $j(e,t){return t.find(t=>t.id===e.mapping_id)?.event_type_id}var eM={class:`grid grid-cols-2 items-start gap-3`},tM=M({__name:`BindingEditor`,props:Va({binding:{},mappings:{},eventTypes:{},workflows:{},saving:{type:Boolean},error:{}},{open:{type:Boolean,required:!0},openModifiers:{}}),emits:Va([`save`],[`update:open`]),setup(e,{emit:t}){let n=e,r=lo(e,`open`),i=t,a=O(Yj());j(r,e=>{e&&(a.value=n.binding?Xj(n.binding,n.mappings):Yj())},{immediate:!0});let o=W(()=>Wj(n.mappings,a.value.eventTypeId));j(()=>a.value.eventTypeId,()=>{o.value.some(e=>e.id===a.value.mappingId)||(a.value.mappingId=``)});let s=W(()=>n.binding?`Edit binding`:`New binding`);return(e,t)=>(I(),R(k(Mj),{open:r.value,"onUpdate:open":t[9]||=e=>r.value=e},{default:A(()=>[B(k(Pj),{class:`max-h-[85vh] overflow-y-auto sm:max-w-lg`},{default:A(()=>[B(k(Lj),null,{default:A(()=>[B(k(Rj),null,{default:A(()=>[V(D(s.value),1)]),_:1}),B(k(Fj),null,{default:A(()=>[...t[10]||=[V(` A binding is not armed until it is approved, and editing one drops it back to pending approval. `,-1)]]),_:1})]),_:1}),z(`form`,{onSubmit:t[8]||=uu(e=>i(`save`,a.value),[`prevent`])},[B(k(IC),null,{default:A(()=>[B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-name`},{default:A(()=>[...t[11]||=[V(`Name`,-1)]]),_:1}),B(k(LO),{id:`binding-name`,modelValue:a.value.name,"onUpdate:modelValue":t[0]||=e=>a.value.name=e},null,8,[`modelValue`])]),_:1}),B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-event-type`},{default:A(()=>[...t[12]||=[V(`Event type`,-1)]]),_:1}),B(k(JS),{modelValue:a.value.eventTypeId,"onUpdate:modelValue":t[1]||=e=>a.value.eventTypeId=e},{default:A(()=>[B(k(CC),{id:`binding-event-type`,class:`w-full`},{default:A(()=>[B(k(wC),{placeholder:`Pick an event type`})]),_:1}),B(k(_C),null,{default:A(()=>[B(k(vC),null,{default:A(()=>[(I(!0),L(F,null,N(n.eventTypes,e=>(I(),R(k(bC),{key:e.id,value:e.id},{default:A(()=>[V(D(k(Vj)(e.id,n.eventTypes)),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`modelValue`])]),_:1}),B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-mapping`},{default:A(()=>[...t[13]||=[V(`Field mapping`,-1)]]),_:1}),B(k(JS),{modelValue:a.value.mappingId,"onUpdate:modelValue":t[2]||=e=>a.value.mappingId=e,disabled:!o.value.length},{default:A(()=>[B(k(CC),{id:`binding-mapping`,class:`w-full`},{default:A(()=>[B(k(wC),{placeholder:a.value.eventTypeId&&!o.value.length?`No mappings for this event type`:`Pick a mapping`},null,8,[`placeholder`])]),_:1}),B(k(_C),null,{default:A(()=>[B(k(vC),null,{default:A(()=>[(I(!0),L(F,null,N(o.value,e=>(I(),R(k(bC),{key:e.id,value:String(e.id)},{default:A(()=>[V(D(e.name),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`modelValue`,`disabled`])]),_:1}),B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-filter`},{default:A(()=>[...t[14]||=[V(`Filter`,-1)]]),_:1}),B(k(LO),{id:`binding-filter`,modelValue:a.value.filter,"onUpdate:modelValue":t[3]||=e=>a.value.filter=e,class:`font-mono text-xs`,placeholder:`severity in ["high", "critical"]`},null,8,[`modelValue`]),B(k(FC),null,{default:A(()=>[...t[15]||=[V(`Optional CEL over the mapping's parameters.`,-1)]]),_:1})]),_:1}),B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-workflow`},{default:A(()=>[...t[16]||=[V(`Workflow`,-1)]]),_:1}),B(k(JS),{modelValue:a.va Line truncated
+40 -9
View File
@@ -6,11 +6,13 @@ import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { eventTypeLabel, type EventType } from "@/captures/event-types";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import {
draftFromBinding,
emptyDraft,
mappingsForEventType,
type Binding,
type BindingDraft,
type MappingOption,
@@ -18,14 +20,16 @@ import {
} from "./binding-draft";
/**
* The binding editor: name, the matcher source senders POST to, the field
* mapping, the workflow and an optional repo pin. Signing is the source's.
* The binding editor: name, the event type it applies to, one of that type's
* mappings, an optional filter over the mapping's parameters, the workflow and
* an optional repo pin. Signing is the source's.
*/
const props = defineProps<{
/** null is a new binding; a binding is an edit. */
binding: Binding | null;
mappings: MappingOption[];
eventTypes: EventType[];
workflows: WorkflowOption[];
saving: boolean;
error: string | null;
@@ -40,11 +44,22 @@ const draft = ref<BindingDraft>(emptyDraft());
watch(
open,
(isOpen) => {
if (isOpen) draft.value = props.binding ? draftFromBinding(props.binding) : emptyDraft();
if (isOpen) draft.value = props.binding ? draftFromBinding(props.binding, props.mappings) : emptyDraft();
},
{ immediate: true },
);
const typeMappings = computed(() => mappingsForEventType(props.mappings, draft.value.eventTypeId));
// A mapping belongs to one event type, so changing the type clears a mapping
// that no longer fits it.
watch(
() => draft.value.eventTypeId,
() => {
if (!typeMappings.value.some((m) => m.id === draft.value.mappingId)) draft.value.mappingId = "";
},
);
const title = computed(() => (props.binding ? "Edit binding" : "New binding"));
</script>
@@ -68,20 +83,30 @@ const title = computed(() => (props.binding ? "Edit binding" : "New binding"));
</Field>
<Field>
<FieldLabel for="binding-source">Source</FieldLabel>
<Input id="binding-source" v-model="draft.source" />
<FieldDescription>The path of a source, from the sources list above.</FieldDescription>
<FieldLabel for="binding-event-type">Event type</FieldLabel>
<Select v-model="draft.eventTypeId">
<SelectTrigger id="binding-event-type" class="w-full">
<SelectValue placeholder="Pick an event type" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem v-for="type in props.eventTypes" :key="type.id" :value="type.id">
{{ eventTypeLabel(type.id, props.eventTypes) }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel for="binding-mapping">Field mapping</FieldLabel>
<Select v-model="draft.mappingId">
<Select v-model="draft.mappingId" :disabled="!typeMappings.length">
<SelectTrigger id="binding-mapping" class="w-full">
<SelectValue placeholder="Pick a saved mapping" />
<SelectValue :placeholder="draft.eventTypeId && !typeMappings.length ? 'No mappings for this event type' : 'Pick a mapping'" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem v-for="mapping in props.mappings" :key="mapping.id" :value="String(mapping.id)">
<SelectItem v-for="mapping in typeMappings" :key="mapping.id" :value="String(mapping.id)">
{{ mapping.name }}
</SelectItem>
</SelectGroup>
@@ -89,6 +114,12 @@ const title = computed(() => (props.binding ? "Edit binding" : "New binding"));
</Select>
</Field>
<Field>
<FieldLabel for="binding-filter">Filter</FieldLabel>
<Input id="binding-filter" v-model="draft.filter" class="font-mono text-xs" placeholder='severity in ["high", "critical"]' />
<FieldDescription>Optional CEL over the mapping's parameters.</FieldDescription>
</Field>
<Field>
<FieldLabel for="binding-workflow">Workflow</FieldLabel>
<Select v-model="draft.workflow">
+7 -3
View File
@@ -5,10 +5,11 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { TableCell, TableRow } from "@/components/ui/table";
import BindingStatusBadge from "./BindingStatusBadge.vue";
import { matcherSource, repoPin, type Binding } from "./binding-draft";
import { eventTypeLabel, type EventType } from "@/captures/event-types";
import { bindingEventType, repoPin, type Binding, type MappingOption } from "./binding-draft";
/** One saved binding's summary row. */
const props = defineProps<{ binding: Binding }>();
const props = defineProps<{ binding: Binding; mappings: MappingOption[]; eventTypes: EventType[] }>();
const emit = defineEmits<{
edit: [binding: Binding];
approve: [binding: Binding];
@@ -21,10 +22,13 @@ const emit = defineEmits<{
<TableCell class="font-medium">{{ props.binding.name }}</TableCell>
<TableCell class="font-mono text-fg-muted">
<div class="flex items-center gap-2">
{{ matcherSource(props.binding) }}
{{ eventTypeLabel(bindingEventType(props.binding, props.mappings), props.eventTypes) }}
<Badge v-if="props.binding.unsigned" variant="warn">Unsigned</Badge>
</div>
</TableCell>
<TableCell class="max-w-56 truncate font-mono text-xs text-fg-muted" :title="props.binding.filter">
{{ props.binding.filter || "—" }}
</TableCell>
<TableCell>{{ props.binding.workflow || "—" }}</TableCell>
<TableCell class="font-mono text-fg-muted">{{ repoPin(props.binding) }}</TableCell>
<TableCell><BindingStatusBadge :status="props.binding.status" /></TableCell>
+6 -2
View File
@@ -13,8 +13,8 @@ import type { Binding, BindingDraft } from "./binding-draft";
import { useBindings } from "./use-bindings";
/**
* Playbook bindings (t2db.8): tie a matcher + payload mapping + workflow
* together, with a draft -> pending_approval -> armed state machine so nothing
* Playbook bindings: tie an event type's mapping, an optional filter and a
* workflow together, with a draft -> pending_approval -> armed state machine so nothing
* self-arms. See docs/architecture/bindings.md and
* docs/prds/payload-field-mapping.md. Owner/Repo optionally pin a multi-repo
* deployment's dispatch target (archie-core-t2db.8's backend fix, commit
@@ -24,6 +24,7 @@ import { useBindings } from "./use-bindings";
const {
bindings,
mappings,
eventTypes,
workflows,
failure,
actionFailure,
@@ -90,6 +91,8 @@ async function handleDelete(binding: Binding): Promise<void> {
<BindingsTable
:bindings="bindings"
:mappings="mappings"
:event-types="eventTypes"
:failure="failure"
@edit="startEdit"
@approve="approve"
@@ -100,6 +103,7 @@ async function handleDelete(binding: Binding): Promise<void> {
v-model:open="editorOpen"
:binding="editing"
:mappings="mappings"
:event-types="eventTypes"
:workflows="workflows"
:saving="saving"
:error="saveFailure"
+9 -3
View File
@@ -6,12 +6,15 @@ import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/u
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import BindingRow from "./BindingRow.vue";
import type { Binding } from "./binding-draft";
import type { EventType } from "@/captures/event-types";
import type { Binding, MappingOption } from "./binding-draft";
import type { LoadFailure } from "./use-bindings";
const props = defineProps<{
/** null means loading, [] means loaded and empty. */
bindings: Binding[] | null;
mappings: MappingOption[];
eventTypes: EventType[];
failure: LoadFailure | null;
}>();
@@ -56,7 +59,8 @@ const failureTitle = computed(() =>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Source</TableHead>
<TableHead>Event type</TableHead>
<TableHead>Filter</TableHead>
<TableHead>Workflow</TableHead>
<TableHead>Repo pin</TableHead>
<TableHead>Status</TableHead>
@@ -66,7 +70,7 @@ const failureTitle = computed(() =>
<TableBody>
<template v-if="loading">
<TableRow v-for="row in 3" :key="row">
<TableCell v-for="col in 6" :key="col"><Skeleton class="h-4 w-full" /></TableCell>
<TableCell v-for="col in 7" :key="col"><Skeleton class="h-4 w-full" /></TableCell>
</TableRow>
</template>
<template v-else>
@@ -74,6 +78,8 @@ const failureTitle = computed(() =>
v-for="binding in rows"
:key="binding.id"
:binding="binding"
:mappings="props.mappings"
:event-types="props.eventTypes"
@edit="emit('edit', $event)"
@approve="emit('approve', $event)"
@delete="emit('delete', $event)"
+28 -9
View File
@@ -5,6 +5,8 @@
* binding-editor.jsx had from bindings.jsx in the Preact build.
*/
import type { EventType } from "../captures/event-types";
/**
* A binding as GET /api/bindings returns it. Signing belongs to the source the
* matcher names; unsigned is set when that source takes unsigned events.
@@ -14,6 +16,8 @@ export interface Binding {
name: string;
matcher?: { source?: string };
mapping_id?: string;
/** Optional CEL over the mapping's parameters; an excluded event is not dispatched. */
filter?: string;
workflow?: string;
/** A pin is a complete owner/repo pair or not a pin at all. */
owner?: string;
@@ -27,6 +31,14 @@ export interface Binding {
export interface MappingOption {
id: string;
name: string;
event_type_id?: string;
}
/** The mappings that belong to one event type, which are the ones a binding
* on that type can use. */
export function mappingsForEventType(mappings: MappingOption[], eventTypeId: string): MappingOption[] {
if (!eventTypeId) return [];
return mappings.filter((m) => m.event_type_id === eventTypeId);
}
/** One entry of GET /api/workflows' `definitions`. */
@@ -66,8 +78,10 @@ export function statusKind(status?: string): StatusKind {
export interface BindingDraft {
id: string | null;
name: string;
source: string;
/** The event type the binding applies to; its source is the binding's. */
eventTypeId: string;
mappingId: string;
filter: string;
workflow: string;
owner: string;
repo: string;
@@ -77,20 +91,23 @@ export function emptyDraft(): BindingDraft {
return {
id: null,
name: "",
source: "",
eventTypeId: "",
mappingId: "",
filter: "",
workflow: "",
owner: "",
repo: "",
};
}
export function draftFromBinding(binding: Binding): BindingDraft {
export function draftFromBinding(binding: Binding, mappings: MappingOption[]): BindingDraft {
const mapping = mappings.find((m) => m.id === binding.mapping_id);
return {
id: binding.id,
name: binding.name,
source: binding.matcher?.source || "",
eventTypeId: mapping?.event_type_id || "",
mappingId: binding.mapping_id || "",
filter: binding.filter || "",
workflow: binding.workflow || "",
owner: binding.owner || "",
repo: binding.repo || "",
@@ -98,11 +115,13 @@ export function draftFromBinding(binding: Binding): BindingDraft {
}
/** The body POST /api/bindings and PATCH /api/bindings/{id} both accept. */
export function bindingPayload(draft: BindingDraft): Record<string, unknown> {
export function bindingPayload(draft: BindingDraft, eventTypes: EventType[]): Record<string, unknown> {
const eventType = eventTypes.find((t) => t.id === draft.eventTypeId);
return {
name: draft.name,
matcher: { source: draft.source },
matcher: { source: eventType?.source || "" },
mapping_id: draft.mappingId,
filter: draft.filter.trim(),
workflow: draft.workflow,
owner: draft.owner,
repo: draft.repo,
@@ -115,7 +134,7 @@ export function repoPin(binding: Binding): string {
return binding.owner && binding.repo ? `${binding.owner}/${binding.repo}` : "—";
}
/** The matcher source a row shows: the path segment senders POST to. */
export function matcherSource(binding: Binding): string {
return binding.matcher?.source || "—";
/** The event type a row shows: its mapping's. */
export function bindingEventType(binding: Binding, mappings: MappingOption[]): string | undefined {
return mappings.find((m) => m.id === binding.mapping_id)?.event_type_id;
}
+7 -2
View File
@@ -1,6 +1,7 @@
import { ref } from "vue";
import { api, ApiError } from "@/lib/api";
import type { EventType } from "@/captures/event-types";
import {
bindingPayload,
type Binding,
@@ -37,6 +38,7 @@ export function useBindings() {
// null means loading, [] means loaded and empty.
const bindings = ref<Binding[] | null>(null);
const mappings = ref<MappingOption[]>([]);
const eventTypes = ref<EventType[]>([]);
const workflows = ref<WorkflowOption[]>([]);
const failure = ref<LoadFailure | null>(null);
// A failed mutation is not a failed load: the list on screen is still
@@ -48,13 +50,15 @@ export function useBindings() {
async function load(): Promise<void> {
failure.value = null;
try {
const [b, m, w] = await Promise.all([
const [b, m, w, t] = await Promise.all([
api.bindings<{ bindings?: Binding[] }>(),
api.mappings<{ mappings?: MappingOption[] }>(),
api.workflows<{ definitions?: WorkflowOption[] }>(),
api.eventTypes<{ event_types?: EventType[] }>(),
]);
bindings.value = b.bindings || [];
mappings.value = m.mappings || [];
eventTypes.value = t.event_types || [];
// Only enabled definitions are offerable: binding to a disabled one
// would persist a binding that can never dispatch.
workflows.value = (w.definitions || []).filter((d) => d.enabled);
@@ -73,7 +77,7 @@ export function useBindings() {
saving.value = true;
saveFailure.value = null;
try {
const body = bindingPayload(draft);
const body = bindingPayload(draft, eventTypes.value);
if (draft.id) {
await api.bindingUpdate(String(draft.id), body);
} else {
@@ -112,6 +116,7 @@ export function useBindings() {
return {
bindings,
mappings,
eventTypes,
workflows,
failure,
actionFailure,
+7
View File
@@ -59,6 +59,13 @@ export function captureIdentity(
return { label: found ? found.name : "Deleted type", identified: true };
}
/** eventTypeLabel names an event type by id as "source / name". */
export function eventTypeLabel(id: string | undefined, types: EventType[]): string {
if (!id) return "No event type";
const found = types.find((t) => t.id === id);
return found ? `${found.source} / ${found.name}` : "Deleted type";
}
/** ruleSummary renders a rule as one line of its conditions. */
export function ruleSummary(rule: Rule): string {
const parts = [
+18 -1
View File
@@ -5,7 +5,8 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ago } from "@/lib/format";
import { captures, capturesEnabled, draft, selectCapture, type Capture } from "./state";
import { eventTypeLabel } from "@/captures/event-types";
import { captures, capturesEnabled, draft, eventTypes, selectCapture, type Capture } from "./state";
/**
* The mapping's own fields: the name it is saved under, the organisational
@@ -49,6 +50,22 @@ const captureHint = computed(() => {
<Input id="mapping-name" v-model="draft.name" />
</div>
<div class="flex flex-col gap-2">
<Label for="mapping-event-type">Event type</Label>
<Select v-model="draft.eventTypeId">
<SelectTrigger id="mapping-event-type" class="w-full">
<SelectValue placeholder="Pick an event type" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem v-for="type in eventTypes" :key="type.id" :value="type.id">
{{ eventTypeLabel(type.id, eventTypes) }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</div>
<div class="flex flex-col gap-2">
<Label for="mapping-source-hint">Source hint (organisational only)</Label>
<Input id="mapping-source-hint" v-model="draft.sourceHint" />
+8 -3
View File
@@ -1,7 +1,10 @@
<script setup lang="ts">
import { Button } from "@/components/ui/button";
import { TableCell, TableRow } from "@/components/ui/table";
import type { Mapping } from "./state";
import { eventTypeLabel } from "@/captures/event-types";
import { ago } from "@/lib/format";
import { matchCountLabel } from "./match-count";
import { eventTypes, type Mapping } from "./state";
/** One saved mapping's summary row. Both of its actions are the page's, not the
* row's: editing opens the editor overlay, deleting opens the confirmation. */
@@ -12,8 +15,10 @@ const emit = defineEmits<{ edit: [mapping: Mapping]; delete: [mapping: Mapping]
<template>
<TableRow>
<TableCell class="font-medium">{{ mapping.name }}</TableCell>
<TableCell class="font-mono">{{ mapping.source_hint || "—" }}</TableCell>
<TableCell>{{ mapping.fields?.length ?? 0 }}</TableCell>
<TableCell class="font-mono text-fg-muted">{{ eventTypeLabel(mapping.event_type_id, eventTypes) }}</TableCell>
<TableCell class="tabular-nums">{{ mapping.fields?.length ?? 0 }}</TableCell>
<TableCell class="tabular-nums">{{ matchCountLabel(mapping) }}</TableCell>
<TableCell class="text-fg-muted">{{ mapping.match_count ? ago(mapping.last_matched_at) : "—" }}</TableCell>
<TableCell>
<div class="flex justify-end gap-2">
<Button variant="outline" size="xs" @click="emit('edit', mapping)">Edit</Button>
+3 -1
View File
@@ -40,8 +40,10 @@ import { listLoading, loadError, mappings, requestDelete, startEdit } from "./st
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Source hint</TableHead>
<TableHead>Event type</TableHead>
<TableHead>Fields</TableHead>
<TableHead>Matched</TableHead>
<TableHead>Last match</TableHead>
<TableHead><span class="sr-only">Actions</span></TableHead>
</TableRow>
</TableHeader>
+6
View File
@@ -0,0 +1,6 @@
/** How many events a mapping has resolved, as the mappings list shows it. */
export function matchCountLabel(mapping: { match_count?: number }): string {
const count = mapping.match_count ?? 0;
if (count === 0) return "Never matched";
return `${count} ${count === 1 ? "event" : "events"}`;
}
+21 -6
View File
@@ -1,6 +1,7 @@
import { ref } from "vue";
import { api, classifyActionError, type ActionErrorKind } from "@/lib/api";
import type { EventType } from "@/captures/event-types";
import { uniqueFieldName, type FieldPick, type FieldType } from "./mapping-fields";
/**
@@ -21,16 +22,18 @@ export interface MappingField {
}
/**
* A named, reusable set of bindings (mapping.Mapping). The source hint is
* organisational only: a mapping is authored by clicking through one example
* captured event but is not pinned to that event or its source, because
* t2db.4's matcher decides which events a mapping applies to.
* A named set of bound fields belonging to one event type (mapping.Mapping).
* The daemon checks the fields against the type's schema on save, and counts
* each event the mapping resolves.
*/
export interface Mapping {
id: number;
name: string;
source_hint?: string;
event_type_id?: string;
fields?: MappingField[];
match_count?: number;
last_matched_at?: string;
}
/** A captured inbound event. Its body is redacted before it is stored, and is
@@ -63,6 +66,8 @@ export interface MappingDraft {
id: number | null;
name: string;
sourceHint: string;
/** The event type the mapping belongs to; its schema checks the fields. */
eventTypeId: string;
fields: MappingField[];
/** The capture the payload and the preview resolve against, or null. */
captureId: number | null;
@@ -82,6 +87,7 @@ export interface ActionFailure {
}
export const mappings = ref<Mapping[]>([]);
export const eventTypes = ref<EventType[]>([]);
export const captures = ref<Capture[]>([]);
/** Whether this deployment has capture storage at all. GET /api/captures
* answers {"enabled": false} rather than failing, which is what lets an empty
@@ -112,6 +118,7 @@ function blankDraft(): MappingDraft {
id: null,
name: "",
sourceHint: "",
eventTypeId: "",
fields: [],
captureId: null,
payload: null,
@@ -126,11 +133,13 @@ export async function loadMappings(): Promise<void> {
// Capture storage is optional infrastructure -- a deployment can serve
// mappings without it -- so a failing capture leg degrades to an empty
// picker instead of taking the mappings list down with it.
const [listed, captured] = await Promise.all([
const [listed, captured, types] = await Promise.all([
api.mappings<{ mappings?: Mapping[] }>(),
api.captures<{ captures?: Capture[]; enabled?: boolean }>(100).catch(() => null),
api.eventTypes<{ event_types?: EventType[] }>().catch(() => null),
]);
mappings.value = listed.mappings || [];
eventTypes.value = types?.event_types || [];
captures.value = captured?.captures || [];
capturesEnabled.value = captured?.enabled !== false;
loadError.value = null;
@@ -153,6 +162,7 @@ export function startEdit(mapping: Mapping): void {
id: mapping.id,
name: mapping.name,
sourceHint: mapping.source_hint || "",
eventTypeId: mapping.event_type_id || "",
// Copied, not aliased: the editor must not write through to the loaded list.
fields: (mapping.fields || []).map((field) => ({ ...field })),
};
@@ -229,7 +239,12 @@ export async function runPreview(): Promise<void> {
export async function saveMapping(): Promise<void> {
if (saving.value) return;
const current = draft.value;
const body = { name: current.name, source_hint: current.sourceHint, fields: current.fields };
const body = {
name: current.name,
source_hint: current.sourceHint,
event_type_id: current.eventTypeId,
fields: current.fields,
};
saving.value = true;
try {
if (current.id !== null) await api.mappingUpdate(String(current.id), body);
+56
View File
@@ -0,0 +1,56 @@
import assert from "node:assert/strict";
import test from "node:test";
const { eventTypeLabel } = await import("../src/captures/event-types.ts");
const { bindingPayload, draftFromBinding, emptyDraft, mappingsForEventType } = await import("../src/bindings/binding-draft.ts");
const { matchCountLabel } = await import("../src/mappings/match-count.ts");
const types = [
{ id: "et1", source: "gh", name: "push", rule: { headers: [], payload: [] } },
{ id: "et2", source: "fw", name: "blocked", rule: { headers: [], payload: [] } },
];
const mappings = [
{ id: "m1", name: "push fields", event_type_id: "et1" },
{ id: "m2", name: "blocked fields", event_type_id: "et2" },
{ id: "m3", name: "more push", event_type_id: "et1" },
];
test("an event type reads as source and name, and a missing one says so", () => {
assert.equal(eventTypeLabel("et1", types), "gh / push");
assert.equal(eventTypeLabel("", types), "No event type");
assert.equal(eventTypeLabel(undefined, types), "No event type");
assert.equal(eventTypeLabel("gone", types), "Deleted type");
});
test("the mapping picker offers only the chosen event type's mappings", () => {
assert.deepEqual(
mappingsForEventType(mappings, "et1").map((m) => m.id),
["m1", "m3"],
);
assert.deepEqual(mappingsForEventType(mappings, ""), []);
});
test("an edited binding opens on its mapping's event type and keeps its filter", () => {
const draft = draftFromBinding(
{ id: "b1", name: "n", matcher: { source: "fw" }, mapping_id: "m2", filter: 'severity == "high"' },
mappings,
);
assert.equal(draft.eventTypeId, "et2");
assert.equal(draft.filter, 'severity == "high"');
});
test("a binding is sent with the source of its event type and its filter", () => {
const draft = { ...emptyDraft(), name: "n", eventTypeId: "et2", mappingId: "m2", workflow: "w", filter: " severity == 'high' " };
const body = bindingPayload(draft, types);
assert.deepEqual(body.matcher, { source: "fw" });
assert.equal(body.mapping_id, "m2");
assert.equal(body.filter, "severity == 'high'");
assert.equal("eventTypeId" in body, false);
});
test("a mapping's match count reads as a number of events or as never matched", () => {
assert.equal(matchCountLabel({ match_count: 0 }), "Never matched");
assert.equal(matchCountLabel({}), "Never matched");
assert.equal(matchCountLabel({ match_count: 1 }), "1 event");
assert.equal(matchCountLabel({ match_count: 12 }), "12 events");
});
+1 -1
View File
@@ -47,6 +47,6 @@ test("a task started by an unsigned event says so on its timeline", () => {
});
test("a binding no longer carries a signing secret", () => {
const payload = bindingPayload(emptyDraft());
const payload = bindingPayload(emptyDraft(), []);
assert.equal("secret" in payload, false);
});