feat(forge): observable webhook receiver + dedup regression proof; decide adversarial review design
archie-core-7d5u.5 (idempotency and poll/webhook parity): the dedup mechanism (TaskEnvelope.IdempotencyKey + PublishUnique + JetStream Nats-Msg-Id dedup) and the shared dispatch predicate were already fully wired by 7d5u.4. What was missing: proof the dedup actually holds, and observability for a wedged receiver. - internal/infrastructure/eventbus/nats/dedup_test.go: regression test proving PublishUnique suppresses a duplicate publish on the same WorkQueuePolicy stream ARCHIE_TASKS uses in production. - internal/forge/webhook/receiver.go: Receiver.Status() tracks authenticated deliveries separately from successful publishes; a GET to the receiver's listen address (GitHub only ever POSTs) now returns it as JSON, so a wedged/non-delivering receiver is observable instead of indistinguishable from an idle repo. Poll/webhook parity (disabling webhook still polls) needed no code change: Cycle()/Run() never reference cfg.Forge.Intake anywhere in internal/daemon, only setupForgeWebhook gates the webhook HTTP server. archie-core-h019.1 (design: adversarial self-review stage): one-page decision at docs/prds/adversarial-self-review.md. Reviewer runs in a second workspace pointed at a .git-stripped snapshot of the reviewed commit, never the implementer's worktree, so isolation is a property of what's mounted rather than a prompt instruction. Findings contract is workflow.ReviewFinding, owned by internal/domain/workflow. A surviving error-level finding sets StatusParked, not WaitingHuman -- the epic's informal wording named two different states in the actual machine; this resolves which. Both changes reviewed by a fresh subagent with no memory of the implementation, per CLAUDE.md's adversarial-verification requirement; zero blocking findings, two minor coverage gaps closed.
This commit is contained in:
1 parent
ee650997c7
commit
8a799cd8cd
6 files changed
+469
-10
No files matched your search
@@ -12,13 +12,33 @@
|
||||
// GitHub's webhook must be configured with "Content type: application/json"
|
||||
// (the UI default). The alternate application/x-www-form-urlencoded delivery
|
||||
// is not decoded here and is rejected as a bad payload.
|
||||
//
|
||||
// Idempotency is not this package's job: it decodes into the same
|
||||
// TaskEnvelope and calls the same publish path the poller uses, so
|
||||
// PublishUnique's dedup (keyed on TaskEnvelope.IdempotencyKey) covers both
|
||||
// sources for free -- see archie-core-7d5u.5. What this package does own is
|
||||
// making a wedged or non-delivering receiver observable: a GET to the
|
||||
// listen address (GitHub only ever POSTs) returns Status, tracking
|
||||
// authenticated deliveries and successful publishes separately so an
|
||||
// operator can tell "receiver is up but nothing is arriving" apart from
|
||||
// "repo has no issue activity."
|
||||
//
|
||||
// The GET/Status route is deliberately unauthenticated, on the same
|
||||
// internet-facing listener GitHub POSTs signed payloads to: it reveals
|
||||
// counters and timestamps only, never repo data, issue content, or the
|
||||
// webhook secret, so treating it as a public liveness probe (the same
|
||||
// tradeoff an unauthenticated /healthz makes) is an acceptable exchange for
|
||||
// not requiring a second credential just to check if the receiver is alive.
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/go-github/v78/github"
|
||||
|
||||
@@ -45,6 +65,12 @@ type Receiver struct {
|
||||
botUser string
|
||||
publish PublishFunc
|
||||
log *slog.Logger
|
||||
|
||||
mu sync.Mutex
|
||||
startedAt time.Time
|
||||
lastReceivedAt time.Time
|
||||
deliveries uint64
|
||||
publishes uint64
|
||||
}
|
||||
|
||||
// New returns an unstarted Receiver.
|
||||
@@ -53,17 +79,73 @@ func New(secret, trigger, label, botUser string, publish PublishFunc, log *slog.
|
||||
log = slog.New(slog.DiscardHandler)
|
||||
}
|
||||
return &Receiver{
|
||||
secret: secret,
|
||||
trigger: trigger,
|
||||
label: label,
|
||||
botUser: botUser,
|
||||
publish: publish,
|
||||
log: log.With("component", "forge-webhook"),
|
||||
secret: secret,
|
||||
trigger: trigger,
|
||||
label: label,
|
||||
botUser: botUser,
|
||||
publish: publish,
|
||||
log: log.With("component", "forge-webhook"),
|
||||
startedAt: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
// ServeHTTP handles one forge webhook delivery.
|
||||
// Status reports the receiver's delivery activity so an operator can tell a
|
||||
// wedged or non-delivering receiver apart from a repo with no issue
|
||||
// activity (archie-core-7d5u.5): Deliveries counts every authenticated,
|
||||
// parseable webhook -- proof GitHub reached this process at all -- while
|
||||
// Publishes counts only what the dispatch predicate turned into work.
|
||||
// LastReceivedAt is nil until the first authenticated delivery arrives.
|
||||
type Status struct {
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
LastReceivedAt *time.Time `json:"last_received_at"`
|
||||
Deliveries uint64 `json:"deliveries"`
|
||||
Publishes uint64 `json:"publishes"`
|
||||
}
|
||||
|
||||
// Status returns a snapshot of the receiver's activity counters.
|
||||
func (r *Receiver) Status() Status {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
s := Status{
|
||||
StartedAt: r.startedAt,
|
||||
Deliveries: r.deliveries,
|
||||
Publishes: r.publishes,
|
||||
}
|
||||
if !r.lastReceivedAt.IsZero() {
|
||||
last := r.lastReceivedAt
|
||||
s.LastReceivedAt = &last
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// recordDelivery marks one authenticated, parseable webhook as received.
|
||||
// Called only after HMAC verification and payload parsing succeed, so an
|
||||
// unauthenticated request (anyone spamming the endpoint with a bad
|
||||
// signature) can never inflate the "receiver is alive" signal.
|
||||
func (r *Receiver) recordDelivery() {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.deliveries++
|
||||
r.lastReceivedAt = time.Now()
|
||||
}
|
||||
|
||||
// recordPublish marks one delivery as having produced a task.
|
||||
func (r *Receiver) recordPublish() {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.publishes++
|
||||
}
|
||||
|
||||
// ServeHTTP handles one forge webhook delivery. GitHub only ever POSTs here,
|
||||
// so any GET is answered with the receiver's Status instead -- an operator
|
||||
// (or a monitor) can curl the same address the webhook is configured against
|
||||
// to check liveness, with no separate health-check surface to wire up.
|
||||
func (r *Receiver) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
if req.Method == http.MethodGet {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(r.Status())
|
||||
return
|
||||
}
|
||||
if req.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
@@ -91,6 +173,9 @@ func (r *Receiver) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
http.Error(w, "bad payload", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// Authenticated and parseable: this is a genuine GitHub delivery,
|
||||
// independent of whether it turns out to be dispatch-eligible.
|
||||
r.recordDelivery()
|
||||
|
||||
issueEvent, ok := event.(*github.IssuesEvent)
|
||||
if !ok {
|
||||
@@ -113,6 +198,8 @@ func (r *Receiver) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
http.Error(w, "publish failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
r.recordPublish()
|
||||
r.log.Info("published", "task", task.Ref())
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
@@ -247,3 +248,141 @@ func TestPublishedEnvelopeCarriesIssueIdentityAndKind(t *testing.T) {
|
||||
t.Errorf("idempotency key = %q, want archie:owner/repo/42", task.IdempotencyKey())
|
||||
}
|
||||
}
|
||||
|
||||
// TestReceiverStatusTracksAuthenticatedDeliveries pins the observability this
|
||||
// receiver needs for archie-core-7d5u.5: a wedged or non-delivering receiver
|
||||
// must not be indistinguishable from an idle repo. Deliveries counts every
|
||||
// authenticated, parseable delivery (proof GitHub is reaching the process at
|
||||
// all) independent of whether that delivery matched the dispatch predicate;
|
||||
// Publishes counts only what actually became work. An unauthenticated
|
||||
// request must not inflate either counter -- that would let anyone spamming
|
||||
// the endpoint with a bad signature manufacture a false "receiver is alive
|
||||
// and busy" signal.
|
||||
func TestReceiverStatusTracksAuthenticatedDeliveries(t *testing.T) {
|
||||
r := New(testSecret, "label", testLabel, testBot, nil, nil)
|
||||
|
||||
before := r.Status()
|
||||
if before.Deliveries != 0 || before.Publishes != 0 {
|
||||
t.Fatalf("initial status = %+v, want zero counters", before)
|
||||
}
|
||||
if before.LastReceivedAt != nil {
|
||||
t.Fatalf("initial LastReceivedAt = %v, want nil", before.LastReceivedAt)
|
||||
}
|
||||
|
||||
// Invalid signature: not a real GitHub delivery, must not count.
|
||||
rejected := issueEvent(t, "labeled", func(ev *github.IssuesEvent) {
|
||||
ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}}
|
||||
})
|
||||
rejectedPayload, err := json.Marshal(rejected)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal event: %v", err)
|
||||
}
|
||||
serve(t, r, signedRequest(t, "wrong-secret", "issues", rejectedPayload))
|
||||
afterRejected := r.Status()
|
||||
if afterRejected.Deliveries != 0 {
|
||||
t.Fatalf("Deliveries after unauthenticated request = %d, want 0", afterRejected.Deliveries)
|
||||
}
|
||||
|
||||
// Authenticated but dispatch-ineligible: counts as a delivery (GitHub
|
||||
// really did reach the receiver), not as a publish.
|
||||
ineligible := issueEvent(t, "unlabeled", func(ev *github.IssuesEvent) {
|
||||
ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}}
|
||||
})
|
||||
ineligiblePayload, err := json.Marshal(ineligible)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal event: %v", err)
|
||||
}
|
||||
serve(t, r, signedRequest(t, testSecret, "issues", ineligiblePayload))
|
||||
afterIneligible := r.Status()
|
||||
if afterIneligible.Deliveries != 1 {
|
||||
t.Fatalf("Deliveries after ineligible authenticated request = %d, want 1", afterIneligible.Deliveries)
|
||||
}
|
||||
if afterIneligible.Publishes != 0 {
|
||||
t.Fatalf("Publishes after ineligible authenticated request = %d, want 0", afterIneligible.Publishes)
|
||||
}
|
||||
if afterIneligible.LastReceivedAt == nil {
|
||||
t.Fatal("LastReceivedAt after authenticated request = nil, want set")
|
||||
}
|
||||
|
||||
// Authenticated and dispatch-eligible: counts as both.
|
||||
matched := issueEvent(t, "labeled", func(ev *github.IssuesEvent) {
|
||||
ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}}
|
||||
})
|
||||
matchedPayload, err := json.Marshal(matched)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal event: %v", err)
|
||||
}
|
||||
serve(t, r, signedRequest(t, testSecret, "issues", matchedPayload))
|
||||
final := r.Status()
|
||||
if final.Deliveries != 2 {
|
||||
t.Fatalf("Deliveries = %d, want 2", final.Deliveries)
|
||||
}
|
||||
if final.Publishes != 1 {
|
||||
t.Fatalf("Publishes = %d, want 1", final.Publishes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReceiverStatusDoesNotCountFailedPublish pins that a Publisher error
|
||||
// still counts the delivery (GitHub really did reach the receiver, and the
|
||||
// payload really was dispatch-eligible) but must not count as a publish --
|
||||
// otherwise Status would report work that never actually reached the queue.
|
||||
func TestReceiverStatusDoesNotCountFailedPublish(t *testing.T) {
|
||||
r := New(testSecret, "label", testLabel, testBot, nil, nil)
|
||||
r.publish = func(context.Context, workintake.TaskEnvelope) error {
|
||||
return errors.New("publish unavailable")
|
||||
}
|
||||
|
||||
ev := issueEvent(t, "labeled", func(ev *github.IssuesEvent) {
|
||||
ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}}
|
||||
})
|
||||
payload, err := json.Marshal(ev)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal event: %v", err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, signedRequest(t, testSecret, "issues", payload))
|
||||
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want 500", rec.Code)
|
||||
}
|
||||
got := r.Status()
|
||||
if got.Deliveries != 1 {
|
||||
t.Errorf("Deliveries = %d, want 1", got.Deliveries)
|
||||
}
|
||||
if got.Publishes != 0 {
|
||||
t.Errorf("Publishes = %d, want 0 (publish failed)", got.Publishes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReceiverServesStatusOnGET proves the counters are reachable without a
|
||||
// separate health-check subsystem: any GET is answered with the JSON status
|
||||
// body, since GitHub only ever POSTs to this receiver.
|
||||
func TestReceiverServesStatusOnGET(t *testing.T) {
|
||||
r := New(testSecret, "label", testLabel, testBot, nil, nil)
|
||||
ev := issueEvent(t, "labeled", func(ev *github.IssuesEvent) {
|
||||
ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}}
|
||||
})
|
||||
payload, err := json.Marshal(ev)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal event: %v", err)
|
||||
}
|
||||
serve(t, r, signedRequest(t, testSecret, "issues", payload))
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("GET status = %d, want 200", rec.Code)
|
||||
}
|
||||
var got Status
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode status body: %v (%s)", err, rec.Body.String())
|
||||
}
|
||||
if got.Deliveries != 1 || got.Publishes != 1 {
|
||||
t.Errorf("decoded status = %+v, want Deliveries=1 Publishes=1", got)
|
||||
}
|
||||
if got.LastReceivedAt == nil {
|
||||
t.Error("decoded status LastReceivedAt = nil, want set")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package nats
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
natstest "github.com/nats-io/nats-server/v2/test"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/eventbus"
|
||||
)
|
||||
|
||||
// TestPublishUniqueSuppressesDuplicateKeyOnWorkQueueStream is the regression
|
||||
// proof behind archie-core-7d5u.5 (idempotency and poll/webhook parity): a
|
||||
// forge issue discovered independently by the poller and the webhook
|
||||
// receiver produces two TaskEnvelopes with the identical
|
||||
// workintake.TaskEnvelope.IdempotencyKey(), published to the SAME
|
||||
// WorkQueuePolicy stream ARCHIE_TASKS uses in production (Config.Retention
|
||||
// left unset, per TestWithDefaultsRetention). A second PublishUnique call
|
||||
// with the same key inside the dedup window must be silently suppressed by
|
||||
// the server, so a single consumer only ever observes one message -- never
|
||||
// two tasks for one issue.
|
||||
func TestPublishUniqueSuppressesDuplicateKeyOnWorkQueueStream(t *testing.T) {
|
||||
srv := natstest.RunServer(&server.Options{Port: -1, JetStream: true, StoreDir: t.TempDir()})
|
||||
t.Cleanup(srv.Shutdown)
|
||||
|
||||
c, err := Connect(t.Context(), Config{
|
||||
URL: srv.ClientURL(),
|
||||
StreamName: "TASKS_DEDUP_TEST",
|
||||
Subjects: []string{"tasks.dedup.test.>"},
|
||||
FilterSubject: "tasks.dedup.test.>",
|
||||
// Retention left unset: defaults to WorkQueuePolicy, the same policy
|
||||
// ARCHIE_TASKS uses in production for task distribution.
|
||||
}, discardLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("Connect = %v", err)
|
||||
}
|
||||
t.Cleanup(c.Close)
|
||||
|
||||
const key = "archie:owner/repo/42"
|
||||
|
||||
// Poll-discovered publish, then webhook-discovered publish of the same
|
||||
// issue moments later -- both carry the identical idempotency key.
|
||||
if err := c.PublishUnique(t.Context(), "tasks.dedup.test.issue", key, []byte("poll")); err != nil {
|
||||
t.Fatalf("PublishUnique (poll) = %v", err)
|
||||
}
|
||||
if err := c.PublishUnique(t.Context(), "tasks.dedup.test.issue", key, []byte("webhook")); err != nil {
|
||||
t.Fatalf("PublishUnique (webhook) = %v", err)
|
||||
}
|
||||
|
||||
msg, err := c.Fetch(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("Fetch (first) = %v", err)
|
||||
}
|
||||
if err := msg.Ack(); err != nil {
|
||||
t.Fatalf("Ack = %v", err)
|
||||
}
|
||||
|
||||
// A second delivery for the same issue would be a double-dispatched
|
||||
// task. There must be none queued.
|
||||
if _, err := c.Fetch(t.Context()); err == nil {
|
||||
t.Fatal("Fetch (second) succeeded, want eventbus.ErrNoMessage -- duplicate was not suppressed")
|
||||
} else if !errors.Is(err, eventbus.ErrNoMessage) {
|
||||
t.Fatalf("Fetch (second) = %v, want eventbus.ErrNoMessage", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user