Files
mesh-catalog/modules/mesh-delivery-gate/cmd/mesh-delivery-gate/consumer.go
T
jschoubben 57984e9b98 GATE-5: the delivery record follows its pipeline to the machines
The record a merge call opened takes the runner's pipeline-started,
pipeline-ended, wait-held and wait-ended, the assigner's wanted and
pipeline-wanted and the node-engine seat's running, read by its key, and
ends on pipeline-wanted (running: every tier runs; tier-late: failed) or
failed on a pipeline that did not pass.

Builds: design 47 H §738 (G §141 to §147); H-A-29, H-A-75, H-A-89 (1) to (5)

Claude-Session: https://claude.ai/code/session_01JG73KHUnBze48rdua8u2sy
2026-11-20 03:33:56 +01:00

349 lines
12 KiB
Go

package main
// The delivery record's consumer (design 47 *The delivery record*: "The outcomes arrive as events, through a durable
// consumer of the gate's own"). The gate's manifest `consumes` each step event of *What each step says* and the waits'
// `wait-held` and `wait-ended`; the runtime binds the module's durable consumer for them (stdio.Subscribe), which resumes
// from the last event the gate took after a restart, and offers an event again until the gate took it. The gate takes an
// event only once its outcome is in every record that holds it, so an event the ledger could not take is offered again;
// one applied twice changes nothing (Records.Outcome); and one is applied only when it comes from its owner's account:
// the event's key is its owner and its event recovered from the subject, which the bus grants its owner's account alone
// (ADR 0363 §2), and an event a node publishes names that node in its subject and in its x-node header.
import (
"bytes"
"encoding/json"
"fmt"
ownmanifest "mesh-delivery-gate"
"strings"
"sync"
"time"
nodeengine "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
runner "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner"
wants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-indexer/takein"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// StepOutcome is what one step event says of one entry, or of the record's merge when it names no module: the merge
// commits it is for (an event of the whole change), or the entry's module, fingerprint and node.
type StepOutcome struct {
Commits []string
Module string
Fingerprint string
Node string
Step string
Outcome string
Why string
At time.Time
}
// stepFamily is one family of events the record is built from: the pattern its manifest consumes it by, its owner
// (the seat or module whose account alone publishes it), whether its subject names the node after the event, and how
// its body reads as outcomes.
type stepFamily struct {
Pattern string
Owner string
// Event is the event's name after its owner; the node is the token after it when NodeScoped.
Event string
NodeScoped bool
// Kind is the event's name on its owner's seat, with no subject tokens: what Follow is told it is.
Kind string
Decode func(body json.RawMessage, at time.Time) ([]StepOutcome, error)
}
// The step events on main the record is built from. A family is added here, with its `consumes` line, when its owner
// publishes it (design 47 *What each step says*); each other step's event is its owner's to add in the same milestone.
var stepFamilies = []stepFamily{
// An entry taken in (the holder of the seat mesh-catalog's own `take-in.taken`, ADR 0633 §1): the merges a source
// revision took in. Its owner is the one the manifest consumes it from.
family(takein.TakeInTakenEvent, decodeTakenIn),
// The record follows its pipeline to the machines (design 47 H §738, H-A-29, H-A-75, H-A-89; recordpipeline.go): the
// runner's pipeline-started, pipeline-ended, wait-held and wait-ended on <branch>.<source>, the assigner's wanted on
// <node>.<module> and pipeline-wanted on <branch>.<source>, and the node-engine seat's running on <node>.<module>.
seatFamily(runner.EventPipelineStarted, 2, false, decodePipelineStarted),
seatFamily(runner.EventPipelineEnded, 2, false, decodePipelineEnded),
seatFamily(runner.EventWaitHeld, 2, false, decodeWait),
seatFamily(runner.EventWaitEnded, 2, false, decodeWait),
seatFamily(wants.EventWanted, 2, false, decodeWanted),
seatFamily(wants.EventPipelineWanted, 2, false, decodePipelineWanted),
seatFamily(nodeengine.EventRunning, 2, true, decodeRunning),
}
// seatFamily is a step family of a seat's event its manifest consumes with each token of its subject a wildcard
// (`<seat>.<event>.*.*`); of a node's event, the node is the first token after the event.
func seatFamily(event string, tokens int, nodeScoped bool, decode func(json.RawMessage, time.Time) ([]StepOutcome, error)) stepFamily {
f := family(event+strings.Repeat(".*", tokens), decode)
f.Kind = event
if nodeScoped {
f.Event, f.NodeScoped = event, true
}
return f
}
// family is a step family of an event as the manifest consumes it: `<owner>.<event>`.
func family(event string, decode func(json.RawMessage, time.Time) ([]StepOutcome, error)) stepFamily {
pattern := declared(event)
owner, _, _ := strings.Cut(pattern, ".")
return stepFamily{Pattern: pattern, Owner: owner, Event: event, Kind: event, Decode: decode}
}
// consumed is what the gate's manifest consumes (its own manifest): every event it follows is one of them.
var consumed = func() []string {
c, err := ownmanifest.Consumes()
if err != nil {
panic(err)
}
return c
}()
// declared is the event the manifest consumes under this name after its owner, `<owner>.<event>`: the gate names no
// other module in code. Empty, and so never followed or matched, when the manifest consumes none.
func declared(event string) string {
for _, c := range consumed {
if _, name, ok := strings.Cut(c, "."); ok && name == event {
return c
}
}
return ""
}
// stepPatterns are the patterns of every family, in the order the manifest consumes them.
func stepPatterns() []string {
out := make([]string, 0, len(stepFamilies))
for _, f := range stepFamilies {
out = append(out, f.Pattern)
}
return out
}
// decodeTakenIn reads a take-in.taken in the seat mesh-catalog's form, refusing a field it does not know, and answers no
// outcome: the take-in is written into its record by its key (takenin.go, H-A-29).
func decodeTakenIn(body json.RawMessage, _ time.Time) ([]StepOutcome, error) {
var t meshcatalog.TakeInTaken
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
if err := dec.Decode(&t); err != nil {
return nil, err
}
if t.Branch == "" || t.Source < 1 {
return nil, fmt.Errorf("a take-in.taken names no branch or source revision")
}
return nil, nil
}
// StepConsumer applies the step events to the records.
type StepConsumer struct {
Records *Records
Families []stepFamily
Now func() time.Time
Logf func(format string, a ...any)
// Taken writes a take-in.taken into the record of its source revision (takenin.go).
Taken func(body json.RawMessage) error
// Follow writes an event of the record's pipeline families into the record of its source revision, told the event's
// kind (recordpipeline.go).
Follow func(kind string, body json.RawMessage) error
mu sync.Mutex
// heard counts, per family, the events applied, refused and the last applied, since this owner started.
heard map[string]*familyHeard
}
type familyHeard struct {
Applied int `json:"applied"`
Refused int `json:"refused"`
Last time.Time `json:"last,omitzero"`
Why string `json:"last-refused,omitempty"`
}
func (c *StepConsumer) now() time.Time {
if c.Now == nil {
return time.Now().UTC()
}
return c.Now().UTC()
}
func (c *StepConsumer) logf(format string, a ...any) {
if c.Logf != nil {
c.Logf(format, a...)
}
}
// familyOf is the family an event's key belongs to.
func (c *StepConsumer) familyOf(key string) (stepFamily, bool) {
for _, f := range c.Families {
if stdio.TopicMatches(f.Pattern, key) || (f.NodeScoped && strings.HasPrefix(key, f.Owner+"."+f.Event+".")) {
return f, true
}
}
return stepFamily{}, false
}
// Takes is whether the consumer takes events of this key.
func (c *StepConsumer) Takes(key string) bool { _, ok := c.familyOf(key); return ok }
// Hear applies one event. It answers an error only when an outcome could not be written, so the event is offered
// again; an event of no family, from another account than its owner's, or that cannot be read is said and taken, since
// offered again it would be refused again.
func (c *StepConsumer) Hear(e stdio.Envelope) error {
f, ok := c.familyOf(e.Key)
if !ok {
return nil
}
if why := ownerRefusal(f, e); why != "" {
c.count(f, false, why)
c.logf("[mesh-delivery] the record does not take %s: %s", e.Key, why)
return nil
}
at := c.now()
outcomes, err := f.Decode(e.Body, at)
if err != nil {
why := fmt.Sprintf("its body is not readable: %v", err)
c.count(f, false, why)
c.logf("[mesh-delivery] the record does not take %s: %s", e.Key, why)
return nil
}
if f.Event == takein.TakeInTakenEvent && c.Taken != nil {
if err := c.Taken(e.Body); err != nil {
return fmt.Errorf("the record of %s is not opened yet: %w", e.Key, err)
}
} else if f.Event != takein.TakeInTakenEvent && c.Follow != nil {
if err := c.Follow(f.Kind, e.Body); err != nil {
return fmt.Errorf("the record of %s is not written yet: %w", e.Key, err)
}
}
id := e.Headers["x-event-id"]
for _, o := range outcomes {
if f.NodeScoped && o.Node == "" {
o.Node = e.Node
}
if err := c.apply(o, id); err != nil {
return fmt.Errorf("the outcome of %s is not recorded yet: %w", e.Key, err)
}
}
c.count(f, true, "")
return nil
}
// ownerRefusal is why an event did not come from its owner's account, or "": its key names its owner, and an event of a
// node names the node its x-node header says.
func ownerRefusal(f stepFamily, e stdio.Envelope) string {
rest, ok := strings.CutPrefix(e.Key, f.Owner+".")
if !ok {
return fmt.Sprintf("it is not %s's own event", f.Owner)
}
if !f.NodeScoped {
return ""
}
after, ok := strings.CutPrefix(rest, f.Event+".")
node, _, _ := strings.Cut(after, ".")
if !ok || node == "" {
return "its subject names no node"
}
if e.Node != node {
return fmt.Sprintf("its subject names the node %s and it came from %q", node, e.Node)
}
return ""
}
// apply writes an outcome into every record that holds it, by its merge commits or by its entry: an open record, or one
// that ended without the node the outcome comes from (a node away that wakes adds its outcomes, and is no longer shown
// away). It ends no record: the assigner's pipeline-wanted does (design 47 H §738, H-A-89 (4)).
func (c *StepConsumer) apply(o StepOutcome, event string) error {
records, err := c.Records.Kept()
if err != nil {
return err
}
for _, r := range records {
_, fromAway := r.Away[o.Node]
fromAway = fromAway && o.Node != ""
if (r.Ended != nil && !fromAway) || !holds(r, o) {
continue
}
ro := RecordOutcome{Module: o.Module, Fingerprint: o.Fingerprint, Node: o.Node, Step: o.Step, Outcome: o.Outcome,
Why: o.Why, At: o.At, Event: event}
if _, err := c.Records.Outcome(r, ro); err != nil {
return err
}
if fromAway {
if err := c.Records.NodeBack(r, o.Node); err != nil {
return err
}
}
}
return nil
}
// holds is whether a record is the one an outcome is for: one of its members merged as a commit the outcome names, or
// its difference holds the entry.
func holds(r *Record, o StepOutcome) bool {
if len(o.Commits) > 0 {
for _, m := range r.mergedAs() {
for _, c := range o.Commits {
if sameCommit(m, c) {
return true
}
}
}
return false
}
_, ok := r.Entries[EntryKey(o.Module, o.Fingerprint, o.Node)]
if !ok && o.Node != "" {
_, ok = r.Entries[EntryKey(o.Module, o.Fingerprint, "")]
}
return ok
}
// mergedAs are the commits the record's members merged as.
func (r *Record) mergedAs() []string {
var out []string
for _, c := range r.Heads {
out = append(out, c)
}
if r.Group == nil {
return out
}
for _, p := range r.Group.Pulls {
if p.Commit != "" {
out = append(out, p.Commit)
}
}
return out
}
func (c *StepConsumer) count(f stepFamily, applied bool, why string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.heard == nil {
c.heard = map[string]*familyHeard{}
}
h := c.heard[f.Pattern]
if h == nil {
h = &familyHeard{}
c.heard[f.Pattern] = h
}
if applied {
h.Applied++
h.Last = c.now()
} else {
h.Refused++
h.Why = why
}
}
// Heard is, per family, what the consumer took since this owner started.
func (c *StepConsumer) Heard() map[string]familyHeard {
c.mu.Lock()
defer c.mu.Unlock()
out := map[string]familyHeard{}
for _, f := range c.Families {
if h := c.heard[f.Pattern]; h != nil {
out[f.Pattern] = *h
} else {
out[f.Pattern] = familyHeard{}
}
}
return out
}