Files
mesh-sdk/go/process/event_hub.go
T
jschoubben dda65f1cf2 S2 events-unheard: the hub says each pattern it does not hear, and the process reader raises the finding
OnUnheard is told the patterns not heard with stream and why (no stream carries it, not composed,
refused, registered after Start), the journal says each; the process reader raises events-unheard
(id module.node) from it and clears it on an empty list. A reader with no findings writer says
them in the journal alone. A late first adopt is among the unheard patterns.

Builds: design 47 H2b §836 4.; H-A-834, H-A-840, H-A-854
2026-11-27 03:00:35 +01:00

647 lines
22 KiB
Go

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/buscompose"
"git.novox.be/novox/mesh-sdk/go/seatdef"
)
// EventHub is the one pull of a module's durable consumer on the shared events stream (novox/hq ADR 0635 §5): a module
// has one durable, `<node>_<module>`, so two loops pulling it each take messages the other needs. Every part of the
// module that hears events registers a handler by subject pattern, and the hub pulls once and hands each message to the
// handler whose pattern it matches. A message no handler takes is acknowledged and said, never left to be redelivered.
// The hub never makes the stream or the consumer: they are the controller's, and a bus without them is an error of Start.
//
// Register every handler, then Start once: a message heard before its handler is registered would be taken by none, so a handler
// registered after Start is refused, naming its pattern.
type EventHub struct {
logf func(string, ...any)
mu sync.RWMutex
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
// late are the patterns refused after Start (they stay unheard); lastTold the list the hooks were last told, and toldOnce says
// a pass told them (Start's, whatever the list).
late []Unheard
lastTold []Unheard
toldOnce bool
passed bool
unheardTo []func([]Unheard)
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)
// 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).
func NewEventHub(logf func(string, ...any)) *EventHub {
if logf == nil {
logf = func(string, ...any) {}
}
h := &EventHub{logf: logf, tick: realTicker}
h.held = newEventHold(logf, func(d time.Duration) (<-chan time.Time, func()) { return h.tick(d) })
h.held.overrun = func(past []Handling) {
h.mu.RLock()
told := h.overruns
h.mu.RUnlock()
for _, f := range told {
f(past)
}
}
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. Its events are handled under one shared key, one at a time (HandleByKey).
func (h *EventHub) Handle(pattern string, handle func(jetstream.Msg)) error {
return h.handleByKey(pattern, handle, nil)
}
// HandleByKey is Handle for a pattern whose events are held by key (design 47 H2 H-A-683 (1), H-A-737 (1)): key is a function of
// a message's subject and body. 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 no key (Handle) hands its events under one shared key.
func (h *EventHub) HandleByKey(pattern string, key EventKey, handle func(jetstream.Msg)) error {
if key == nil {
return fmt.Errorf("the events %q are given no key function", pattern)
}
return h.handleByKey(pattern, handle, key)
}
func (h *EventHub) handleByKey(pattern string, handle func(jetstream.Msg), keyOf EventKey) error {
if pattern == "" || handle == nil {
return fmt.Errorf("an event handler needs a subject pattern and a handler")
}
h.mu.Lock()
for _, r := range h.routes {
if subjectsOverlap(r.pattern, pattern) {
h.mu.Unlock()
return fmt.Errorf("the events %q overlap %q, already handled: a message has one taker", pattern, r.pattern)
}
}
if h.started {
// An event no registered pattern covers (its first adopt) is not heard; one an earlier handler takes is.
err := fmt.Errorf("the events %q are registered after Start: register every handler, then Start once (design 47 H2b §836 3.)", pattern)
late := Unheard{pattern, "", "registered after Start"}
if !slices.Contains(h.late, late) {
h.late = append(h.late, late)
}
h.mu.Unlock()
h.announce()
return err
}
defer h.mu.Unlock()
h.routes = append(h.routes, hubRoute{pattern, handle, keyOf})
return nil
}
// OnBound registers f, told each time the hub binds the module's consumer, with when the bus made it. A consumer is made
// from now (ADR 0443), so an event said before it was made is not delivered to it: a part that took a picture before
// that must ask its owner again (views.Follower.ConsumerMade). So every handler of an event that ends a kept call's wait
// (a callee's "my state changed") also registers here the call it makes on that event, made again once at each bind
// (novox/hq ADR 0668; issue 1966). Register before Start.
func (h *EventHub) OnBound(f func(created time.Time)) {
h.mu.Lock()
h.bound = append(h.bound, f)
h.mu.Unlock()
}
// OnUnhandled registers f, told the subject of each message no handler takes, after the hub said it in the log and
// acknowledged it: the module's process reader counts them in its finding `event-unhandled` (design 47 H, H-A-166,
// H-A-169).
func (h *EventHub) OnUnhandled(f func(subject string)) {
h.mu.Lock()
h.unhandled = append(h.unhandled, f)
h.mu.Unlock()
}
// OnOverrun registers f, told the handlings of events that run past the setting event-overrun (1 second to 1 hour, 60 seconds by
// default), the one begun first first, each time a handling passes that bound while it still runs and each time one that was
// past it ends: an empty list says none is past it. The process reader wires it into the module's finding `event-overrun`
// (design 47 H2 H-A-683 (3), H-A-697).
func (h *EventHub) OnOverrun(f func(past []Handling)) {
h.mu.Lock()
h.overruns = append(h.overruns, f)
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()
}
// OnUnheard registers f, told the patterns the hub does not hear, each with its stream and why, whenever that list changes, Start
// included, and an empty list once every pattern is heard, as OnOverrun is told (design 47 H2b §836 4.): the process reader raises
// the finding `events-unheard` from it. A pattern refused after Start is in the list. Register before Start.
func (h *EventHub) OnUnheard(f func(unheard []Unheard)) {
h.mu.Lock()
h.unheardTo = append(h.unheardTo, f)
h.mu.Unlock()
}
// Patterns are the registered subject patterns, in order.
func (h *EventHub) Patterns() []string {
h.mu.RLock()
defer h.mu.RUnlock()
out := make([]string, len(h.routes))
for i, r := range h.routes {
out[i] = r.pattern
}
return out
}
// 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(buscompose.GrantsModule, "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 (design 47
// H2b §836 4.): "no stream carries it", "not composed", "refused: <the bus's words>" or "registered after Start".
type Unheard struct{ Pattern, Stream, Why string }
func (h *EventHub) start(ctx context.Context, bus hubBus, cred Account) error {
h.mu.Lock()
if h.started {
h.mu.Unlock()
return nil
}
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 {
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.mu.Lock()
h.stopWake = stop
h.mu.Unlock()
}
bus.reconnected(rebind)
h.pass(ctx, bus, cred)
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)
}
}
// 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, h.passed = not, true
all := len(not) == 0
tell := all && !h.allTold
h.allTold = all
told := h.allHeard
h.mu.Unlock()
h.announce()
if tell {
for _, f := range told {
f()
}
}
}
// announce says the patterns not heard (the journal, one line each) and tells each OnUnheard hook, when the list differs from the one
// told last or none was told yet (Start's pass tells even an empty list: a restarted program clears what an earlier process raised).
// Nothing is told before a pass has made the list.
func (h *EventHub) announce() {
h.mu.Lock()
if !h.passed {
h.mu.Unlock()
return
}
list := append(slices.Clone(h.unheardNow), h.late...)
if h.toldOnce && slices.Equal(list, h.lastTold) {
h.mu.Unlock()
return
}
h.toldOnce, h.lastTold = true, list
hooks := slices.Clone(h.unheardTo)
h.mu.Unlock()
for _, u := range list {
switch {
case u.Stream == "":
h.logf("events: the pattern %s is not heard: %s", u.Pattern, u.Why)
default:
h.logf("events: the pattern %s is not heard on %s: %s", u.Pattern, u.Stream, u.Why)
}
}
for _, f := range hooks {
f(slices.Clone(list))
}
}
// 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()
for _, cc := range h.heard {
cc.Stop()
}
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
h.passed, h.toldOnce, h.lastTold, h.late = false, false, nil, 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
}
// 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) {
rest, isKept := strings.CutPrefix(stream, seatdef.KeptStreamPrefix)
if !isKept {
return "", "", false
}
seat, event, ok = strings.Cut(rest, "_")
if !ok || seat == "" || event == "" || strings.Contains(event, "_") {
return "", "", false
}
return seat, event, true
}
// 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 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
}
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()})
}
}
// subjectMatches says whether subject is one the pattern (`*` one token, `>` the rest) names.
func subjectMatches(pattern, subject string) bool {
pt, st := strings.Split(pattern, "."), strings.Split(subject, ".")
for i, t := range pt {
if t == ">" {
return len(st) > i
}
if i >= len(st) || (t != "*" && t != st[i]) {
return false
}
}
return len(pt) == len(st)
}
// subjectsOverlap says whether some subject matches both patterns.
func subjectsOverlap(a, b string) bool {
at, bt := strings.Split(a, "."), strings.Split(b, ".")
for i := 0; ; i++ {
if i >= len(at) || i >= len(bt) {
return len(at) == len(bt)
}
if at[i] == ">" || bt[i] == ">" {
return true
}
if at[i] != "*" && bt[i] != "*" && at[i] != bt[i] {
return false
}
}
}