Files
mesh-tools/node-tools/internal/bus/caller_bus_test.go
T
jschoubben 6a1b4817f8 node-tools: every wait on the bus in a test waits the shared bound, not a few seconds (issue 1754)
TestAStaleWriteIsRefusedAndWritesNothing gave the watch 5 s to hear a 1 s
key's expire and failed main.505's integration step on a loaded build node;
TestARunnerAtItsStopAnswersNoCallAndItsCallersMeetNoResponders failed its
rerun while it asked 1 s of two round trips and 5 s and 10 s of its waits.
The second of a kind after 3850eb8, so the kind is fixed: meshtest.Bound
(30 s, Until's bound, named once) is what every node-tools test that starts
a bus waits for what the bus carries; Until becomes a deadline of it, so a
try that waits does not multiply it; an upper bound on how long a call or a
wait took is half the bound it tells apart (bus.RequestTimeout, the call's
or the wait's own), at most meshtest.Bound. A wait that hears ends then: no
passing test is longer (per-test durations before and after, equal).

A guard (meshtest waits_test.go) reads every test file that imports
meshtest and refuses a wait whose constant bound is a second or more under
meshtest.Bound; it names 34 such waits at 309069de.

Builds: issue 1754 note 8 (the quick fix), note 9 (1754/AC1 to AC4); principle 11
2026-11-23 19:21:28 +01:00

311 lines
12 KiB
Go

package bus_test
import (
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"
"github.com/nats-io/nats-server/v2/server"
"github.com/nats-io/nats.go"
"github.com/novox/mesh-tools/node-tools/internal/bus"
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
)
// A bus whose users are granted as the controller grants them (mesh-module-assigner internal/broker): each named
// user publishes the subjects listed for it.
func grantedBus(t *testing.T, publish map[string][]string) string {
t.Helper()
var users []*server.User
for user, allow := range publish {
// And the membership's direct get every connection asks once, answered "no responders" here.
allow = append(allow, "$JS.API.DIRECT.GET.>")
users = append(users, &server.User{Username: user, Password: "pw", Permissions: &server.Permissions{
Publish: &server.SubjectPermission{Allow: allow},
Subscribe: &server.SubjectPermission{Allow: []string{">"}},
}})
}
s, err := server.NewServer(&server.Options{Host: "127.0.0.1", Port: server.RANDOM_PORT, NoLog: true, NoSigs: true,
Users: users})
if err != nil {
t.Fatal(err)
}
go s.Start()
if !s.ReadyForConnections(mt.Bound) {
t.Fatal("the bus did not come up")
}
t.Cleanup(s.Shutdown)
return s.ClientURL()
}
func dial(t *testing.T, url, module, node, user string) *bus.Conn {
t.Helper()
c, err := bus.Connect(bus.Credential{URL: url, Module: module, Node: node, User: user, Password: "pw"})
if err != nil {
t.Fatal(err)
}
c.Logf = func(string, ...any) {}
t.Cleanup(c.Close)
return c
}
type heard struct {
mu sync.Mutex
callers []string
}
func (h *heard) handler(caller, _ string, _ json.RawMessage) (any, error) {
h.mu.Lock()
defer h.mu.Unlock()
h.callers = append(h.callers, caller)
return map[string]any{"caller": caller}, nil
}
func (h *heard) all() []string {
h.mu.Lock()
defer h.mu.Unlock()
return append([]string(nil), h.callers...)
}
// A caller asks on the caller-named subject first; where nothing serves it yet — a runtime from before issue
// 365 — the same call is asked once on the subject that names no caller, at once, and done once.
func TestACallerFallsBackAtOnceWhereNothingServesTheCallerNamedSubject(t *testing.T) {
url := mt.URL(t)
server := dial(t, url, "ledger", "anchor", "")
h := &heard{}
// An older runtime: the subject that names no caller, alone.
stop, err := server.HandleSubject("mesh.mod.ledger.tool.who", func(body json.RawMessage) (any, error) {
return h.handler("", "", body)
})
if err != nil {
t.Fatal(err)
}
defer stop()
server.Flush()
asker := dial(t, url, "node-tools", "shanks", "shanks.node-tools")
began := time.Now()
answered, err := asker.Ask("ledger.who", map[string]any{}, "")
if err != nil {
t.Fatal(err)
}
if took := time.Since(began); took > bus.RequestTimeout/2 { // 1754/AC4: at once, not after the caller-named call's timeout
t.Errorf("the fall-back took %s", took)
}
if got := h.all(); len(got) != 1 || got[0] != "" || !strings.Contains(string(answered.Result), `"caller":""`) {
t.Errorf("the call was answered %v, heard %v; want once, on the old subject", string(answered.Result), got)
}
}
// Where the bus does not grant the caller-named subject yet — the controller's grants not yet delivered — the
// refusal ends the call at once and it is asked on the subject that names no caller: no caller waits out
// RequestTimeout for a grant that is on its way.
func TestACallerTheBusRefusesTheCallerNamedSubjectFallsBackAtOnce(t *testing.T) {
url := grantedBus(t, map[string][]string{
"anchor.node-tools": {"_INBOX.>"},
"shanks.node-tools": {"mesh.mod.*.tool.>"},
})
server := dial(t, url, "node-tools", "anchor", "anchor.node-tools")
h := &heard{}
stop, err := server.HandleSubjectCalled("mesh.mod.ledger.tool.who", h.handler)
if err != nil {
t.Fatal(err)
}
defer stop()
server.Flush()
asker := dial(t, url, "node-tools", "shanks", "shanks.node-tools")
var said []string
var mu sync.Mutex
asker.Logf = func(f string, a ...any) { mu.Lock(); said = append(said, fmt.Sprintf(f, a...)); mu.Unlock() }
began := time.Now()
if _, err := asker.Ask("ledger.who", map[string]any{}, ""); err != nil {
t.Fatal(err)
}
mu.Lock()
if !strings.Contains(strings.Join(said, "\n"), "the bus refused this account the caller-named mesh.mod.ledger.call.who.shanks~node-tools") {
t.Errorf("the refusal was not said: %v", said)
}
mu.Unlock()
if took := time.Since(began); took > bus.RequestTimeout/2 { // 1754/AC4: at once, not after RequestTimeout
t.Errorf("the refused caller-named call held the caller %s", took)
}
if got := h.all(); len(got) != 1 || got[0] != "" {
t.Errorf("heard %v; want one call, on the subject that names no caller", got)
}
}
// With the controller's grant — the caller-named subjects with its own name last — a caller is heard as itself;
// and a caller cannot publish on a subject naming another, however it asks.
func TestAGrantedCallerIsHeardAsItselfAndCannotNameAnother(t *testing.T) {
url := grantedBus(t, map[string][]string{
"anchor.node-tools": {"_INBOX.>"},
"shanks.node-tools": {"mesh.mod.*.call.*.shanks~node-tools", "mesh.mod.*.call.*.*.shanks~node-tools"},
})
server := dial(t, url, "node-tools", "anchor", "anchor.node-tools")
h := &heard{}
stop, err := server.HandleSubjectCalled("mesh.mod.ledger.tool.who", h.handler)
if err != nil {
t.Fatal(err)
}
defer stop()
server.Flush()
asker := dial(t, url, "node-tools", "shanks", "shanks.node-tools")
if _, err := asker.Ask("ledger.who", map[string]any{}, ""); err != nil {
t.Fatal(err)
}
// Naming another on the subject itself: refused by the bus, so nothing is heard.
refusals := make(chan error, 4)
forger, err := nats.Connect(url, nats.UserInfo("shanks.node-tools", "pw"),
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) { refusals <- err }))
if err != nil {
t.Fatal(err)
}
defer forger.Close()
if err := forger.Publish("mesh.mod.ledger.call.who.novox~node-tools", []byte(`{}`)); err != nil {
t.Fatal(err)
}
_ = forger.Flush()
select {
case err := <-refusals:
if !errors.Is(err, nats.ErrPermissionViolation) {
t.Errorf("the bus said %v, want a permissions violation", err)
}
case <-time.After(mt.Bound):
t.Error("the bus did not refuse a call naming another caller")
}
if got := h.all(); len(got) != 1 || got[0] != "shanks.node-tools" {
t.Errorf("heard %v; want the asker alone, as itself", got)
}
}
// A fall-back for want of a responder on the caller-named subject is said, once per subject, so a runtime or
// grant that drifted behind is seen rather than read as a quiet "unproven".
func TestAFallBackForWantOfAResponderIsSaidOncePerSubject(t *testing.T) {
url := mt.URL(t)
// A runtime from before issue 365: the subject that names no caller, alone.
older, err := nats.Connect(url)
if err != nil {
t.Fatal(err)
}
defer older.Close()
if _, err := older.Subscribe("mesh.mod.ledger.tool.who", func(m *nats.Msg) { _ = m.Respond([]byte(`{"result":{}}`)) }); err != nil {
t.Fatal(err)
}
_ = older.Flush()
asker := dial(t, url, "node-tools", "shanks", "shanks.node-tools")
var mu sync.Mutex
var said []string
asker.Logf = func(f string, a ...any) { mu.Lock(); said = append(said, fmt.Sprintf(f, a...)); mu.Unlock() }
for i := 0; i < 3; i++ {
if _, err := asker.Ask("ledger.who", map[string]any{}, ""); err != nil {
t.Fatal(err)
}
}
mu.Lock()
defer mu.Unlock()
n := 0
for _, s := range said {
if strings.Contains(s, "nothing answers the caller-named mesh.mod.ledger.call.who.shanks~node-tools") {
n++
}
}
if n != 1 {
t.Errorf("the fall-back was said %d times, want once: %v", n, said)
}
}
// Design 47 H §760: a call waits the bound its verb's definition names, and ends there with the timeout; the caller of a verb whose
// definition names none waits the tool runner's own bound, RequestTimeout.
func TestACallWaitsTheBoundItsVerbNamesAndTimesOutThere(t *testing.T) {
url := grantedBus(t, map[string][]string{"anchor.node-tools": {"_INBOX.>"}, "shanks.node-tools": {"mesh.mod.*.tool.>"}})
server := dial(t, url, "node-tools", "anchor", "anchor.node-tools")
release := make(chan struct{})
stop, err := server.HandleSubjectCalled("mesh.mod.ledger.tool.slow", func(string, string, json.RawMessage) (any, error) {
<-release
return map[string]any{}, nil
})
if err != nil {
t.Fatal(err)
}
defer stop()
defer close(release)
server.Flush()
asker := dial(t, url, "node-tools", "shanks", "shanks.node-tools")
began := time.Now()
_, err = asker.AskWithin("ledger.slow", map[string]any{}, "", 200*time.Millisecond)
if err == nil || err.Error() != "timeout" {
t.Fatalf("a call whose verb names a bound the holder outlasts: %v, want the timeout", err)
}
if took := time.Since(began); took > bus.RequestTimeout/2 {
t.Errorf("the call waited %s, want its own bound of 200ms, not the tool runner's %s", took, bus.RequestTimeout)
}
}
// 721/AC4: once told to stop, the tool runner unsubscribes from every subject it answers calls on before it finishes the
// calls in flight (design 47 H2 H-A-570 (1)): a call heard after the stop began gets no answer from it, no typed fault, and its
// caller meets no responders at once; the call in flight at the stop is still answered; a subject served once the stop began
// is not subscribed, and says so.
// 1754/AC3: its order is held (StopAnswering returns once the bus holds the unsubscriptions), so it needs no clock of its
// own: each call and the held call's arrival wait meshtest.Bound, and "at once" is the bus's word, no responders, where a
// subscription left behind would end the call at its bound in a timeout. It failed on a loaded build node (main.505)
// while it asked 1 s of two round trips and 5 s and 10 s of its waits.
func TestARunnerAtItsStopAnswersNoCallAndItsCallersMeetNoResponders(t *testing.T) {
url := mt.URL(t)
server := dial(t, url, "ledger", "anchor", "")
began, release := make(chan struct{}, 1), make(chan struct{})
stop, err := server.HandleSubjectCalled("mesh.mod.ledger.tool.who", func(_, _ string, body json.RawMessage) (any, error) {
if strings.Contains(string(body), "held") {
began <- struct{}{}
<-release
}
return map[string]any{"who": "ledger"}, nil
})
if err != nil {
t.Fatal(err)
}
defer stop()
server.Flush()
asker := dial(t, url, "node-tools", "shanks", "shanks.node-tools")
held := make(chan error, 1)
go func() {
_, err := asker.AskWithin("ledger.who", map[string]any{"held": true}, "", mt.Bound)
held <- err
}()
select {
case <-began:
case <-time.After(mt.Bound):
t.Fatal("the call to hold never reached the runner")
}
server.StopAnswering()
at := time.Now()
answered, err := asker.AskWithin("ledger.who", map[string]any{}, "", mt.Bound)
if took := time.Since(at); !errors.Is(err, bus.ErrNoResponders) || took > mt.Bound/2 {
t.Errorf("a call after the stop began was answered %s, %v in %s; want no responders at once", answered.Result, err, took)
}
if _, err := server.HandleSubjectCalled("mesh.mod.ledger.tool.late", func(string, string, json.RawMessage) (any, error) {
return nil, nil
}); err == nil || !strings.Contains(err.Error(), "took down every subscription") {
t.Errorf("a subject served once the stop began was subscribed (%v), want it refused and said", err)
}
close(release)
if err := <-held; err != nil {
t.Errorf("the call in flight at the stop ended %v, want it answered", err)
}
// A serve racing the stop (a membership change, a bundle's new tool): the stop begins between its subscription and its
// keeping, and still the subject is not left answered, its subscription taken down and the serve refused.
raced := dial(t, url, "ledger", "anchor", "")
var once sync.Once
bus.SetSubscribedHook(raced, func(string) { once.Do(raced.StopAnswering) })
if _, err := raced.HandleSubjectCalled("mesh.mod.ledger.tool.raced", func(string, string, json.RawMessage) (any, error) {
return map[string]any{"raced": true}, nil
}); err == nil {
t.Error("a serve that raced the stop was kept, want it refused")
}
if answered, err := asker.AskWithin("ledger.raced", map[string]any{}, "", mt.Bound); !errors.Is(err, bus.ErrNoResponders) {
t.Errorf("a call of a tool whose serve raced the stop was answered %s, %v; want no responders", answered.Result, err)
}
}