Merge pull request #875 from samcharles93/feat/archie-reactions-stream
feat(nats): provision the ARCHIE_REACTIONS fan-out stream
This commit is contained in:
commit
cae63b37c4
5 files changed
+244
-11
No files matched your search
@@ -453,6 +453,15 @@ func (b *boot) setupObservability(ctx context.Context) {
|
||||
go persistEvents(ctx, sink, b.stateStore, log)
|
||||
}
|
||||
|
||||
// reactionStreamMaxAge bounds how long a reaction survives in the fan-out
|
||||
// stream before JetStream discards it. Reactions are producer-only wake
|
||||
// events (docs/prds/event-sources-and-reactions.md): a dropped reaction only
|
||||
// delays work until the next poll, never loses it, because the authoritative
|
||||
// state is re-read at pass time. One day therefore tolerates a consumer that
|
||||
// is down or lagging for a full maintenance window without letting
|
||||
// acknowledged reactions accumulate without bound.
|
||||
const reactionStreamMaxAge = 24 * time.Hour
|
||||
|
||||
// connectNATS opens the NATS client. External mode dials cfg.NATS.URL;
|
||||
// embedded mode starts an in-process nats-server and dials it, so single-
|
||||
// process deployments get task distribution and reaction delivery without a
|
||||
@@ -507,11 +516,40 @@ func (b *boot) connectNATS(ctx context.Context) error { //nolint:nestif // embed
|
||||
log.Error("nats connect failed", "err", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Reactions are producer-only fan-out events: every interested consumer
|
||||
// must see each one, so they get their own stream under LimitsPolicy
|
||||
// rather than the work-queue policy ARCHIE_TASKS uses (which lets a
|
||||
// second consumer on an overlapping filter silently receive nothing).
|
||||
// LimitsPolicy retains every message until a limit is reached, so without
|
||||
// a finite limit acknowledged reactions would accumulate forever; the
|
||||
// MaxAge cap bounds that by time.
|
||||
reactionMaxAge := reactionStreamMaxAge
|
||||
reactionClient, err := nats.Connect(ctx, nats.Config{
|
||||
URL: url,
|
||||
Token: natsToken,
|
||||
StreamName: nats.DefaultReactionStreamName,
|
||||
Subjects: []string{workintake.SubjectReactionWildcard},
|
||||
FilterSubject: workintake.SubjectReactionWildcard,
|
||||
Retention: nats.FanOutRetention(),
|
||||
MaxAge: &reactionMaxAge,
|
||||
}, log)
|
||||
if err != nil {
|
||||
log.Error("nats reaction stream connect failed", "err", err)
|
||||
natsClient.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
b.natsClient = natsClient
|
||||
b.natsURL = url
|
||||
b.natsToken = natsToken
|
||||
b.addCleanup(func() { natsClient.Close() })
|
||||
log.Info("nats connected", "url", url)
|
||||
// The reaction client is kept only so its connection stays open for the
|
||||
// daemon's lifetime and is closed at shutdown; the stream it provisions
|
||||
// is the deliverable. A future producer (bead archie-core-8li9.3) will
|
||||
// need its own publisher surface, wired when that step lands.
|
||||
b.addCleanup(func() { reactionClient.Close() })
|
||||
log.Info("nats connected", "url", url, "task_stream", nats.DefaultStreamName, "reaction_stream", nats.DefaultReactionStreamName)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
// TestConnectNATSCreatesReactionStream pins the two JetStream streams the
|
||||
// daemon must provision alongside each other: ARCHIE_TASKS (work-queue task
|
||||
// distribution) and ARCHIE_REACTIONS (fan-out reaction delivery). Each case
|
||||
// asserts the ACTUAL stream configuration the embedded broker reports, not
|
||||
// just the Config struct that composed it.
|
||||
//
|
||||
// ARCHIE_REACTIONS must be a LimitsPolicy stream so two consumers on
|
||||
// overlapping filter subjects both receive a reaction (the trap documented in
|
||||
// CLAUDE.md), and it must carry a finite retention limit so acknowledged
|
||||
// reactions do not accumulate without bound. ARCHIE_TASKS must remain a
|
||||
// WorkQueuePolicy stream with no age/count/byte limit: acked messages are
|
||||
// discarded, so its only bound is outstanding work, and imposing a limit
|
||||
// could silently drop undelivered tasks.
|
||||
func TestConnectNATSCreatesReactionStream(t *testing.T) {
|
||||
b := &boot{
|
||||
cfg: config.Config{
|
||||
DBPath: filepath.Join(t.TempDir(), "archie.db"),
|
||||
NATS: config.NATSConfig{Mode: config.NATSModeEmbedded},
|
||||
},
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
if err := b.connectNATS(t.Context()); err != nil {
|
||||
t.Fatalf("connectNATS = %v", err)
|
||||
}
|
||||
t.Cleanup(b.cleanup)
|
||||
|
||||
conn, err := natsio.Connect(b.natsURL, natsio.Token(b.natsToken))
|
||||
if err != nil {
|
||||
t.Fatalf("raw nats connect = %v", err)
|
||||
}
|
||||
t.Cleanup(conn.Close)
|
||||
|
||||
js, err := jetstream.New(conn)
|
||||
if err != nil {
|
||||
t.Fatalf("jetstream.New = %v", err)
|
||||
}
|
||||
|
||||
streamCases := []struct {
|
||||
name string
|
||||
stream string
|
||||
retention jetstream.RetentionPolicy
|
||||
subjects []string
|
||||
wantMaxAge time.Duration
|
||||
}{
|
||||
{
|
||||
name: "reactions fan-out with finite retention",
|
||||
stream: "ARCHIE_REACTIONS",
|
||||
retention: jetstream.LimitsPolicy,
|
||||
subjects: []string{"archie.reaction.>"},
|
||||
wantMaxAge: reactionStreamMaxAge,
|
||||
},
|
||||
{
|
||||
name: "tasks work-queue unchanged and unbounded",
|
||||
stream: "ARCHIE_TASKS",
|
||||
retention: jetstream.WorkQueuePolicy,
|
||||
subjects: []string{"archie.task.>"},
|
||||
// wantMaxAge zero asserts ARCHIE_TASKS stays unbounded by age.
|
||||
},
|
||||
}
|
||||
for _, tc := range streamCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
stream, err := js.Stream(t.Context(), tc.stream)
|
||||
if err != nil {
|
||||
t.Fatalf("js.Stream(%s) = %v", tc.stream, err)
|
||||
}
|
||||
info, err := stream.Info(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("stream.Info(%s) = %v", tc.stream, err)
|
||||
}
|
||||
if info.Config.Retention != tc.retention {
|
||||
t.Fatalf("%s retention = %v, want %v", tc.stream, info.Config.Retention, tc.retention)
|
||||
}
|
||||
for _, subject := range tc.subjects {
|
||||
if !slices.Contains(info.Config.Subjects, subject) {
|
||||
t.Errorf("%s subjects = %v, want to contain %s", tc.stream, info.Config.Subjects, subject)
|
||||
}
|
||||
}
|
||||
if info.Config.MaxAge != tc.wantMaxAge {
|
||||
t.Fatalf("%s MaxAge = %v, want %v", tc.stream, info.Config.MaxAge, tc.wantMaxAge)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Fan-out proof: two consumers on the same overlapping filter subject
|
||||
// both receive the one published message. A work-queue stream would
|
||||
// deliver it to only one of them.
|
||||
reactionStream, err := js.Stream(t.Context(), "ARCHIE_REACTIONS")
|
||||
if err != nil {
|
||||
t.Fatalf("js.Stream(ARCHIE_REACTIONS) = %v", err)
|
||||
}
|
||||
if _, err := js.PublishMsg(t.Context(), &natsio.Msg{
|
||||
Subject: "archie.reaction.test",
|
||||
Data: []byte("x"),
|
||||
}); err != nil {
|
||||
t.Fatalf("publish to archie.reaction.* = %v, want it to land in ARCHIE_REACTIONS", err)
|
||||
}
|
||||
|
||||
got := make(chan string, 2)
|
||||
fetch := func() {
|
||||
consumer, err := reactionStream.CreateOrUpdateConsumer(t.Context(), jetstream.ConsumerConfig{
|
||||
FilterSubject: "archie.reaction.>",
|
||||
AckPolicy: jetstream.AckExplicitPolicy,
|
||||
})
|
||||
if err != nil {
|
||||
t.Errorf("create reaction consumer: %v", err)
|
||||
return
|
||||
}
|
||||
batch, err := consumer.Fetch(1, jetstream.FetchMaxWait(5*time.Second))
|
||||
if err != nil {
|
||||
t.Errorf("reaction consumer fetch: %v", err)
|
||||
return
|
||||
}
|
||||
for msg := range batch.Messages() {
|
||||
if msg == nil {
|
||||
continue
|
||||
}
|
||||
got <- string(msg.Data())
|
||||
_ = msg.Ack()
|
||||
}
|
||||
}
|
||||
go fetch()
|
||||
go fetch()
|
||||
|
||||
var received []string
|
||||
deadline := time.After(10 * time.Second)
|
||||
for len(received) < 2 {
|
||||
select {
|
||||
case data := <-got:
|
||||
received = append(received, data)
|
||||
case <-deadline:
|
||||
t.Fatalf("fan-out: received %v, want both consumers to receive x", received)
|
||||
}
|
||||
}
|
||||
for _, data := range received {
|
||||
if data != "x" {
|
||||
t.Errorf("reaction consumer received %q, want x", data)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,14 @@ const (
|
||||
SubjectTaskWildcard = "archie.task.>"
|
||||
)
|
||||
|
||||
// SubjectReactionWildcard matches every reaction subject under archie.reaction.
|
||||
// Reactions are producer-only fan-out events
|
||||
// (docs/prds/event-sources-and-reactions.md) delivered on a separate
|
||||
// LimitsPolicy stream, so every registered consumer sees every matching event
|
||||
// -- unlike the work-queue ARCHIE_TASKS stream, where one consumer claims each
|
||||
// message.
|
||||
const SubjectReactionWildcard = "archie.reaction.>"
|
||||
|
||||
// ErrUnknownKind reports a kind with no subject. Routing it to the default
|
||||
// queue instead would silently misdeliver work.
|
||||
var ErrUnknownKind = errors.New("workintake: unknown task kind")
|
||||
|
||||
@@ -59,13 +59,20 @@ func Connect(ctx context.Context, cfg Config, log *slog.Logger) (*Client, error)
|
||||
return nil, fmt.Errorf("nats jetstream init: %w", err)
|
||||
}
|
||||
|
||||
stream, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
|
||||
streamConfig := jetstream.StreamConfig{
|
||||
Name: cfg.StreamName,
|
||||
Subjects: cfg.Subjects,
|
||||
Storage: jetstream.FileStorage,
|
||||
Retention: *cfg.Retention,
|
||||
Duplicates: cfg.DedupWindow,
|
||||
})
|
||||
}
|
||||
// Limits are applied only when the composition explicitly sets them;
|
||||
// leaving MaxAge nil keeps the stream unbounded exactly as before.
|
||||
if cfg.MaxAge != nil {
|
||||
streamConfig.MaxAge = *cfg.MaxAge
|
||||
}
|
||||
|
||||
stream, err := js.CreateOrUpdateStream(ctx, streamConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("nats create stream %q: %w", cfg.StreamName, err)
|
||||
}
|
||||
|
||||
@@ -10,13 +10,17 @@ import (
|
||||
// Defaults for Config. Previously these were unexported package constants,
|
||||
// which made stream naming and timeouts untunable per deployment.
|
||||
const (
|
||||
DefaultStreamName = "ARCHIE_TASKS"
|
||||
DefaultConsumerName = "archie-daemon"
|
||||
DefaultDedupWindow = 2 * time.Minute
|
||||
DefaultPollTimeout = 2 * time.Second
|
||||
DefaultAckWait = 5 * time.Minute
|
||||
DefaultMaxDeliver = 3
|
||||
DefaultInactiveTTL = 24 * time.Hour
|
||||
DefaultStreamName = "ARCHIE_TASKS"
|
||||
// DefaultReactionStreamName is the fan-out stream carrying reaction
|
||||
// subjects. It coexists with DefaultStreamName (ARCHIE_TASKS), which
|
||||
// stays work-queue for task distribution.
|
||||
DefaultReactionStreamName = "ARCHIE_REACTIONS"
|
||||
DefaultConsumerName = "archie-daemon"
|
||||
DefaultDedupWindow = 2 * time.Minute
|
||||
DefaultPollTimeout = 2 * time.Second
|
||||
DefaultAckWait = 5 * time.Minute
|
||||
DefaultMaxDeliver = 3
|
||||
DefaultInactiveTTL = 24 * time.Hour
|
||||
)
|
||||
|
||||
// Config describes how to reach NATS and how the stream and consumer should
|
||||
@@ -59,6 +63,16 @@ type Config struct {
|
||||
// (LimitsPolicy) is a valid explicit choice.
|
||||
Retention *jetstream.RetentionPolicy
|
||||
|
||||
// MaxAge is the maximum age of messages the stream retains. Nil leaves
|
||||
// the stream unbounded by age, which is correct for ARCHIE_TASKS: under
|
||||
// WorkQueuePolicy acked messages are discarded, so its only bound is
|
||||
// outstanding work. The pointer form distinguishes "unset" (nil,
|
||||
// unbounded, today's behaviour) from an explicit zero (also unbounded,
|
||||
// but expressed on purpose), exactly like Retention. The fan-out
|
||||
// reaction stream sets a finite MaxAge so acknowledged reactions cannot
|
||||
// accumulate forever.
|
||||
MaxAge *time.Duration
|
||||
|
||||
// DedupWindow is how long JetStream remembers a Nats-Msg-Id, suppressing
|
||||
// republished duplicates of the same issue within the window.
|
||||
DedupWindow time.Duration
|
||||
@@ -88,7 +102,7 @@ func (c Config) Validate() error {
|
||||
if c.FilterSubject == "" {
|
||||
return fmt.Errorf("%w: FilterSubject is required", ErrInvalidConfig)
|
||||
}
|
||||
if c.PollTimeout < 0 || c.AckWait < 0 || c.DedupWindow < 0 {
|
||||
if c.PollTimeout < 0 || c.AckWait < 0 || c.DedupWindow < 0 || (c.MaxAge != nil && *c.MaxAge < 0) {
|
||||
return fmt.Errorf("%w: durations must not be negative", ErrInvalidConfig)
|
||||
}
|
||||
if c.MaxDeliver < 0 {
|
||||
@@ -127,3 +141,15 @@ func (c Config) withDefaults() Config {
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// FanOutRetention returns a pointer to jetstream.LimitsPolicy for use as
|
||||
// Config.Retention. It exists so composition can select fan-out retention
|
||||
// without importing the NATS SDK: the retention policy type stays behind this
|
||||
// package's boundary, like every other JetStream type. LimitsPolicy is the one
|
||||
// policy that cannot be expressed by leaving Retention unset (withDefaults
|
||||
// treats nil as WorkQueuePolicy), so the choice must be visible at the call
|
||||
// site.
|
||||
func FanOutRetention() *jetstream.RetentionPolicy {
|
||||
policy := jetstream.LimitsPolicy
|
||||
return &policy
|
||||
}
|
||||
Reference in new issue
Block a user