feat(archieui): mount the capture intake receiver over the State Store

At the cutover (archie-core-8cda.5.4) the UI process is the only listener
serving POST /webhooks/capture/{source}: the receiver is a persistence shim
over the State Store contract, and the daemon's binding-dispatch loop keeps
consuming captures from the same store, so the HTTP front door moves without
moving the owner of work intake. Zero [capture] options fall back to
configuration.DefaultCapture; the arrival announcement persists through
InsertEvent so the event pump delivers it, where the daemon's bus drain
persisted it before.
This commit is contained in:
sam committed 2026-09-10 00:50:28 +10:00
1 parent d6b2589448
commit 428a7879f6
10 files changed
+253 -50

No files matched your search

+71 -6
View File
@@ -1,10 +1,15 @@
package archieui
import (
"context"
"log/slog"
"time"
"github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/infrastructure/captureintake"
"github.com/samcharles93/archie-core/internal/webhookguard"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/webui"
)
@@ -39,12 +44,15 @@ type deps struct {
// Defining one amends the owning service's contract first
// (docs/prds/ui-service-boundary.md:205-207); the route migration is
// archie-core-8cda.5.3.
// - Captures, CaptureIntake: withheld for the duration of the seam. The
// daemon's receiver (internal/infrastructure/captureintake) serves
// POST /webhooks/capture/{source} from the daemon's listener; wiring it
// here too would give two listeners the same intake authority, which
// the PRD forbids (lines 30-33). Turned on at cutover, once the
// daemon's listener is gone.
// - Captures, CaptureIntake, CaptureMaxEvents: wired below. From the
// cutover change (archie-core-8cda.5.4) this process is the only
// listener serving POST /webhooks/capture/{source}: the receiver is a
// persistence shim over the State Store contract, and the daemon's
// binding-dispatch loop keeps consuming captures from the same store,
// so the HTTP front door moved here without moving the owner of work
// intake. Mounting it before the daemon's listener was gone would have
// given two listeners the same intake authority, which the PRD forbids
// (docs/prds/ui-service-boundary.md:30-33).
func compose(d deps) *webui.Server {
srv := &webui.Server{
Store: d.Store,
@@ -69,5 +77,62 @@ func compose(d deps) *webui.Server {
if d.Chat != nil {
srv.Chat = &webui.ChatService{Contract: d.Chat}
}
wireCaptureSurfaces(d, srv)
return srv
}
// wireCaptureSurfaces attaches the capture read and the intake receiver.
// Both resolve from d.Store's contracts: CaptureStore backs the inspector's
// list and the mapping preview's scan window, BindingDispatcher resolves the
// armed binding whose secret HMAC-verifies a source. A store that does not
// implement one degrades that half with a warning rather than aborting the
// process, mirroring the daemon's own adapter selection.
func wireCaptureSurfaces(d deps, srv *webui.Server) {
captures, hasCaptures := d.Store.(store.CaptureStore)
bindings, hasBindings := d.Store.(store.BindingDispatcher)
if !hasCaptures {
d.Log.Warn("capture storage unavailable: state store does not implement CaptureStore")
return
}
if !hasBindings {
d.Log.Warn("binding dispatcher unavailable: state store does not implement BindingDispatcher")
}
capture := d.Options.Capture.withDefaults()
srv.Captures = captures
srv.CaptureMaxEvents = capture.MaxEvents
srv.CaptureIntake = &captureintake.Receiver{
Captures: captures,
Limiter: webhookguard.NewRateLimiter(capture.RatePerSecond, capture.RateBurst, time.Now),
Bindings: bindings,
Retention: capture.Retention,
MaxEvents: capture.MaxEvents,
MaxBodyBytes: int64(capture.MaxBodyBytes),
Publish: captureArrivalPublisher(d),
Log: d.Log,
}
}
// captureArrivalPublisher persists a capture's arrival event through the
// State Store, where the daemon's bus drain persists every other activity
// event; the event pump then delivers it to every connected browser. A nil
// store records captures without announcing them (compose's test-only
// shape); an insert failure is logged, not surfaced -- the capture row is
// already durable, and the inspector refetches on its next view.
func captureArrivalPublisher(d deps) func(events.Event) {
if d.Store == nil {
return nil
}
return func(e events.Event) {
ctx, cancel := context.WithTimeout(context.Background(), captureEventTimeout)
defer cancel()
if _, err := d.Store.InsertEvent(ctx, e); err != nil {
d.Log.Warn("capture arrival event not published", "err", err)
}
}
}
// captureEventTimeout bounds the synchronous announce of one capture
// arrival. A capture POST already paid the rate limiter and a store insert;
// a hung State Store must not hold the sender's webhook past this.
const captureEventTimeout = 5 * time.Second
+34 -12
View File
@@ -8,6 +8,7 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/store"
@@ -91,8 +92,6 @@ func TestComposeUIServerHoldsNoDaemonState(t *testing.T) {
"LogFeed": srv.LogFeed,
"TaskLogs": srv.TaskLogs,
"WorkRequests": srv.WorkRequests,
"Captures": srv.Captures,
"CaptureIntake": srv.CaptureIntake,
}
for name, handle := range unwired {
if !isNil(handle) {
@@ -113,15 +112,38 @@ func TestComposeUIServerHoldsNoDaemonState(t *testing.T) {
}
}
// TestComposeLeavesCaptureIntakeUnset pins the seam rule: while the daemon
// still serves intake (its receiver is internal/infrastructure/captureintake;
// the dashboard's own removal is bead archie-core-8cda.5.4), a second
// process wiring Captures/CaptureIntake would give two listeners the same
// webhook intake authority, which docs/prds/ui-service-boundary.md:30-33
// forbids. The capture list answers {"enabled": false} instead.
func TestComposeLeavesCaptureIntakeUnset(t *testing.T) {
srv := compose(deps{Options: Options{}, Log: slog.New(slog.DiscardHandler)})
if srv.Captures != nil || srv.CaptureIntake != nil {
t.Fatal("capture intake is wired in the UI process; it must stay unset until the daemon's listener is gone (bead archie-core-8cda.5.4)")
// TestComposeWiresCaptureIntake pins the cutover rule: once the daemon's
// dashboard listener is gone (archie-core-8cda.5.4), this process is the
// only listener serving POST /webhooks/capture/{source}, so compose must
// mount the receiver when the store contract carries it -- a capture POST
// answered by a token-gated 404 would leave intake with no owner. Zero
// Options.Capture falls back to configuration.DefaultCapture, the same
// defaults a decoded config would project.
func TestComposeWiresCaptureIntake(t *testing.T) {
stateConn, err := grpc.NewClient("passthrough:///127.0.0.1:1", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatalf("state client: %v", err)
}
defer stateConn.Close()
srv := compose(deps{
Options: Options{},
Log: slog.New(slog.DiscardHandler),
Store: staterpc.NewClient(stateConn),
})
if srv.Captures == nil || srv.CaptureIntake == nil {
t.Fatal("capture intake is unset; the UI process is the only listener serving POST /webhooks/capture/{source} after the cutover (bead archie-core-8cda.5.4)")
}
defaults := configuration.DefaultCapture()
if srv.CaptureMaxEvents != defaults.MaxEvents {
t.Errorf("CaptureMaxEvents = %d, want the default %d", srv.CaptureMaxEvents, defaults.MaxEvents)
}
// A store without the capture contract keeps both surfaces unset and
// degrades the read instead of mounting an intake route that cannot
// persist what arrives.
empty := compose(deps{Options: Options{}, Log: slog.New(slog.DiscardHandler)})
if empty.Captures != nil || empty.CaptureIntake != nil || empty.CaptureMaxEvents != 0 {
t.Error("capture surfaces wired without a CaptureStore behind them")
}
}
+26 -2
View File
@@ -17,9 +17,10 @@ import (
// to a process default. It ends with validate, so a caller that gets no error
// holds a startable configuration.
//
// The projection is an allowlist of exactly six values --
// The projection is an allowlist of the values this process needs --
// [services.gateway].{target,target_token}, [services.state].{target,
// target_token} and [web].{listen,trust_forwarded_headers}. The UI reads the
// target_token}, [web].{listen,trust_forwarded_headers} and [capture] (the
// receiver this process mounts; archie-core-8cda.5.4). The UI reads the
// same file the daemon does because operators already keep the service
// endpoints there, but Options has no field for anything else in it: the
// daemon's forge credentials, model catalog, workflow routing, NATS settings,
@@ -69,6 +70,7 @@ type projection struct {
trustForwardedHeaders bool
gateway ServiceTarget
state ServiceTarget
capture CaptureOptions
}
func project(cfg config.Config) projection {
@@ -77,6 +79,13 @@ func project(cfg config.Config) projection {
trustForwardedHeaders: cfg.Web.TrustForwardedHeaders,
gateway: ServiceTarget{Target: cfg.Services.Gateway.Target, Token: cfg.Services.Gateway.TargetToken},
state: ServiceTarget{Target: cfg.Services.State.Target, Token: cfg.Services.State.TargetToken},
capture: CaptureOptions{
Retention: cfg.Capture.Retention.Std(),
MaxEvents: cfg.Capture.MaxEvents,
MaxBodyBytes: cfg.Capture.MaxBodyBytes,
RatePerSecond: cfg.Capture.RatePerSecond,
RateBurst: cfg.Capture.RateBurst,
},
}
}
@@ -129,6 +138,21 @@ func merge(o Options, p projection) Options {
if o.State.Token == "" {
o.State.Token = p.state.Token
}
if o.Capture.Retention <= 0 {
o.Capture.Retention = p.capture.Retention
}
if o.Capture.MaxEvents <= 0 {
o.Capture.MaxEvents = p.capture.MaxEvents
}
if o.Capture.MaxBodyBytes <= 0 {
o.Capture.MaxBodyBytes = p.capture.MaxBodyBytes
}
if o.Capture.RatePerSecond <= 0 {
o.Capture.RatePerSecond = p.capture.RatePerSecond
}
if o.Capture.RateBurst <= 0 {
o.Capture.RateBurst = p.capture.RateBurst
}
return o
}
@@ -97,6 +97,14 @@ func TestRoutesWithoutAContractDegradeExplicitly(t *testing.T) {
body: `{"repository":"acme/widget","workflow":"implement","title":"do it"}`,
want: http.StatusServiceUnavailable,
},
{
// The capture surfaces are wired in this process from the cutover
// (archie-core-8cda.5.4): the read resolves from the State Store,
// not from a daemon handle, so the inspector answers enabled with
// an empty list rather than the degraded shape.
name: "capture inspector", method: http.MethodGet, path: "/api/captures",
want: http.StatusOK, emptyJSON: `"enabled":true`,
},
{
// The browser reads this to decide which sections to show at
// all, so it is the one route that must answer here.
@@ -152,7 +160,7 @@ func composeUIProcess(t *testing.T) (*webui.Server, int64) {
t.Cleanup(func() { _ = st.Close() })
target, stop := serveGRPC(t, func(r grpc.ServiceRegistrar) {
staterpc.RegisterServer(r, staterpc.Deps{Tasks: st, ConfigSnapshots: st, Log: slog.New(slog.DiscardHandler)})
staterpc.RegisterServer(r, staterpc.Deps{Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st, Log: slog.New(slog.DiscardHandler)})
})
t.Cleanup(stop)
client, closeClient, err := staterpc.Dial(target, "")
+60 -1
View File
@@ -15,7 +15,11 @@
// that the PRD's deletion gate forbids the UI process from linking.
package archieui
import "time"
import (
"time"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
)
// Process defaults. Listen matches the dashboard's historical bind
// (internal/infrastructure/configuration/defaults.go) so an operator moving
@@ -60,6 +64,17 @@ type Options struct {
// operator did not say, and the file (else false) decides.
TrustForwardedHeaders *bool
// Capture configures the unbound webhook capture receiver this process
// mounts on its bypass mux (docs/prds/event-capture-storage.md). At the
// cutover (archie-core-8cda.5.4) this process is the only listener
// serving POST /webhooks/capture/{source}: the receiver persists what
// arrives through the State Store contract, and the daemon's
// binding-dispatch loop consumes captures from the same store, so the
// HTTP front door moves without moving the owner of work intake. Zero
// fields fall back to configuration.DefaultCapture, the same defaults a
// decoded config would carry.
Capture CaptureOptions
// Gateway and State are the two remote contracts the dashboard consumes.
Gateway ServiceTarget
State ServiceTarget
@@ -77,6 +92,50 @@ type Options struct {
ShutdownTimeout time.Duration
}
// CaptureOptions carries the [capture] settings the capture receiver needs.
// Every field is an endpoint-adjacent process setting: the receiver runs in
// this process, so the operator's capture tuning must reach it directly
// rather than through the daemon's configuration.
type CaptureOptions struct {
// Retention is how long a captured event is kept before prune-on-write
// deletes it. Zero means configuration.DefaultCapture's value.
Retention time.Duration
// MaxEvents caps the capture table at this many newest rows. Zero means
// the default.
MaxEvents int
// MaxBodyBytes rejects (413) a body larger than this before it is read.
// Zero means the default.
MaxBodyBytes int
// RatePerSecond and RateBurst configure the per-remote-address token
// bucket applied before a request body is read. Zero means the defaults.
RatePerSecond float64
RateBurst int
}
// withDefaults resolves zero fields to configuration.DefaultCapture, the
// same "zero means default" semantics config.CaptureConfig documents. A
// resolved config never carries zeros (its decoder applies the defaults),
// so this only fires for a flags-only deployment or a direct compose call.
func (c CaptureOptions) withDefaults() CaptureOptions {
d := configuration.DefaultCapture()
if c.Retention <= 0 {
c.Retention = d.Retention.Std()
}
if c.MaxEvents <= 0 {
c.MaxEvents = d.MaxEvents
}
if c.MaxBodyBytes <= 0 {
c.MaxBodyBytes = d.MaxBodyBytes
}
if c.RatePerSecond <= 0 {
c.RatePerSecond = d.RatePerSecond
}
if c.RateBurst <= 0 {
c.RateBurst = d.RateBurst
}
return c
}
// trustForwardedHeaders reports the resolved value, treating "not specified"
// as off: trusting forwarded headers unconditionally lets an untrusted client
// spoof the Origin scheme check.
+13 -8
View File
@@ -9,6 +9,7 @@ import (
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"google.golang.org/grpc"
@@ -118,7 +119,7 @@ func TestUIServesDashboardAgainstRemoteContracts(t *testing.T) {
}
stateTarget, stopState := serveGRPC(t, func(r grpc.ServiceRegistrar) {
staterpc.RegisterServer(r, staterpc.Deps{Tasks: st, ConfigSnapshots: st, Log: slog.New(slog.DiscardHandler)})
staterpc.RegisterServer(r, staterpc.Deps{Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st, Log: slog.New(slog.DiscardHandler)})
})
defer stopState()
chat := &fakeChat{sessions: []gateway.SessionContext{
@@ -257,7 +258,11 @@ func TestUIServesDashboardAgainstRemoteContracts(t *testing.T) {
t.Errorf("GET /api/version = %d, want 501", code)
}
// Capture intake stays with the daemon until bead archie-core-8cda.5.4.
// The capture POST is served by this process from the cutover change:
// the receiver persists through the State Store contract, and the
// daemon's binding-dispatch loop consumes what arrives from the same
// store (archie-core-8cda.5.4). It bypasses the dashboard token like
// /healthz -- capture accepts unauthenticated senders by design.
capReq, err := http.NewRequestWithContext(t.Context(), http.MethodPost, ts.URL+"/webhooks/capture/demo", http.NoBody)
if err != nil {
t.Fatalf("capture request: %v", err)
@@ -266,13 +271,13 @@ func TestUIServesDashboardAgainstRemoteContracts(t *testing.T) {
if err != nil {
t.Fatalf("POST /webhooks/capture/demo: %v", err)
}
// Capture intake stays with the daemon until bead archie-core-8cda.5.4:
// the UI process mounts no intake route at all (compose leaves
// CaptureIntake unset), so the POST falls through to the token-gated
// dashboard rather than answering as a capture endpoint.
capResp.Body.Close()
if capResp.StatusCode == http.StatusAccepted {
t.Errorf("POST /webhooks/capture/demo = %d, want anything but an accepted capture: two processes must not share webhook intake authority", capResp.StatusCode)
if capResp.StatusCode != http.StatusAccepted {
t.Errorf("POST /webhooks/capture/demo = %d, want an accepted capture: this process is the only listener serving intake after the cutover", capResp.StatusCode)
}
code, body = get("/api/captures")
if code != http.StatusOK || !strings.Contains(string(body), `"enabled":true`) {
t.Errorf("GET /api/captures = %d (%s), want an enabled capture list over the State Store", code, body)
}
// Readiness aggregates the two remote dependencies, and drops when one dies.
@@ -5,7 +5,11 @@
// It belongs to the process that owns work intake, not to the dashboard that
// displays captures. It served from the dashboard's listener while the two
// shared a process; the split gives the read to the dashboard, over the State
// Store, and keeps the write here (archie-core-8cda.5.4).
// Store, and keeps the write here (archie-core-8cda.5.4). From the cutover
// change in the same bead it is a persistence shim over the State Store
// contract mounted by the UI process -- the only dashboard listener left --
// while the daemon's binding-dispatch loop consumes captures from the same
// store: the HTTP front door moved without moving work intake.
package captureintake
import (
@@ -90,23 +90,39 @@ func applyMemoryDefaults(cfg *config.Config) {
}
}
// DefaultCapture returns the webhook capture endpoint's default settings
// (docs/prds/event-capture-storage.md). applyCaptureDefaults fills a decoded
// config with them; the UI process composes the same capture receiver and
// must produce the same effective values when it is driven by flags alone
// and no configuration file projected [capture] to it.
func DefaultCapture() config.CaptureConfig {
return config.CaptureConfig{
Retention: config.Duration(defaultCaptureRetention),
MaxEvents: defaultCaptureMaxEvents,
MaxBodyBytes: defaultCaptureMaxBodyBytes,
RatePerSecond: defaultCaptureRatePerSecond,
RateBurst: defaultCaptureRateBurst,
}
}
// applyCaptureDefaults fills the webhook capture endpoint's settings. See
// [config.CaptureConfig].
func applyCaptureDefaults(cfg *config.Config) {
c := DefaultCapture()
if cfg.Capture.Retention == 0 {
cfg.Capture.Retention = config.Duration(defaultCaptureRetention)
cfg.Capture.Retention = c.Retention
}
if cfg.Capture.MaxEvents == 0 {
cfg.Capture.MaxEvents = defaultCaptureMaxEvents
cfg.Capture.MaxEvents = c.MaxEvents
}
if cfg.Capture.MaxBodyBytes == 0 {
cfg.Capture.MaxBodyBytes = defaultCaptureMaxBodyBytes
cfg.Capture.MaxBodyBytes = c.MaxBodyBytes
}
if cfg.Capture.RatePerSecond == 0 {
cfg.Capture.RatePerSecond = defaultCaptureRatePerSecond
cfg.Capture.RatePerSecond = c.RatePerSecond
}
if cfg.Capture.RateBurst == 0 {
cfg.Capture.RateBurst = defaultCaptureRateBurst
cfg.Capture.RateBurst = c.RateBurst
}
}
+4 -4
View File
@@ -17,10 +17,10 @@ const defaultCapturesListLimit = 100
// /api/* route -- captured payloads are visible only to an authenticated
// operator, per docs/prds/webhook-intake-security.md point 5.
//
// This is the read half of event capture. The write belongs to the process
// that owns work intake (internal/infrastructure/captureintake), which the
// host mounts on the bypass mux via CaptureIntake -- the dashboard displays
// captures and mounts the route; it no longer stores them (archie-core-8cda.5.4).
// This is the read half of event capture. The write half is the receiver in
// internal/infrastructure/captureintake, mounted on the bypass mux via
// CaptureIntake; the dashboard displays captures and mounts the route; it
// no longer stores them (archie-core-8cda.5.4).
func (s *Server) handleCaptures(w http.ResponseWriter, r *http.Request) {
if s.Captures == nil {
writeJSON(w, map[string]any{"captures": []any{}, "enabled": false})
+10 -10
View File
@@ -149,20 +149,20 @@ type Server struct {
// answer {"enabled": false} rather than the dashboard failing to start.
Captures store.CaptureStore
// CaptureMaxEvents is the operator's configured [capture] max_events,
// used to bound captureByID's scan window (api_mapping.go). The write
// half of capture -- the receiver, its rate limiter, body cap and HMAC
// verification -- belongs to the process that does work intake and is
// mounted here through CaptureIntake.
// used to bound captureByID's scan window (api_mapping.go).
// CaptureIntake is the write half's mount.
CaptureMaxEvents int
// CaptureIntake serves POST /webhooks/capture/{source} on the bypass
// mux, alongside /healthz: capture must accept unauthenticated
// senders, so it cannot sit behind requireToken. The handler is owned
// by the host process that does work intake
// (internal/infrastructure/captureintake.Receiver); this package only
// mounts the route and reads the rows back. Nil removes the route,
// which is how the UI process stays off intake -- two listeners with
// the same intake authority is what the boundary forbids
// (docs/prds/ui-service-boundary.md:30-33).
// by internal/infrastructure/captureintake.Receiver; this package only
// mounts the route and reads the rows back. The UI process composes
// it from the cutover change (archie-core-8cda.5.4) -- it is the only
// dashboard listener left, and a capture POST answered by the
// token-gated mux would leave intake with no owner. Nil removes the
// route, which is what a store without the capture contract gets:
// two listeners with the same intake authority is what the boundary
// forbids (docs/prds/ui-service-boundary.md:30-33).
CaptureIntake http.Handler
// Mappings persists payload field mappings (docs/prds/payload-field-mapping.md).