S6 event-hub-by-key: the hub hands events by key, holds each and says it in progress
Builds: design 47 H2 H-A-683 (1), H-A-695 (1) to (5)
This commit is contained in:
@@ -20,6 +20,9 @@ type bindMsg struct {
|
||||
func (m *bindMsg) Subject() string { return m.subject }
|
||||
func (m *bindMsg) Data() []byte { return []byte(m.data) }
|
||||
func (m *bindMsg) Ack() error { m.acked = true; return nil }
|
||||
func (m *bindMsg) Metadata() (*jetstream.MsgMetadata, error) {
|
||||
return &jetstream.MsgMetadata{Stream: "EVENTS"}, nil
|
||||
}
|
||||
|
||||
// design 47 G §577: a process reaches the kept data its `requires` declares through its Binding: `show` of the seat
|
||||
// mesh-broker at the start, asked again on `recreated` and `dropped` of the entry, and a wait naming the entry until it answers.
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// The event hub's settings, read by the runtime under these names at their defaults when not composed (design 47 H2 H-A-683
|
||||
// (1), H-A-695 (2), (5)): how many keys are handled at once, and how many messages the hub holds at most.
|
||||
const (
|
||||
EventsAtOnceSetting = "events-at-once"
|
||||
EventsWaitingSetting = "events-waiting"
|
||||
defaultEventsAtOnce = 8
|
||||
defaultEventsWaiting = 100
|
||||
mostEventsAtOnce = 64
|
||||
mostEventsWaiting = 1000
|
||||
sharedEventKey = "\x00shared"
|
||||
keyedEventKeyPrefix = "k:"
|
||||
)
|
||||
|
||||
// EventKey is the key a pattern's events are handled under: a function of a message's subject and body (design 47 H2 H-A-683
|
||||
// (1)). One key's events are handled one at a time in the order heard, different keys side by side.
|
||||
type EventKey func(subject string, body []byte) string
|
||||
|
||||
// settingCount reads the setting key as a whole number from lo to hi, def when none is composed; one that is no such number
|
||||
// is an error naming the setting.
|
||||
func settingCount(key string, def, lo, hi int) (int, error) {
|
||||
v, ok := stdio.Setting(key)
|
||||
if v = strings.TrimSpace(v); !ok || v == "" {
|
||||
return def, nil
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < lo || n > hi {
|
||||
return 0, fmt.Errorf("the setting %s (%s) holds %q, which is not a whole number from %d to %d", key, stdio.SettingWord(key), v, lo, hi)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// heldEvent is one message the hub took, held until its handler ends.
|
||||
type heldEvent struct {
|
||||
msg jetstream.Msg
|
||||
handle func(jetstream.Msg)
|
||||
feed *eventFeed
|
||||
id string // the stream and its sequence: what a delivery again is told by
|
||||
key string
|
||||
subject string
|
||||
again bool // a delivery again was said already
|
||||
}
|
||||
|
||||
// eventHold is every message the hub holds, across its durables: one queue per key, the keys handled at once bounded.
|
||||
type eventHold struct {
|
||||
logf func(string, ...any)
|
||||
tick ticker
|
||||
|
||||
mu sync.Mutex
|
||||
room *sync.Cond // signalled when a message leaves
|
||||
atOnce int
|
||||
bound int
|
||||
queues map[string][]*heldEvent
|
||||
active map[string]bool
|
||||
waiting []string // keys with events waiting and no handling running, in the order heard
|
||||
ids map[string]*heldEvent
|
||||
atBound bool
|
||||
stopped bool
|
||||
}
|
||||
|
||||
func newEventHold(logf func(string, ...any), tick ticker) *eventHold {
|
||||
e := &eventHold{logf: logf, tick: tick, atOnce: defaultEventsAtOnce, bound: defaultEventsWaiting,
|
||||
queues: map[string][]*heldEvent{}, active: map[string]bool{}, ids: map[string]*heldEvent{}}
|
||||
e.room = sync.NewCond(&e.mu)
|
||||
return e
|
||||
}
|
||||
|
||||
// settle reads the hub's settings, an error naming one that is none.
|
||||
func (e *eventHold) settle() error {
|
||||
atOnce, err := settingCount(EventsAtOnceSetting, defaultEventsAtOnce, 1, mostEventsAtOnce)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bound, err := settingCount(EventsWaitingSetting, defaultEventsWaiting, 1, mostEventsWaiting)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
e.mu.Lock()
|
||||
e.atOnce, e.bound, e.stopped = atOnce, bound, false
|
||||
e.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// take holds a message under its key and hands it on when its key's turn comes. A delivery again of a held message is
|
||||
// handed to nobody and said once. At the bound of messages held it waits for room, so the hub pulls no more (H-A-695 (2)).
|
||||
func (e *eventHold) take(h *heldEvent) {
|
||||
e.mu.Lock()
|
||||
if first, again := e.ids[h.id]; again && h.id != "" {
|
||||
if !first.again {
|
||||
first.again = true
|
||||
e.logf("events: %s (%s) was given again while it is held, its handling not ended: handed to no handler", h.subject, h.id)
|
||||
}
|
||||
e.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if h.id != "" {
|
||||
e.ids[h.id] = h
|
||||
}
|
||||
e.queues[h.key] = append(e.queues[h.key], h)
|
||||
switch {
|
||||
case e.active[h.key] || len(e.queues[h.key]) > 1:
|
||||
// its key is running or already waits its turn: it follows in order
|
||||
case len(e.active) < e.atOnce:
|
||||
e.active[h.key] = true
|
||||
go e.run(h.key)
|
||||
default:
|
||||
e.waiting = append(e.waiting, h.key)
|
||||
}
|
||||
e.refill()
|
||||
for len(e.ids) >= e.bound && !e.stopped {
|
||||
if !e.atBound {
|
||||
e.atBound = true
|
||||
e.logf("events: the hub holds %d messages, its bound: it pulls no more until one ends; the key holding most is %s", len(e.ids), e.mostKey())
|
||||
}
|
||||
e.room.Wait()
|
||||
}
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
// mostKey names the key that holds most messages; the caller holds mu.
|
||||
func (e *eventHold) mostKey() string {
|
||||
best, n := "", 0
|
||||
keys := make([]string, 0, len(e.queues))
|
||||
for k := range e.queues {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
held := len(e.queues[k])
|
||||
if e.active[k] {
|
||||
held++
|
||||
}
|
||||
if held > n {
|
||||
best, n = k, held
|
||||
}
|
||||
}
|
||||
return displayKey(best)
|
||||
}
|
||||
|
||||
func displayKey(k string) string {
|
||||
if k == sharedEventKey {
|
||||
return "the shared key"
|
||||
}
|
||||
return strings.TrimPrefix(k, keyedEventKeyPrefix)
|
||||
}
|
||||
|
||||
// refill starts the waiting keys while there are handlings to spare; the caller holds mu.
|
||||
func (e *eventHold) refill() {
|
||||
for len(e.waiting) > 0 && len(e.active) < e.atOnce {
|
||||
k := e.waiting[0]
|
||||
e.waiting = e.waiting[1:]
|
||||
e.active[k] = true
|
||||
go e.run(k)
|
||||
}
|
||||
}
|
||||
|
||||
// run handles one key's events in the order heard, until it has none; then its turn goes to the next key waiting.
|
||||
func (e *eventHold) run(key string) {
|
||||
for {
|
||||
e.mu.Lock()
|
||||
q := e.queues[key]
|
||||
if len(q) == 0 {
|
||||
delete(e.queues, key)
|
||||
delete(e.active, key)
|
||||
e.refill()
|
||||
e.mu.Unlock()
|
||||
return
|
||||
}
|
||||
h := q[0]
|
||||
e.queues[key] = q[1:]
|
||||
e.mu.Unlock()
|
||||
e.handle(h)
|
||||
e.mu.Lock()
|
||||
if h.id != "" {
|
||||
delete(e.ids, h.id)
|
||||
}
|
||||
if e.atBound && len(e.ids) < e.bound {
|
||||
e.atBound = false
|
||||
e.logf("events: the hub holds %d messages, below its bound: it pulls again", len(e.ids))
|
||||
}
|
||||
e.room.Broadcast()
|
||||
e.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// handle runs a message's handler; a panic in it is said and the message is left unacknowledged, so the bus gives it again.
|
||||
func (e *eventHold) handle(h *heldEvent) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
e.logf("events: the handler of %s failed: %v; the message is not acknowledged", h.subject, r)
|
||||
}
|
||||
}()
|
||||
h.handle(h.msg)
|
||||
}
|
||||
|
||||
// stop releases a part waiting for room.
|
||||
func (e *eventHold) stop() {
|
||||
e.mu.Lock()
|
||||
e.stopped = true
|
||||
e.room.Broadcast()
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
// heldOf are the messages held that came by feed.
|
||||
func (e *eventHold) heldOf(f *eventFeed) []jetstream.Msg {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
var out []jetstream.Msg
|
||||
for _, h := range e.ids {
|
||||
if h.feed == f {
|
||||
out = append(out, h.msg)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// eventFeed is one durable the hub pulls: its one ticker says in progress for every message of it the hub holds, at every
|
||||
// third of its ack wait (design 47 H2 H-A-695 (1)), read once at the bind as H-A-281 has it.
|
||||
type eventFeed struct {
|
||||
hold *eventHold
|
||||
done chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func newEventFeed(h *eventHold) *eventFeed { return &eventFeed{hold: h, done: make(chan struct{})} }
|
||||
|
||||
// start begins the feed's ticker for a durable of this ack wait; none when it is unknown.
|
||||
func (f *eventFeed) start(ackWait time.Duration) {
|
||||
every := ackWait / 3
|
||||
if every <= 0 {
|
||||
return
|
||||
}
|
||||
f.once.Do(func() {
|
||||
ticks, stop := f.hold.tick(every)
|
||||
go func() {
|
||||
defer stop()
|
||||
for {
|
||||
select {
|
||||
case <-f.done:
|
||||
return
|
||||
case <-ticks:
|
||||
for _, m := range f.hold.heldOf(f) {
|
||||
_ = m.InProgress()
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
})
|
||||
}
|
||||
|
||||
func (f *eventFeed) end() {
|
||||
select {
|
||||
case <-f.done:
|
||||
default:
|
||||
close(f.done)
|
||||
}
|
||||
}
|
||||
+84
-22
@@ -3,6 +3,7 @@ package process
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -30,11 +31,17 @@ type EventHub struct {
|
||||
unhandled []func(subject string)
|
||||
// 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
|
||||
feeds []*eventFeed
|
||||
tick ticker
|
||||
}
|
||||
|
||||
type hubRoute struct {
|
||||
pattern string
|
||||
handle func(jetstream.Msg)
|
||||
key EventKey
|
||||
}
|
||||
|
||||
// NewEventHub is a hub saying through logf (nil says nothing).
|
||||
@@ -42,16 +49,29 @@ func NewEventHub(logf func(string, ...any)) *EventHub {
|
||||
if logf == nil {
|
||||
logf = func(string, ...any) {}
|
||||
}
|
||||
return &EventHub{logf: logf}
|
||||
h := &EventHub{logf: logf, tick: realTicker}
|
||||
h.held = newEventHold(logf, func(d time.Duration) (<-chan time.Time, func()) { return h.tick(d) })
|
||||
return h
|
||||
}
|
||||
|
||||
// Handle registers handle for the subjects matching pattern (`*` one token, `>` the rest). The handler acknowledges
|
||||
// the message itself. A pattern that overlaps one registered (one matches every subject of the other) is refused,
|
||||
// so a message always has one taker.
|
||||
func (h *EventHub) Handle(pattern string, handle func(jetstream.Msg)) error {
|
||||
//
|
||||
// key, when given, is the key of the pattern's events (design 47 H2 H-A-683 (1)): one key's events are handled one at a
|
||||
// time in the order heard and the events of different keys side by side, at most `events-at-once` keys at once; every pattern
|
||||
// given none hands its events under one shared key, so a caller that gives none is handled one at a time as before.
|
||||
func (h *EventHub) Handle(pattern string, handle func(jetstream.Msg), key ...EventKey) error {
|
||||
if pattern == "" || handle == nil {
|
||||
return fmt.Errorf("an event handler needs a subject pattern and a handler")
|
||||
}
|
||||
if len(key) > 1 {
|
||||
return fmt.Errorf("the events %q are given more than one key function", pattern)
|
||||
}
|
||||
var keyOf EventKey
|
||||
if len(key) == 1 {
|
||||
keyOf = key[0]
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
for _, r := range h.routes {
|
||||
@@ -59,7 +79,7 @@ func (h *EventHub) Handle(pattern string, handle func(jetstream.Msg)) error {
|
||||
return fmt.Errorf("the events %q overlap %q, already handled: a message has one taker", pattern, r.pattern)
|
||||
}
|
||||
}
|
||||
h.routes = append(h.routes, hubRoute{pattern, handle})
|
||||
h.routes = append(h.routes, hubRoute{pattern, handle, keyOf})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -105,7 +125,17 @@ func (h *EventHub) Start(ctx context.Context, js jetstream.JetStream, cred Accou
|
||||
}
|
||||
cons, err := cred.EventConsumer(ctx, js, EventsStream)
|
||||
if err == nil {
|
||||
h.cons, err = HearEvents(cons, h.hear, h.logf)
|
||||
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.hearOn(feed), h.logf)
|
||||
if err != nil {
|
||||
feed.end()
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("the consumer %s on %s is not heard: %w", cred.EventConsumerName(), EventsStream, err)
|
||||
@@ -171,6 +201,18 @@ func (h *EventHub) Stop() {
|
||||
cc.Stop()
|
||||
}
|
||||
h.kept = nil
|
||||
for _, f := range h.feeds {
|
||||
f.end()
|
||||
}
|
||||
h.feeds = nil
|
||||
h.held.stop()
|
||||
}
|
||||
|
||||
// newFeed makes the ticker of one durable the hub pulls (event_hold.go).
|
||||
func (h *EventHub) newFeed() *eventFeed {
|
||||
f := newEventFeed(h.held)
|
||||
h.feeds = append(h.feeds, f)
|
||||
return f
|
||||
}
|
||||
|
||||
// StartKept binds, beside EVENTS, the module's durable on each kept seat event's stream (`SEAT_<seat>_<event>`) whose event a
|
||||
@@ -209,8 +251,12 @@ func (h *EventHub) StartKept(ctx context.Context, js jetstream.JetStream, cred A
|
||||
if !taken {
|
||||
continue
|
||||
}
|
||||
cc, err := cred.HearSeatEvents(ctx, js, stream, h.hear, h.logf)
|
||||
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
|
||||
}
|
||||
@@ -237,26 +283,42 @@ func keptSeatEvent(stream string) (seat, event string, ok bool) {
|
||||
return seat, event, true
|
||||
}
|
||||
|
||||
func (h *EventHub) hear(m jetstream.Msg) {
|
||||
h.mu.RLock()
|
||||
var take func(jetstream.Msg)
|
||||
for _, r := range h.routes {
|
||||
if subjectMatches(r.pattern, m.Subject()) {
|
||||
take = r.handle
|
||||
break
|
||||
// hear is hearOn for a message with no durable of its own to say in progress on.
|
||||
func (h *EventHub) hear(m jetstream.Msg) { h.hearOn(nil)(m) }
|
||||
|
||||
// hearOn is the handler of one durable's messages: it finds the message's taker and key, and holds it for them (event_hold.go),
|
||||
// so the pull goes on while a handler runs and every message held is said in progress by the durable's ticker. A message no
|
||||
// handler takes is acknowledged and said, never held.
|
||||
func (h *EventHub) hearOn(feed *eventFeed) func(jetstream.Msg) {
|
||||
return func(m jetstream.Msg) {
|
||||
h.mu.RLock()
|
||||
var route *hubRoute
|
||||
for i := range h.routes {
|
||||
if subjectMatches(h.routes[i].pattern, m.Subject()) {
|
||||
route = &h.routes[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
told := h.unhandled
|
||||
h.mu.RUnlock()
|
||||
if take == nil {
|
||||
h.logf("events: %s is taken by no handler of this module, acknowledged", m.Subject())
|
||||
_ = m.Ack()
|
||||
for _, f := range told {
|
||||
f(m.Subject())
|
||||
told := h.unhandled
|
||||
h.mu.RUnlock()
|
||||
if route == nil {
|
||||
h.logf("events: %s is taken by no handler of this module, acknowledged", m.Subject())
|
||||
_ = m.Ack()
|
||||
for _, f := range told {
|
||||
f(m.Subject())
|
||||
}
|
||||
return
|
||||
}
|
||||
return
|
||||
key := sharedEventKey
|
||||
if route.key != nil {
|
||||
key = keyedEventKeyPrefix + route.key(m.Subject(), m.Data())
|
||||
}
|
||||
id := ""
|
||||
if md, err := m.Metadata(); err == nil {
|
||||
id = md.Stream + "/" + strconv.FormatUint(md.Sequence.Stream, 10)
|
||||
}
|
||||
h.held.take(&heldEvent{msg: m, handle: route.handle, feed: feed, id: id, key: key, subject: m.Subject()})
|
||||
}
|
||||
take(m)
|
||||
}
|
||||
|
||||
// subjectMatches says whether subject is one the pattern (`*` one token, `>` the rest) names.
|
||||
|
||||
@@ -290,6 +290,68 @@ func TestTheHubBindsALateConsumerAndSaysItIsLive(t *testing.T) {
|
||||
t.Run("AModuleHearsAnotherModulesStreamKeptLastPerSubject", subAModuleHearsAnotherModulesStreamKeptLastPerSubject)
|
||||
t.Run("AModuleHearsAStreamKeptByAgeFromItsFirstMessage", subAModuleHearsAStreamKeptByAgeFromItsFirstMessage)
|
||||
t.Run("AProcessPullsADurableOnce", subAProcessPullsADurableOnce)
|
||||
t.Run("TheHubKeepsAHeldMessageAliveWhileAnotherKeyIsHandled", subTheHubKeepsAHeldMessageAliveWhileAnotherKeyIsHandled)
|
||||
}
|
||||
|
||||
// Design 47 H2 H-A-683 (1), H-A-695 (1): with the durable's ack wait shortened and one key's handling blocked past several ack
|
||||
// waits, no message is given again (the durable's redelivered count stays 0) and another key's events are handled.
|
||||
func subTheHubKeepsAHeldMessageAliveWhileAnotherKeyIsHandled(t *testing.T) {
|
||||
nc, err := nats.Connect(testbus.URL(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer nc.Close()
|
||||
js, err := jetstream.New(nc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: process.EventsStream, Subjects: []string{"mesh.mod.*.event.>"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cred := process.Account{Node: "n1", Module: "keyed"}
|
||||
if _, err := js.CreateOrUpdateConsumer(ctx, process.EventsStream, jetstream.ConsumerConfig{Durable: cred.EventConsumerName(),
|
||||
AckPolicy: jetstream.AckExplicitPolicy, AckWait: 600 * time.Millisecond}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hub := process.NewEventHub(t.Logf)
|
||||
release, handled := make(chan struct{}), make(chan string, 4)
|
||||
if err := hub.Handle("mesh.mod.m.event.>", func(m jetstream.Msg) {
|
||||
if strings.HasSuffix(m.Subject(), ".slow") {
|
||||
<-release
|
||||
}
|
||||
_ = m.Ack()
|
||||
handled <- m.Subject()
|
||||
}, func(subject string, _ []byte) string { return subject }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := hub.Start(ctx, js, cred); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer hub.Stop()
|
||||
for _, name := range []string{"slow", "fast"} {
|
||||
if _, err := js.Publish(ctx, "mesh.mod.m.event."+name, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if got := <-handled; !strings.HasSuffix(got, ".fast") {
|
||||
t.Fatalf("the first event handled was %s: the blocked key held the other back", got)
|
||||
}
|
||||
// Five ack waits pass with the slow key's handling blocked: the hub says its message in progress, so the bus gives none again.
|
||||
held := time.After(3 * time.Second)
|
||||
<-held
|
||||
cons, err := cred.EventConsumer(ctx, js, process.EventsStream)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info, err := cons.Info(ctx); err != nil || info.NumRedelivered != 0 || info.NumAckPending != 1 {
|
||||
t.Fatalf("after five ack waits the durable holds %+v (%v): want one pending and none given again", info, err)
|
||||
}
|
||||
close(release)
|
||||
if got := <-handled; !strings.HasSuffix(got, ".slow") {
|
||||
t.Fatalf("handled %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A second pull loop on a durable this process already pulls is refused at bind time, naming the durable and both
|
||||
|
||||
@@ -2,7 +2,11 @@ package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -147,3 +151,200 @@ func TestTheHubPullsSmallBatchesAndKeepsSlowHandlersAlive(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -138,6 +138,15 @@ func hearEvents(cons jetstream.Consumer, binder string, handle func(jetstream.Ms
|
||||
}))
|
||||
}
|
||||
|
||||
// hearHeld is HearEvents for a handler that holds each message and returns (the event hub's, event_hold.go): the pull says
|
||||
// nothing in progress itself, since the hub's ticker of the durable does for every message held.
|
||||
func hearHeld(cons jetstream.Consumer, binder string, handle func(jetstream.Msg), logf func(string, ...any)) (jetstream.ConsumeContext, error) {
|
||||
return ConsumeOnce(cons, binder, handle, jetstream.PullMaxMessages(hubPullMessages),
|
||||
jetstream.ConsumeErrHandler(func(_ jetstream.ConsumeContext, err error) {
|
||||
logf("hearing the bus: %v", err)
|
||||
}))
|
||||
}
|
||||
|
||||
// keptInProgress is handle that says in progress for its message at every tick of every while the handler runs, the
|
||||
// ticker stopped at the handler's return (design 47 H, H-A-281); with no every it is handle as it is.
|
||||
func keptInProgress(handle func(jetstream.Msg), every time.Duration, tick ticker) jetstream.MessageHandler {
|
||||
|
||||
@@ -49,8 +49,15 @@ type HearOption func(*hearOptions)
|
||||
type hearOptions struct {
|
||||
onRead func(state string)
|
||||
fromFirst bool
|
||||
// held is the event hub's feed of this durable (EventHub.StartKept): its messages are held and said in progress by the
|
||||
// hub's ticker, so the pull says none itself.
|
||||
held *eventFeed
|
||||
}
|
||||
|
||||
// heldBy makes the pull of a durable the event hub's: its handler holds each message and returns, and the feed's ticker says in
|
||||
// progress for every one held, at every third of the durable's ack wait (design 47 H2 H-A-695 (1), (4)).
|
||||
func heldBy(f *eventFeed) HearOption { return func(o *hearOptions) { o.held = f } }
|
||||
|
||||
// OnRead is the callback HearSeatEvents calls with ReadWaiting and then ReadDone around its start read; the module wires it
|
||||
// to its first views (design 47 G A-19), so this package imports nothing of views.
|
||||
func OnRead(f func(state string)) HearOption { return func(o *hearOptions) { o.onRead = f } }
|
||||
@@ -144,6 +151,11 @@ func (a Account) HearStream(ctx context.Context, js jetstream.JetStream, stream
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the stream %s is not read: %w", stream, err)
|
||||
}
|
||||
if o.held != nil {
|
||||
if info := cons.CachedInfo(); info != nil {
|
||||
o.held.start(info.Config.AckWait)
|
||||
}
|
||||
}
|
||||
if from, whole := wholeRead(st.CachedInfo().Config.MaxMsgsPerSubject, o.fromFirst); whole {
|
||||
if o.onRead != nil {
|
||||
o.onRead(ReadWaiting)
|
||||
@@ -161,7 +173,12 @@ func (a Account) HearStream(ctx context.Context, js jetstream.JetStream, stream
|
||||
}
|
||||
logf("events: %s is read whole at its start", stream)
|
||||
}
|
||||
cc, err := HearEvents(cons, handle, logf)
|
||||
var cc jetstream.ConsumeContext
|
||||
if o.held != nil {
|
||||
cc, err = hearHeld(cons, callerOutside(), handle, logf)
|
||||
} else {
|
||||
cc, err = HearEvents(cons, handle, logf)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the consumer %s on %s is not heard: %w", a.EventConsumerName(), stream, err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user