B16 events-by-key (1): the builder's events go through mesh-sdk's hub by key; its eventWorkers go

Builds: design 47 H2 H-A-683 (1), H-A-695, H-A-737 (1)
This commit is contained in:
2026-11-25 17:27:21 +01:00
parent 94afdcb6b4
commit d77bff56c4
4 changed files with 54 additions and 121 deletions
@@ -14,6 +14,7 @@ import (
// handlers is where a part of the builder registers its handler of the events it hears: the event hub, or agedHub over it.
type handlers interface {
Handle(pattern string, handle func(jetstream.Msg)) error
HandleByKey(pattern string, key process.EventKey, handle func(jetstream.Msg)) error
}
// ledgers are the builder's durable consumers' ledgers, one per consumer as a message's metadata names it (the events consumer
@@ -56,7 +57,16 @@ type agedHub struct {
}
func (a agedHub) Handle(pattern string, handle func(jetstream.Msg)) error {
return a.hub.Handle(pattern, func(m jetstream.Msg) {
return a.hub.Handle(pattern, a.aged(handle))
}
// HandleByKey registers handle held by key, each message noted as Handle's are.
func (a agedHub) HandleByKey(pattern string, key process.EventKey, handle func(jetstream.Msg)) error {
return a.hub.HandleByKey(pattern, key, a.aged(handle))
}
func (a agedHub) aged(handle func(jetstream.Msg)) func(jetstream.Msg) {
return func(m jetstream.Msg) {
led := a.ledgers.of(m)
if led == nil {
handle(m)
@@ -64,7 +74,7 @@ func (a agedHub) Handle(pattern string, handle func(jetstream.Msg)) error {
}
led.Delivered(m)
handle(&agedMsg{Msg: m, ledger: led})
})
}
}
// agedMsg is a message whose acknowledgement or end is noted applied on its consumer's ledger, once.
@@ -3,12 +3,12 @@ package main
import (
"encoding/json"
"errors"
"slices"
"sync"
"strings"
"time"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
stdio "git.novox.be/novox/mesh-sdk/go"
@@ -60,78 +60,29 @@ func takeEvent(m jetstream.Msg, takers []eventTaker, rest eventTaker, slow time.
}
}
// eventWorkers hands each event of the builder's durable to a worker of its key (design 47 H2 H-A-514 addenda): the name the
// event carries (a registry seat's outcome's package name, a version-released's module), one shared worker for the events that
// name none. One key's events are handled in the order heard, the keys side by side, so a slow event of one name delays no
// other name's. A worker ends when its queue is empty. The builder holds no timer (ADR 0437 §8), so the events still waiting in
// a queue are said in progress to the bus each time its worker ends a handling, and none waits out the ack wait behind another.
type eventWorkers struct {
handle func(jetstream.Msg)
keyOf func(jetstream.Msg) string
mu sync.Mutex
queues map[string]*eventQueue
}
// eventQueue is one key's events not yet handled, the one handled now first.
type eventQueue struct{ msgs []jetstream.Msg }
// take queues m on its key's worker, starting the worker when none runs.
func (w *eventWorkers) take(m jetstream.Msg) {
key := w.keyOf(m)
w.mu.Lock()
if w.queues == nil {
w.queues = map[string]*eventQueue{}
}
q, running := w.queues[key]
if !running {
q = &eventQueue{}
w.queues[key] = q
}
q.msgs = append(q.msgs, m)
w.mu.Unlock()
if !running {
go w.run(key, q)
}
}
// run handles key's events in order until its queue is empty, saying those still waiting in progress after each.
func (w *eventWorkers) run(key string, q *eventQueue) {
for {
w.mu.Lock()
if len(q.msgs) == 0 {
delete(w.queues, key)
w.mu.Unlock()
return
}
m := q.msgs[0]
w.mu.Unlock()
w.handle(m)
w.mu.Lock()
q.msgs = q.msgs[1:]
waiting := slices.Clone(q.msgs)
w.mu.Unlock()
for _, m := range waiting {
_ = m.InProgress()
}
}
}
// eventKey is the worker key of a builder's event (H-A-514 second addendum): a registry seat's outcome's name, a
// version-released's module, else "" (one worker for the events naming none).
func eventKey(m jetstream.Msg) string {
if _, ok := seatEvents[m.Subject()]; ok {
// eventKey is the key the hub holds a builder's event under (design 47 H2 H-A-683 (1), H-A-737 (1)): a registry seat's outcome's
// name, a version-released's module, the node the subject of the seat node-engine's running and manifest-reads-changed names,
// else "" (the events naming none share one key). One key's events are handled one at a time in the order heard, the keys side by
// side, so a slow handling of one node's event holds back no other node's.
func eventKey(subject string, data []byte) string {
if _, ok := seatEvents[subject]; ok {
var o versions.Outcome
if json.Unmarshal(m.Data(), &o) == nil {
if json.Unmarshal(data, &o) == nil {
return "name " + o.Name
}
return ""
}
if m.Subject() == meshcatalog.SubjectVersionReleased {
if subject == meshcatalog.SubjectVersionReleased {
var ev meshcatalog.VersionReleasedEvent
if json.Unmarshal(m.Data(), &ev) == nil {
if json.Unmarshal(data, &ev) == nil {
return "module " + ev.Module
}
return ""
}
// mesh.seat.node-engine.event.running.<node>.<module> and mesh.seat.node-engine.event.manifest-reads-changed.<node>
if t := strings.Split(subject, "."); len(t) >= 6 && t[2] == "node-engine" && t[3] == "event" &&
(t[4] == nodeengine.EventRunning || t[4] == nodeengine.EventManifestReadsChanged) {
return "node " + t[5]
}
return ""
}
@@ -483,9 +483,8 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
{"the registry seats' outcomes", func(m jetstream.Msg) bool { return seatHeard.heard(ctx, m) }},
}
gone := eventTaker{"the artifacts gone", func(m jetstream.Msg) bool { heardGone(ctx, b, m, logger.Printf); return true }}
// Each event goes to a worker of the name it carries, one name's events in order, the names side by side (H-A-514 addenda).
workers := &eventWorkers{keyOf: eventKey, handle: func(m jetstream.Msg) { takeEvent(m, takers, gone, slow, nil, logger.Printf) }}
events := workers.take
// The hub holds each event under its key (eventKey), one key's events in order, the keys side by side (H-A-683 (1), H-A-737 (1)).
events := func(m jetstream.Msg) { takeEvent(m, takers, gone, slow, nil, logger.Printf) }
// The seats' events (artifacts-gone, the registry seats' words, the build seats' toolchain-reported, the indexer's take-in.taken and
// manifest-reads-changed and the seat mesh-conditions' condition-cleared: seatEventPatterns); the owners' views events and the
// catalog half's catalog-revision and registration-changed and the gate's source-moved are the views reader's (a message has
@@ -534,7 +533,7 @@ func run(ctx context.Context, getenv func(string) string, logOut io.Writer) erro
seatGate.Follow(seatlist.ProcessBus(calls.Call, aged), func() { seatsChanged(ctx); b.SayUnbuildable(ctx) }, logger.Printf)
half.holders = func() { seatsChanged(ctx) }
for _, pattern := range seatEventPatterns {
if err := aged.Handle(pattern, events); err != nil {
if err := aged.HandleByKey(pattern, eventKey, events); err != nil {
return err
}
}
@@ -7,7 +7,6 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds"
"slices"
"strings"
"sync/atomic"
"testing"
"time"
@@ -19,6 +18,7 @@ import (
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/process"
"mesh-delivery-builder/internal/versions"
)
@@ -875,62 +875,35 @@ func TestAPublishedThatMarksNothingIsSaidFromWhatItRead(t *testing.T) {
})
}
// Design 47 H2 H-A-514 addenda: each event goes to the worker of the name it carries, so a slow handling of one name holds
// no other name's events, one name's events are handled in the order heard, and an event waiting in its worker's queue is
// said in progress at each tick, so the bus does not give it again.
func TestEventsAreHandledByAWorkerPerName(t *testing.T) {
pub := func(name, v string) *queuedEvent {
return &queuedEvent{wakeMsg: wakeMsg{subject: gopackageregistry.SubjectPublished, data: []byte(`{"name":"` + name + `","version":"` + v + `","digest":"sha256:aa"}`)}}
}
if got := eventKey(&pub("a", "1").wakeMsg); got != "name a" {
t.Errorf("a published's key is %q, want its name", got)
}
if got := eventKey(&wakeMsg{subject: meshcatalog.SubjectVersionReleased, data: []byte(`{"module":"m","version":"0.1.0"}`)}); got != "module m" {
t.Errorf("a version-released's key is %q, want its module", got)
}
if got := eventKey(&wakeMsg{subject: "mesh.seat.mesh-artifact-sweep.event.artifacts-gone", data: []byte(`{}`)}); got != "" {
t.Errorf("an event naming no name has the key %q, want the shared worker's", got)
}
release := make(chan struct{})
handled := make(chan string, 4)
w := &eventWorkers{keyOf: eventKey, handle: func(m jetstream.Msg) {
var o versions.Outcome
_ = json.Unmarshal(m.Data(), &o)
if o.Name == "a" && o.Version == "1" {
<-release
// Design 47 H2 H-A-683 (1), H-A-737 (1): the builder gives the hub each pattern's key: a registry seat's outcome by its name,
// version-released by its module, the seat node-engine's running and manifest-reads-changed by the node their subject names;
// the hub holds one key's events in order and the keys side by side (mesh-sdk's tests).
func TestEventsAreHeldByTheKeyTheyName(t *testing.T) {
for _, c := range []struct {
name, subject, body, want string
}{
{"a registry seat's outcome by its name", gopackageregistry.SubjectPublished, `{"name":"a","version":"1","digest":"sha256:aa"}`, "name a"},
{"a version-released by its module", meshcatalog.SubjectVersionReleased, `{"module":"m","version":"0.1.0"}`, "module m"},
{"a running by its node", "mesh.seat.node-engine.event.running.ace.mod", `{}`, "node ace"},
{"a manifest-reads-changed by its node", "mesh.seat.node-engine.event.manifest-reads-changed.g14", `{}`, "node g14"},
{"another node's manifest-reads-changed by its node", "mesh.seat.node-engine.event.manifest-reads-changed.ace", `{}`, "node ace"},
{"another event of the seat node-engine shares", "mesh.seat.node-engine.event.composed.ace", `{}`, ""},
{"an event naming none shares", "mesh.seat.mesh-artifact-sweep.event.artifacts-gone", `{}`, ""},
} {
if got := eventKey(c.subject, []byte(c.body)); got != c.want {
t.Errorf("%s: the key is %q, want %q", c.name, got, c.want)
}
handled <- o.Name + "@" + o.Version
}}
a1, a2, a3, b1 := pub("a", "1"), pub("a", "2"), pub("a", "3"), pub("b", "1")
w.take(a1)
w.take(a2)
w.take(a3)
w.take(b1)
if got := <-handled; got != "b@1" {
t.Fatalf("handled %s first, want b's event while a's first one is slow", got)
}
close(release)
if got := []string{<-handled, <-handled, <-handled}; !slices.Equal(got, []string{"a@1", "a@2", "a@3"}) {
t.Errorf("a's events handled %v, want in the order heard", got)
}
// a's worker said its waiting events in progress at each end: a2 and a3 after a1, a3 again after a2.
if a1.progressed.Load() != 0 || a2.progressed.Load() != 1 || a3.progressed.Load() != 2 {
t.Errorf("in progress said %d, %d and %d times of a's events, want 0, 1 and 2", a1.progressed.Load(), a2.progressed.Load(), a3.progressed.Load())
}
}
// queuedEvent is an event of the builder's durable that counts its in-progress.
type queuedEvent struct {
wakeMsg
progressed atomic.Int32
}
func (m *queuedEvent) InProgress() error { m.progressed.Add(1); return nil }
// oneHandler is an event hub with one handler.
type oneHandler struct{ handle func(jetstream.Msg) }
func (h *oneHandler) Handle(_ string, f func(jetstream.Msg)) error { h.handle = f; return nil }
func (h *oneHandler) HandleByKey(_ string, _ process.EventKey, f func(jetstream.Msg)) error {
h.handle = f
return nil
}
// agedTestMsg is a message of the builder's events consumer, with the metadata a ledger reads.
type agedTestMsg struct {