Files
mesh-tools/node-tools/internal/bus/streams.go
T
jschoubben ba82044cc0 node-tools: the runner makes its twin from the membership's spec, removes it when withdrawn
The grants part no longer composes the tool runner's `_tools` twin: at a child's
first subscribe the runner creates or updates `<node>_<module>_tools` on EVENTS and
on every heard stream from the spec the membership's entry carries (filters, ack
wait, max deliver, max ack pending, deliver policy), and binds by name an entry an
older grants part wrote without one. When the grants part withdraws the module's
membership on this node, the runner removes the twins from the streams the last
entry named and makes none again until a membership is issued; it removes nothing
at its start. The heard entry is mesh-sdk's type, so the hearing keys its loops by
stream and consumer.

Builds: design 47 H2 H-A-472 (fifth, sixth, seventh, eighth and ninth addenda)
2026-11-22 19:35:08 +01:00

432 lines
16 KiB
Go

package bus
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-sdk/go/membership"
"git.novox.be/novox/mesh-sdk/go/process"
)
// A module's own stream, as the runtime publishes to it and hears it (novox/hq ADR 0363 §8, issue 725).
//
// A module may declare a stream of its own; the mesh creates it and says, in the module's
// membership, which of its events go there and on which subject (`streams`), and, in the membership of
// each module granted to hear it, which durable consumer on it to bind (`hears`). The runtime publishes and
// binds exactly as the membership says. A membership naming neither is what every membership was before:
// every event on EVENTS, and only the consumer on EVENTS bound.
// StreamIssued is one of a module's own streams as its membership names it: the events it carries, as the
// bus spells them (`*` one token, `>` the rest), and the subject an event of them is published on, `{event}`
// standing for the event.
type StreamIssued struct {
Stream string `json:"stream"`
Events []string `json:"events"`
Subject string `json:"subject"`
}
// HeardIssued is one stream an assignment hears, EVENTS like any other: the stream, the module's durable consumer the
// runner's twin on it is named from, and, from a grants part that writes it, the twin's whole spec (mesh-sdk's
// membership.HeardIssued; design 47 H2, H-A-472 seventh and eighth addenda). An entry with a spec is created or updated
// from it by the runner at a child's first subscribe; one without, an older writer's, is bound by name as before.
type HeardIssued = membership.HeardIssued
// heardKey is one consumer a hearing binds: the stream and the runner's twin on it. The spec rides beside it, never in
// it, so a map is keyed by the consumer alone.
type heardKey struct{ Stream, Consumer string }
// twinConfig is the configuration of the runner's twin of a heard entry with a spec: its filters, ack wait, max deliver,
// max ack pending and deliver policy as the grants part composed them, under the twin's own name. Every filter goes in
// FilterSubjects, one alone too, so the create is on the name alone, the form the reader is granted.
func twinConfig(h HeardIssued) (jetstream.ConsumerConfig, error) {
cfg := jetstream.ConsumerConfig{
Durable: h.Consumer + ToolsSuffix,
AckPolicy: jetstream.AckExplicitPolicy,
AckWait: time.Duration(h.AckWaitSeconds) * time.Second,
MaxDeliver: h.MaxDeliver,
MaxAckPending: h.MaxAckPending,
FilterSubjects: append([]string(nil), h.Filters...),
}
switch h.DeliverPolicy {
case membership.DeliverFromNow:
cfg.DeliverPolicy = jetstream.DeliverNewPolicy
case membership.DeliverLastPerSubject:
cfg.DeliverPolicy = jetstream.DeliverLastPerSubjectPolicy
case membership.DeliverAll, "":
cfg.DeliverPolicy = jetstream.DeliverAllPolicy
default:
return cfg, fmt.Errorf("the membership names the deliver policy %q, which the runner does not know", h.DeliverPolicy)
}
return cfg, nil
}
// makeTwin creates or updates the runner's twin of a heard entry from its spec (H-A-472 fifth to seventh addenda): what
// the bus lacks is made as a part's process makes it, and one held is brought to the spec, its delivery position kept.
// An entry without a spec makes nothing: its consumer is the grants part's, bound by name.
func makeTwin(ctx context.Context, js jetstream.JetStream, h HeardIssued) error {
if !h.HasSpec() {
return nil
}
cfg, err := twinConfig(h)
if err != nil {
return err
}
_, err = js.CreateOrUpdateConsumer(ctx, h.Stream, cfg)
return err
}
// eventSubject is where a module's event is published: on the subject of the first of its membership's
// streams that carries it, else on EVENTS — `mesh.mod.<module>.event.<event>`, as every event was before.
func eventSubject(m *Membership, module, event string) string {
if m != nil {
for _, s := range m.Streams {
if s.Subject == "" || !strings.Contains(s.Subject, "{event}") {
continue
}
for _, pattern := range s.Events {
if eventMatches(pattern, event) {
return strings.ReplaceAll(s.Subject, "{event}", event)
}
}
}
}
return "mesh.mod." + module + ".event." + event
}
// eventMatches says whether an event's name falls under a pattern as the bus matches subjects: `*` is one
// token, `>` (or `**`, the manifest's spelling) the one or more tokens left.
func eventMatches(pattern, event string) bool {
if pattern == "" || event == "" {
return false
}
ps, es := strings.Split(pattern, "."), strings.Split(event, ".")
for i, p := range ps {
if p == ">" || p == "**" {
return i == len(ps)-1 && len(es) > i
}
if i >= len(es) || (p != "*" && p != es[i]) {
return false
}
}
return len(ps) == len(es)
}
// RebindEvery is how often a consumer the membership names and the bus did not let the runtime bind is
// tried again: the mesh makes the consumer and sends the user list carrying its grant in the
// composition that issues the membership, so one may arrive before the other (ADR 0363 §6).
var RebindEvery = 30 * time.Second
// hearing is one module's consumers: the one on EVENTS, and each on a module stream its membership names.
// Every event of all of them is handed to the module one at a time, as the consumer on EVENTS alone did.
type hearing struct {
c *Conn
js jetstream.JetStream
module string
deliver func(Envelope) error
// serial hands the module one event at a time across its consumers (novox/hq issue 387).
serial sync.Mutex
// halted is stopped, read by handle without mu: the bus's loops hand events while mu is held.
halted atomic.Bool
mu sync.Mutex
stopped bool
bound map[heardKey]jetstream.ConsumeContext
// made is when the bus made each bound consumer: a consumer deleted and made again under its name has
// another time, and a loop bound to the old one is not reading the new one.
made map[heardKey]time.Time
said map[heardKey]bool
// why is the last error the bus gave a consumer's loop, said when the loop ends on it.
// Guarded by whyMu, not mu: the bus hands errors from its own goroutines, possibly while mu is held.
whyMu sync.Mutex
why map[heardKey]error
kick chan struct{}
done chan struct{}
unhear func()
// rebind, nakDelay and heartbeat are RebindEvery, NakDelay and EventHeartbeat as they stood when the hearing was
// made: its loops outlive the call that started them, so they never read a setting again, which a test may set
// back as it ends (design 47 H, H-A-363: a goroutine outliving its settings).
rebind, nakDelay, heartbeat time.Duration
}
func newHearing(c *Conn, js jetstream.JetStream, module string, deliver func(Envelope) error) *hearing {
return &hearing{c: c, js: js, module: module, deliver: deliver,
bound: map[heardKey]jetstream.ConsumeContext{}, made: map[heardKey]time.Time{}, said: map[heardKey]bool{}, why: map[heardKey]error{},
kick: make(chan struct{}, 1), done: make(chan struct{}),
rebind: RebindEvery, nakDelay: NakDelay, heartbeat: EventHeartbeat}
}
// bind reads the runner's twin of one heard entry, made first from the entry's spec where it carries one (makeTwin), else
// bound by name, and on failure says what it was doing. Errors the bus gives the loop afterwards are handed to onErr, when
// given.
func (h *hearing) bind(heard HeardIssued, onErr func(error)) (jetstream.ConsumeContext, time.Time, string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stream, durable := heard.Stream, heard.Consumer+ToolsSuffix
if err := makeTwin(ctx, h.js, heard); err != nil {
return nil, time.Time{}, "making", err
}
consumer, err := h.js.Consumer(ctx, stream, durable)
if err != nil {
return nil, time.Time{}, "binding", err
}
var created time.Time
if info := consumer.CachedInfo(); info != nil {
created = info.Created
}
opts := []jetstream.PullConsumeOpt{jetstream.PullMaxMessages(1)}
if onErr != nil {
opts = append(opts, jetstream.ConsumeErrHandler(func(_ jetstream.ConsumeContext, err error) { onErr(err) }))
}
// Claimed through the SDK's one guard as it is pulled (design 47 H, H-A-196, H-A-197): a second pull loop on a durable
// this process pulls already would take every other event from the first, so it is refused here, loud. The claim is
// released as the loop is stopped, or once the bus ended it, before its Closed is closed.
reading, err := process.ConsumeOnce(consumer, "the tool runner's hearing of "+h.module, h.handle, opts...)
if err != nil {
return nil, time.Time{}, "reading", err
}
return reading, created, "", nil
}
// handle hands one delivered event to the module: acknowledged when it took it, offered again after NakDelay
// when it did not, terminated when it is not an event at all.
func (h *hearing) handle(msg jetstream.Msg) {
env, ok := envelopeOf(msg.Subject(), msg.Headers(), msg.Data())
if !ok {
// Unparseable: redelivering bytes no version of a handler can read is a loop.
_ = msg.Term()
return
}
// Kept alive while the bundle works on it, as a worker's work is (seat.go): the consumer's ack wait
// (30 seconds) is for a runtime that died, not a handler that is slow — the runtime gives a handler
// launch.EventTimeout. Without it an event handled longer than the ack wait was offered again while
// it was handled, and counted toward max-deliver (novox/hq issue 387). Kept alive too while it waits
// for an event from another of the module's consumers to be handled.
done, stopped := make(chan struct{}), make(chan struct{})
go func() {
defer close(stopped)
tick := time.NewTicker(h.heartbeat)
defer tick.Stop()
for {
select {
case <-done:
return
case <-tick.C:
_ = msg.InProgress()
}
}
}()
h.serial.Lock()
halted := h.halted.Load()
var err error
if !halted {
err = h.deliver(env)
}
h.serial.Unlock()
close(done)
// No in-progress after the answer: one after a Nak would stretch its delay to the whole ack wait.
<-stopped
if halted {
// **A hearing stopped hands nothing on** (issue 1945): the module's bundle that subscribed may be
// gone, loaded again in its place; offered again at once, to the consumer bound after it.
_ = msg.Nak()
return
}
if err != nil {
_ = msg.NakWithDelay(h.nakDelay)
return
}
_ = msg.Ack()
}
// start binds what the membership names now, and follows it: a new membership binds what it adds and stops
// what it no longer names, and a consumer not bound yet is tried again every RebindEvery.
func (h *hearing) start() {
h.reconcile()
h.unhear = h.c.onMembership(func(m Membership) {
if m.Module != h.module {
return
}
h.nudge()
})
go func() {
tick := time.NewTicker(h.rebind)
defer tick.Stop()
for {
select {
case <-h.done:
return
case <-h.kick:
case <-tick.C:
}
h.reconcile()
}
}()
}
// forget drops the last error a consumer's loop was given.
func (h *hearing) forget(heard heardKey) {
h.whyMu.Lock()
delete(h.why, heard)
h.whyMu.Unlock()
}
// nudge asks the loop to reconcile now.
func (h *hearing) nudge() {
select {
case h.kick <- struct{}{}:
default:
}
}
// stop stops every consumer on a module stream this module reads; the one on EVENTS is its caller's.
func (h *hearing) stop() {
h.mu.Lock()
defer h.mu.Unlock()
if h.stopped {
return
}
h.stopped = true
h.halted.Store(true)
close(h.done)
if h.unhear != nil {
h.unhear()
}
for heard, reading := range h.bound {
reading.Stop()
delete(h.bound, heard)
delete(h.made, heard)
}
}
// replaced says whether the consumer a loop is bound to is gone from the bus or was made again since. A bus
// that cannot be asked right now says no: the loop is left as it is.
func (h *hearing) replaced(heard heardKey) bool {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
consumer, err := h.js.Consumer(ctx, heard.Stream, heard.Consumer)
if errors.Is(err, jetstream.ErrConsumerNotFound) {
return true
}
if err != nil || consumer.CachedInfo() == nil {
return false
}
created := h.made[heard]
return !created.IsZero() && !consumer.CachedInfo().Created.Equal(created)
}
// reconcile makes what is bound what the module's membership names now.
func (h *hearing) reconcile() {
want := map[heardKey]HeardIssued{}
// A module whose membership was withdrawn hears nothing more here, and its twins are not made again (H-A-472 ninth addendum).
if m := h.c.Membership(h.module); m != nil && !h.c.Withdrawn(h.module) {
for _, heard := range m.Hears {
// EVENTS is its caller's, bound beside the hearing (ConsumeAsBeatingWhen).
if heard.Stream != "" && heard.Consumer != "" && heard.Stream != EventsStream {
// The runner's own durable beside the program's (A-397).
want[heardKey{heard.Stream, heard.Consumer + ToolsSuffix}] = heard
}
}
}
h.mu.Lock()
defer h.mu.Unlock()
if h.stopped {
return
}
for heard, reading := range h.bound {
if _, still := want[heard]; !still {
reading.Stop()
delete(h.bound, heard)
delete(h.made, heard)
h.c.Logf("[mesh-tools] %s no longer hears %s: its membership stopped naming its consumer %s",
h.module, heard.Stream, heard.Consumer)
}
}
for heard := range h.said {
if _, still := want[heard]; !still {
delete(h.said, heard)
h.forget(heard)
}
}
// **A loop the bus ended is no longer reading** (nats.go ends a pull loop on its own when its consumer is
// deleted): the mesh deletes and makes again under the same name a restricted consumer it cannot
// narrow (ADR 0363 §6), and the membership, unchanged, says nothing — so it is bound again here.
// **A loop the bus did not end is asked about**: nats.go learns of a deleted consumer only from the answer
// to a pull it has pending, and a consumer deleted and made again between two pulls, or while none is
// pending, leaves the loop waiting out its heartbeat (30 seconds) on a consumer that is gone. So each
// bound consumer is looked up by name: gone, or made at another time, ends its loop here.
for heard, reading := range h.bound {
if h.replaced(heard) {
h.whyMu.Lock()
if h.why[heard] == nil {
h.why[heard] = errors.New("the consumer was deleted or made again")
}
h.whyMu.Unlock()
reading.Stop()
}
}
for heard, reading := range h.bound {
select {
case <-reading.Closed():
delete(h.bound, heard)
delete(h.made, heard)
h.whyMu.Lock()
why := h.why[heard]
h.whyMu.Unlock()
if why == nil {
why = errors.New("no reason given")
}
h.c.Logf("[mesh-tools] %s stopped hearing %s: the bus ended reading its consumer %s (%v); bound again as it exists",
h.module, heard.Stream, heard.Consumer, why)
h.said[heard] = true
default:
}
}
missing := make([]heardKey, 0, len(want))
for heard := range want {
if h.bound[heard] == nil {
missing = append(missing, heard)
}
}
sort.Slice(missing, func(i, j int) bool { return missing[i].Stream < missing[j].Stream })
for _, heard := range missing {
heard := heard
h.forget(heard)
reading, created, doing, err := h.bind(want[heard], func(err error) {
h.whyMu.Lock()
h.why[heard] = err
h.whyMu.Unlock()
})
if err != nil {
// Said once, not at every attempt; said again when it is bound.
if !h.said[heard] {
h.c.Logf("[mesh-tools] %s does not hear %s yet: %s its consumer %s failed: %v; tried again every %s",
h.module, heard.Stream, doing, heard.Consumer, err, h.rebind)
h.said[heard] = true
}
continue
}
h.bound[heard] = reading
h.made[heard] = created
delete(h.said, heard)
h.c.Logf("[mesh-tools] %s hears %s on its consumer %s", h.module, heard.Stream, heard.Consumer)
// When the bus ends the loop, look again at once rather than at the next tick.
go func() {
select {
case <-reading.Closed():
h.nudge()
case <-h.done:
}
}()
}
}