S1 hub-binds-every-pattern: Start binds every kept stream a pattern needs, OnAllHeard, wake on durables-composed

StartKept is folded into Start and StartUntilBound goes with its timer; a durable not bound is
bound on the grants part's durables-composed and at the bus connection's reconnect; OnBound is
told at each durable's bind.

Builds: design 47 H2b §836 1., 2.; H-A-834, H-A-835
This commit is contained in:
2026-11-27 02:55:06 +01:00
parent c42ada4525
commit 2e192b4ebf
3 changed files with 465 additions and 145 deletions
+333 -125
View File
@@ -2,12 +2,15 @@ package process
import (
"context"
"errors"
"fmt"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-sdk/go/seatdef"
@@ -27,12 +30,28 @@ type EventHub struct {
routes []hubRoute
cons jetstream.ConsumeContext
bound []func(created time.Time)
// allHeard are told each time every registered pattern comes to be heard (OnAllHeard).
allHeard []func()
// started is Start's; gen numbers it; bus, cred and ctx are what its wakes bind with; stopWake ends the wake.
started bool
gen int
bus hubBus
cred Account
ctx context.Context
stopWake func()
// heard are the durables bound, by stream; why is what each stream not bound is said to lack.
heard map[string]jetstream.ConsumeContext
why map[string]string
// eventsSubjects are EVENTS' own, read once; unheardNow the patterns not heard as of the last pass; allTold says
// OnAllHeard was told for the present state.
eventsSubjects []string
unheardNow []unheard
allTold bool
passMu sync.Mutex
// unhandled are told each subject no handler took (OnUnhandled).
unhandled []func(subject string)
// overruns are told the handlings past event-overrun (OnOverrun).
overruns []func(past []Handling)
// kept are the module's durables on the kept seat events' streams it handles (StartKept).
kept []jetstream.ConsumeContext
// held is every message the hub took and has not seen end, across its durables (event_hold.go); feeds are the durables'
// tickers. tick is the clock of the tickers, a test's to replace.
held *eventHold
@@ -126,6 +145,14 @@ func (h *EventHub) OnOverrun(f func(past []Handling)) {
h.mu.Unlock()
}
// OnAllHeard registers f, told each time the hub comes to hear every registered pattern: at Start, or at the bind that completes
// them (design 47 H2b §836 1.). A part that does what waits on its events being live does it there. Register before Start.
func (h *EventHub) OnAllHeard(f func()) {
h.mu.Lock()
h.allHeard = append(h.allHeard, f)
h.mu.Unlock()
}
// Patterns are the registered subject patterns, in order.
func (h *EventHub) Patterns() []string {
h.mu.RLock()
@@ -137,93 +164,328 @@ func (h *EventHub) Patterns() []string {
return out
}
// Start binds the module's durable on the shared events stream and pulls it; a call after a start that took does
// nothing. It makes no stream and no consumer: a consumer the bus does not hold yet is the error of this call, and a
// later call (the module's next change of membership) binds it, so a part is not lost for the bus's order.
// durablesComposedSubject is where the seat `mesh-grants` says it composed a module's durables, for the module on its node:
// the hub binds again each stream it has not bound (design 47 H2b §836 2., H-A-835). The subject is the seat's definition's
// alone: the hub reads no body.
func durablesComposedSubject(cred Account) string {
return seatdef.EventSubject("mesh-grants", "durables-composed") + "." + cred.Node + "." + cred.Module
}
// Start binds the module's durable `<node>_<module>` on the shared events stream and on every kept seat event's stream
// (`SEAT_<seat>_<event>`) that carries a registered pattern, and pulls them (design 47 H2b §836 1.); a call after a start does
// nothing. It makes no stream and no consumer. A durable the bus does not hold yet, or refuses, is no error of this call and
// is not waited for on a timer: it is said (the journal) and bound when the seat `mesh-grants` says it composed the module's
// durables, and at the bus connection's reconnect (§836 2.), and OnAllHeard is told when every pattern is heard.
func (h *EventHub) Start(ctx context.Context, js jetstream.JetStream, cred Account) error {
return h.start(ctx, natsHubBus{js: js, cred: cred}, cred)
}
// hubBus is what the hub asks of the bus: the kept streams, the subjects of EVENTS, the pulls of its durables, and the wakes.
type hubBus interface {
streamNames(ctx context.Context) ([]string, error)
streamSubjects(ctx context.Context, stream string) ([]string, error)
// hearEvents pulls the module's durable on EVENTS, held by feed; created is when the bus made the durable.
hearEvents(ctx context.Context, feed *eventFeed, handle func(jetstream.Msg), logf func(string, ...any)) (cc jetstream.ConsumeContext, created time.Time, err error)
hearKept(ctx context.Context, stream string, feed *eventFeed, handle func(jetstream.Msg), logf func(string, ...any)) (cc jetstream.ConsumeContext, created time.Time, err error)
// wake calls f at each message on subject (a plain subscription); stop ends it.
wake(subject string, f func()) (stop func(), err error)
// reconnected calls f at each reconnect of the bus connection.
reconnected(f func())
}
type natsHubBus struct {
js jetstream.JetStream
cred Account
}
func (b natsHubBus) streamNames(ctx context.Context) ([]string, error) {
names := b.js.StreamNames(ctx)
var out []string
for name := range names.Name() {
out = append(out, name)
}
return out, names.Err()
}
func (b natsHubBus) streamSubjects(ctx context.Context, stream string) ([]string, error) {
s, err := b.js.Stream(ctx, stream)
if err != nil {
return nil, err
}
return s.CachedInfo().Config.Subjects, nil
}
func (b natsHubBus) hearEvents(ctx context.Context, feed *eventFeed, handle func(jetstream.Msg), logf func(string, ...any)) (jetstream.ConsumeContext, time.Time, error) {
cons, err := b.cred.EventConsumer(ctx, b.js, EventsStream)
if err != nil {
return nil, time.Time{}, err
}
if info := cons.CachedInfo(); info != nil {
feed.start(info.Config.AckWait)
}
cc, err := hearHeld(cons, callerOutside(), feed.hold, handle, logf)
if err != nil {
return nil, time.Time{}, err
}
info, err := cons.Info(ctx)
if err != nil {
logf("events: the consumer %s on %s is heard, but its information is not read (%v): a first view taken before it was made is not asked again", b.cred.EventConsumerName(), EventsStream, err)
return cc, time.Time{}, nil
}
return cc, info.Created.UTC(), nil
}
func (b natsHubBus) hearKept(ctx context.Context, stream string, feed *eventFeed, handle func(jetstream.Msg), logf func(string, ...any)) (jetstream.ConsumeContext, time.Time, error) {
cc, err := b.cred.HearSeatEvents(ctx, b.js, stream, handle, logf, heldBy(feed))
if err != nil {
return nil, time.Time{}, err
}
cons, err := b.cred.EventConsumer(ctx, b.js, stream)
if err != nil {
return cc, time.Time{}, nil
}
info, err := cons.Info(ctx)
if err != nil {
return cc, time.Time{}, nil
}
return cc, info.Created.UTC(), nil
}
func (b natsHubBus) wake(subject string, f func()) (func(), error) {
sub, err := b.js.Conn().Subscribe(subject, func(*nats.Msg) { f() })
if err != nil {
return nil, err
}
return func() { _ = sub.Unsubscribe() }, nil
}
func (b natsHubBus) reconnected(f func()) {
nc := b.js.Conn()
before := nc.Opts.ReconnectedCB
nc.SetReconnectHandler(func(c *nats.Conn) {
if before != nil {
before(c)
}
f()
})
}
// unheard is a registered pattern the hub does not hear: the stream that should carry it ("" when none does) and why.
type unheard struct{ pattern, stream, why string }
func (h *EventHub) start(ctx context.Context, bus hubBus, cred Account) error {
h.mu.Lock()
defer h.mu.Unlock()
if h.cons != nil {
if h.started {
h.mu.Unlock()
return nil
}
cons, err := cred.EventConsumer(ctx, js, EventsStream)
if err == nil {
err = h.held.settle()
}
if err == nil {
feed := h.newFeed()
if info := cons.CachedInfo(); info != nil {
feed.start(info.Config.AckWait)
}
h.cons, err = hearHeld(cons, callerOutside(), h.held, h.hearOn(feed), h.logf)
if err != nil {
feed.end()
}
}
h.started = true
h.gen++
gen := h.gen
h.bus, h.cred, h.ctx = bus, cred, ctx
h.mu.Unlock()
rebind := func() { h.rebind(gen) }
// The wake is made before the first bind, so a durable composed while a bind fails is heard (§836 2.).
stop, err := bus.wake(durablesComposedSubject(cred), rebind)
if err != nil {
return fmt.Errorf("the consumer %s on %s is not heard: %w", cred.EventConsumerName(), EventsStream, err)
}
if info, ierr := cons.Info(ctx); ierr != nil {
h.logf("events: the consumer %s on %s is heard, but its information is not read (%v): a first view taken before it was made is not asked again", cred.EventConsumerName(), EventsStream, ierr)
h.logf("events: 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 module's next start", err)
} else {
h.logf("events: the consumer %s on %s is heard; the bus made it at %s", cred.EventConsumerName(), EventsStream, info.Created.UTC().Format(time.RFC3339))
for _, f := range h.bound {
f(info.Created.UTC())
}
h.mu.Lock()
h.stopWake = stop
h.mu.Unlock()
}
bus.reconnected(rebind)
h.pass(ctx, bus, cred)
return nil
}
// StartUntilBound is Start that does not give up: when the module's consumer is not there yet it returns that error at
// once, and tries again on a goroutine of its own, after each wait, until it binds or ctx ends; then live is called (nil
// calls nothing), so a part that needs the events path live does what it does only then. wait returns false to stop
// trying (nil waits five seconds or for ctx). The bus makes the consumer when the module's account is composed, which
// says nothing a module can hear before the consumer exists, so the retry is a wait on that, bounded by ctx.
func (h *EventHub) StartUntilBound(ctx context.Context, js jetstream.JetStream, cred Account, wait func(context.Context) bool, live func()) error {
err := h.Start(ctx, js, cred)
if err == nil {
if live != nil {
live()
}
return nil
// rebind is a pass of the start numbered gen, at a wake or a reconnect; one of an ended or later start does nothing.
func (h *EventHub) rebind(gen int) {
h.mu.RLock()
ok, ctx, bus, cred := h.started && h.gen == gen, h.ctx, h.bus, h.cred
h.mu.RUnlock()
if ok && ctx.Err() == nil {
h.pass(ctx, bus, cred)
}
if wait == nil {
wait = func(ctx context.Context) bool {
t := time.NewTimer(5 * time.Second)
defer t.Stop()
select {
case <-ctx.Done():
return false
case <-t.C:
return true
}
}
}
go func() {
for wait(ctx) && ctx.Err() == nil {
if h.Start(ctx, js, cred) == nil {
if live != nil {
live()
}
return
}
}
}()
return err
}
// Stop ends the pull.
// pass binds every durable not bound that a registered pattern needs (EVENTS' always), says OnBound at each bind and OnAllHeard
// when the hub comes to hear every registered pattern.
func (h *EventHub) pass(ctx context.Context, bus hubBus, cred Account) {
h.passMu.Lock()
defer h.passMu.Unlock()
patterns := h.Patterns()
names, nerr := bus.streamNames(ctx)
if nerr != nil {
h.logf("events: the kept seat events' streams are not listed (%v): none of them is heard now", nerr)
}
h.mu.RLock()
eventsSubjects := h.eventsSubjects
h.mu.RUnlock()
if eventsSubjects == nil {
subjects, err := bus.streamSubjects(ctx, EventsStream)
if err != nil {
h.logf("events: the subjects of %s are not read (%v): every pattern no kept stream takes is taken to be carried by it", EventsStream, err)
} else {
h.mu.Lock()
h.eventsSubjects = subjects
h.mu.Unlock()
eventsSubjects = subjects
}
}
// Each pattern is carried by every kept stream whose subjects take it, else by EVENTS (H-A-834).
carriers := make([][]string, len(patterns))
need := map[string]bool{}
for i, p := range patterns {
for _, stream := range names {
seat, event, ok := keptSeatEvent(stream)
if !ok {
continue
}
subject := seatdef.EventSubject(seat, event)
if subjectMatches(p, subject) || subjectMatches(p, subject+".x") {
carriers[i] = append(carriers[i], stream)
need[stream] = true
}
}
if len(carriers[i]) == 0 && h.eventsTake(eventsSubjects, p) {
carriers[i] = []string{EventsStream}
}
}
if !h.hasKept(EventsStream) {
h.bindOne(ctx, bus, cred, EventsStream)
}
var streams []string
for stream := range need {
streams = append(streams, stream)
}
slices.Sort(streams)
for _, stream := range streams {
if !h.hasKept(stream) {
h.bindOne(ctx, bus, cred, stream)
}
}
var not []unheard
h.mu.RLock()
for i, p := range patterns {
if len(carriers[i]) == 0 {
why := "no stream carries it"
if nerr != nil {
why = fmt.Sprintf("the streams are not listed (%v)", nerr)
}
not = append(not, unheard{p, "", why})
}
for _, stream := range carriers[i] {
if _, bound := h.heard[stream]; !bound {
not = append(not, unheard{p, stream, h.why[stream]})
}
}
}
h.mu.RUnlock()
h.mu.Lock()
h.unheardNow = not
all := len(not) == 0
tell := all && !h.allTold
h.allTold = all
told := h.allHeard
h.mu.Unlock()
if tell {
for _, f := range told {
f()
}
}
}
// eventsTake says whether EVENTS carries pattern: some subject of its own overlaps it (all of them, when they are not read).
func (h *EventHub) eventsTake(subjects []string, pattern string) bool {
if subjects == nil {
return true
}
for _, s := range subjects {
if subjectsOverlap(s, pattern) {
return true
}
}
return false
}
func (h *EventHub) hasKept(stream string) bool {
h.mu.RLock()
defer h.mu.RUnlock()
_, ok := h.heard[stream]
return ok
}
// bindOne binds the module's durable on stream (EventsStream or a kept seat event's) and says each bind to OnBound; what it
// cannot is said and kept as the stream's reason.
func (h *EventHub) bindOne(ctx context.Context, bus hubBus, cred Account, stream string) {
h.mu.Lock()
feed := h.newFeed()
h.mu.Unlock()
var (
cc jetstream.ConsumeContext
created time.Time
err error
)
if stream == EventsStream {
if err = h.held.settle(); err == nil {
cc, created, err = bus.hearEvents(ctx, feed, h.hearOn(feed), h.logf)
}
} else {
cc, created, err = bus.hearKept(ctx, stream, feed, h.hearOn(feed), h.logf)
}
if err != nil {
feed.end()
why := "refused: " + err.Error()
if errors.Is(err, jetstream.ErrConsumerNotFound) {
why = "not composed: the bus holds no durable " + cred.EventConsumerName() + " on it"
}
h.mu.Lock()
if h.why == nil {
h.why = map[string]string{}
}
changed := h.why[stream] != why
h.why[stream] = why
h.mu.Unlock()
if changed {
h.logf("events: the consumer %s on %s is not heard: %s (%v)", cred.EventConsumerName(), stream, why, err)
}
return
}
h.mu.Lock()
if h.heard == nil {
h.heard = map[string]jetstream.ConsumeContext{}
}
h.heard[stream] = cc
delete(h.why, stream)
if stream == EventsStream {
h.cons = cc
}
bound := h.bound
h.mu.Unlock()
if created.IsZero() {
h.logf("events: the consumer %s on %s is heard", cred.EventConsumerName(), stream)
return
}
h.logf("events: the consumer %s on %s is heard; the bus made it at %s", cred.EventConsumerName(), stream, created.Format(time.RFC3339))
for _, f := range bound {
f(created)
}
}
// Stop ends the pulls and the wake.
func (h *EventHub) Stop() {
h.mu.Lock()
defer h.mu.Unlock()
if h.cons != nil {
h.cons.Stop()
h.cons = nil
}
for _, cc := range h.kept {
for _, cc := range h.heard {
cc.Stop()
}
h.kept = nil
h.heard, h.why, h.cons = nil, nil, nil
if h.stopWake != nil {
h.stopWake()
h.stopWake = nil
}
h.started, h.allTold, h.unheardNow = false, false, nil
for _, f := range h.feeds {
f.end()
}
@@ -238,60 +500,6 @@ func (h *EventHub) newFeed() *eventFeed {
return f
}
// StartKept binds, beside EVENTS, the module's durable on each kept seat event's stream (`SEAT_<seat>_<event>`) whose event a
// registered pattern takes: a kept event is never on EVENTS, and the tool runner reads its own twin of that durable (lead
// answer A-397), so the program hears it only here. Each stream bound is said, and each it cannot bind (no durable composed
// for this module there, or the bus refuses) is said and passed over. It returns how many it bound.
func (h *EventHub) StartKept(ctx context.Context, js jetstream.JetStream, cred Account) int {
h.mu.RLock()
var patterns []string
for _, r := range h.routes {
patterns = append(patterns, r.pattern)
}
h.mu.RUnlock()
names := js.StreamNames(ctx)
var streams []string
for name := range names.Name() {
streams = append(streams, name)
}
if err := names.Err(); err != nil {
h.logf("events: the kept seat events' streams are not listed (%v): none of them is heard", err)
}
bound := 0
for _, stream := range streams {
seat, event, ok := keptSeatEvent(stream)
if !ok {
continue
}
subject := "mesh.seat." + seat + ".event." + event
taken := false
for _, p := range patterns {
if subjectMatches(p, subject) || subjectMatches(p, subject+".x") {
taken = true
break
}
}
if !taken {
continue
}
h.mu.Lock()
feed := h.newFeed()
h.mu.Unlock()
cc, err := cred.HearSeatEvents(ctx, js, stream, h.hearOn(feed), h.logf, heldBy(feed))
if err != nil {
feed.end()
h.logf("events: the kept event %s.%s is not heard on %s: %v", seat, event, stream, err)
continue
}
h.mu.Lock()
h.kept = append(h.kept, cc)
h.mu.Unlock()
bound++
h.logf("events: the consumer %s on %s is heard (the kept event %s.%s)", cred.EventConsumerName(), stream, seat, event)
}
return bound
}
// keptSeatEvent is the seat and the event a kept seat event's stream carries, from its name `SEAT_<seat>_<event>` (seatdef.KeptStream):
// a seat's and an event's names hold no underscore.
func keptSeatEvent(stream string) (seat, event string, ok bool) {
+16 -20
View File
@@ -16,8 +16,8 @@ import (
"git.novox.be/novox/mesh-sdk/go/testbus"
)
// A module whose consumer the bus makes after the module started is not lost for that order: the hub tries again after
// each wait and calls live once it is bound (the checker's "until it starts again" hole).
// A module whose durable the bus makes after the module started is not lost for that order: the hub binds it when the
// grants part says it composed the module's durables, and tells OnAllHeard.
func subTheHubBindsALateConsumerAndSaysItIsLive(t *testing.T) {
nc, err := nats.Connect(testbus.URL(t))
if err != nil {
@@ -35,35 +35,32 @@ func subTheHubBindsALateConsumerAndSaysItIsLive(t *testing.T) {
}
cred := process.Account{Node: "n1", Module: "late"}
hub := process.NewEventHub(t.Logf)
waits, live := make(chan chan bool), make(chan struct{}, 1)
wait := func(ctx context.Context) bool {
step := make(chan bool)
select {
case waits <- step:
case <-ctx.Done():
return false
}
return <-step
live := make(chan struct{}, 4)
hub.OnAllHeard(func() { live <- struct{}{} })
if err := hub.Handle("mesh.mod.p.event.x", func(jetstream.Msg) {}); err != nil {
t.Fatal(err)
}
if err := hub.StartUntilBound(ctx, js, cred, wait, func() { live <- struct{}{} }); err == nil {
t.Fatal("no consumer was there, and the start said nothing")
// Start with no durable composed says nothing is live and arms no timer; the grants part's word that it composed the
// module's durables binds it (design 47 H2b §836 2.).
if err := hub.Start(ctx, js, cred); err != nil {
t.Fatal(err)
}
defer hub.Stop()
select {
case <-live:
t.Fatal("live before the consumer was there")
default:
case <-time.After(300 * time.Millisecond):
}
step := <-waits
step <- true // tried again: still no consumer
step = <-waits
if _, err := js.CreateOrUpdateConsumer(ctx, process.EventsStream, jetstream.ConsumerConfig{Durable: cred.EventConsumerName(), AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
t.Fatal(err)
}
step <- true
if err := nc.Publish("mesh.seat.mesh-grants.event.durables-composed.n1.late", []byte("{}")); err != nil {
t.Fatal(err)
}
select {
case <-live:
case <-ctx.Done():
t.Fatal("the consumer was made and the hub never said it is live")
t.Fatal("the durables were composed and the hub never said it is live")
}
// H-A-90: a durable named for a suffix is bound beside the module's own.
if _, err := js.CreateOrUpdateConsumer(ctx, process.EventsStream, jetstream.ConsumerConfig{Durable: cred.EventConsumerName() + "_main", AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
@@ -76,7 +73,6 @@ func subTheHubBindsALateConsumerAndSaysItIsLive(t *testing.T) {
if _, err := cred.NamedEventConsumer(ctx, js, process.EventsStream, "other"); err == nil {
t.Fatal("a named consumer nobody made was bound")
}
hub.Stop()
}
// W1.12: a module hears a seat's event kept last per subject on its own stream through its durable, made by the maker
+116
View File
@@ -2,6 +2,7 @@ package process
import (
"context"
"errors"
"fmt"
stdio "git.novox.be/novox/mesh-sdk/go"
"slices"
@@ -31,6 +32,7 @@ func TestTheHubMatchesSubjectsAndRefusesOverlappingPatterns(t *testing.T) {
t.Errorf("overlap(%s, %s) = %v", c.a, c.b, got)
}
}
t.Run("TheHubStartBindsEveryPatternAndSaysWhenAllAreHeard", subTheHubStartBindsEveryPatternAndSaysWhenAllAreHeard)
h := NewEventHub(nil)
nop := func(jetstream.Msg) {}
if err := h.Handle("mesh.mod.p.event.>", nop); err != nil {
@@ -433,3 +435,117 @@ func TestAHandlingPastEventOverrunTellsItsHookWhileItRuns(t *testing.T) {
var _ interface {
Handle(string, func(jetstream.Msg)) error
} = (*EventHub)(nil)
// fakeHubBus is the bus the hub's start asks of: which durables are composed, and the wakes it is given.
type fakeHubBus struct {
mu sync.Mutex
streams []string
subjects []string
composed map[string]error // a stream whose durable is composed has a nil entry; any other is not
binds []string
wakeAt string
onWake func()
reconn func()
stopped bool
}
func (b *fakeHubBus) streamNames(context.Context) ([]string, error) { return b.streams, nil }
func (b *fakeHubBus) streamSubjects(context.Context, string) ([]string, error) {
return b.subjects, nil
}
func (b *fakeHubBus) bind(stream string) (jetstream.ConsumeContext, time.Time, error) {
b.mu.Lock()
defer b.mu.Unlock()
err, ok := b.composed[stream]
if !ok {
return nil, time.Time{}, fmt.Errorf("no durable: %w", jetstream.ErrConsumerNotFound)
}
if err != nil {
return nil, time.Time{}, err
}
b.binds = append(b.binds, stream)
return &pullContext{closed: make(chan struct{})}, time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), nil
}
func (b *fakeHubBus) hearEvents(_ context.Context, _ *eventFeed, _ func(jetstream.Msg), _ func(string, ...any)) (jetstream.ConsumeContext, time.Time, error) {
return b.bind(EventsStream)
}
func (b *fakeHubBus) hearKept(_ context.Context, stream string, _ *eventFeed, _ func(jetstream.Msg), _ func(string, ...any)) (jetstream.ConsumeContext, time.Time, error) {
return b.bind(stream)
}
func (b *fakeHubBus) wake(subject string, f func()) (func(), error) {
b.wakeAt, b.onWake = subject, f
return func() { b.stopped = true }, nil
}
func (b *fakeHubBus) reconnected(f func()) { b.reconn = f }
// Design 47 H2b §836 1., 2. (1984/AC-836a, AC-836b): Start alone binds a kept seat event's stream beside EVENTS and tells OnAllHeard
// once; a durable not composed at Start is bound when the grants part says it composed the module's durables, and again at a
// reconnect when its bind was refused, OnAllHeard told once each time the patterns are all heard, a bound stream never bound again.
func subTheHubStartBindsEveryPatternAndSaysWhenAllAreHeard(t *testing.T) {
kept := "SEAT_node-engine_running"
cred := Account{Node: "ace", Module: "teller"}
newHub := func(bus *fakeHubBus) (h *EventHub, allHeard *int, created *[]time.Time) {
h, allHeard, created = NewEventHub(t.Logf), new(int), new([]time.Time)
h.OnAllHeard(func() { *allHeard++ })
h.OnBound(func(at time.Time) { *created = append(*created, at) })
if err := h.Handle("mesh.seat.node-engine.event.running.>", func(jetstream.Msg) {}); err != nil {
t.Fatal(err)
}
if err := h.Handle("mesh.mod.p.event.x", func(jetstream.Msg) {}); err != nil {
t.Fatal(err)
}
return h, allHeard, created
}
base := func(composed map[string]error) *fakeHubBus {
return &fakeHubBus{streams: []string{kept, "SEAT_other_thing", "EVENTS"}, subjects: []string{"mesh.mod.*.event.>"}, composed: composed}
}
t.Run("start alone", func(t *testing.T) {
bus := base(map[string]error{EventsStream: nil, kept: nil})
h, allHeard, created := newHub(bus)
if err := h.start(context.Background(), bus, cred); err != nil {
t.Fatal(err)
}
defer h.Stop()
if *allHeard != 1 || len(bus.binds) != 2 || len(*created) != 2 {
t.Errorf("all heard %d times, binds %v, bound told %d times", *allHeard, bus.binds, len(*created))
}
if bus.wakeAt != "mesh.seat.mesh-grants.event.durables-composed.ace.teller" {
t.Errorf("the wake is on %q", bus.wakeAt)
}
bus.onWake()
bus.reconn()
if *allHeard != 1 || len(bus.binds) != 2 {
t.Errorf("a bound stream was told or bound again: %d, %v", *allHeard, bus.binds)
}
})
t.Run("composed late, refused then bound at a reconnect", func(t *testing.T) {
bus := base(map[string]error{EventsStream: nil})
h, allHeard, _ := newHub(bus)
h.start(context.Background(), bus, cred)
defer h.Stop()
if *allHeard != 0 || len(h.unheardNow) != 1 || h.unheardNow[0].stream != kept || !strings.Contains(h.unheardNow[0].why, "not composed") {
t.Fatalf("all heard %d, unheard %+v", *allHeard, h.unheardNow)
}
bus.composed[kept] = errors.New("the bus refuses")
bus.onWake()
if *allHeard != 0 || !strings.Contains(h.unheardNow[0].why, "refused") {
t.Fatalf("a refused bind: all heard %d, unheard %+v", *allHeard, h.unheardNow)
}
bus.composed[kept] = nil
bus.reconn()
bus.onWake()
if *allHeard != 1 || len(h.unheardNow) != 0 || len(bus.binds) != 2 {
t.Errorf("all heard %d, unheard %+v, binds %v", *allHeard, h.unheardNow, bus.binds)
}
})
t.Run("no stream carries a pattern", func(t *testing.T) {
bus := base(map[string]error{EventsStream: nil, kept: nil})
bus.subjects = []string{"mesh.seat.*.event.>"}
h, allHeard, _ := newHub(bus)
h.start(context.Background(), bus, cred)
defer h.Stop()
if *allHeard != 0 || len(h.unheardNow) != 1 || h.unheardNow[0].pattern != "mesh.mod.p.event.x" || h.unheardNow[0].why != "no stream carries it" {
t.Errorf("all heard %d, unheard %+v", *allHeard, h.unheardNow)
}
})
}