package process import ( "context" "fmt" stdio "git.novox.be/novox/mesh-sdk/go" "slices" "strings" "sync" "testing" "time" "github.com/nats-io/nats.go/jetstream" ) func TestTheHubMatchesSubjectsAndRefusesOverlappingPatterns(t *testing.T) { for _, c := range []struct { a, b string match, overlap bool }{ {"mesh.mod.*.event.views.*", "mesh.mod.o.event.views.x", true, true}, {"mesh.mod.p.event.>", "mesh.mod.p.event", false, false}, {"mesh.mod.p.event.a", "mesh.mod.q.event.a", false, false}, {"mesh.mod.p.event.>", "mesh.mod.*.event.a", false, true}, {"mesh.mod.p.event.a", "mesh.mod.p.event.a.b", false, false}, } { if got := subjectMatches(c.a, c.b); got != c.match && c.match { t.Errorf("%s should match %s", c.a, c.b) } if got := subjectsOverlap(c.a, c.b); got != c.overlap { t.Errorf("overlap(%s, %s) = %v", c.a, c.b, got) } } h := NewEventHub(nil) nop := func(jetstream.Msg) {} if err := h.Handle("mesh.mod.p.event.>", nop); err != nil { t.Fatal(err) } if err := h.Handle("mesh.mod.*.event.a", nop); err == nil { t.Fatal("an overlapping pattern was accepted") } if err := h.Handle("mesh.mod.q.event.>", nop); err != nil { t.Fatal(err) } // H-A-169: a message no handler takes is acknowledged and told to each OnUnhandled hook, with its subject; one taken is not. var told []string h.OnUnhandled(func(subject string) { told = append(told, subject) }) taken, lost := &bindMsg{subject: "mesh.mod.q.event.x"}, &bindMsg{subject: "mesh.seat.s.event.nobody"} h.hear(taken) h.hear(lost) if !lost.acked || len(told) != 1 || told[0] != "mesh.seat.s.event.nobody" { t.Errorf("the unhandled message: acked %v, told %v", lost.acked, told) } // W1.12: a seat's event kept in a stream of its own is heard on one bus name and one durable, the maker's and the // hearer's alike; an event kept last per subject is delivered from the last of each subject. The name is the // contract's Stream as it stands (seatdef.KeptStream), never made again here: a dotted or unprefixed name is // refused by name before the bus is asked. a := Account{Node: "ace", Module: "mesh-grants"} for _, stream := range []string{"node-engine.running", "SEAT_node-engine.running", "SEAT_", "EVENTS"} { if _, err := a.HearSeatEvents(context.Background(), nil, stream, func(jetstream.Msg) {}, nil); err == nil || !strings.Contains(err.Error(), "is not the bus's name of a seat event's stream") { t.Errorf("hearing %q: %v", stream, err) } } cfg := a.SeatEventConsumerConfig([]string{"mesh.seat.node-engine.event.running.>"}, true) if cfg.Durable != "ace_mesh-grants" || cfg.DeliverPolicy != jetstream.DeliverLastPerSubjectPolicy || cfg.AckPolicy != jetstream.AckExplicitPolicy || len(cfg.FilterSubjects) != 1 { t.Errorf("the durable on a stream kept last per subject: %+v", cfg) } if cfg := a.SeatEventConsumerConfig(nil, false); cfg.DeliverPolicy != jetstream.DeliverAllPolicy { t.Errorf("the durable on a stream kept with an age starts from its first message, got %v", cfg.DeliverPolicy) } } type pullConsumer struct { jetstream.Consumer info *jetstream.ConsumerInfo handle jetstream.MessageHandler options []jetstream.PullConsumeOpt } func (c *pullConsumer) CachedInfo() *jetstream.ConsumerInfo { return c.info } func (c *pullConsumer) Consume(handle jetstream.MessageHandler, opts ...jetstream.PullConsumeOpt) (jetstream.ConsumeContext, error) { c.handle, c.options = handle, opts return &pullContext{closed: make(chan struct{})}, nil } type pullContext struct { jetstream.ConsumeContext closed chan struct{} } func (p *pullContext) Stop() { close(p.closed) } func (p *pullContext) Closed() <-chan struct{} { return p.closed } type slowMsg struct { jetstream.Msg said chan struct{} } func (m *slowMsg) InProgress() error { m.said <- struct{}{}; return nil } // H-A-281: the hub pulls at most twenty messages per pull, and says in progress for a message whose handler runs past a // third of the consumer's ack wait, at each third until it returns; a handler that returns first says nothing. func TestTheHubPullsSmallBatchesAndKeepsSlowHandlersAlive(t *testing.T) { cons := &pullConsumer{info: &jetstream.ConsumerInfo{Config: jetstream.ConsumerConfig{AckWait: 30 * time.Second}}} ticks := make(chan time.Time) var every time.Duration stopped := 0 tick := func(d time.Duration) (<-chan time.Time, func()) { every = d; return ticks, func() { stopped++ } } var handled func(jetstream.Msg) cc, err := hearEvents(cons, "the test", func(m jetstream.Msg) { handled(m) }, t.Logf, tick) if err != nil { t.Fatal(err) } defer cc.Stop() pulls := 0 for _, o := range cons.options { if n, ok := o.(jetstream.PullMaxMessages); ok { pulls = int(n) } } if pulls != 20 { t.Errorf("the hub pulls %d messages per pull, want 20 (0: the bus client's default of 500)", pulls) } slow := &slowMsg{said: make(chan struct{}, 4)} handled = func(jetstream.Msg) { for range 2 { // two thirds of the ack wait pass while the handler runs select { case ticks <- time.Time{}: case <-time.After(5 * time.Second): t.Error("no ticker runs while the handler runs") return } select { case <-slow.said: case <-time.After(5 * time.Second): t.Error("a handler running past a third of the ack wait said no in progress") return } } } cons.handle(slow) if every != 10*time.Second || stopped != 1 { t.Errorf("in progress every %v (want 10s, a third of the ack wait), ticker stopped %d times (want 1)", every, stopped) } fast := &slowMsg{said: make(chan struct{}, 1)} handled = func(jetstream.Msg) {} cons.handle(fast) if len(fast.said) != 0 { t.Error("a handler that returned before a third of the ack wait said in progress") } } // seqMsg is a message of the stream EVENTS at a sequence, counting what is said of it. type seqMsg struct { jetstream.Msg subject string seq uint64 mu sync.Mutex progress int acked bool } func (m *seqMsg) Subject() string { return m.subject } func (m *seqMsg) Data() []byte { return nil } func (m *seqMsg) Ack() error { m.mu.Lock(); m.acked = true; m.mu.Unlock(); return nil } func (m *seqMsg) InProgress() error { m.mu.Lock() m.progress++ m.mu.Unlock() return nil } func (m *seqMsg) Metadata() (*jetstream.MsgMetadata, error) { return &jetstream.MsgMetadata{Stream: "EVENTS", Sequence: jetstream.SequencePair{Stream: m.seq}}, nil } func (m *seqMsg) said() int { m.mu.Lock(); defer m.mu.Unlock(); return m.progress } // Design 47 H2 H-A-683 (1), H-A-695 (1) to (3): the hub hands events by key, one key's events one at a time in the order heard // and different keys side by side, at most events-at-once keys at once; the patterns given no key share one key; every message // held is said in progress at every third of its durable's ack wait by one ticker, with the handling of its key blocked past // five ack waits, and handled once; a delivery again of a held sequence reaches no handler; holding events-waiting messages the // hub takes no more and says so once; a setting not composed reads its default. func TestTheHubHoldsEventsByKeyAndSaysThemInProgress(t *testing.T) { events := make(chan string, 32) gate := map[string]chan struct{}{"a1": make(chan struct{}), "b1": make(chan struct{})} handler := func(m jetstream.Msg) { name := m.Subject()[len("mesh.mod.m.event."):] events <- "start " + name if g := gate[name]; g != nil { <-g } _ = m.Ack() events <- "end " + name } lastToken := func(subject string, _ []byte) string { return subject[len(subject)-2 : len(subject)-1] } var journal []string var jmu sync.Mutex logf := func(f string, a ...any) { jmu.Lock(); journal = append(journal, fmt.Sprintf(f, a...)); jmu.Unlock() } newHub := func() (*EventHub, chan time.Time) { h := NewEventHub(logf) ticks := make(chan time.Time) h.tick = func(time.Duration) (<-chan time.Time, func()) { return ticks, func() {} } if err := h.Handle("mesh.mod.m.event.>", handler, lastToken); err != nil { t.Fatal(err) } if err := h.held.settle(); err != nil { t.Fatal(err) } return h, ticks } next := func(want string) { t.Helper() select { case got := <-events: if got != want { t.Fatalf("the hub did %q, want %q", got, want) } case <-time.After(5 * time.Second): t.Fatalf("the hub did nothing, want %q", want) } } msg := func(name string, seq uint64) *seqMsg { return &seqMsg{subject: "mesh.mod.m.event." + name, seq: seq} } t.Run("a blocked key holds back no other key, its own events keep their order, every held message is said in progress", func(t *testing.T) { h, ticks := newHub() feed := h.newFeed() feed.start(30 * time.Second) first, second, other := msg("a1", 1), msg("a2", 2), msg("b1", 3) for _, m := range []*seqMsg{first, second, other} { h.hearOn(feed)(m) } started := []string{<-events, <-events} if slices.Sort(started); strings.Join(started, ",") != "start a1,start b1" { t.Fatalf("with one key's handler blocked another key's was not handled: %v", started) } // five ack waits pass: every held message, handled or waiting, is said in progress at each tick for range 15 { ticks <- time.Time{} } again := msg("a1", 1) // given again: handed to no handler h.hearOn(feed)(again) close(gate["b1"]) next("end b1") close(gate["a1"]) next("end a1") next("start a2") next("end a2") for _, m := range []*seqMsg{first, second, other} { if m.said() < 14 { t.Errorf("%s was said in progress %d times, want one at every tick", m.subject, m.said()) } } select { case got := <-events: t.Errorf("a delivery again reached a handler: %s", got) default: } h.Stop() }) t.Run("the patterns given no key share one, and events-at-once bounds the keys", func(t *testing.T) { started := make(chan string, 8) blockOn := func(release chan struct{}) func(jetstream.Msg) { return func(m jetstream.Msg) { started <- m.Subject(); <-release } } release := make(chan struct{}) noOther := func(want string, why string) { t.Helper() select { case got := <-started: t.Fatalf("%s: %s", why, got) case <-time.After(50 * time.Millisecond): } _ = want } shared := NewEventHub(logf) for _, p := range []string{"x.>", "y.>"} { if err := shared.Handle(p, blockOn(release)); err != nil { t.Fatal(err) } } go shared.hearOn(nil)(&seqMsg{subject: "x.1", seq: 1}) <-started go shared.hearOn(nil)(&seqMsg{subject: "y.1", seq: 2}) noOther("", "two patterns given no key were handled side by side") close(release) <-started t.Setenv(stdio.SettingWord(EventsAtOnceSetting), "1") release2 := make(chan struct{}) one := NewEventHub(logf) if err := one.Handle("k.>", blockOn(release2), func(subject string, _ []byte) string { return subject }); err != nil { t.Fatal(err) } if err := one.held.settle(); err != nil { t.Fatal(err) } go one.hearOn(nil)(&seqMsg{subject: "k.a", seq: 1}) <-started go one.hearOn(nil)(&seqMsg{subject: "k.b", seq: 2}) noOther("", "a second key ran with events-at-once 1") close(release2) if got := <-started; got != "k.b" { t.Fatalf("the waiting key ran %s", got) } }) t.Run("holding events-waiting messages it takes no more, said once; defaults when not composed", func(t *testing.T) { h := NewEventHub(logf) if err := h.held.settle(); err != nil || h.held.atOnce != 8 || h.held.bound != 100 { t.Fatalf("defaults: %d at once, %d waiting (%v)", h.held.atOnce, h.held.bound, err) } t.Setenv(stdio.SettingWord(EventsWaitingSetting), "2") release := make(chan struct{}) if err := h.Handle("w.>", func(m jetstream.Msg) { <-release }); err != nil { t.Fatal(err) } if err := h.held.settle(); err != nil { t.Fatal(err) } h.hearOn(nil)(&seqMsg{subject: "w.1", seq: 1}) taken := make(chan struct{}) go func() { h.hearOn(nil)(&seqMsg{subject: "w.2", seq: 2}); close(taken) }() select { case <-taken: t.Fatal("the hub took a message past its bound") case <-time.After(50 * time.Millisecond): } close(release) select { case <-taken: case <-time.After(5 * time.Second): t.Fatal("the hub took no message once room was made") } jmu.Lock() said := 0 for _, l := range journal { if strings.Contains(l, "its bound: it pulls no more") { said++ } } jmu.Unlock() if said != 1 { t.Errorf("the bound was said %d times, want once", said) } t.Setenv(stdio.SettingWord(EventsWaitingSetting), "0") if err := h.held.settle(); err == nil { t.Error("a bound of 0 was accepted") } }) }