N1 fix: the keeper hears its kept seat events through mesh-sdk's hub under its own durable; the copy in kept.go goes; the row raises and clears events-unheard on a fixture in the writer's form

Fixes review r1 part 4 items 1, 4 and 5 (H-A-876, AC-836g).
Builds: design 47 H2b §836 5.
This commit is contained in:
2026-11-27 03:57:09 +01:00
parent 37c350fb89
commit 264dfb1660
3 changed files with 45 additions and 123 deletions
+31 -15
View File
@@ -375,18 +375,13 @@ func (r *eventRoutes) get(subject string) func(jetstream.Msg) {
return r.by[subject]
}
// hearer binds the keeper's durable consumer on EVENTS (<node>_nats_keeper, filtered on its consumes): a message of the
// catalog half or the seat list goes to take, which acknowledges it; every other to handle, acknowledged once applied.
// bound is told when the bus made the consumer.
// hearer hears the events the keeper consumes through mesh-sdk's event hub, which binds the process's own durable
// `<node>_nats_keeper` on EVENTS and on every kept seat event's stream that carries one of its patterns, binds the ones it
// could not when the grants part says it composed the module's durables and at a reconnect, and says each it cannot (design 47
// H2b §836 5., H-A-876): a message of the catalog half or the seat list goes to take, which acknowledges it; every other to
// handle, acknowledged once applied. bound is told when the bus made a durable; unheard, the patterns not heard.
func hearer(js jetstream.JetStream, a process.Account, take func(jetstream.Msg) bool, bound func(time.Time), unheard func([]process.Unheard), logf func(string, ...any)) func(context.Context, func(subject string, body []byte) error) error {
return func(ctx context.Context, handle func(string, []byte) error) error {
cons, err := js.Consumer(ctx, process.EventsStream, a.QueueConsumerName())
if err != nil {
return fmt.Errorf("the keeper's consumer %s on %s: %w", a.QueueConsumerName(), process.EventsStream, err)
}
if info, err := cons.Info(ctx); err == nil && bound != nil {
bound(info.Created.UTC())
}
deliver := func(m jetstream.Msg) {
if take != nil && take(m) {
return
@@ -398,17 +393,38 @@ func hearer(js jetstream.JetStream, a process.Account, take func(jetstream.Msg)
}
_ = m.Ack()
}
cc, err := process.HearEvents(cons, deliver, logf)
if err != nil {
hub := process.NewEventHub(logf)
if err := hub.ForProcess(a.ProcessID()); err != nil {
return err
}
go func() { <-ctx.Done(); cc.Stop() }()
// The kept seat events its module consumes, on the durable the grants part composes on each stream (design 47 H2b §836 5.).
(&keptHearing{js: js, a: a, deliver: deliver, unheard: unheard, logf: logf}).start(ctx)
if bound != nil {
hub.OnBound(bound)
}
if unheard != nil {
hub.OnUnheard(unheard)
}
for _, pattern := range consumedPatterns {
if err := hub.Handle(pattern, deliver); err != nil {
return err
}
}
if err := hub.Start(ctx, js, a); err != nil {
return err
}
go func() { <-ctx.Done(); hub.Stop() }()
return nil
}
}
// consumedPatterns are the subjects of the events the keeper consumes (its module's `consumes` and the operator channel's decided
// for its own asks); which of them a kept stream carries is the hub's to find, never listed here.
var consumedPatterns = []string{
"mesh.seat." + catalog.Seat + ".event.>",
seatdef.EventSubject(sourcebranches.Seat, sourcebranches.EventSourceMoved) + ".>",
seatdef.EventSubject(meshconditions.Seat, meshconditions.EventFindingsAsked) + ".>",
DecidedSubject,
}
// FillEvery is how often the keeper's fill pass runs: a minute (a test's shorter bound beside).
var FillEvery = time.Minute
@@ -140,7 +140,7 @@ func TestTheBusModuleRunsWhole(t *testing.T) {
// What the grants part creates for the bus module from its manifest's old sections: EVENTS and the keeper's
// consumer on it, its own stream, and its two states.
for _, c := range []jetstream.StreamConfig{
{Name: "EVENTS", Subjects: []string{"mesh.mod.*.event.>", "mesh.seat.mesh-broker.event.>", "mesh.seat.operator-channel.event.>", "mesh.seat.mesh-conditions.event.>"}},
{Name: "EVENTS", Subjects: []string{"mesh.mod.*.event.>", "mesh.seat.*.event.>"}},
{Name: BrokerEventsStream, Subjects: []string{"mesh.stream.nats.event.>"}, MaxAge: 30 * 24 * time.Hour, MaxBytes: 256 << 20},
{Name: "CONDITIONS", Subjects: []string{"mesh.seat.operator-channel.accept.condition.>"}},
} {
@@ -843,23 +843,32 @@ func TestTheBusModuleRunsWhole(t *testing.T) {
// durable not composed yet, the keeper says it unheard and binds it on the durables-composed that follows.
t.Run("a kept seat event reaches the keeper, its durable bound when the grants part says it composed it", func(t *testing.T) {
const stream = "SEAT_mesh-delivery_source-moved"
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: stream, Subjects: []string{"mesh.seat.mesh-delivery.event.source-moved.>"}}); err != nil {
// The kept stream as the grants part composes it: sourced from EVENTS by the event's subject (mesh-grants buscompose).
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: stream,
Sources: []*jetstream.StreamSource{{Name: "EVENTS", FilterSubject: "mesh.seat.mesh-delivery.event.source-moved.>"}}}); err != nil {
t.Fatal(err)
}
findings, err := js.KeyValue(ctx, "nats_findings")
if err != nil {
t.Fatal(err)
}
const findingKey = "module.nats.anchor.events-unheard"
var cmu sync.Mutex
var told [][]process.Unheard
var got []string
kctx, kstop := context.WithCancel(ctx)
defer kstop()
hear := hearer(js, account, nil, nil, func(l []process.Unheard) { cmu.Lock(); told = append(told, l); cmu.Unlock() }, t.Logf)
raise := unheardFinding(writer, account, t.Logf)
hear := hearer(js, account, nil, nil, func(l []process.Unheard) { cmu.Lock(); told = append(told, l); cmu.Unlock(); raise(l) }, t.Logf)
if err := hear(kctx, func(subject string, _ []byte) error { cmu.Lock(); got = append(got, subject); cmu.Unlock(); return nil }); err != nil {
t.Fatal(err)
}
eventually(t, "the stream's durable said not composed", func() bool {
cmu.Lock()
defer cmu.Unlock()
return len(told) > 0 && slices.ContainsFunc(told[0], func(u process.Unheard) bool { return u.Stream == stream && u.Why == "not composed" })
return len(told) > 0 && slices.ContainsFunc(told[0], func(u process.Unheard) bool { return u.Stream == stream && strings.HasPrefix(u.Why, "not composed") })
})
eventually(t, "the finding events-unheard raised", func() bool { _, err := findings.Get(ctx, findingKey); return err == nil })
if _, err := js.CreateOrUpdateConsumer(ctx, stream, jetstream.ConsumerConfig{Durable: account.QueueConsumerName(), AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
t.Fatal(err)
}
@@ -875,6 +884,7 @@ func TestTheBusModuleRunsWhole(t *testing.T) {
return slices.Contains(got, "mesh.seat.mesh-delivery.event.source-moved.main") &&
!slices.ContainsFunc(told[len(told)-1], func(u process.Unheard) bool { return u.Stream == stream })
})
eventually(t, "the finding events-unheard cleared", func() bool { _, err := findings.Get(ctx, findingKey); return errors.Is(err, jetstream.ErrKeyNotFound) })
})
}
-104
View File
@@ -2,119 +2,15 @@ package main
import (
"context"
"errors"
"fmt"
"slices"
"sync"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
meshgrants "git.novox.be/novox/mesh-contracts/identity-and-access/go/seats/meshgrants"
catalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/sourcebranches"
"git.novox.be/novox/mesh-sdk/go/process"
"git.novox.be/novox/mesh-sdk/go/seatdef"
"git.novox.be/novox/mesh-sdk/go/views"
"nats-tools/internal/keeper"
)
// keptConsumed are the kept seat events the bus module's module consumes, each on its own stream `SEAT_<seat>_<event>`, where the
// grants part composes the keeper a durable named as its durable on EVENTS (design 47 H2b §836 5.).
var keptConsumed = []struct{ seat, event string }{
{catalog.Seat, catalog.EventRegistrationChanged},
{sourcebranches.Seat, sourcebranches.EventSourceMoved},
{meshconditions.Seat, meshconditions.EventFindingsAsked},
}
// keptHearing binds the keeper's durable on each kept stream it consumes and pulls it with the keeper's one handler. A stream
// it cannot bind is said (the journal, and unheard), and bound again when the grants part says it composed the module's durables
// and at the bus connection's reconnect, never on a timer.
type keptHearing struct {
js jetstream.JetStream
a process.Account
deliver func(jetstream.Msg)
unheard func([]process.Unheard)
logf func(string, ...any)
mu sync.Mutex // one pass at a time
bind map[string]bool
told bool
last []process.Unheard
}
// start makes the wake and the reconnect hook, then binds what it can.
func (k *keptHearing) start(ctx context.Context) {
k.bind = map[string]bool{}
nc := k.js.Conn()
sub, err := nc.Subscribe(meshgrants.SubjectDurablesComposed(k.a.Node, k.a.Module), func(*nats.Msg) { k.pass(ctx) })
if err != nil {
k.logf("the grants part's word of the module's durables is not heard (%v): a stream not bound is bound at the bus connection's reconnect or the next start", err)
} else {
go func() { <-ctx.Done(); _ = sub.Unsubscribe() }()
}
before := nc.Opts.ReconnectedCB
nc.SetReconnectHandler(func(c *nats.Conn) {
if before != nil {
before(c)
}
k.pass(ctx)
})
k.pass(ctx)
}
// pass binds every kept stream's durable not bound yet, and says the streams it could not.
func (k *keptHearing) pass(ctx context.Context) {
if ctx.Err() != nil {
return
}
k.mu.Lock()
defer k.mu.Unlock()
var not []process.Unheard
for _, c := range keptConsumed {
stream := seatdef.KeptStreamPrefix + c.seat + "_" + c.event
if k.bind[stream] {
continue
}
pattern := seatdef.EventSubject(c.seat, c.event) + ".>"
if why := k.bindOne(ctx, stream); why != "" {
not = append(not, process.Unheard{Pattern: pattern, Stream: stream, Why: why})
}
}
if k.told && slices.Equal(not, k.last) {
return
}
k.told, k.last = true, not
for _, u := range not {
k.logf("events: the pattern %s is not heard on %s: %s", u.Pattern, u.Stream, u.Why)
}
if k.unheard != nil {
k.unheard(slices.Clone(not))
}
}
// bindOne binds the keeper's durable on stream; the why it could not, or "".
func (k *keptHearing) bindOne(ctx context.Context, stream string) string {
cons, err := k.js.Consumer(ctx, stream, k.a.QueueConsumerName())
switch {
case errors.Is(err, jetstream.ErrStreamNotFound):
return "no stream carries it"
case errors.Is(err, jetstream.ErrConsumerNotFound):
return "not composed"
case err != nil:
return fmt.Sprintf("refused: %v", err)
}
cc, err := process.HearEvents(cons, k.deliver, k.logf)
if err != nil {
return fmt.Sprintf("refused: %v", err)
}
k.bind[stream] = true
go func() { <-ctx.Done(); cc.Stop() }()
return ""
}
// unheardFinding raises the module's finding events-unheard through the held writer, naming each pattern not heard, and clears it
// on an empty list (design 47 H2b §836 4., 5.).
func unheardFinding(w interface {