diff --git a/modules/nats/cmd/nats-tools/keep.go b/modules/nats/cmd/nats-tools/keep.go index 1a946c07a..36bbc69d3 100644 --- a/modules/nats/cmd/nats-tools/keep.go +++ b/modules/nats/cmd/nats-tools/keep.go @@ -251,7 +251,7 @@ func runKeeper(ctx context.Context, getenv func(string) string, logOut io.Writer } defer stopAnswers() logger.Printf("started on the account %s: following the catalog half of every watched branch through the seat %s", account.User, catalog.Seat) - return Keep(ctx, k, hearer(js, account, follow.take, follow.bound, logger.Printf), requestsOf(conn), moved, logger.Printf) + return Keep(ctx, k, hearer(js, account, follow.take, follow.bound, unheardFinding(writer, account, logger.Printf), logger.Printf), requestsOf(conn), moved, logger.Printf) } // catalogFollow is the keeper's reading of the catalog half and the seat list (design 47 G §532, §614): the reader, the @@ -378,7 +378,7 @@ func (r *eventRoutes) get(subject string) func(jetstream.Msg) { // hearer binds the keeper's durable consumer on EVENTS (_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. -func hearer(js jetstream.JetStream, a process.Account, take func(jetstream.Msg) bool, bound func(time.Time), logf func(string, ...any)) func(context.Context, func(subject string, body []byte) error) error { +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 { @@ -387,7 +387,7 @@ func hearer(js jetstream.JetStream, a process.Account, take func(jetstream.Msg) if info, err := cons.Info(ctx); err == nil && bound != nil { bound(info.Created.UTC()) } - cc, err := process.HearEvents(cons, func(m jetstream.Msg) { + deliver := func(m jetstream.Msg) { if take != nil && take(m) { return } @@ -397,11 +397,14 @@ func hearer(js jetstream.JetStream, a process.Account, take func(jetstream.Msg) return } _ = m.Ack() - }, logf) + } + cc, err := process.HearEvents(cons, deliver, logf) if 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) return nil } } diff --git a/modules/nats/cmd/nats-tools/keeper_integration_test.go b/modules/nats/cmd/nats-tools/keeper_integration_test.go index f9aa7e903..1f34e2ff4 100644 --- a/modules/nats/cmd/nats-tools/keeper_integration_test.go +++ b/modules/nats/cmd/nats-tools/keeper_integration_test.go @@ -24,6 +24,7 @@ import ( "git.novox.be/novox/mesh-contracts/go/seats/meshbroker" "git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient" "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" occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient" oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel" catalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog" @@ -139,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.*.event.>"}}, + {Name: "EVENTS", Subjects: []string{"mesh.mod.*.event.>", "mesh.seat.mesh-broker.event.>", "mesh.seat.operator-channel.event.>", "mesh.seat.mesh-conditions.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.>"}}, } { @@ -231,7 +232,10 @@ func TestTheBusModuleRunsWhole(t *testing.T) { }() return nil } - go func() { _ = Keep(kctx, k, hearer(js, account, nil, nil, t.Logf), watch, moved, t.Logf); close(done) }() + go func() { + _ = Keep(kctx, k, hearer(js, account, nil, nil, nil, t.Logf), watch, moved, t.Logf) + close(done) + }() return func() { stop(); <-done } } // onBranch puts a module's entry in a branch's newest revision (none: the module leaves it), and moves the keeper. @@ -835,6 +839,43 @@ func TestTheBusModuleRunsWhole(t *testing.T) { }) }) stop() + // Design 47 H2b §836 5. (1984/AC-836g): a source-moved said on its kept stream reaches the keeper's handler; with that + // 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 { + t.Fatal(err) + } + 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) + 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" }) + }) + if _, err := js.CreateOrUpdateConsumer(ctx, stream, jetstream.ConsumerConfig{Durable: account.QueueConsumerName(), AckPolicy: jetstream.AckExplicitPolicy}); err != nil { + t.Fatal(err) + } + if err := nc.Publish(meshgrants.SubjectDurablesComposed(account.Node, account.Module), nil); err != nil { + t.Fatal(err) + } + if _, err := js.Publish(ctx, "mesh.seat.mesh-delivery.event.source-moved.main", []byte(`{}`)); err != nil { + t.Fatal(err) + } + eventually(t, "the source-moved at the keeper's handler", func() bool { + cmu.Lock() + defer cmu.Unlock() + 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 }) + }) + }) } func entry(name, storage, template string, options map[string]string) catalogue.BusStateEntry { diff --git a/modules/nats/cmd/nats-tools/kept.go b/modules/nats/cmd/nats-tools/kept.go new file mode 100644 index 000000000..81f4e479f --- /dev/null +++ b/modules/nats/cmd/nats-tools/kept.go @@ -0,0 +1,147 @@ +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__`, 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 { + Write(ctx context.Context, finding meshconditions.Finding) error + Clear(ctx context.Context, scope, id, kind, why string) error +}, a process.Account, logf func(string, ...any)) func([]process.Unheard) { + id := a.Module + "." + a.Node + return func(list []process.Unheard) { + ctx := context.Background() + if len(list) == 0 { + if err := w.Clear(ctx, "module", id, views.EventsUnheardKind, "the part hears every event it consumes"); err != nil { + logf("the finding %s cannot be cleared: %v", views.EventsUnheardKind, err) + } + return + } + var named []string + for _, u := range list { + named = append(named, fmt.Sprintf("%s on %s (%s)", u.Pattern, u.Stream, u.Why)) + } + f := meshconditions.Finding{Scope: "module", ID: id, Kind: views.EventsUnheardKind, + Subject: meshconditions.Subject{Scope: "module", ID: keeper.Module}, + Severity: meshconditions.FindingSeverityWarning, Headline: "The bus module does not hear all its events", + Summary: fmt.Sprintf("%s on %s does not hear %d event patterns: %v: what it consumes there it does not act on; a bind the bus refuses while its durable stands is made again by the node's service manager restarting the module's unit", + keeper.Module, a.Node, len(list), named), + Needs: "the grants part's durables composed, or the module's unit restarted", Source: "events", Observer: keeper.Module, At: time.Now().UTC()} + if err := w.Write(ctx, f); err != nil { + logf("the finding %s cannot be written: %v", views.EventsUnheardKind, err) + } + } +} diff --git a/modules/nats/go.mod b/modules/nats/go.mod index 711418167..f3a35604f 100644 --- a/modules/nats/go.mod +++ b/modules/nats/go.mod @@ -6,6 +6,7 @@ require ( git.novox.be/novox/mesh-contracts/go/seats/meshbroker v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions v0.0.0-00010101000000-000000000000 + git.novox.be/novox/mesh-contracts/identity-and-access/go/seats/meshgrants v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel v0.0.0-00010101000000-000000000000 git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient v0.0.0-00010101000000-000000000000