diff --git a/node-tools/internal/bus/bus.go b/node-tools/internal/bus/bus.go index 3a04870..f7a4737 100644 --- a/node-tools/internal/bus/bus.go +++ b/node-tools/internal/bus/bus.go @@ -212,6 +212,8 @@ type Conn struct { bound map[string]*binding // bind binds one bucket: jetstream's KeyValue (a stream-info request on the bus) unless a test replaces it. bind func(ctx context.Context, bucket string) (jetstream.KeyValue, error) + // pulls are the workers bound and the messages pulled on this connection (seat_pull.go). + pulls pulls } // answered is one subject the runtime answers on: what to subscribe again with, and how often it was @@ -425,29 +427,33 @@ func (c *Conn) issue(module string, m Membership) { // right after its boot, a timeout), is said once and read again, with a growing wait, until it can be or the // connection closes: Follow runs once per module, so nothing else would ever read it again. func (c *Conn) followGrants(module string) { - if c.watchGrants(module, true) { + // Read here, not in the loop: the loop outlives Follow, and a test sets them back as it ends (design 47 H, H-A-363). + patience, timeout := GrantsPatience, StateTimeout + if c.watchGrants(module, true, patience, timeout) { return } + wait, most := GrantsRetry, GrantsRetryMost go func() { - wait := GrantsRetry for !c.nc.IsClosed() { time.Sleep(wait) if c.nc.IsClosed() { return } - if c.watchGrants(module, false) { + if c.watchGrants(module, false, patience, timeout) { c.Logf("[mesh-tools] the grants part's memberships are read again; %s on %s follows its key", module, c.node) return } - if wait *= 2; wait > GrantsRetryMost { - wait = GrantsRetryMost + if wait *= 2; wait > most { + wait = most } } }() } -// watchGrants is one attempt of followGrants: true once the key is watched. A failure is said when say is true. -func (c *Conn) watchGrants(module string, say bool) bool { +// watchGrants is one attempt of followGrants: true once the key is watched. A failure is said when say is true. Its +// bounds, patience for the key's direct get and timeout for the bucket and its current value, are GrantsPatience and +// StateTimeout as they stood when followGrants began. +func (c *Conn) watchGrants(module string, say bool, patience, timeout time.Duration) bool { logf := func(format string, a ...any) { if say { c.Logf(format, a...) @@ -457,7 +463,7 @@ func (c *Conn) watchGrants(module string, say bool) bool { // First the key's direct get, which the account is granted alone: a bus that refuses it, or a state not there yet, // answers at once, where binding the bucket would wait out its bound on a refusal. bucket := membership.GrantsBucket - probe, err := c.nc.Request("$JS.API.DIRECT.GET.KV_"+bucket+".$KV."+bucket+"."+key, nil, GrantsPatience) + probe, err := c.nc.Request("$JS.API.DIRECT.GET.KV_"+bucket+".$KV."+bucket+"."+key, nil, patience) if err != nil || probe.Header.Get("Status") == "503" { why := "it did not answer" if err != nil { @@ -471,7 +477,7 @@ func (c *Conn) watchGrants(module string, say bool) bool { if err != nil { return false } - ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) + ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() kv, err := js.KeyValue(ctx, bucket) if err != nil { @@ -504,7 +510,7 @@ func (c *Conn) watchGrants(module string, say bool) bool { } c.issue(module, m) } - timer := time.NewTimer(StateTimeout) + timer := time.NewTimer(timeout) defer timer.Stop() for current := true; current; { select { @@ -520,7 +526,7 @@ func (c *Conn) watchGrants(module string, say bool) bool { case <-timer.C: _ = w.Stop() logf("[mesh-tools] %s's key %s of the grants part's memberships did not answer in %s; %s has no membership "+ - "until it can be", module, key, StateTimeout, module) + "until it can be", module, key, timeout, module) return false } } diff --git a/node-tools/internal/bus/seat.go b/node-tools/internal/bus/seat.go index f703d16..2a9f8c8 100644 --- a/node-tools/internal/bus/seat.go +++ b/node-tools/internal/bus/seat.go @@ -279,6 +279,8 @@ func (c *Conn) SeatTake(module, consumer string, deliver func(Work) error) (func if err != nil { return nil, fmt.Errorf("binding %s's worker %s on %s: %w", module, w.Consumer, w.Stream, err) } + // Read once, as the take starts: its loop outlives SeatTake, and a test sets it back as it ends (design 47 H, H-A-363). + heartbeat := WorkHeartbeat reading, err := bound.Consume(func(msg jetstream.Msg) { if !json.Valid(msg.Data()) { _ = msg.Term() @@ -292,7 +294,7 @@ func (c *Conn) SeatTake(module, consumer string, deliver func(Work) error) (func // that died, not one that is slow. done := make(chan struct{}) go func() { - tick := time.NewTicker(WorkHeartbeat) + tick := time.NewTicker(heartbeat) defer tick.Stop() for { select { diff --git a/node-tools/internal/bus/seat_pull.go b/node-tools/internal/bus/seat_pull.go index d0e4625..7cd3dc0 100644 --- a/node-tools/internal/bus/seat_pull.go +++ b/node-tools/internal/bus/seat_pull.go @@ -33,8 +33,10 @@ type Pulled struct { Delivered uint64 `json:"delivered"` } -// pulls are the messages modules pulled and have not settled, by id; each kept with the module it was pulled for, so -// one module never settles another's. +// 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 @@ -46,8 +48,6 @@ type pulledMsg struct { msg jetstream.Msg } -var seatPulls = &pulls{held: map[string]pulledMsg{}, cons: map[string]jetstream.Consumer{}} - func pullID() string { var b [8]byte _, _ = rand.Read(b[:]) @@ -111,17 +111,20 @@ func (c *Conn) SeatPull(module, consumer string, wait time.Duration) (*Pulled, e } p := &Pulled{ID: pullID(), Worker: w.Consumer, Subject: msg.Subject(), Body: json.RawMessage(msg.Data()), Headers: headers, Delivered: delivered} - seatPulls.mu.Lock() - seatPulls.held[p.ID] = pulledMsg{module: module, msg: msg} - seatPulls.mu.Unlock() + 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 - seatPulls.mu.Lock() - bound, ok := seatPulls.cons[key] - seatPulls.mu.Unlock() + c.pulls.mu.Lock() + bound, ok := c.pulls.cons[key] + c.pulls.mu.Unlock() if ok { return bound, nil } @@ -135,9 +138,12 @@ func (c *Conn) pullConsumer(module string, w SeatWorker) (jetstream.Consumer, er if err != nil { return nil, fmt.Errorf("binding %s's worker %s on %s: %w", module, w.Consumer, w.Stream, err) } - seatPulls.mu.Lock() - seatPulls.cons[key] = bound - seatPulls.mu.Unlock() + 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 } @@ -168,15 +174,15 @@ func (c *Conn) SeatSettleAfter(module, id string, delay time.Duration) error { } func (c *Conn) settle(module, id, fate string, delay time.Duration) error { - seatPulls.mu.Lock() - p, ok := seatPulls.held[id] + c.pulls.mu.Lock() + p, ok := c.pulls.held[id] if ok && p.module != module { ok = false } if ok && fate != SettleProgress { - delete(seatPulls.held, id) + delete(c.pulls.held, id) } - seatPulls.mu.Unlock() + c.pulls.mu.Unlock() if !ok { return fmt.Errorf("%s holds no pulled message %s", module, id) } @@ -192,8 +198,8 @@ func (c *Conn) settle(module, id, fate string, delay time.Duration) error { case SettleNakAfter: return p.msg.NakWithDelay(delay) } - seatPulls.mu.Lock() - seatPulls.held[id] = p // an unknown fate settles nothing - seatPulls.mu.Unlock() + 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) } diff --git a/node-tools/internal/bus/seat_pull_test.go b/node-tools/internal/bus/seat_pull_test.go index c43c98d..451e73d 100644 --- a/node-tools/internal/bus/seat_pull_test.go +++ b/node-tools/internal/bus/seat_pull_test.go @@ -19,17 +19,22 @@ func TestAHolderPullsOneMessageWhenItHasRoom(t *testing.T) { t.Fatal(err) } } - first, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0) + // A pull that wants a message waits for it: the worker learns of a stored message after the publish is answered, so + // a pull that waits for nothing can find none yet on a loaded machine (design 47 H, H-A-363). A wait is a bound, not a + // measure: it ends at the delivery. + first, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 10*time.Second) if err != nil || first == nil || string(first.Body) != `{"id":"a1"}` || first.Delivered != 1 { t.Fatalf("the first pull = %+v, %v", first, err) } - // One pulled, one still waiting on the stream: nothing was fetched ahead. + // One pulled and in hand, the other never delivered: nothing was fetched ahead. What is in hand is the worker's own + // count, set by the delivery itself; the count still waiting is the worker's figure of the stream, learnt later, so + // the second message's first delivery says it instead. info, err := js.ConsumerInfo("SEAT_OPERATOR_CHANNEL", "SEAT_OPERATOR_CHANNEL_worker") - if err != nil || info.NumPending != 1 || info.NumAckPending != 1 { - t.Fatalf("after one pull: pending %d, in hand %d (%v); want 1 and 1", info.NumPending, info.NumAckPending, err) + if err != nil || info.NumAckPending != 1 { + t.Fatalf("after one pull: in hand %d (%v); want 1", info.NumAckPending, err) } - second, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0) - if err != nil || second == nil || string(second.Body) != `{"id":"a2"}` { + second, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 10*time.Second) + if err != nil || second == nil || string(second.Body) != `{"id":"a2"}` || second.Delivered != 1 { t.Fatalf("the second pull = %+v, %v", second, err) } if none, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0); err != nil || none != nil { @@ -54,22 +59,23 @@ func TestAHolderPullsOneMessageWhenItHasRoom(t *testing.T) { if err := conn.SeatSettle("messenger", second.ID, bus.SettleNak); err != nil { t.Fatal(err) } - again, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", time.Second) + again, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 10*time.Second) if err != nil || again == nil || string(again.Body) != `{"id":"a2"}` || again.Delivered != 2 { t.Fatalf("the message handed back = %+v, %v", again, err) } // Issue 1748: a message settled with a delay is not given again at once, is after it, one delivery higher; a delay - // of 0 settles nothing. + // of 0 settles nothing. The delay is what the next pull must come within to see nothing, so it is a second, not a + // moment a loaded machine can spend between two calls. if err := conn.SeatSettleAfter("messenger", again.ID, 0); err == nil { t.Error("a delay of 0 was accepted") } - if err := conn.SeatSettleAfter("messenger", again.ID, 300*time.Millisecond); err != nil { + if err := conn.SeatSettleAfter("messenger", again.ID, time.Second); err != nil { t.Fatal(err) } if early, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0); err != nil || early != nil { t.Fatalf("a message given again after a delay came at once: %+v, %v", early, err) } - late, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 2*time.Second) + late, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 10*time.Second) if err != nil || late == nil || late.Delivered != 3 { t.Fatalf("the message given again after its delay = %+v, %v", late, err) } diff --git a/node-tools/internal/bus/seat_test.go b/node-tools/internal/bus/seat_test.go index c8dbd0e..6fd65e5 100644 --- a/node-tools/internal/bus/seat_test.go +++ b/node-tools/internal/bus/seat_test.go @@ -34,11 +34,13 @@ func seatMesh(t *testing.T) (*mt.Mesh, *bus.Conn, nats.JetStreamContext) { t.Fatal(err) } } + // The workers' acknowledgement wait is wider than a test spends holding a message on a loaded machine: a message + // held past it is delivered again, and a pull that wants none would get it (design 47 H, H-A-363). for stream, c := range map[string]*nats.ConsumerConfig{ "SEAT_OPERATOR_CHANNEL": {Durable: "SEAT_OPERATOR_CHANNEL_worker", AckPolicy: nats.AckExplicitPolicy, - FilterSubject: "mesh.seat.operator-channel.accept.>", AckWait: 2 * time.Second}, + FilterSubject: "mesh.seat.operator-channel.accept.>", AckWait: 30 * time.Second}, "SEAT_CHANNEL": {Durable: "SEAT_CHANNEL_TELEGRAM_worker", AckPolicy: nats.AckExplicitPolicy, - FilterSubject: "mesh.seat.channel.accept.*.telegram", AckWait: 2 * time.Second}, + FilterSubject: "mesh.seat.channel.accept.*.telegram", AckWait: 30 * time.Second}, } { if _, err := js.AddConsumer(stream, c); err != nil { t.Fatal(err) diff --git a/node-tools/internal/bus/state_bind_integration_test.go b/node-tools/internal/bus/state_bind_integration_test.go index 22e4a20..e76588a 100644 --- a/node-tools/internal/bus/state_bind_integration_test.go +++ b/node-tools/internal/bus/state_bind_integration_test.go @@ -4,7 +4,6 @@ package bus_test import ( "strings" - "sync/atomic" "testing" "github.com/nats-io/nats.go" @@ -26,8 +25,11 @@ func TestAStateReadOnTheBusBindsItsBucketOnce(t *testing.T) { t.Fatal(err) } t.Cleanup(watcher.Close) - var infos atomic.Int32 - if _, err := watcher.Subscribe("$JS.API.STREAM.INFO.KV_"+bucket, func(*nats.Msg) { infos.Add(1) }); err != nil { + // Each bind the runtime asks is heard onto a channel by the watcher's reader itself, so what the bus sent before a + // flush's answer is on it when the flush returns. A counter a callback raised was read before the callback ran, on a + // loaded machine, and counted one bind short (design 47 H, H-A-363). + infos := make(chan *nats.Msg, 16) + if _, err := watcher.ChanSubscribe("$JS.API.STREAM.INFO.KV_"+bucket, infos); err != nil { t.Fatal(err) } if err := watcher.Flush(); err != nil { @@ -46,7 +48,7 @@ func TestAStateReadOnTheBusBindsItsBucketOnce(t *testing.T) { if err := watcher.Flush(); err != nil { t.Fatal(err) } - if got := infos.Load(); got != 1 { + if got := len(infos); got != 1 { t.Fatalf("three reads asked the bucket's stream info %d times, want once", got) } @@ -75,7 +77,7 @@ func TestAStateReadOnTheBusBindsItsBucketOnce(t *testing.T) { if err := watcher.Flush(); err != nil { t.Fatal(err) } - if got := infos.Load(); got != 3 { + if got := len(infos); got != 3 { t.Fatalf("the bucket's stream info was asked %d times in all, want 3: once, once more when it was gone, once when made afresh", got) } } diff --git a/node-tools/internal/bus/state_pernode_test.go b/node-tools/internal/bus/state_pernode_test.go index 82baf52..ce6af1a 100644 --- a/node-tools/internal/bus/state_pernode_test.go +++ b/node-tools/internal/bus/state_pernode_test.go @@ -69,6 +69,7 @@ func TestAPerNodeStateIsServedAcrossEveryNodesBucket(t *testing.T) { var mu sync.Mutex var current, live []string + heard := make(chan struct{}, 1) stop, err := conn.StateWatch("mesh-provisioner", "mesh-host.composed", "", func(ch bus.StateChange) error { mu.Lock() defer mu.Unlock() @@ -77,6 +78,10 @@ func TestAPerNodeStateIsServedAcrossEveryNodesBucket(t *testing.T) { } else { live = append(live, ch.Key) } + select { + case heard <- struct{}{}: + default: + } return nil }) if err != nil { @@ -98,7 +103,10 @@ func TestAPerNodeStateIsServedAcrossEveryNodesBucket(t *testing.T) { if _, err := a.Put("a.m1.f5", []byte(`{"v":1}`)); err != nil { t.Fatal(err) } - mt.Until(t, func() error { + // Waited for as the watch hands each change over, not polled within a fixed five seconds: the new bucket is taken + // in on the bus's creation advisory, which a loaded machine delivers later (design 47 H, H-A-363). The bound only + // ends a watch that never hears it. + missing := func() error { mu.Lock() defer mu.Unlock() got := strings.Join(append(append([]string(nil), current...), live...), ",") @@ -108,5 +116,13 @@ func TestAPerNodeStateIsServedAcrossEveryNodesBucket(t *testing.T) { } } return nil - }) + } + bound := time.After(30 * time.Second) + for err := missing(); err != nil; err = missing() { + select { + case <-heard: + case <-bound: + t.Fatal(err) + } + } } diff --git a/node-tools/internal/bus/streams.go b/node-tools/internal/bus/streams.go index b9b70aa..ddd0e34 100644 --- a/node-tools/internal/bus/streams.go +++ b/node-tools/internal/bus/streams.go @@ -106,12 +106,18 @@ type hearing struct { kick chan struct{} done chan struct{} unhear func() + + // rebind, nakDelay and heartbeat are RebindEvery, NakDelay and EventHeartbeat as they stood when the hearing was + // made: its loops outlive the call that started them, so they never read a setting again, which a test may set + // back as it ends (design 47 H, H-A-363: a goroutine outliving its settings). + rebind, nakDelay, heartbeat time.Duration } func newHearing(c *Conn, js jetstream.JetStream, module string, deliver func(Envelope) error) *hearing { return &hearing{c: c, js: js, module: module, deliver: deliver, bound: map[HeardIssued]jetstream.ConsumeContext{}, made: map[HeardIssued]time.Time{}, said: map[HeardIssued]bool{}, why: map[HeardIssued]error{}, - kick: make(chan struct{}, 1), done: make(chan struct{})} + kick: make(chan struct{}, 1), done: make(chan struct{}), + rebind: RebindEvery, nakDelay: NakDelay, heartbeat: EventHeartbeat} } // bind reads one durable consumer by name, and on failure says what it was doing. Errors the bus gives @@ -158,7 +164,7 @@ func (h *hearing) handle(msg jetstream.Msg) { done, stopped := make(chan struct{}), make(chan struct{}) go func() { defer close(stopped) - tick := time.NewTicker(EventHeartbeat) + tick := time.NewTicker(h.heartbeat) defer tick.Stop() for { select { @@ -186,7 +192,7 @@ func (h *hearing) handle(msg jetstream.Msg) { return } if err != nil { - _ = msg.NakWithDelay(NakDelay) + _ = msg.NakWithDelay(h.nakDelay) return } _ = msg.Ack() @@ -203,7 +209,7 @@ func (h *hearing) start() { h.nudge() }) go func() { - tick := time.NewTicker(RebindEvery) + tick := time.NewTicker(h.rebind) defer tick.Stop() for { select { @@ -353,7 +359,7 @@ func (h *hearing) reconcile() { // Said once, not at every attempt; said again when it is bound. if !h.said[heard] { h.c.Logf("[mesh-tools] %s does not hear %s yet: %s its consumer %s failed: %v; tried again every %s", - h.module, heard.Stream, doing, heard.Consumer, err, RebindEvery) + h.module, heard.Stream, doing, heard.Consumer, err, h.rebind) h.said[heard] = true } continue diff --git a/node-tools/internal/meshtest/meshtest.go b/node-tools/internal/meshtest/meshtest.go index 04fca72..e6bfed6 100644 --- a/node-tools/internal/meshtest/meshtest.go +++ b/node-tools/internal/meshtest/meshtest.go @@ -260,11 +260,13 @@ func Fixture(name string) string { return filepath.Join(filepath.Dir(here), "..", "..", "test", "fixtures", name) } -// Until retries while the bus answers "no responders" — something not yet served. +// Until retries while the bus answers "no responders" — something not yet served. Its bound only ends a wait that never +// hears what it waits for: 30 s, which a loaded machine stays within, where the earlier 5 s did not (design 47 H, +// H-A-363; fix-a-bug-met-twice: a fixed bound a loaded machine overruns, fixed for every package that waits here). func Until(t *testing.T, try func() error) { t.Helper() var err error - for i := 0; i < 50; i++ { + for i := 0; i < 300; i++ { if err = try(); err == nil { return }