Files
mesh-tools/node-tools/internal/bus/seat_pull.go
T
jschoubben a75d86236b Tool runner bus: pulled workers belong to their connection; two tests wait for what they assert
A worker bound for a pull was kept for the process, so a later connection's pull
used a worker bound on a closed connection and answered "connection closed"
(every run of TestAHolderPullsOneMessageWhenItHasRoom after the first). The
bound workers and the pulled messages are now the Conn's.

The two tests that failed main.165 and main.115 asserted on bus figures before
the bus had delivered them: the worker's pending count right after a publish, a
no-wait pull right after a publish, a callback counter read when a flush
returned, a 300 ms delay and a 2 s ack wait a loaded machine overruns. They now
count binds on a channel the watcher's reader fills, pull with a wait that ends
at the delivery, prove "nothing fetched ahead" by the second message's first
delivery, and use bounds a loaded machine stays within.

Builds: design 47 H H-A-363 (fix-a-bug-met-twice; whole-module tests under load, H-A-327)
2026-11-21 23:39:25 +01:00

206 lines
6.7 KiB
Go

package bus
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"strings"
"sync"
"time"
"github.com/nats-io/nats.go/jetstream"
)
// **A holder that pulls one piece of work when it has room** (novox/hq ADR 0525 §4, §6; issue 1887 A11). SeatTake
// hands a bundle every piece a worker holds, one at a time and prefetched; a build module must instead take one ask
// only when it has a free slot, from its workers in their order (delivery, then check, then recheck), and decide each
// ask's fate when its step ends. SeatPull is one fetch of at most one message from a worker the module's membership
// lists, never a prefetch; SeatSettle gives a pulled message its fate. A message the bundle never settles (its process
// died) is delivered again by the worker's own acknowledgement wait.
// MaxPullWait bounds how long one pull waits for a message: under the bundle's 30 s wait for its answer.
var MaxPullWait = 25 * time.Second
// Pulled is one message a module pulled from a seat's worker, named by an id the runtime gave it.
type Pulled struct {
ID string `json:"id"`
Worker string `json:"worker"`
Subject string `json:"subject"`
Body json.RawMessage `json:"body"`
Headers map[string]string `json:"headers,omitempty"`
Delivered uint64 `json:"delivered"`
}
// pulls are the messages modules pulled on one connection and have not settled, by id, each kept with the module it was
// pulled for, so one module never settles another's; and the workers bound on that connection. They are the Conn's, not
// the process's: a worker bound on a connection since closed answered every later pull "connection closed" (design
// 47 H, H-A-363: state outliving the connection it was made on).
type pulls struct {
mu sync.Mutex
held map[string]pulledMsg
cons map[string]jetstream.Consumer // by module and consumer
}
type pulledMsg struct {
module string
msg jetstream.Msg
}
func pullID() string {
var b [8]byte
_, _ = rand.Read(b[:])
return hex.EncodeToString(b[:])
}
// SeatPull fetches at most one message from consumer for module, waiting at most wait (none when 0): nil when none
// came. The consumer must be one the module's membership lists as its worker (novox/hq ADR 0259); the runtime binds to
// it by name and never makes one.
func (c *Conn) SeatPull(module, consumer string, wait time.Duration) (*Pulled, error) {
t, err := c.trafficOf(module)
if err != nil {
return nil, err
}
var w *SeatWorker
var names []string
for i := range t.Workers {
names = append(names, t.Workers[i].Consumer)
if t.Workers[i].Consumer == consumer {
w = &t.Workers[i]
}
}
if w == nil {
return nil, fmt.Errorf("%s pulls no work from %s: its membership lists %s (novox/hq ADR 0259)", module,
consumer, strings.Join(names, ", "))
}
if wait > MaxPullWait {
wait = MaxPullWait
}
bound, err := c.pullConsumer(module, *w)
if err != nil {
return nil, err
}
var batch jetstream.MessageBatch
if wait <= 0 {
batch, err = bound.FetchNoWait(1)
} else {
batch, err = bound.Fetch(1, jetstream.FetchMaxWait(wait))
}
if err != nil {
return nil, fmt.Errorf("pulling %s's worker %s: %w", module, w.Consumer, err)
}
msg, ok := <-batch.Messages()
if !ok {
if err := batch.Error(); err != nil {
return nil, fmt.Errorf("pulling %s's worker %s: %w", module, w.Consumer, err)
}
return nil, nil
}
if !json.Valid(msg.Data()) {
_ = msg.Term()
return nil, nil
}
headers := map[string]string{}
for k := range msg.Headers() {
headers[k] = msg.Headers().Get(k)
}
delivered := uint64(1)
if meta, merr := msg.Metadata(); merr == nil && meta != nil {
delivered = meta.NumDelivered
}
p := &Pulled{ID: pullID(), Worker: w.Consumer, Subject: msg.Subject(), Body: json.RawMessage(msg.Data()),
Headers: headers, Delivered: delivered}
c.pulls.mu.Lock()
if c.pulls.held == nil {
c.pulls.held = map[string]pulledMsg{}
}
c.pulls.held[p.ID] = pulledMsg{module: module, msg: msg}
c.pulls.mu.Unlock()
return p, nil
}
func (c *Conn) pullConsumer(module string, w SeatWorker) (jetstream.Consumer, error) {
key := module + " " + w.Consumer
c.pulls.mu.Lock()
bound, ok := c.pulls.cons[key]
c.pulls.mu.Unlock()
if ok {
return bound, nil
}
js, err := jetstream.New(c.nc)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
bound, err = js.Consumer(ctx, w.Stream, w.Consumer)
if err != nil {
return nil, fmt.Errorf("binding %s's worker %s on %s: %w", module, w.Consumer, w.Stream, err)
}
c.pulls.mu.Lock()
if c.pulls.cons == nil {
c.pulls.cons = map[string]jetstream.Consumer{}
}
c.pulls.cons[key] = bound
c.pulls.mu.Unlock()
return bound, nil
}
// The fates SeatSettle gives a pulled message.
const (
SettleAck = "ack" // done: never delivered again
SettleNak = "nak" // handed back, to be delivered again at once
SettleTerm = "term" // dropped
SettleProgress = "progress" // still being worked: its acknowledgement wait starts again
// SettleNakAfter hands the message back to be delivered again after a delay: the bus's own redelivery, so no part
// keeps a timer for a step given again (novox/hq ADR 0664 §1; issue 1748). SeatSettleAfter gives it.
SettleNakAfter = "nak-after"
)
// SeatSettle gives the message module pulled under id its fate. A message pulled for another module, or settled
// already, is refused.
func (c *Conn) SeatSettle(module, id, fate string) error {
return c.settle(module, id, fate, 0)
}
// SeatSettleAfter hands the message module pulled under id back to be delivered again after delay (SettleNakAfter),
// counting one more delivery. A delay of 0 or below is refused and settles nothing.
func (c *Conn) SeatSettleAfter(module, id string, delay time.Duration) error {
if delay <= 0 {
return fmt.Errorf("a message given again after a delay needs a delay above 0, not %s", delay)
}
return c.settle(module, id, SettleNakAfter, delay)
}
func (c *Conn) settle(module, id, fate string, delay time.Duration) error {
c.pulls.mu.Lock()
p, ok := c.pulls.held[id]
if ok && p.module != module {
ok = false
}
if ok && fate != SettleProgress {
delete(c.pulls.held, id)
}
c.pulls.mu.Unlock()
if !ok {
return fmt.Errorf("%s holds no pulled message %s", module, id)
}
switch fate {
case SettleAck:
return p.msg.Ack()
case SettleNak:
return p.msg.Nak()
case SettleTerm:
return p.msg.Term()
case SettleProgress:
return p.msg.InProgress()
case SettleNakAfter:
return p.msg.NakWithDelay(delay)
}
c.pulls.mu.Lock()
c.pulls.held[id] = p // an unknown fate settles nothing
c.pulls.mu.Unlock()
return fmt.Errorf("a pulled message's fate is ack, nak, nak-after, term or progress, not %q", fate)
}