Files
mesh-delivery/modules/mesh-delivery-builder/cmd/mesh-delivery-builder/stepqueue.go
T
jschoubben 49bf651e32 Builder: say step-progress every minute while a build step builds or waits
A build step whose build waited for a package said nothing after ask-taken,
so the runner's bound of the ask ended it unanswered. The builder now says the
seat mesh-builds' step-progress of each ask it holds once a minute.

Builds: design 47 H2 H-A-514 addendum
2026-11-23 02:40:32 +01:00

366 lines
13 KiB
Go

package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshbuilds"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/buscompose"
"git.novox.be/novox/mesh-sdk/go/process"
"git.novox.be/novox/mesh-sdk/go/seatdef"
"mesh-delivery-builder/internal/build"
)
// **The seat mesh-builds takes its asks from a work queue and says ask-taken** (design 47 H2 §777, §775; ADR 0525 §1, §2,
// §6; ADR 0668 §2): the broker derives the seat's stream and its one shared worker from the seat's definition; the builder
// pulls every ask waiting at once, takes each once by its id in its state taken (TakenKey <seat>.<ask>, for
// ask-taken-bound; H-A-381 (2)), says ask-taken at the pull, sends in-progress while it builds, and acknowledges an ask
// when it said the ask's end. An ask put while the builder is down waits on the stream.
// askTakenBoundSetting is the setting the taken key's time to live is (H-A-381 (2)): the holder never receives the
// caller's bound, so the largest caller's, the runner's ask-unanswered-bound, is its default.
const (
askTakenBoundSetting = "ask-taken-bound"
defaultAskTakenBound = 10 * time.Minute
)
// askTaker is the state taken (process.State): an ask taken once by its id, and the drop of an ask not pulled yet kept
// under build.DroppedKey (H-A-404).
type askTaker interface {
TakeOnce(seat, ask string, bound time.Duration) (bool, error)
Get(key string) (*stdio.StateEntry, error)
CreateTTL(key string, value any, ttl time.Duration) (uint64, error)
}
// stepBuilder is build.Builder's BuildStep.
type stepBuilder interface {
BuildStep(ctx context.Context, ask string, run meshbuilds.StepRun) meshbuilds.StepEnded
}
// queueMsg is what the queue reads of a message pulled from the seat's work queue (jetstream.Msg).
type queueMsg interface {
Data() []byte
Headers() nats.Header
Ack() error
Nak() error
Term() error
InProgress() error
}
// stepQueue is the builder's pull of the seat mesh-builds' work queue.
type stepQueue struct {
node string
builder stepBuilder
taken askTaker
takenBound time.Duration
// inProgress is how often a running ask is said in progress: the seat definition's in-progress.
inProgress func() time.Duration
// progress is the clock step-progress is said on while an ask builds or its build waits for a package: every
// stepProgressEvery (design 47 H2 H-A-514 addendum); a test's when set.
progress func() (<-chan time.Time, func())
// say publishes a seat event of the builder (emitSeatEvent).
say func(ctx context.Context, subject, id string, body any) error
logf func(string, ...any)
now func() time.Time
mu sync.Mutex
running map[string]*runningAsk
}
// stepProgressEvery is how often the builder says step-progress of an ask it builds (design 47 H2 H-A-514 addendum): once a
// minute, as the seat mesh-wants' holder says its own.
const stepProgressEvery = time.Minute
// progressClock is the clock of step-progress: the test's, else a ticker of stepProgressEvery.
func (q *stepQueue) progressClock() (<-chan time.Time, func()) {
if q.progress != nil {
return q.progress()
}
t := time.NewTicker(stepProgressEvery)
return t.C, t.Stop
}
// runningAsk is an ask the builder took and builds now.
type runningAsk struct {
run meshbuilds.StepRun
taken time.Time
cancel context.CancelCauseFunc
}
// askIDOf is the ask's id a put carries: its event id, else its message id.
func askIDOf(h nats.Header) string {
if id := h.Get("x-event-id"); id != "" {
return id
}
return h.Get(nats.MsgIdHdr)
}
// take handles one ask pulled from the queue: an ask that is no build step with an id is terminated, said; one this
// builder runs already (handed again while it runs) is left to the run that holds it; any other is held here and handed to
// a worker of its own, started at once (design 47 H2 H-A-514): the pull never waits on a state call or a publish of an
// earlier ask, so each ask's ask-taken is said within its bound whatever the others do.
func (q *stepQueue) take(ctx context.Context, m queueMsg) {
id := askIDOf(m.Headers())
var run meshbuilds.StepRun
err := json.Unmarshal(m.Data(), &run)
if err != nil || id == "" || run.Step != meshbuilds.StepRunStepBuild {
q.logf("a step ask on the seat %s's work queue that is no build step with an id is ended: %v", meshbuilds.Seat, err)
_ = m.Term()
return
}
q.mu.Lock()
if _, held := q.running[id]; held {
q.mu.Unlock()
q.logf("the ask %s (%s) was handed again while it runs here: its run answers it", id, run.Pipeline)
return
}
work, cancel := context.WithCancelCause(ctx)
ra := &runningAsk{run: run, taken: q.now(), cancel: cancel}
q.running[id] = ra
q.mu.Unlock()
go q.work(ctx, work, m, id, ra)
}
// work is one ask's worker (H-A-514): an ask dropped before it was pulled ends could-not-run naming the drop, with no build
// (H-A-404); any other is taken once by its id in the state taken (ask-taken said the first time it is taken) and built, in
// progress while it runs, acknowledged once its end is said. A repeat of an id taken before that runs here no longer (the
// builder started again) is answered as its builds stand now, read afresh by BuildStep (H-A-381 (1)): an entry built is
// answered built, never built twice. An ask the state taken refuses is let go and handed again.
func (q *stepQueue) work(ctx, work context.Context, m queueMsg, id string, ra *runningAsk) {
if d := q.droppedAsk(id); d != nil {
ra.cancel(d)
q.logf("the ask %s (%s) was dropped before it was pulled: %s", id, ra.run.Pipeline, d.Error())
q.build(work, m, id, ra)
return
}
first, err := q.taken.TakeOnce(meshbuilds.Seat, id, q.takenBound)
if err != nil {
ra.cancel(nil)
q.mu.Lock()
delete(q.running, id)
q.mu.Unlock()
q.logf("the ask %s (%s) is not taken, the state %s refused it: %v; it is handed again", id, ra.run.Pipeline, process.TakenState, err)
_ = m.Nak()
return
}
if first {
if err := q.say(ctx, meshbuilds.SubjectAskTaken(id), id+"-taken", meshbuilds.AskTakenEvent{Ask: id, Node: q.node, At: ra.taken.UTC()}); err != nil {
q.logf("saying ask-taken of %s: %v", id, err)
}
} else {
q.logf("the ask %s (%s) was taken before: it is answered as its builds stand now", id, ra.run.Pipeline)
}
q.build(work, m, id, ra)
}
// build runs one taken ask to its end and says it.
func (q *stepQueue) build(ctx context.Context, m queueMsg, id string, ra *runningAsk) {
defer func() {
ra.cancel(nil)
q.mu.Lock()
delete(q.running, id)
q.mu.Unlock()
}()
every := q.inProgress()
var tick <-chan time.Time
if every > 0 {
t := time.NewTicker(every)
defer t.Stop()
tick = t.C
}
// step-progress is said every minute while the step builds or waits for a package, so the asker's bound of the ask is
// armed again (design 47 H2 H-A-514 addendum).
progress, stop := q.progressClock()
defer stop()
done := make(chan meshbuilds.StepEnded, 1)
go func() { done <- q.builder.BuildStep(ctx, id, ra.run) }()
var end meshbuilds.StepEnded
for waiting := true; waiting; {
select {
case end = <-done:
waiting = false
case <-tick:
_ = m.InProgress()
case at := <-progress:
p := meshbuilds.StepProgressEvent{Ask: id, Asker: ra.run.Pipeline, Phase: meshbuilds.StepProgressEventPhaseBuild, At: at.UTC()}
if err := q.say(ctx, meshbuilds.SubjectStepProgress(q.node), fmt.Sprintf("%s-progress-%d", id, at.UnixNano()), p); err != nil {
q.logf("saying step-progress of %s: %v", id, err)
}
}
}
if err := q.say(context.WithoutCancel(ctx), meshbuilds.SubjectStepEnded(q.node), id, end); err != nil {
q.logf("saying the end of the build step %s: %v; the ask is handed again", id, err)
_ = m.Nak()
return
}
_ = m.Ack()
}
// droppedAsk is the drop kept for the ask id in the state taken, nil for none.
func (q *stepQueue) droppedAsk(id string) *build.Dropped {
e, err := q.taken.Get(build.DroppedKey(id))
if err != nil || e == nil {
return nil
}
var d build.Dropped
if json.Unmarshal(e.Value, &d) != nil {
return nil
}
return &d
}
// drop is the seat mesh-builds' verb drop (§778; H-A-401, H-A-404): the drop is kept in the state taken under
// build.DroppedKey for ask-taken-bound, so a pull of the ask within the bound ends it, and an ask that runs here is
// cancelled; both end the step could-not-run naming the drop and who asked it. held says whether it ran here.
func (q *stepQueue) drop(id, by, why string) (held bool, err error) {
if strings.TrimSpace(id) == "" || strings.TrimSpace(why) == "" {
return false, errors.New("give the ask's id and why it is dropped")
}
d := &build.Dropped{By: by, Why: why}
if _, err := q.taken.CreateTTL(build.DroppedKey(id), d, q.takenBound); err != nil && !errors.Is(err, stdio.ErrChanged) {
return false, fmt.Errorf("the drop of %s is not kept in the state %s: %w", id, process.TakenState, err)
}
q.mu.Lock()
ra := q.running[id]
q.mu.Unlock()
if ra != nil {
ra.cancel(d)
}
q.logf("the ask %s is dropped by %s: %s", id, by, why)
return ra != nil, nil
}
// dropVerb is the handler of the seat mesh-builds' verb drop: who drops it is the input's by, else the caller.
func dropVerb(q *stepQueue) process.SeatHandler {
return func(caller string, body json.RawMessage) (any, error) {
var in meshbuilds.DropInput
if err := json.Unmarshal(body, &in); err != nil {
return nil, fmt.Errorf("the arguments do not fit the verb drop: %w", err)
}
by := in.By
if by == "" {
by = caller
}
held, err := q.drop(in.ID, by, in.Why)
if err != nil {
return nil, err
}
return meshbuilds.DropAnswer{"held": held}, nil
}
}
// running answers the asks this builder runs now, by id.
func (q *stepQueue) runningAsks() map[string]runningAsk {
q.mu.Lock()
defer q.mu.Unlock()
out := make(map[string]runningAsk, len(q.running))
for id, ra := range q.running {
out[id] = *ra
}
return out
}
// inProgressOf is the seat's in-progress as its definition names it, once the seat list is read; before, a third of the
// worker's ack wait, which the broker derived from the same definition (60 s and 20 s, §777).
func inProgressOf(def func() (seatdef.Definition, bool), ackWait func() time.Duration) func() time.Duration {
return func() time.Duration {
if d, ok := def(); ok {
if _, worker, ok, err := buscompose.SeatQueue(meshbuilds.Seat, d.Accepts); err == nil && ok && worker.InProgressSeconds > 0 {
return time.Duration(worker.InProgressSeconds) * time.Second
}
}
return ackWait() / 3
}
}
// serveSteps pulls the seat's work queue through its one shared worker, every ask waiting at once (at most the worker's
// max ack pending), once the broker made it: a worker not there yet is said, and bound when the bus says it was created.
// The advisories are heard for as long as the builder runs (design 47 H2 H-A-468 (2)): a worker deleted is let go and said,
// and bound again when the bus says it was created again.
func serveSteps(ctx context.Context, conn *nats.Conn, js jetstream.JetStream, q *stepQueue, ackWait *atomic.Int64) error {
stream, worker := buscompose.SeatQueueStreamName(meshbuilds.Seat), buscompose.SeatQueueWorkerName(meshbuilds.Seat)
var mu sync.Mutex
var pulling jetstream.ConsumeContext
bind := func() bool {
mu.Lock()
defer mu.Unlock()
if pulling != nil {
return true
}
c, err := js.Consumer(ctx, stream, worker)
if err != nil {
return false
}
info := c.CachedInfo()
if info != nil && info.Config.AckWait > 0 {
ackWait.Store(int64(info.Config.AckWait))
}
pending := 1000
if info != nil && info.Config.MaxAckPending > 0 {
pending = info.Config.MaxAckPending
}
cc, err := c.Consume(func(m jetstream.Msg) { q.take(ctx, m) }, jetstream.PullMaxMessages(pending))
if err != nil {
q.logf("the seat %s's work queue %s is not pulled: %v", meshbuilds.Seat, worker, err)
return false
}
pulling = cc
q.logf("pulling the seat %s's asks from %s", meshbuilds.Seat, worker)
return true
}
release := func() {
mu.Lock()
defer mu.Unlock()
if pulling == nil {
return
}
pulling.Stop()
pulling = nil
q.logf("the seat %s's work queue %s on %s was deleted: its asks wait on it, and it is pulled again when the bus says it was created", meshbuilds.Seat, worker, stream)
}
created, err := conn.Subscribe("$JS.EVENT.ADVISORY.CONSUMER.CREATED."+stream+"."+worker, func(*nats.Msg) { go bind() })
if err != nil {
return fmt.Errorf("hearing the creation of the seat %s's work queue: %w", meshbuilds.Seat, err)
}
deleted, err := conn.Subscribe("$JS.EVENT.ADVISORY.CONSUMER.DELETED."+stream+"."+worker, func(*nats.Msg) {
go func() {
release()
bind() // made again before the deletion was heard
}()
})
if err != nil {
_ = created.Unsubscribe()
return fmt.Errorf("hearing the deletion of the seat %s's work queue: %w", meshbuilds.Seat, err)
}
go func() {
<-ctx.Done()
_ = created.Unsubscribe()
_ = deleted.Unsubscribe()
release()
}()
if !bind() {
q.logf("the seat %s's work queue %s on %s is not there yet: its asks wait on it, and it is pulled when the bus says it was created", meshbuilds.Seat, worker, stream)
}
return nil
}
// askTakenBound reads the setting ask-taken-bound (§781).
func askTakenBound() (time.Duration, error) {
d, err := stdio.SettingDuration(askTakenBoundSetting, defaultAskTakenBound)
if err != nil {
return 0, errors.New("the builder's " + err.Error())
}
return d, nil
}