272 lines
7.2 KiB
Go
272 lines
7.2 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"
|
|
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)
|
|
}
|
|
}
|