feat(daemon): resolve the producing identity's org before publishing work

The poller, the forge webhook intake and the review scan built envelopes
without an Org, so every task and reaction keyed on the default org no
matter which org its identity served. Resolve the org through the State
Store's PrincipalSource (the existing org RPC over the staterpc client)
on the single publish paths:

- PublishTask stamps the envelope's identity org before encoding, so the
  idempotency key is org/identity/owner/repo/number; a resolve failure
  stops the publish instead of keying under a guess.
- PublishReaction is the one reaction write path, stamping the root org
  when the webhook producer could not; the poll scan stamps its task's
  already-resolved org, so both deliveries of one review key the same.
- The webhook receiver's inline publish closure moves onto the daemon
  method, removing the second reaction write path.
This commit is contained in:
sam committed 2026-10-02 03:12:42 +10:00
1 parent a4abafe0ad
commit 04dedde52c
4 files changed
+337 -26

No files matched your search

+3 -9
View File
@@ -1504,15 +1504,9 @@ func (b *boot) setupForgeWebhook() {
// The reaction publisher is the consumer's supply side: the same typed
// reaction the poll produces, keyed source-independently, so webhook and
// poll deliveries of one review dedup (pr-review-remediation.md
// decision 2).
publishReaction := func(ctx context.Context, reaction workintake.ReviewCommentEnvelope) error {
payload, err := reaction.Encode()
if err != nil {
return err
}
return b.d.Tasks.PublishUnique(ctx, reaction.Subject(), reaction.IdempotencyKey(), payload)
}
receiver := forgewebhook.New(secretValue, cfg.Dispatch.Trigger, cfg.Label, cfg.BotUser, b.d.PublishTask, publishReaction, log)
// decision 2). The daemon's PublishReaction is the single reaction write
// path: it stamps the root org a webhook delivery would otherwise lack.
receiver := forgewebhook.New(secretValue, cfg.Dispatch.Trigger, cfg.Label, cfg.BotUser, b.d.PublishTask, b.d.PublishReaction, log)
host, port := parseListenAddr(cfg.Forge.WebhookAddr, "0.0.0.0", 8645)
addr := fmt.Sprintf("%s:%d", host, port)
srv := &http.Server{Addr: addr, Handler: receiver}
+71 -5
View File
@@ -26,6 +26,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
@@ -1137,11 +1138,13 @@ func (d *Daemon) pollNATS(ctx context.Context, fg forge.Forge, cfg config.Config
d.acknowledge(ctx, fg, cfg, repo, is)
}
// PublishTask validates, encodes and publishes a task envelope. The
// idempotency key means rediscovering the same issue on a later poll does not
// enqueue the work twice. It is the single enqueue path shared by the poller
// and the forge webhook intake, so neither can drift in how a discovered issue
// becomes a task.
// PublishTask validates, resolves the producing identity's org, encodes and
// publishes a task envelope. The idempotency key means rediscovering the same
// issue on a later poll does not enqueue the work twice. It is the single
// enqueue path shared by the poller and the forge webhook intake, so neither
// can drift in how a discovered issue becomes a task -- including the org the
// key is built from (docs/prds/orgs-and-access.md, "Events and task
// identity").
func (d *Daemon) PublishTask(ctx context.Context, task workintake.TaskEnvelope) error {
if d.Tasks == nil {
return fmt.Errorf("publish task %s: no task bus configured", task.Ref())
@@ -1149,6 +1152,11 @@ func (d *Daemon) PublishTask(ctx context.Context, task workintake.TaskEnvelope)
if err := task.Kind.Validate(); err != nil {
return fmt.Errorf("publish task %s: %w", task.Ref(), err)
}
resolved, err := d.identityOrg(ctx, d.publisherIdentity(task.Identity))
if err != nil {
return fmt.Errorf("publish task %s: resolve org: %w", task.Ref(), err)
}
task.Org = resolved
payload, err := task.Encode()
if err != nil {
return err
@@ -1156,6 +1164,64 @@ func (d *Daemon) PublishTask(ctx context.Context, task workintake.TaskEnvelope)
return d.Tasks.PublishUnique(ctx, task.Subject(), task.IdempotencyKey(), payload)
}
// PublishReaction stamps the resolved org on a reaction and publishes it on
// the reaction subject. A reaction the review scan already stamped with its
// task's org keeps it; otherwise (the webhook producer, single-identity) the
// root identity's org is used, so a webhook and a poll delivery of one review
// key the same. It is the single reaction write path shared by the scan and
// the webhook receiver.
func (d *Daemon) PublishReaction(ctx context.Context, reaction workintake.ReviewCommentEnvelope) error {
if d.Tasks == nil {
return fmt.Errorf("publish reaction %s: no task bus configured", reaction.Ref())
}
if reaction.Org == "" {
resolved, err := d.identityOrg(ctx, d.RootIdentityID)
if err != nil {
return fmt.Errorf("publish reaction %s: resolve org: %w", reaction.Ref(), err)
}
reaction.Org = resolved
}
payload, err := reaction.Encode()
if err != nil {
return err
}
return d.Tasks.PublishUnique(ctx, reaction.Subject(), reaction.IdempotencyKey(), payload)
}
// publisherIdentity is the identity a producer publishes as: the envelope's
// identity when it names one (an ID, or a name for a hand-built envelope),
// otherwise the root identity of a single-identity install.
func (d *Daemon) publisherIdentity(ref string) identity.IdentityID {
if ref == "" {
return d.RootIdentityID
}
for _, runner := range d.Identities {
if runner == nil {
continue
}
if runner.Name == ref || string(runner.ID) == ref {
return runner.ID
}
}
return identity.IdentityID(ref)
}
// identityOrg resolves the org an identity serves through the State Store
// before a producer publishes. An unwired PrincipalSource (an install with no
// State Store) resolves to the default org; a store failure is returned so the
// producer retries rather than publishing under a guessed org, which would key
// the same issue differently on a later delivery.
func (d *Daemon) identityOrg(ctx context.Context, id identity.IdentityID) (org.OrgID, error) {
if d.Principals == nil {
return org.DefaultOrgID, nil
}
principal, err := d.Principals.PrincipalFor(ctx, id)
if err != nil {
return "", err
}
return principal.Org, nil
}
// acknowledge posts the pickup reaction and queued event
// using fg -- the forge client that owns repo (identity-scoped or root) --
// and the ack reaction from cfg, the dispatch config that owns this poll.
+247
View File
@@ -0,0 +1,247 @@
package daemon
import (
"context"
"encoding/json"
"errors"
"log/slog"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/eventbus"
"github.com/samcharles93/archie-core/internal/forge"
)
// captureBus is a TaskBus that records the one published envelope, so a test
// can assert the org the producer resolved before encoding.
type captureBus struct {
subject string
key string
payload []byte
publish int
pubErr error
fetchErr error
}
func (b *captureBus) PublishUnique(_ context.Context, subject, key string, payload []byte) error {
if b.pubErr != nil {
return b.pubErr
}
b.subject, b.key, b.payload = subject, key, payload
b.publish++
return nil
}
func (b *captureBus) Fetch(context.Context) (eventbus.Message, error) {
if b.fetchErr != nil {
return nil, b.fetchErr
}
return nil, eventbus.ErrNoMessage
}
func (b *captureBus) Request(context.Context, string, []byte) ([]byte, error) {
return nil, errors.New("captureBus: Request is not part of this test")
}
// stubPrincipals is the access.PrincipalSource the producer resolves against,
// keyed by identity so a test can make each identity serve a distinct org.
type stubPrincipals struct {
orgs map[identity.IdentityID]org.OrgID
err error
}
func (s stubPrincipals) PrincipalFor(_ context.Context, id identity.IdentityID) (access.Principal, error) {
if s.err != nil {
return access.Principal{}, s.err
}
return access.Principal{IdentityID: id, Org: s.orgs[id]}, nil
}
func decodedTask(t *testing.T, payload []byte) workintake.TaskEnvelope {
t.Helper()
var got workintake.TaskEnvelope
if err := json.Unmarshal(payload, &got); err != nil {
t.Fatalf("decode published task: %v", err)
}
return got
}
// TestPublishTaskStampsTheResolvedIdentityOrg is the core scbe assertion: the
// poller's envelope must carry the org the identity serves, not the default,
// so the idempotency key is org/identity/owner/repo/number for a multi-org
// install (docs/prds/orgs-and-access.md, "Events and task identity").
func TestPublishTaskStampsTheResolvedIdentityOrg(t *testing.T) {
id := identity.StableID("worker")
bus := &captureBus{}
d := &Daemon{
Tasks: bus,
Log: slog.New(slog.DiscardHandler),
Identities: []*IdentityRunner{{ID: id, Name: "worker"}},
Principals: stubPrincipals{orgs: map[identity.IdentityID]org.OrgID{id: "soc"}},
}
err := d.PublishTask(t.Context(), workintake.TaskEnvelope{
Owner: "acme", Repo: "widget", Number: 1, Identity: string(id),
})
if err != nil {
t.Fatalf("PublishTask: %v", err)
}
got := decodedTask(t, bus.payload)
if got.Org != "soc" {
t.Errorf("published org = %q, want the identity's org %q", got.Org, "soc")
}
if want := "soc/" + string(id) + "/acme/widget/1"; !strings.Contains(bus.key, want) {
t.Errorf("idempotency key = %q, want it to contain %q", bus.key, want)
}
}
// TestPublishTaskUsesTheRootOrgForASingleIdentityEnvelope pins the webhook
// producer's shape: an empty identity is the root identity of a
// single-operator install, so its org is the org the key must carry.
func TestPublishTaskUsesTheRootOrgForASingleIdentityEnvelope(t *testing.T) {
root := identity.StableID("root")
bus := &captureBus{}
d := &Daemon{
Tasks: bus,
Log: slog.New(slog.DiscardHandler),
RootIdentityID: root,
Principals: stubPrincipals{orgs: map[identity.IdentityID]org.OrgID{root: "soc"}},
}
if err := d.PublishTask(t.Context(), workintake.TaskEnvelope{
Owner: "acme", Repo: "widget", Number: 2,
}); err != nil {
t.Fatalf("PublishTask: %v", err)
}
if got := decodedTask(t, bus.payload).Org; got != "soc" {
t.Errorf("published org = %q, want the root identity's org %q", got, "soc")
}
}
// TestPublishTaskFailsClosedWhenTheOrgCannotBeResolved: publishing under a
// guessed org would let the same issue key differently across deliveries, so
// an org-RPC failure must stop the publish rather than fall back to default.
func TestPublishTaskFailsClosedWhenTheOrgCannotBeResolved(t *testing.T) {
id := identity.StableID("worker")
bus := &captureBus{}
d := &Daemon{
Tasks: bus,
Log: slog.New(slog.DiscardHandler),
Identities: []*IdentityRunner{{ID: id, Name: "worker"}},
Principals: stubPrincipals{err: errors.New("state store unavailable")},
}
err := d.PublishTask(t.Context(), workintake.TaskEnvelope{
Owner: "acme", Repo: "widget", Number: 3, Identity: string(id),
})
if err == nil {
t.Fatal("PublishTask succeeded with an unresolved org; it must fail closed")
}
if bus.publish != 0 {
t.Fatalf("published %d envelope(s) after an org resolve failure, want 0", bus.publish)
}
}
// TestPublishTaskDefaultsToTheDefaultOrgWithoutAPrincipalSource: an install
// with no State Store has no org surface, so the default org remains correct.
func TestPublishTaskDefaultsToTheDefaultOrgWithoutAPrincipalSource(t *testing.T) {
bus := &captureBus{}
d := &Daemon{Tasks: bus, Log: slog.New(slog.DiscardHandler)}
if err := d.PublishTask(t.Context(), workintake.TaskEnvelope{
Owner: "acme", Repo: "widget", Number: 4,
}); err != nil {
t.Fatalf("PublishTask: %v", err)
}
if got := decodedTask(t, bus.payload).Org; got != org.DefaultOrgID {
t.Errorf("published org = %q, want %q", got, org.DefaultOrgID)
}
}
// TestScanPRReviewReactionsCarriesTheTaskOrg: the review scan already holds
// the task, so the org it resolved for the PR is the org its reactions must
// key on -- no second lookup and no cross-org drift between the two producers.
func TestScanPRReviewReactionsCarriesTheTaskOrg(t *testing.T) {
reader := &fakeReviewReader{
reviews: []forge.Review{{ID: 7, Author: "alice", State: "requested_changes", Body: "fix"}},
}
publisher := &recordingPublisher{}
task := openTask(42, 0, 0)
task.Org = "soc"
if _, _, err := scanPRReviewReactions(
t.Context(), reader, task, "archie-bot", 0, 0, publisher.publish); err != nil {
t.Fatal(err)
}
if len(publisher.reactions) != 1 {
t.Fatalf("published = %d, want 1", len(publisher.reactions))
}
if got := publisher.reactions[0].Org; got != "soc" {
t.Errorf("reaction org = %q, want the task's org %q", got, "soc")
}
}
// TestPublishReactionStampsTheRootOrgWhenTheProducerCouldNot: the webhook
// producer has no owned task to read an org from, so the reaction write path
// resolves the root identity's org -- the same org the poll's scan stamps --
// or the two deliveries of one review key differently.
func TestPublishReactionStampsTheRootOrgWhenTheProducerCouldNot(t *testing.T) {
root := identity.StableID("root")
bus := &captureBus{}
d := &Daemon{
Tasks: bus,
Log: slog.New(slog.DiscardHandler),
RootIdentityID: root,
Principals: stubPrincipals{orgs: map[identity.IdentityID]org.OrgID{root: "soc"}},
}
err := d.PublishReaction(t.Context(), workintake.ReviewCommentEnvelope{
Owner: "acme", Repo: "widget", PRNumber: 1,
Kind: workintake.ReviewReactionReview, ReviewID: 5, Author: "alice",
})
if err != nil {
t.Fatalf("PublishReaction: %v", err)
}
var got workintake.ReviewCommentEnvelope
if err := json.Unmarshal(bus.payload, &got); err != nil {
t.Fatalf("decode published reaction: %v", err)
}
if got.Org != "soc" {
t.Errorf("published org = %q, want the root identity's org %q", got.Org, "soc")
}
if want := "review/soc/acme/widget/1/review/5"; !strings.Contains(bus.key, want) {
t.Errorf("idempotency key = %q, want it to contain %q", bus.key, want)
}
}
// TestPublishReactionKeepsTheScansResolvedOrg: a reaction the scan already
// resolved from its task must not be re-resolved to the root org, or a
// multi-identity install would collapse every org's reactions onto one key.
func TestPublishReactionKeepsTheScansResolvedOrg(t *testing.T) {
bus := &captureBus{}
d := &Daemon{Tasks: bus, Log: slog.New(slog.DiscardHandler)}
err := d.PublishReaction(t.Context(), workintake.ReviewCommentEnvelope{
Owner: "acme", Repo: "widget", PRNumber: 1,
Kind: workintake.ReviewReactionReview, ReviewID: 5, Org: "soc",
})
if err != nil {
t.Fatalf("PublishReaction: %v", err)
}
var got workintake.ReviewCommentEnvelope
if err := json.Unmarshal(bus.payload, &got); err != nil {
t.Fatalf("decode published reaction: %v", err)
}
if got.Org != "soc" {
t.Errorf("published org = %q, want the scan's org %q", got.Org, "soc")
}
}
+16 -12
View File
@@ -48,6 +48,7 @@ func scanPRReviewReactions(
Owner: task.Owner, Repo: task.Repo, PRNumber: task.PRNumber,
Kind: workintake.ReviewReactionReview,
ReviewID: r.ID, Author: r.Author, State: r.State, Body: r.Body,
Org: task.Org,
}
if err := publish(ctx, reaction); err != nil {
return reviewCursor, commentCursor, fmt.Errorf("publish review %d: %w", r.ID, err)
@@ -71,6 +72,7 @@ func scanPRReviewReactions(
ReviewID: cm.ReviewID,
CommentID: cm.ID,
Author: cm.Author, Body: cm.Body, Path: cm.Path, Line: cm.Line,
Org: task.Org,
}
if err := publish(ctx, reaction); err != nil {
return reviewCursor, commentCursor, fmt.Errorf("publish comment %d: %w", cm.ID, err)
@@ -95,7 +97,7 @@ func (d *Daemon) scanPRReviews(ctx context.Context) {
return
}
if d.reactionPublisher == nil {
d.reactionPublisher = d.publishReaction
d.reactionPublisher = d.PublishReaction
}
for i := range tasks {
t := &tasks[i]
@@ -108,6 +110,19 @@ func (d *Daemon) scanPRReviews(ctx context.Context) {
}
func (d *Daemon) scanOnePR(ctx context.Context, reader forge.PullRequestReviewReader, t *workflowtask.Task) {
// The reactions this scan publishes key on the task's org, resolved from
// the owning identity through the same org RPC the poll uses, so a poll
// and a webhook delivery of one review collapse under one key. An org-RPC
// failure skips the task for this scan, cursors unchanged, rather than
// publishing under the default org.
if t.Org == "" {
resolved, err := d.identityOrg(ctx, d.publisherIdentity(t.Identity))
if err != nil {
d.Log.Warn("review scan org resolve failed", "task", t.ID, "err", err)
return
}
t.Org = resolved
}
// A forge read failure skips the task for this scan with its cursors
// unchanged: the next scan re-fetches, and PublishUnique's dedup covers
// anything the previous scan already published.
@@ -128,14 +143,3 @@ func (d *Daemon) scanOnePR(ctx context.Context, reader forge.PullRequestReviewRe
d.Log.Warn("review cursor persist failed", "task", t.ID, "err", err)
}
}
// publishReaction encodes one reaction and publishes it on the reaction
// subject with its source-independent idempotency key, so a webhook delivery
// and a poll record of the same review collapse into one.
func (d *Daemon) publishReaction(ctx context.Context, reaction workintake.ReviewCommentEnvelope) error {
payload, err := reaction.Encode()
if err != nil {
return err
}
return d.Tasks.PublishUnique(ctx, reaction.Subject(), reaction.IdempotencyKey(), payload)
}