385 lines
11 KiB
Go
385 lines
11 KiB
Go
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"
|
|
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
|
|
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
|
|
|
|
// 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) {
|
|
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
|
|
// 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
|
|
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, 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
|
|
}
|
|
|
|
// 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
|
|
}
|
|
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.slow, e.over, e.stopped = atOnce, bound, slow, over, 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()
|
|
}
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
|
|
// waitRoom waits while the hub holds as many messages as events-waiting allows, so the pull takes no more.
|
|
func (e *eventHold) waitRoom() {
|
|
e.mu.Lock()
|
|
for len(e.ids) >= e.bound && !e.stopped {
|
|
e.room.Wait()
|
|
}
|
|
e.mu.Unlock()
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
}
|