S7 event-overrun: the hub times each handling, the finding event-overrun, ViewKinds names both

Builds: design 47 H2 H-A-683 (3), H-A-697 (1) (2) (3)
This commit is contained in:
2026-11-25 17:16:27 +01:00
parent fd01ec91a2
commit 065e73e1dd
9 changed files with 364 additions and 9 deletions
+107 -3
View File
@@ -18,6 +18,12 @@ import (
const (
EventsAtOnceSetting = "events-at-once"
EventsWaitingSetting = "events-waiting"
SlowEventSetting = "slow-event"
EventOverrunSetting = "event-overrun"
defaultSlowEvent = 100 * time.Millisecond
defaultEventOverrun = 60 * time.Second
leastEventOverrun = time.Second
mostEventOverrun = time.Hour
defaultEventsAtOnce = 8
defaultEventsWaiting = 100
mostEventsAtOnce = 64
@@ -30,6 +36,13 @@ const (
// (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
// Handling is one handling of an event that runs past the setting event-overrun: its subject, its key and since when it ran
// (design 47 H2 H-A-683 (3), H-A-697 (3)).
type Handling struct {
Subject, Key string
Since time.Time
}
// 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) {
@@ -59,11 +72,21 @@ type heldEvent struct {
type eventHold struct {
logf func(string, ...any)
tick ticker
// now and after are the clock and the timer of the timed handlings, a test's to replace: after calls f once d has passed and
// answers what cancels it.
now func() time.Time
after func(d time.Duration, f func()) (cancel func())
// overrun is told the handlings past the bound of event-overrun, oldest first, each time one passes it or ends.
overrun func(past []Handling)
toldMu sync.Mutex // the hook of the overrun is told one at a time
mu sync.Mutex
room *sync.Cond // signalled when a message leaves
atOnce int
bound int
slow time.Duration
over time.Duration
running map[*heldEvent]*timed
queues map[string][]*heldEvent
active map[string]bool
waiting []string // keys with events waiting and no handling running, in the order heard
@@ -73,7 +96,9 @@ type eventHold struct {
}
func newEventHold(logf func(string, ...any), tick ticker) *eventHold {
e := &eventHold{logf: logf, tick: tick, atOnce: defaultEventsAtOnce, bound: defaultEventsWaiting,
e := &eventHold{logf: logf, tick: tick, atOnce: defaultEventsAtOnce, bound: defaultEventsWaiting, now: time.Now,
slow: defaultSlowEvent, over: defaultEventOverrun, running: map[*heldEvent]*timed{},
after: func(d time.Duration, f func()) func() { t := time.AfterFunc(d, f); return func() { t.Stop() } },
queues: map[string][]*heldEvent{}, active: map[string]bool{}, ids: map[string]*heldEvent{}}
e.room = sync.NewCond(&e.mu)
return e
@@ -89,8 +114,20 @@ func (e *eventHold) settle() error {
if err != nil {
return err
}
slow, err := stdio.SettingDuration(SlowEventSetting, defaultSlowEvent)
if err != nil {
return err
}
over, err := stdio.SettingDuration(EventOverrunSetting, defaultEventOverrun)
if err != nil {
return err
}
if over < leastEventOverrun || over > mostEventOverrun {
return fmt.Errorf("the setting %s (%s) holds %s, which is not from %s to %s", EventOverrunSetting, stdio.SettingWord(EventOverrunSetting),
over, leastEventOverrun, mostEventOverrun)
}
e.mu.Lock()
e.atOnce, e.bound, e.stopped = atOnce, bound, false
e.atOnce, e.bound, e.slow, e.over, e.stopped = atOnce, bound, slow, over, false
e.mu.Unlock()
return nil
}
@@ -197,16 +234,83 @@ func (e *eventHold) run(key string) {
}
}
// handle runs a message's handler; a panic in it is said and the message is left unacknowledged, so the bus gives it again.
// timed is one handling that runs: when it began, and whether it is past event-overrun.
type timed struct {
since time.Time
past bool
cancel func()
}
// handle runs a message's handler, timed: past slow-event the journal says how long it took and which key's it was; while it
// runs past event-overrun the hook of the overrun is told at once, and again when it ends (design 47 H2 H-A-683 (3), H-A-697
// (3)). A panic in it is said and the message is left unacknowledged, so the bus gives it again.
func (e *eventHold) handle(h *heldEvent) {
e.mu.Lock()
t := &timed{since: e.now()}
over, slow := e.over, e.slow
e.running[h] = t
e.mu.Unlock()
t.cancel = e.after(over, func() {
e.mu.Lock()
if _, ok := e.running[h]; !ok {
e.mu.Unlock()
return
}
t.past = true
e.mu.Unlock()
e.told()
})
defer func() {
if r := recover(); r != nil {
e.logf("events: the handler of %s failed: %v; the message is not acknowledged", h.subject, r)
}
t.cancel()
e.mu.Lock()
delete(e.running, h)
took := e.now().Sub(t.since)
wasPast := t.past
e.mu.Unlock()
if took > slow {
e.logf("events: the event %s (key %s) took %s to handle, over %s", h.subject, displayKey(h.key), took.Round(time.Millisecond), slow)
}
if wasPast {
e.told()
}
}()
h.handle(h.msg)
}
// pastLocked are the handlings past the bound, the one begun first first; the caller holds mu.
func (e *eventHold) pastLocked() []Handling {
var out []Handling
for h, t := range e.running {
if t.past {
out = append(out, Handling{Subject: h.subject, Key: displayKey(h.key), Since: t.since})
}
}
sort.Slice(out, func(i, j int) bool {
if !out[i].Since.Equal(out[j].Since) {
return out[i].Since.Before(out[j].Since)
}
return out[i].Subject < out[j].Subject
})
return out
}
// told hands the handlings past the bound, as they are now, to the hook; one call at a time, each reading the handlings after the
// one before it ended, so the hook's last word is the true one.
func (e *eventHold) told() {
if e.overrun == nil {
return
}
e.toldMu.Lock()
defer e.toldMu.Unlock()
e.mu.Lock()
past := e.pastLocked()
e.mu.Unlock()
e.overrun(past)
}
// stop releases a part waiting for room.
func (e *eventHold) stop() {
e.mu.Lock()
+20
View File
@@ -29,6 +29,8 @@ type EventHub struct {
bound []func(created time.Time)
// 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'
@@ -51,6 +53,14 @@ func NewEventHub(logf func(string, ...any)) *EventHub {
}
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
}
@@ -103,6 +113,16 @@ func (h *EventHub) OnUnhandled(f func(subject string)) {
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()
}
// Patterns are the registered subject patterns, in order.
func (h *EventHub) Patterns() []string {
h.mu.RLock()
+79
View File
@@ -348,3 +348,82 @@ func TestTheHubHoldsEventsByKeyAndSaysThemInProgress(t *testing.T) {
}
})
}
// Design 47 H2 H-A-683 (3), H-A-697 (3): a handling past event-overrun tells the hook once while it runs, naming its subject, key
// and since when, the oldest first, and once more when it ends with none past it; a handling past slow-event is said in the
// journal with its key and how long it took; a setting outside 1 second to 1 hour is refused naming it.
func TestAHandlingPastEventOverrunTellsItsHookWhileItRuns(t *testing.T) {
now := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC)
var clock sync.Mutex
var lines []string
h := NewEventHub(func(f string, a ...any) { clock.Lock(); lines = append(lines, fmt.Sprintf(f, a...)); clock.Unlock() })
h.held.now = func() time.Time { clock.Lock(); defer clock.Unlock(); return now }
advance := func(d time.Duration) { clock.Lock(); now = now.Add(d); clock.Unlock() }
var fire []func()
h.held.after = func(d time.Duration, f func()) func() {
if d != 60*time.Second {
t.Errorf("the overrun is timed at %s, want the default 60s", d)
}
clock.Lock()
fire = append(fire, f)
clock.Unlock()
return func() {}
}
release := make(chan struct{})
entered := make(chan struct{}, 4)
if err := h.Handle("mesh.mod.m.event.>", func(jetstream.Msg) { entered <- struct{}{}; <-release },
func(subject string, _ []byte) string { return subject[len("mesh.mod.m.event."):] }); err != nil {
t.Fatal(err)
}
var told [][]Handling
h.OnOverrun(func(past []Handling) { clock.Lock(); told = append(told, past); clock.Unlock() })
if err := h.held.settle(); err != nil {
t.Fatal(err)
}
h.hearOn(nil)(&seqMsg{subject: "mesh.mod.m.event.first", seq: 1})
<-entered
advance(time.Second)
h.hearOn(nil)(&seqMsg{subject: "mesh.mod.m.event.second", seq: 2})
<-entered
advance(59 * time.Second)
clock.Lock()
timers := fire
clock.Unlock()
for _, f := range timers {
f()
}
clock.Lock()
if len(told) != 2 || len(told[1]) != 2 || told[1][0].Subject != "mesh.mod.m.event.first" || told[1][0].Key != "first" ||
!told[1][0].Since.Equal(now.Add(-60*time.Second)) || told[1][1].Key != "second" {
t.Fatalf("the hook was told %+v", told)
}
clock.Unlock()
close(release)
deadline := time.After(5 * time.Second)
for {
clock.Lock()
n, last := len(told), []Handling(nil)
if n > 0 {
last = told[n-1]
}
clock.Unlock()
if n >= 4 && len(last) == 0 {
break
}
select {
case <-deadline:
t.Fatalf("the hook was told %d times, the last of %v", n, last)
case <-time.After(5 * time.Millisecond):
}
}
clock.Lock()
said := strings.Join(lines, "\n")
clock.Unlock()
if !strings.Contains(said, "the event mesh.mod.m.event.first (key first) took 1m0s to handle, over 100ms") {
t.Errorf("the journal says %q", said)
}
t.Setenv(stdio.SettingWord(EventOverrunSetting), "500ms")
if err := h.held.settle(); err == nil || !strings.Contains(err.Error(), EventOverrunSetting) {
t.Errorf("an overrun of 500ms was accepted: %v", err)
}
}
+22
View File
@@ -8,6 +8,7 @@ import (
"time"
"git.novox.be/novox/mesh-sdk/go/keys"
"git.novox.be/novox/mesh-sdk/go/process"
)
// The findings a views part writes in its own state `findings`, which the condition keeper raises and clears
@@ -26,6 +27,9 @@ const (
// EventUnhandledKind is a process's finding of the events its durable consumer delivered that no handler of the module
// took, one per module, counted since the process started (design 47 H, H-A-166, H-A-169).
EventUnhandledKind = "event-unhandled"
// EventOverrunKind is a process's finding of the handlings of events that run past the setting event-overrun, one per module,
// its summary naming each (design 47 H2 H-A-683 (3), H-A-697).
EventOverrunKind = "event-overrun"
)
// viewFinding is what a views part says is wrong with a state it owns or follows, in plain fields: kind and id name it, summary
@@ -131,3 +135,21 @@ func unhandledFinding(module string, count int, last string, since, at time.Time
module, count, since.UTC().Format(time.RFC3339), last)
return viewFinding{kind: EventUnhandledKind, id: module, summary: summary, headline: fmt.Sprintf("%s hears events it does not handle", module), at: at.UTC()}
}
// overrunMost is how many handlings the finding event-overrun names before it says how many more.
const overrunMost = 5
// overrunFinding is the module's one finding of the handlings past event-overrun (H-A-697 (3)): its id the module, its summary
// each handling, the one begun first first, with its subject, its key and since when, at most five and then how many more.
func overrunFinding(module string, past []process.Handling, at time.Time) viewFinding {
var named []string
for i, h := range past {
if i == overrunMost {
named = append(named, fmt.Sprintf("and %d more", len(past)-overrunMost))
break
}
named = append(named, fmt.Sprintf("%s (key %s) since %s", h.Subject, h.Key, h.Since.UTC().Format(time.RFC3339)))
}
summary := fmt.Sprintf("%s has %d event handlings past their bound: %s: the events behind them wait", module, len(past), strings.Join(named, "; "))
return viewFinding{kind: EventOverrunKind, id: module, summary: summary, headline: fmt.Sprintf("%s handles an event very slowly", module), at: at.UTC()}
}
+28 -4
View File
@@ -435,8 +435,29 @@ func (r *ProcessReader) unhandled(subject string) {
}
}
// clearUnhandled clears the module's finding `event-unhandled` at the process's start: a new build may handle the event
// (H-A-169).
// overrun is the event hub's word of the handlings past event-overrun: the module's finding `event-overrun`, written again at
// each handling that passes the bound or ends, and cleared once none is past it (design 47 H2 H-A-697 (3)).
func (r *ProcessReader) overrun(past []process.Handling) {
if r.Findings == nil {
return
}
w := r.Findings()
if w == nil {
return
}
if len(past) == 0 {
if err := (viewFinding{kind: EventOverrunKind, id: r.Module}).drop(w); err != nil {
r.logf("views: the finding %s of %s is not cleared: %v", EventOverrunKind, r.Module, err)
}
return
}
if err := overrunFinding(r.Module, past, r.now()).put(w); err != nil {
r.logf("views: the finding %s of %s is not written: %v", EventOverrunKind, r.Module, err)
}
}
// clearUnhandled clears the module's findings `event-unhandled` and `event-overrun` at the process's start: a new build may
// handle the event (H-A-169), and no handling of the new process runs yet (H-A-697 (1)).
func (r *ProcessReader) clearUnhandled() {
if r.Findings == nil {
return
@@ -445,8 +466,10 @@ func (r *ProcessReader) clearUnhandled() {
if w == nil {
return
}
if err := (viewFinding{kind: EventUnhandledKind, id: r.Module}).drop(w); err != nil {
r.logf("views: the finding %s of %s is not cleared at its start: %v", EventUnhandledKind, r.Module, err)
for _, kind := range []string{EventUnhandledKind, EventOverrunKind} {
if err := (viewFinding{kind: kind, id: r.Module}).drop(w); err != nil {
r.logf("views: the finding %s of %s is not cleared at its start: %v", kind, r.Module, err)
}
}
}
@@ -908,6 +931,7 @@ func (r *ProcessReader) Start(ctx context.Context, js jetstream.JetStream, cred
r.mu.Unlock()
if wire {
hub.OnUnhandled(r.unhandled)
hub.OnOverrun(r.overrun)
}
}
r.mu.Lock()
@@ -345,6 +345,82 @@ func TestAReaderHearsAnOwnersChangesAsOrdinaryEvents(t *testing.T) {
t.Run("AReaderHearsAnOwnersChangesAsOrdinaryEvents", subAReaderHearsAnOwnersChangesAsOrdinaryEvents)
t.Run("TheViewsReaderAndTwoHandlersShareTheModulesOneDurable", subTheViewsReaderAndTwoHandlersShareTheModulesOneDurable)
t.Run("WriterSaysItsEventsAndHearsAsksOnTheBus", subWriterSaysItsEventsAndHearsAsksOnTheBus)
t.Run("AHandlingPastEventOverrunRaisesItsFindingAndTheNextStartClearsIt", subAHandlingPastEventOverrunRaisesItsFindingAndTheNextStartClearsIt)
}
// clearedFindings is a findings writer that hands each finding written and each cleared to the test.
type clearedFindings struct{ put, cleared chan string }
func (f *clearedFindings) WriteWire(_ context.Context, w map[string]any) error {
f.put <- fmt.Sprintf("%v %v %v", w["kind"], w["id"], w["summary"])
return nil
}
func (f *clearedFindings) Clear(_ context.Context, _, id, kind, _ string) error {
f.cleared <- kind + " " + id
return nil
}
func (f *clearedFindings) ModuleNode() (string, string) { return "reader", "n1" }
// Design 47 H2 H-A-683 (3), H-A-697: a handling past a short event-overrun raises the module's finding event-overrun, naming its
// key and since when, clears it when the handling ends, and the process started again clears it at its start.
func subAHandlingPastEventOverrunRaisesItsFindingAndTheNextStartClearsIt(t *testing.T) {
t.Setenv("MESH_CONFIG_EVENT_OVERRUN", "1s")
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: "reader"}
if _, err := js.CreateOrUpdateConsumer(ctx, process.EventsStream, jetstream.ConsumerConfig{Durable: cred.EventConsumerName(), AckPolicy: jetstream.AckExplicitPolicy}); err != nil {
t.Fatal(err)
}
hub := process.NewEventHub(t.Logf)
release := make(chan struct{})
if err := hub.Handle("mesh.mod.p.event.slow", func(m jetstream.Msg) { <-release; _ = m.Ack() },
func(string, []byte) string { return "the-slow-key" }); err != nil {
t.Fatal(err)
}
found := &clearedFindings{put: make(chan string, 8), cleared: make(chan string, 8)}
r := &views.ProcessReader{Module: "reader", Hub: hub, Logf: t.Logf, Findings: func() views.WireWriter { return found }}
r.Start(ctx, nil, cred, nil)
if err := hub.Start(ctx, js, cred); err != nil {
t.Fatal(err)
}
defer hub.Stop()
for range 2 { // the start clears event-unhandled and event-overrun
<-found.cleared
}
if _, err := js.Publish(ctx, "mesh.mod.p.event.slow", []byte("{}")); err != nil {
t.Fatal(err)
}
select {
case got := <-found.put:
if !strings.HasPrefix(got, "event-overrun reader ") || !strings.Contains(got, "mesh.mod.p.event.slow (key the-slow-key) since ") {
t.Fatalf("the finding: %s", got)
}
case <-ctx.Done():
t.Fatal("a handling past event-overrun raised no finding")
}
close(release)
if got := <-found.cleared; got != "event-overrun reader" {
t.Fatalf("the handling ended and %s was cleared", got)
}
again := &views.ProcessReader{Module: "reader", Hub: process.NewEventHub(t.Logf), Logf: t.Logf, Findings: func() views.WireWriter { return found }}
again.Start(ctx, nil, cred, nil)
cleared := []string{<-found.cleared, <-found.cleared}
slices.Sort(cleared)
if cleared[0] != "event-overrun reader" || cleared[1] != "event-unhandled reader" {
t.Fatalf("the start cleared %v", cleared)
}
}
// seenFindings is a findings writer that hands each finding written to the test.
+23
View File
@@ -1562,3 +1562,26 @@ func TestAFirstViewIsUnreadUntilItsAnswerIsIn(t *testing.T) {
t.Fatalf("no phase kept: %v", none)
}
}
// Design 47 H2 H-A-697 (3): the finding event-overrun names each handling past the bound, the one begun first first, with its
// subject, its key and since when, at most five and then how many more.
func TestTheOverrunFindingNamesTheHandlingsOldestFirst(t *testing.T) {
at := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC)
past := func(n int) []process.Handling {
var out []process.Handling
for i := range n {
out = append(out, process.Handling{Subject: fmt.Sprintf("mesh.mod.m.event.e%d", i), Key: fmt.Sprintf("key%d", i), Since: at.Add(time.Duration(i) * time.Minute)})
}
return out
}
three := overrunFinding("builder", past(3), at)
if three.kind != EventOverrunKind || three.id != "builder" || !strings.Contains(three.summary, "3 event handlings") ||
strings.Index(three.summary, "e0 (key key0)") > strings.Index(three.summary, "e1 (key key1)") ||
strings.Index(three.summary, "e1 (key key1)") > strings.Index(three.summary, "e2 (key key2) since 2026-11-25T12:02:00Z") ||
strings.Contains(three.summary, "more") {
t.Errorf("three handlings: %+v", three)
}
if eight := overrunFinding("builder", past(8), at); !strings.Contains(eight.summary, "and 3 more") || strings.Contains(eight.summary, "e5 ") {
t.Errorf("eight handlings: %s", eight.summary)
}
}
+1 -1
View File
@@ -74,7 +74,7 @@ func requireFields[T any](what string, fields ...string) error {
}
// ViewKinds are the finding kinds a views reader writes through the part's writer (design 47 G §639).
var ViewKinds = []string{ViewWaitsKind, UnansweredKind, UnsaidKind, TooLargeKind, EntryNotFoundKind}
var ViewKinds = []string{ViewWaitsKind, UnansweredKind, UnsaidKind, TooLargeKind, EntryNotFoundKind, EventUnhandledKind, EventOverrunKind}
var (
sessionForm = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*@[a-z0-9][a-z0-9-]*$`)
+8 -1
View File
@@ -451,6 +451,12 @@ func subWriterKindsAndReaderFindings(t *testing.T) {
if err := views.PutViewFinding(r.w, views.ViewWaitsKind, "m.o.s", "waits", ""); err != nil {
t.Fatal(err)
}
// H-A-697 (2): a writer given its own kinds writes event-unhandled and event-overrun too, and states them.
for _, kind := range []string{views.EventUnhandledKind, views.EventOverrunKind} {
if err := views.PutViewFinding(r.w, kind, "m", "sum", "head"); err != nil {
t.Errorf("a writer given its own kinds refuses %s: %v", kind, err)
}
}
r.observe = func(context.Context) (testObserved, error) {
return testObserved{Findings: []testFinding{finding("a", "observed")}}, nil
}
@@ -472,7 +478,8 @@ func subWriterKindsAndReaderFindings(t *testing.T) {
_ = json.Unmarshal(e.data, &stated)
}
}
if !slices.Contains(stated.Kinds, "k") || !slices.Contains(stated.Kinds, views.ViewWaitsKind) || len(stated.Findings) != 2 {
if !slices.Contains(stated.Kinds, "k") || !slices.Contains(stated.Kinds, views.ViewWaitsKind) ||
!slices.Contains(stated.Kinds, views.EventUnhandledKind) || !slices.Contains(stated.Kinds, views.EventOverrunKind) || len(stated.Findings) != 4 {
t.Errorf("the statement: kinds %v, %d findings", stated.Kinds, len(stated.Findings))
}
if err := views.DropViewFinding(r.w, views.ViewWaitsKind, "m.o.s"); err != nil {