The builder bound the seat mesh-builds' worker once, under a sync.Once, and stopped hearing the bus's advisories after that, so a worker deleted and made again by the grants part was never pulled again and the asks piled up. The advisories CREATED and DELETED are now heard for as long as the builder runs: a deletion lets the worker go and says so, and a creation binds it again. The step test deletes the worker, makes it again and has an ask ended through it. Builds: design 47 H2 H-A-468 (2)
335 lines
12 KiB
Go
335 lines
12 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
|
|
// 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
|
|
}
|
|
|
|
// 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 taken (ask-taken said
|
|
// the first time its id is taken) and built on its own goroutine, 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.
|
|
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
|
|
}
|
|
// An ask dropped before it was pulled ends could-not-run naming the drop, with no build (H-A-404).
|
|
if d := q.droppedAsk(id); d != nil {
|
|
work, cancel := context.WithCancelCause(ctx)
|
|
cancel(d)
|
|
ra := &runningAsk{run: run, taken: q.now(), cancel: cancel}
|
|
q.running[id] = ra
|
|
q.mu.Unlock()
|
|
q.logf("the ask %s (%s) was dropped before it was pulled: %s", id, run.Pipeline, d.Error())
|
|
go q.build(work, m, id, ra)
|
|
return
|
|
}
|
|
first, err := q.taken.TakeOnce(meshbuilds.Seat, id, q.takenBound)
|
|
if err != nil {
|
|
q.mu.Unlock()
|
|
q.logf("the ask %s (%s) is not taken, the state %s refused it: %v; it is handed again", id, run.Pipeline, process.TakenState, err)
|
|
_ = m.Nak()
|
|
return
|
|
}
|
|
work, cancel := context.WithCancelCause(ctx)
|
|
ra := &runningAsk{run: run, taken: q.now(), cancel: cancel}
|
|
q.running[id] = ra
|
|
q.mu.Unlock()
|
|
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, run.Pipeline)
|
|
}
|
|
go 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
|
|
}
|
|
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()
|
|
}
|
|
}
|
|
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
|
|
}
|