37 changed files with 369 additions and 1944 deletions
+1 -22
View File
@@ -1,6 +1,6 @@
// node-tools — the node's tool runtime, in Go (novox/hq ADR 0175, ADR 0193; to-be 38 WP4d). // node-tools — the node's tool runtime, in Go (novox/hq ADR 0175, ADR 0193; to-be 38 WP4d).
// (Its pipeline is asked again by this line, 2026-11-16 23:45: main.981 passed all but composition, whose revision 433 was removed; the assigner now waits 3 minutes for composing nodes.) // (Its pipeline is asked again by this line, 2026-11-16 23:45: main.981 passed all but composition, whose revision 433 was removed; the assigner now waits 3 minutes for composing nodes.)
// Design 47 H1, proof 2: the tool runner delivered by its pipeline at the current mesh-sdk release. // Design 47 H1, proof 2 once more: the importer half of the edge mesh-delivery-sdk to node-tools.
// //
// One process per machine: it connects to the bus on the node's credential, launches every assigned // One process per machine: it connects to the bus on the node's credential, launches every assigned
// module's tools bundle and serves its tools and its seats' verbs; as the node-tools module — or // module's tools bundle and serves its tools and its seats' verbs; as the node-tools module — or
@@ -29,9 +29,7 @@ import (
handacts "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts" handacts "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts"
"git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient" "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/approval" "git.novox.be/novox/mesh-sdk/go/approval"
"git.novox.be/novox/mesh-sdk/go/busretry"
"github.com/novox/mesh-tools/node-tools/internal/alive" "github.com/novox/mesh-tools/node-tools/internal/alive"
runnerapproval "github.com/novox/mesh-tools/node-tools/internal/approval" runnerapproval "github.com/novox/mesh-tools/node-tools/internal/approval"
@@ -67,15 +65,6 @@ func main() {
// serve is the tool runner: it reads its credential and serves until ctx ends, then shuts down in order. It is the entry a whole test // serve is the tool runner: it reads its credential and serves until ctx ends, then shuts down in order. It is the entry a whole test
// starts, beside the process's own (design 47 H §774, H-A-61). // starts, beside the process's own (design 47 H §774, H-A-61).
func serve(ctx context.Context) error { func serve(ctx context.Context) error {
// The drain bound, read first so a setting that is no duration stops the runner before it serves (design 47 H2 §813 (12)).
drainBound, err := drainBoundSetting()
if err != nil {
return err
}
// And the pace of its kept calls, its settings kept-call-pace-first and kept-call-pace-max (design 47 H2 §775).
if err := busretry.ReadPace(stdio.SettingDuration); err != nil {
return err
}
until := time.Now().Add(startWait) until := time.Now().Add(startWait)
cred := credential(until) cred := credential(until)
conn := connectPatiently(cred, until) conn := connectPatiently(cred, until)
@@ -166,9 +155,6 @@ func serve(ctx context.Context) error {
// First of all: the service manager signalled every bundle with this process, and none is started again // First of all: the service manager signalled every bundle with this process, and none is started again
// (issue 1126). // (issue 1126).
launch.ShutDown() launch.ShutDown()
// Then it drains (design 47 H2 §813 (12), H-A-353): no new call is taken, the calls in flight finish within the drain bound
// or are cut and said, and only then are the bundles stopped, by the runner itself.
launch.Drain(drainBound, log.Printf)
stopSaying() stopSaying()
stopProviding() stopProviding()
stop() stop()
@@ -179,13 +165,6 @@ func serve(ctx context.Context) error {
return nil return nil
} }
// drainBoundSetting is how long the runner, told to stop, waits for the calls in flight to finish: the module's setting
// drain-bound, a duration text the node-engine composes as MESH_CONFIG_DRAIN_BOUND, read through the one settings reader, 30 s
// when none is composed (design 47 H2 §813 (12), H-A-369, H-A-370, H-A-377).
func drainBoundSetting() (time.Duration, error) {
return stdio.SettingDuration(launch.DrainBoundSetting, launch.DefaultDrainBound)
}
// startWait is how long a runtime waits, from its start, for its broker credential to be on the machine and for the bus // startWait is how long a runtime waits, from its start, for its broker credential to be on the machine and for the bus
// to accept the account it names (issue 1496): the node-engine starts a module's runtime before the provisioner's client // to accept the account it names (issue 1496): the node-engine starts a module's runtime before the provisioner's client
// fills the credential, and the bus carries a new account only after it reloads its users. Past it the runtime gives up, // fills the credential, and the bus carries a new account only after it reloads its users. Past it the runtime gives up,
+2 -34
View File
@@ -13,43 +13,11 @@ import (
"github.com/novox/mesh-tools/node-tools/internal/runtime" "github.com/novox/mesh-tools/node-tools/internal/runtime"
) )
// The runner's start waits for its credential and its bus within the start's bound (issue 1496), and reads its settings // The runner's start waits for its credential and its bus within the start's bound (issue 1496): one test, two cases, so
// before it serves: one test, three cases, so design 46 7-approval-mark §22's whole test of the gate adds no test to the // design 46 7-approval-mark §22's whole test of the gate adds no test to the module (design 47 G §419, §626).
// module (design 47 G §419, §626).
func TestTheRunnersStartWaitsForItsCredentialAndItsBus(t *testing.T) { func TestTheRunnersStartWaitsForItsCredentialAndItsBus(t *testing.T) {
t.Run("the credential", awaitsCredential) t.Run("the credential", awaitsCredential)
t.Run("the bus", connectsWithin) t.Run("the bus", connectsWithin)
// **The runner's settings are read through the one settings reader** (design 47 H2 §813 (12), §775, H-A-369, H-A-370,
// H-A-377): drain-bound, a duration text the node-engine composes as MESH_CONFIG_DRAIN_BOUND, 30 s when none is composed; a
// value that is no duration, of it or of the kept call's pace, stops the runner before it serves, naming the setting.
t.Run("its settings", func(t *testing.T) {
for _, row := range []struct {
word, composed, refused string
want time.Duration
}{
{"MESH_CONFIG_DRAIN_BOUND", "", "", 30 * time.Second},
{"MESH_CONFIG_DRAIN_BOUND", "5s", "", 5 * time.Second},
{"MESH_CONFIG_DRAIN_BOUND", "30", "drain-bound", 0},
{"MESH_CONFIG_KEPT_CALL_PACE_FIRST", "1", "kept-call-pace-first", 30 * time.Second},
{"MESH_CONFIG_KEPT_CALL_PACE_MAX", "100ms", "kept-call-pace-max", 30 * time.Second},
} {
t.Run(row.word+"="+row.composed, func(t *testing.T) {
t.Setenv(row.word, row.composed)
if row.refused != "" {
if err := serve(t.Context()); err == nil || !strings.Contains(err.Error(), row.refused) {
t.Errorf("the runner with %s=%q served (%v); want it stopped before it serves, naming %s", row.word,
row.composed, err, row.refused)
}
if row.want == 0 {
return
}
}
if got, err := drainBoundSetting(); err != nil || got != row.want {
t.Errorf("drain-bound read %s, %v; want %s", got, err, row.want)
}
})
}
})
} }
// A runtime started before its credential is on the machine waits for it, woken by the watch of its directory, and gives // A runtime started before its credential is on the machine waits for it, woken by the watch of its directory, and gives
@@ -5,8 +5,6 @@ package main
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"fmt"
"log"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -67,17 +65,7 @@ func (c *catalogStandIn) handle(body json.RawMessage) (any, error) {
// for a verb that sends chunks (design 47 G A-490m). // for a verb that sends chunks (design 47 G A-490m).
func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *testing.T) { func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *testing.T) {
mesh := mt.New(t) mesh := mt.New(t)
ledger := mt.MembershipOf("ledger", "anchor", true, map[string][]string{"node-desk": {"who", "slow"}}) mesh.Issue(t, mt.MembershipOf("ledger", "anchor", true, map[string][]string{"node-desk": {"who", "slow"}}))
ledger.State = []bus.StateIssued{{Name: "pages", Bucket: "ledger_pages", Writes: true}}
mesh.Issue(t, ledger)
// a state of 10,000 keys of 300 bytes each, about four pages of 768 KB (design 47 H2 §779)
pages := mesh.Bucket(t, "ledger_pages")
value := []byte(`"` + strings.Repeat("v", 298) + `"`)
for i := range 10000 {
if _, err := pages.Put(fmt.Sprintf("k%05d", i), value); err != nil {
t.Fatal(err)
}
}
dir := t.TempDir() dir := t.TempDir()
credential, _ := json.Marshal(bus.Credential{URL: mt.URL(t), Module: runtimeModule, Node: "anchor"}) credential, _ := json.Marshal(bus.Credential{URL: mt.URL(t), Module: runtimeModule, Node: "anchor"})
file := filepath.Join(dir, "broker") file := filepath.Join(dir, "broker")
@@ -87,8 +75,6 @@ func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *te
t.Setenv("MESH_BROKER_FILE", file) t.Setenv("MESH_BROKER_FILE", file)
t.Setenv("MESH_TOOL_MODULES", "ledger="+mt.Fixture("whole-bundle.py")) t.Setenv("MESH_TOOL_MODULES", "ledger="+mt.Fixture("whole-bundle.py"))
t.Setenv("MESH_CONSOLE_LISTEN", "127.0.0.1:0") t.Setenv("MESH_CONSOLE_LISTEN", "127.0.0.1:0")
heldFile := filepath.Join(dir, "held")
t.Setenv("HELD_FILE", heldFile)
open := func(module, node string) *bus.Conn { open := func(module, node string) *bus.Conn {
c, err := bus.Connect(bus.Credential{URL: mt.URL(t), Module: module, Node: node, User: node + "." + module, Password: "unused"}) c, err := bus.Connect(bus.Credential{URL: mt.URL(t), Module: module, Node: node, User: node + "." + module, Password: "unused"})
@@ -118,31 +104,20 @@ func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *te
} }
holder.Flush() holder.Flush()
// The journal, read for the drain's line at the stop (design 47 H2 §813 (12)).
journal := &said{}
log.SetOutput(journal)
t.Cleanup(func() { log.SetOutput(os.Stderr) })
// the setting drain-bound as the node-engine composes it (H-A-370, H-A-377)
t.Setenv("MESH_CONFIG_DRAIN_BOUND", "2s")
ctx, stop := context.WithCancel(context.Background()) ctx, stop := context.WithCancel(context.Background())
ended := make(chan error, 1) ended := make(chan error, 1)
go func() { ended <- serve(ctx) }() go func() { ended <- serve(ctx) }()
var stopped sync.Once t.Cleanup(func() {
stopServe := func() { stop()
stopped.Do(func() { select {
stop() case err := <-ended:
select { if err != nil {
case err := <-ended: t.Errorf("serve ended with %v", err)
if err != nil {
t.Errorf("serve ended with %v", err)
}
case <-time.After(30 * time.Second):
t.Error("the tool runner did not stop within 30s")
} }
}) case <-time.After(30 * time.Second):
} t.Error("the tool runner did not stop within 30s")
t.Cleanup(stopServe) }
})
// a module's account, which the approval gate runs unmarked while the catalog half is unread (the stand-in serves no catalog half) // a module's account, which the approval gate runs unmarked while the catalog half is unread (the stand-in serves no catalog half)
asker := open("shop", "workstation") asker := open("shop", "workstation")
ask := func(key string) (string, error) { ask := func(key string) (string, error) {
@@ -182,110 +157,8 @@ func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *te
listings := catalog.listings listings := catalog.listings
catalog.mu.Unlock() catalog.mu.Unlock()
mu.Lock() mu.Lock()
defer mu.Unlock()
if listings != 2 || len(fresh) != 1 || fresh[0]["call"] == nil || fresh[0]["call"] == "" { if listings != 2 || len(fresh) != 1 || fresh[0]["call"] == nil || fresh[0]["call"] == "" {
t.Errorf("the list was read %d times (want 2) and the holder of node-desk.fresh was asked %v (want once, with a call token)", listings, fresh) t.Errorf("the list was read %d times (want 2) and the holder of node-desk.fresh was asked %v (want once, with a call token)", listings, fresh)
} }
mu.Unlock()
// a state read in pages by the bundle, each after the cursor the page before answered, delivers each kept message once
// across the pages, and a key written again mid-read comes again in a later page marked seen-again (design 47 H2 §779,
// H-A-382)
type paged struct {
Keys []string `json:"keys"`
Again []string `json:"again"`
Next string `json:"next"`
Error any `json:"error"`
}
readPage := func(cursor string) paged {
t.Helper()
answered, err := asker.AskWithin("ledger.page", map[string]any{"cursor": cursor}, "", 30*time.Second)
var p paged
if err != nil || json.Unmarshal(answered.Result, &p) != nil || p.Error != nil {
t.Fatalf("the page after %q was answered %.300s, %v", cursor, answered.Result, err)
}
return p
}
handed, again, count := map[string]int{}, []string{}, 0
for p, n := readPage(""), 1; ; p, n = readPage(p.Next), n+1 {
count++
for _, k := range p.Keys {
handed[k]++
}
again = append(again, p.Again...)
if n == 1 {
if len(p.Keys) == 0 || p.Keys[0] != "k00000" || p.Next == "" {
t.Fatalf("the first page holds %d keys from %v and next %q; want k00000 first and more to follow", len(p.Keys), p.Keys[:min(1, len(p.Keys))], p.Next)
}
if _, err := pages.Put("k00000", []byte(`"again"`)); err != nil {
t.Fatal(err)
}
}
if p.Next == "" {
break
}
if count > 20 {
t.Fatal("the read did not end within 20 pages")
}
}
if count < 3 || len(handed) != 10000 || len(again) != 1 || again[0] != "k00000" {
t.Errorf("the read took %d pages, handed %d keys and marked %v seen-again; want at least 3 pages, 10,000 keys and k00000", count, len(handed), again)
}
for k, n := range handed {
if n != 1 {
t.Errorf("%s was handed %d times outside of seen-again, want once", k, n)
}
}
// at its stop the runner drains (design 47 H2 §813 (12), H-A-353; the bound 2 s here for the setting's 30 s): a call of 1 s in
// flight is answered, one of 6 s is cut at the bound, said, and its caller answered nothing; a call after the stop is answered nothing
type answer struct {
got string
err error
}
hold := func(seconds int, within time.Duration) chan answer {
out := make(chan answer, 1)
go func() {
answered, err := asker.AskWithin("ledger.hold", map[string]any{"seconds": seconds}, "", within)
out <- answer{string(answered.Result), err}
}()
return out
}
short, long := hold(1, 10*time.Second), hold(6, 5*time.Second)
// both calls are in flight once the bundle noted them
mt.Until(t, func() error {
if noted, _ := os.ReadFile(heldFile); strings.Count(string(noted), "hold") != 2 {
return fmt.Errorf("the bundle noted %q, want both calls", noted)
}
return nil
})
stop()
// a call after the stop began is answered nothing, never refused, so the caller's kept call paces and meets the new runner
// (H-A-369): until the drain began it is still answered
mt.Until(t, func() error {
answered, err := asker.AskWithin("ledger.who", map[string]any{}, "", 500*time.Millisecond)
if err == nil || err.Error() != "timeout" {
return fmt.Errorf("a call after the stop was answered %s, %v; want no answer", answered.Result, err)
}
return nil
})
if got := <-short; got.err != nil || !strings.Contains(got.got, `"held":1`) {
t.Errorf("the call of 1 s in flight at the stop was answered %s, %v; want it finished", got.got, got.err)
}
if got := <-long; got.err == nil || strings.Contains(got.err.Error(), "cut") {
t.Errorf("the call of 6 s was answered %s, %v; want no answer, a transport fault for its caller", got.got, got.err)
}
stopServe()
if !journal.has("cut ledger's call hold") {
t.Errorf("the journal does not say the cut call: %s", journal.String())
}
} }
// said is the runner's journal in a test, safe to read while it writes.
type said struct {
mu sync.Mutex
b strings.Builder
}
func (s *said) Write(p []byte) (int, error) { s.mu.Lock(); defer s.mu.Unlock(); return s.b.Write(p) }
func (s *said) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() }
func (s *said) has(words string) bool { return strings.Contains(s.String(), words) }
+14 -33
View File
@@ -196,28 +196,19 @@ func (c *Conn) ObjectsList(module string, r buscalls.ObjectsRequest) (buscalls.O
return out, nil return out, nil
} }
// ObjectsInfo is how full the module's object store is, from the figures the bus keeps for its stream: its bytes, its // ObjectsInfo is how full the module's object store is: its objects, its bytes and its cap.
// messages' live subjects as the count, and its cap. It never lists the store: a store's descriptions, the leftovers
// of deleted objects among them, may be many thousands, and a fill read per chunk of a transfer read them all each
// time (design 47 H lead answers H-A-227).
func (c *Conn) ObjectsInfo(module string, r buscalls.ObjectsRequest) (buscalls.Fill, error) { func (c *Conn) ObjectsInfo(module string, r buscalls.ObjectsRequest) (buscalls.Fill, error) {
b, err := c.objectBucketOf(module, r.Objects) listed, err := c.ObjectsList(module, r)
if err != nil { if err != nil {
return buscalls.Fill{}, err return buscalls.Fill{}, err
} }
info, err := c.streamInfo("OBJ_" + b.ObjectStore) b, _ := c.objectBucketOf(module, r.Objects)
fill, err := c.streamFill("OBJ_" + b.ObjectStore)
if err != nil { if err != nil {
return buscalls.Fill{}, err return buscalls.Fill{}, err
} }
return objectsFillOf(info), nil fill.Count = uint64(len(listed.Objects))
} return fill.Fill, nil
// objectsFillOf is an object store's fill from its stream's info alone: the bytes the stream keeps, its live subjects
// as the count (H-A-227: the stream's live subjects, or none) and its cap.
func objectsFillOf(info *jetstream.StreamInfo) buscalls.Fill {
fill := streamFillOf(info).Fill
fill.Count = uint64(info.State.NumSubjects)
return fill
} }
// ObjectsWatch hands deliver every object of the module's object store as it is, then each stored or deleted. // ObjectsWatch hands deliver every object of the module's object store as it is, then each stored or deleted.
@@ -270,39 +261,29 @@ func (c *Conn) ObjectsWatch(module string, r buscalls.ObjectsWatchRequest, deliv
// streamFill is a stream's fill and its first and last sequence, by its name on the bus. // streamFill is a stream's fill and its first and last sequence, by its name on the bus.
func (c *Conn) streamFill(name string) (buscalls.StreamFilled, error) { func (c *Conn) streamFill(name string) (buscalls.StreamFilled, error) {
info, err := c.streamInfo(name)
if err != nil {
return buscalls.StreamFilled{}, err
}
return streamFillOf(info), nil
}
// streamInfo is a stream's info as the bus keeps it, by its name on the bus: one request, whatever the stream holds.
func (c *Conn) streamInfo(name string) (*jetstream.StreamInfo, error) {
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel() defer cancel()
js, err := c.JetStream() js, err := c.JetStream()
if err != nil { if err != nil {
return nil, err return buscalls.StreamFilled{}, err
} }
s, err := js.Stream(ctx, name) s, err := js.Stream(ctx, name)
if errors.Is(err, jetstream.ErrStreamNotFound) { if errors.Is(err, jetstream.ErrStreamNotFound) {
return nil, fmt.Errorf("the stream %s is bound and not on the bus", name) return buscalls.StreamFilled{}, fmt.Errorf("the stream %s is bound and not on the bus", name)
} }
if err != nil { if err != nil {
return nil, err return buscalls.StreamFilled{}, err
}
info, err := s.Info(ctx)
if err != nil {
return buscalls.StreamFilled{}, err
} }
return s.Info(ctx)
}
// streamFillOf is a stream's fill and its first and last sequence from its info.
func streamFillOf(info *jetstream.StreamInfo) buscalls.StreamFilled {
max := uint64(0) max := uint64(0)
if info.Config.MaxBytes > 0 { if info.Config.MaxBytes > 0 {
max = uint64(info.Config.MaxBytes) max = uint64(info.Config.MaxBytes)
} }
return buscalls.StreamFilled{Fill: buscalls.Fill{Count: info.State.Msgs, Bytes: info.State.Bytes, MaxBytes: max}, return buscalls.StreamFilled{Fill: buscalls.Fill{Count: info.State.Msgs, Bytes: info.State.Bytes, MaxBytes: max},
First: info.State.FirstSeq, Last: info.State.LastSeq} First: info.State.FirstSeq, Last: info.State.LastSeq}, nil
} }
// streamBinding is the module's binding of a stream by its local name, a work queue among them. // streamBinding is the module's binding of a stream by its local name, a work queue among them.
-5
View File
@@ -95,11 +95,6 @@ func TestABundleReachesItsOwnBoundObjectsAndStreamsOnly(t *testing.T) {
if listed, err := conn.ObjectsList("m", buscalls.ObjectsRequest{Objects: "files"}); err != nil || len(listed.Objects) != 1 { if listed, err := conn.ObjectsList("m", buscalls.ObjectsRequest{Objects: "files"}); err != nil || len(listed.Objects) != 1 {
t.Fatalf("listed %+v, %v", listed, err) t.Fatalf("listed %+v, %v", listed, err)
} }
// H-A-227: the fill is the stream's own figures, its live subjects as the count (a's chunk and description, big's
// description left by its delete), never the count of its listed objects.
if fill, err := conn.ObjectsInfo("m", buscalls.ObjectsRequest{Objects: "files"}); err != nil || fill.Count != 3 || fill.Bytes == 0 {
t.Fatalf("objects fill %+v, %v", fill, err)
}
// A-380: an old `objects` entry is reached by the store grants creates for it, `<module>_<name>`, with no binding of that name. // A-380: an old `objects` entry is reached by the store grants creates for it, `<module>_<name>`, with no binding of that name.
if _, err := conn.ObjectsPut("m", buscalls.ObjectsPutRequest{Objects: "old", Name: "r", Data: []byte("old section")}); err != nil { if _, err := conn.ObjectsPut("m", buscalls.ObjectsPutRequest{Objects: "old", Name: "r", Data: []byte("old section")}); err != nil {
t.Fatalf("put into the old objects section: %v", err) t.Fatalf("put into the old objects section: %v", err)
+22 -112
View File
@@ -7,8 +7,6 @@
// mesh.seat.<seat>.tool.<verb> a role's verb, answered by whoever holds the seat // mesh.seat.<seat>.tool.<verb> a role's verb, answered by whoever holds the seat
// mesh.mod.<module>.call.<tool>.<caller>, mesh.seat.<seat>.call.<verb>.<caller> // mesh.mod.<module>.call.<tool>.<caller>, mesh.seat.<seat>.call.<verb>.<caller>
// the same, naming the bus user that called (caller.go, hq issue 365) // the same, naming the bus user that called (caller.go, hq issue 365)
//
// Design 47 H1, proof 2: the SDK and its importer delivered in one merge call, 2026-11-21.
package bus package bus
import ( import (
@@ -20,7 +18,6 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/membership" "git.novox.be/novox/mesh-sdk/go/membership"
"log" "log"
"regexp" "regexp"
@@ -191,12 +188,9 @@ type Conn struct {
cred Credential cred Credential
mu sync.Mutex mu sync.Mutex
issued map[string]*Membership // module → membership; present with nil = followed, none issued issued map[string]*Membership // module → membership; present with nil = followed, none issued
// withdrawn are the modules whose membership the grants part deleted: no longer assigned on this node (design 47 H2, onNew []*func(Membership)
// H-A-472 ninth addendum); their twins are removed and not made again, until a membership is issued again. subs []*nats.Subscription
withdrawn map[string]bool Logf func(format string, args ...any)
onNew []*func(Membership)
subs []*nats.Subscription
Logf func(format string, args ...any)
// answering is every subject this runtime answers on, so a subscription the bus refused can be // answering is every subject this runtime answers on, so a subscription the bus refused can be
// asked for again (novox/hq issue 222). // asked for again (novox/hq issue 222).
answering map[string]*answered answering map[string]*answered
@@ -209,15 +203,6 @@ type Conn struct {
waits map[string]map[chan string]bool waits map[string]map[chan string]bool
// inboxSaid is when a refused answer publish was last said, by subject (answerRefused). // inboxSaid is when a refused answer publish was last said, by subject (answerRefused).
inboxSaid map[string]time.Time inboxSaid map[string]time.Time
// bound is each state's binding, kept for the process and bound again only when the bus says its bucket is gone
// (state.go, design 47 H lead answers H-A-251): one Conn is one account's connection, so a binding is per account
// and bucket.
bindMu sync.Mutex
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 // answered is one subject the runtime answers on: what to subscribe again with, and how often it was
@@ -414,7 +399,6 @@ var (
func (c *Conn) issue(module string, m Membership) { func (c *Conn) issue(module string, m Membership) {
c.mu.Lock() c.mu.Lock()
c.issued[module] = &m c.issued[module] = &m
delete(c.withdrawn, module)
handlers := make([]func(Membership), 0, len(c.onNew)) handlers := make([]func(Membership), 0, len(c.onNew))
for _, h := range c.onNew { for _, h := range c.onNew {
handlers = append(handlers, *h) handlers = append(handlers, *h)
@@ -432,33 +416,29 @@ 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 // 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. // connection closes: Follow runs once per module, so nothing else would ever read it again.
func (c *Conn) followGrants(module string) { func (c *Conn) followGrants(module string) {
// 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). if c.watchGrants(module, true) {
patience, timeout := GrantsPatience, StateTimeout
if c.watchGrants(module, true, patience, timeout) {
return return
} }
wait, most := GrantsRetry, GrantsRetryMost
go func() { go func() {
wait := GrantsRetry
for !c.nc.IsClosed() { for !c.nc.IsClosed() {
time.Sleep(wait) time.Sleep(wait)
if c.nc.IsClosed() { if c.nc.IsClosed() {
return return
} }
if c.watchGrants(module, false, patience, timeout) { if c.watchGrants(module, false) {
c.Logf("[mesh-tools] the grants part's memberships are read again; %s on %s follows its key", module, c.node) c.Logf("[mesh-tools] the grants part's memberships are read again; %s on %s follows its key", module, c.node)
return return
} }
if wait *= 2; wait > most { if wait *= 2; wait > GrantsRetryMost {
wait = most wait = GrantsRetryMost
} }
} }
}() }()
} }
// watchGrants is one attempt of followGrants: true once the key is watched. A failure is said when say is true. Its // watchGrants is one attempt of followGrants: true once the key is watched. A failure is said when say is true.
// bounds, patience for the key's direct get and timeout for the bucket and its current value, are GrantsPatience and func (c *Conn) watchGrants(module string, say bool) bool {
// 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) { logf := func(format string, a ...any) {
if say { if say {
c.Logf(format, a...) c.Logf(format, a...)
@@ -468,7 +448,7 @@ func (c *Conn) watchGrants(module string, say bool, patience, timeout time.Durat
// First the key's direct get, which the account is granted alone: a bus that refuses it, or a state not there yet, // 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. // answers at once, where binding the bucket would wait out its bound on a refusal.
bucket := membership.GrantsBucket bucket := membership.GrantsBucket
probe, err := c.nc.Request("$JS.API.DIRECT.GET.KV_"+bucket+".$KV."+bucket+"."+key, nil, patience) probe, err := c.nc.Request("$JS.API.DIRECT.GET.KV_"+bucket+".$KV."+bucket+"."+key, nil, GrantsPatience)
if err != nil || probe.Header.Get("Status") == "503" { if err != nil || probe.Header.Get("Status") == "503" {
why := "it did not answer" why := "it did not answer"
if err != nil { if err != nil {
@@ -482,7 +462,7 @@ func (c *Conn) watchGrants(module string, say bool, patience, timeout time.Durat
if err != nil { if err != nil {
return false return false
} }
ctx, cancel := context.WithTimeout(context.Background(), timeout) ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel() defer cancel()
kv, err := js.KeyValue(ctx, bucket) kv, err := js.KeyValue(ctx, bucket)
if err != nil { if err != nil {
@@ -498,9 +478,7 @@ func (c *Conn) watchGrants(module string, say bool, patience, timeout time.Durat
} }
apply := func(e jetstream.KeyValueEntry) { apply := func(e jetstream.KeyValueEntry) {
if e.Operation() != jetstream.KeyValuePut { if e.Operation() != jetstream.KeyValuePut {
// A membership withdrawn: the module is no longer assigned on this node, so its twins go (H-A-472 ninth addendum). return // a membership withdrawn is the stream's, or the module's unassignment's, to say
c.withdraw(js, module)
return
} }
// Read through mesh-sdk's one codec of this state, the grants part's writer's (issue 774): it takes the bare // Read through mesh-sdk's one codec of this state, the grants part's writer's (issue 774): it takes the bare
// membership and a wrapper the part wrote before of one published or unchanged, and refuses a held-back one's // membership and a wrapper the part wrote before of one published or unchanged, and refuses a held-back one's
@@ -517,7 +495,7 @@ func (c *Conn) watchGrants(module string, say bool, patience, timeout time.Durat
} }
c.issue(module, m) c.issue(module, m)
} }
timer := time.NewTimer(timeout) timer := time.NewTimer(StateTimeout)
defer timer.Stop() defer timer.Stop()
for current := true; current; { for current := true; current; {
select { select {
@@ -533,7 +511,7 @@ func (c *Conn) watchGrants(module string, say bool, patience, timeout time.Durat
case <-timer.C: case <-timer.C:
_ = w.Stop() _ = w.Stop()
logf("[mesh-tools] %s's key %s of the grants part's memberships did not answer in %s; %s has no membership "+ 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, timeout, module) "until it can be", module, key, StateTimeout, module)
return false return false
} }
} }
@@ -547,60 +525,6 @@ func (c *Conn) watchGrants(module string, say bool, patience, timeout time.Durat
return true return true
} }
// withdraw removes the runner's twin `<consumer>_tools` from each stream the module's last membership named, as the grants
// part withdrew the membership (design 47 H2, H-A-472 ninth addendum): the module left this node. The membership is kept as
// it was, and the module marked withdrawn, so no hearing makes a twin again. A module with no membership issued names no
// stream, so a delete read at the start removes nothing (the runner removes nothing at its start). Each removal is said; a
// twin the bus does not hold is no failure.
func (c *Conn) withdraw(js jetstream.JetStream, module string) {
c.mu.Lock()
m := c.issued[module]
if c.withdrawn == nil {
c.withdrawn = map[string]bool{}
}
c.withdrawn[module] = true
c.mu.Unlock()
if m == nil {
return
}
for _, h := range m.Hears {
if h.Stream == "" || h.Consumer == "" {
continue
}
twin := h.Consumer + ToolsSuffix
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
err := js.DeleteConsumer(ctx, h.Stream, twin)
cancel()
switch {
case err == nil:
c.Logf("[mesh-tools] %s's membership on %s was withdrawn; its consumer %s on %s is removed", module, c.node, twin, h.Stream)
case errors.Is(err, jetstream.ErrConsumerNotFound):
default:
c.Logf("[mesh-tools] %s's membership on %s was withdrawn, and its consumer %s on %s cannot be removed: %v", module, c.node, twin, h.Stream, err)
}
}
}
// Withdrawn says whether the grants part withdrew the module's membership here, and none was issued since.
func (c *Conn) Withdrawn(module string) bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.withdrawn[module]
}
// heardOn is the entry of the module's membership for a stream, or, where it names none, the entry an older membership
// implies: the module's consumer by name, bound and never made.
func (c *Conn) heardOn(module, stream string) HeardIssued {
if m := c.Membership(module); m != nil {
for _, h := range m.Hears {
if h.Stream == stream && h.Consumer != "" {
return h
}
}
}
return HeardIssued{Stream: stream, Consumer: ConsumerOf(c.node, module)}
}
// Membership is what the mesh issued a module here, or nil when nothing has been issued. // Membership is what the mesh issued a module here, or nil when nothing has been issued.
func (c *Conn) Membership(module string) *Membership { func (c *Conn) Membership(module string) *Membership {
c.mu.Lock() c.mu.Lock()
@@ -693,7 +617,7 @@ type reply struct {
// answerOn answers one subject with one handler, and says which machine answered (ADR 0159). // answerOn answers one subject with one handler, and says which machine answered (ADR 0159).
func (c *Conn) answerOn(subject, queue string, h Handler) (func(), error) { func (c *Conn) answerOn(subject, queue string, h Handler) (func(), error) {
return c.answerCalledOn(subject, queue, func(_, _ string, body json.RawMessage) (any, error) { return h(body) }) return c.answerCalledOn(subject, queue, func(_ string, body json.RawMessage) (any, error) { return h(body) })
} }
// answerCalledOn answers one subject, handing the handler the caller the subject a call arrived on names: // answerCalledOn answers one subject, handing the handler the caller the subject a call arrived on names:
@@ -703,17 +627,7 @@ func (c *Conn) answerCalledOn(subject, queue string, h CalledHandler) (func(), e
cb := func(msg *nats.Msg) { cb := func(msg *nats.Msg) {
go func() { go func() {
var r reply var r reply
ask := "" result, err := h(callerOn(subject, msg.Subject), json.RawMessage(msg.Data))
if msg.Header != nil {
ask = msg.Header.Get(stdio.AskHeader)
}
result, err := h(callerOn(subject, msg.Subject), ask, json.RawMessage(msg.Data))
// A call the runner's drain cut at its stop is answered nothing: its caller sees a transport fault (design 47 H2
// §813 (12)).
var unanswered interface{ Unanswered() bool }
if errors.As(err, &unanswered) && unanswered.Unanswered() {
return
}
if err != nil { if err != nil {
r.Error = err.Error() r.Error = err.Error()
} else { } else {
@@ -766,7 +680,7 @@ func nullable(v any) any {
// HandleSubject answers a subject outright: a seat's verb where the mesh issued it. // HandleSubject answers a subject outright: a seat's verb where the mesh issued it.
func (c *Conn) HandleSubject(subject string, h Handler) (func(), error) { func (c *Conn) HandleSubject(subject string, h Handler) (func(), error) {
return c.HandleSubjectCalled(subject, func(_, _ string, body json.RawMessage) (any, error) { return h(body) }) return c.HandleSubjectCalled(subject, func(_ string, body json.RawMessage) (any, error) { return h(body) })
} }
// HandleSubjectCalled answers a tool subject and its caller-named counterpart (novox/hq issue 365): a call on // HandleSubjectCalled answers a tool subject and its caller-named counterpart (novox/hq issue 365): a call on
@@ -804,7 +718,7 @@ func (c *Conn) answerBoth(subject, queue string, h CalledHandler) (func(), error
// Handle serves `<module>.<tool>` where the mesh issued that module, and follows its membership: // Handle serves `<module>.<tool>` where the mesh issued that module, and follows its membership:
// when a new one arrives, it serves where it now says and stops where it no longer does. // when a new one arrives, it serves where it now says and stops where it no longer does.
func (c *Conn) Handle(key string, h Handler) (func(), error) { func (c *Conn) Handle(key string, h Handler) (func(), error) {
return c.HandleCalled(key, func(_, _ string, body json.RawMessage) (any, error) { return h(body) }) return c.HandleCalled(key, func(_ string, body json.RawMessage) (any, error) { return h(body) })
} }
// HandleCalled is Handle telling the handler who called: the bus user a caller-named subject names, or "" for // HandleCalled is Handle telling the handler who called: the bus user a caller-named subject names, or "" for
@@ -1265,13 +1179,9 @@ func (c *Conn) ConsumeAsBeatingWhen(module string, deliver func(Envelope) error,
missed.Store(false) // an event arrived: the consumer is heard, whatever was said before missed.Store(false) // an event arrived: the consumer is heard, whatever was said before
return deliver(env) return deliver(env)
}) })
// Made first from the membership's spec where its EVENTS entry carries one (H-A-472 fifth to eighth addenda), else bound // Bound by name, never created and never matched against a subject: the consumer and its
// by name: then the consumer and its filters are the mesh's (design 29 §3), exactly as the module's own runtime bound it. // filters are the mesh's (design 29 §3), exactly as the module's own runtime bound it.
heard := c.heardOn(module, EventsStream) events, _, doing, err := h.bind(EventsStream, durable, func(err error) {
if c.Withdrawn(module) {
heard.Filters = nil
}
events, _, doing, err := h.bind(heard, func(err error) {
if errors.Is(err, jetstream.ErrNoHeartbeat) { if errors.Is(err, jetstream.ErrNoHeartbeat) {
say("the bus's heartbeat to the consumer " + durable + " stopped arriving") say("the bus's heartbeat to the consumer " + durable + " stopped arriving")
} }
+2 -3
View File
@@ -106,9 +106,8 @@ func callerOn(pattern, subject string) string {
return UserOfToken(subject[dot+1:]) return UserOfToken(subject[dot+1:])
} }
// CalledHandler answers one call, told who called: the bus user the subject named, or "" when it named none; and the ask id the // CalledHandler answers one call, told who called: the bus user the subject named, or "" when it named none.
// call carried in its request header stdio.AskHeader, or "" (design 47 H2 §775, H-A-351). type CalledHandler func(caller string, body json.RawMessage) (any, error)
type CalledHandler func(caller, ask string, body json.RawMessage) (any, error)
// callers is what a connection keeps of its caller-named calls: those in flight, by subject, so a refused // callers is what a connection keeps of its caller-named calls: those in flight, by subject, so a refused
// publish ends its call at once instead of after RequestTimeout. // publish ends its call at once instead of after RequestTimeout.
+3 -3
View File
@@ -58,7 +58,7 @@ type heard struct {
callers []string callers []string
} }
func (h *heard) handler(caller, _ string, _ json.RawMessage) (any, error) { func (h *heard) handler(caller string, _ json.RawMessage) (any, error) {
h.mu.Lock() h.mu.Lock()
defer h.mu.Unlock() defer h.mu.Unlock()
h.callers = append(h.callers, caller) h.callers = append(h.callers, caller)
@@ -79,7 +79,7 @@ func TestACallerFallsBackAtOnceWhereNothingServesTheCallerNamedSubject(t *testin
h := &heard{} h := &heard{}
// An older runtime: the subject that names no caller, alone. // 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) { stop, err := server.HandleSubject("mesh.mod.ledger.tool.who", func(body json.RawMessage) (any, error) {
return h.handler("", "", body) return h.handler("", body)
}) })
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -223,7 +223,7 @@ func TestACallWaitsTheBoundItsVerbNamesAndTimesOutThere(t *testing.T) {
url := grantedBus(t, map[string][]string{"anchor.node-tools": {"_INBOX.>"}, "shanks.node-tools": {"mesh.mod.*.tool.>"}}) 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") server := dial(t, url, "node-tools", "anchor", "anchor.node-tools")
release := make(chan struct{}) release := make(chan struct{})
stop, err := server.HandleSubjectCalled("mesh.mod.ledger.tool.slow", func(string, string, json.RawMessage) (any, error) { stop, err := server.HandleSubjectCalled("mesh.mod.ledger.tool.slow", func(string, json.RawMessage) (any, error) {
<-release <-release
return map[string]any{}, nil return map[string]any{}, nil
}) })
+1 -3
View File
@@ -77,8 +77,6 @@ func TestAConsumerSaysItIsBoundWhileIdleAndOnceWhenTheBusEndedIt(t *testing.T) {
} }
})) }))
mesh.Consumer(t, "anchor", "quiet", []string{"mesh.mod.alpha.event.>"}, time.Second) mesh.Consumer(t, "anchor", "quiet", []string{"mesh.mod.alpha.event.>"}, time.Second)
// The unasked consume below pulls a durable of its own: a second loop on quiet's is refused (H-A-196, H-A-197).
mesh.Consumer(t, "anchor", "unasked", []string{"mesh.mod.alpha.event.>"}, time.Second)
c, err := bus.Connect(bus.Credential{URL: mt.URL(t), Module: "node-tools", Node: "anchor"}) c, err := bus.Connect(bus.Credential{URL: mt.URL(t), Module: "node-tools", Node: "anchor"})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -99,7 +97,7 @@ func TestAConsumerSaysItIsBoundWhileIdleAndOnceWhenTheBusEndedIt(t *testing.T) {
t.Cleanup(stop) t.Cleanup(stop)
// A consume nobody asked a heartbeat of says nothing and asks the bus nothing, however many intervals pass. // A consume nobody asked a heartbeat of says nothing and asks the bus nothing, however many intervals pass.
var unaskedBeats atomic.Int32 var unaskedBeats atomic.Int32
unasked, err := c.ConsumeAsBeatingWhen("unasked", func(bus.Envelope) error { return nil }, unasked, err := c.ConsumeAsBeatingWhen("quiet", func(bus.Envelope) error { return nil },
func(bus.Beat) { unaskedBeats.Add(1) }, func() bool { return false }) func(bus.Beat) { unaskedBeats.Add(1) }, func() bool { return false })
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
-101
View File
@@ -1,101 +0,0 @@
package bus
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-sdk/go/buscompose"
)
// QueueWaitingMost is the most a waiting read holds, in its asks' ids and modules (design 47 H2 H-A-410).
const QueueWaitingMost = 768 << 10
// WaitingAsk is one ask that waits on a seat's work queue: its id (the publisher's own, as it published it), the module that
// put it and how long it has waited.
type WaitingAsk struct {
ID string `json:"id"`
Module string `json:"module"`
AgeSeconds int64 `json:"age_seconds"`
// Again says the ask was handed to a worker at least once and not acknowledged: held now, or handed back to wait again;
// the holder tells the two apart by its own state taken (H-A-410, second addendum).
Again bool `json:"again,omitempty"`
}
// QueueWaiting is what waits on a seat's work queue, oldest first, and whether the read stopped at QueueWaitingMost.
type QueueWaiting struct {
Asks []WaitingAsk `json:"asks"`
Capped bool `json:"capped,omitempty"`
}
// QueueWaitingOf reads, without consuming, the asks that wait on the seat's work queue for module, the holder whose
// membership lists the queue's workers: its own store (ADR 0596). For each of its workers on the seat's stream, every message
// after the worker's acknowledgement floor is read by a direct get by subject, never by a consumer of its own; one at or
// below the worker's delivered sequence is marked again (design 47 H2 H-A-410 and its addenda).
func (c *Conn) QueueWaitingOf(module, seat string) (QueueWaiting, error) {
t, err := c.trafficOf(module)
if err != nil {
return QueueWaiting{}, err
}
// The work-queue stream a seat's asks are kept on, by the one derivation every part takes (H-A-410, P9).
stream := buscompose.SeatQueueStreamName(seat)
var workers []SeatWorker
for _, w := range t.Workers {
if w.Stream == stream {
workers = append(workers, w)
}
}
if len(workers) == 0 {
return QueueWaiting{}, fmt.Errorf("%s holds no work queue of the seat %s: its membership lists no worker on %s "+
"(novox/hq ADR 0596: a holder reads its own queue)", module, seat, stream)
}
js, err := jetstream.New(c.nc)
if err != nil {
return QueueWaiting{}, err
}
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel()
kept, err := js.Stream(ctx, stream)
if err != nil {
return QueueWaiting{}, fmt.Errorf("reading %s's queue %s: %w", module, stream, err)
}
out := QueueWaiting{Asks: []WaitingAsk{}}
size, now := 0, time.Now()
for _, w := range workers {
bound, err := c.pullConsumer(module, w)
if err != nil {
return QueueWaiting{}, err
}
info, err := bound.Info(ctx)
if err != nil {
return QueueWaiting{}, fmt.Errorf("reading %s's worker %s: %w", module, w.Consumer, err)
}
filter := w.Filter
if filter == "" {
filter = ">"
}
for seq := info.AckFloor.Stream + 1; ; {
m, err := kept.GetMsg(ctx, seq, jetstream.WithGetMsgSubject(filter))
if errors.Is(err, jetstream.ErrMsgNotFound) {
break
}
if err != nil {
return QueueWaiting{}, fmt.Errorf("reading %s's queue %s: %w", module, stream, err)
}
seq = m.Sequence + 1
ask := WaitingAsk{Module: m.Header.Get("x-source"), AgeSeconds: int64(now.Sub(m.Time) / time.Second),
Again: m.Sequence <= info.Delivered.Stream}
ask.ID = strings.TrimPrefix(m.Header.Get("x-event-id"), ask.Module+".")
if size += len(ask.ID) + len(ask.Module) + 48; size > QueueWaitingMost {
out.Capped = true
return out, nil
}
out.Asks = append(out.Asks, ask)
}
}
return out, nil
}
+7 -12
View File
@@ -195,8 +195,7 @@ func (c *Conn) SeatProve(module, subject string, body json.RawMessage) (json.Raw
} }
// SeatAnswer answers every proof on a subject the module's seat traffic lists among its answers, with what // SeatAnswer answers every proof on a subject the module's seat traffic lists among its answers, with what
// answer returns. A returned error is answered as `{"error": "<words>"}`, never as silence, but for one that says it is // answer returns. A returned error is answered as `{"error": "<words>"}`, never as silence.
// unanswered (a proof after the stop or cut at the bound).
func (c *Conn) SeatAnswer(module, subject string, answer func(subject string, body json.RawMessage) (json.RawMessage, error)) (func(), error) { func (c *Conn) SeatAnswer(module, subject string, answer func(subject string, body json.RawMessage) (json.RawMessage, error)) (func(), error) {
t, err := c.trafficOf(module) t, err := c.trafficOf(module)
if err != nil { if err != nil {
@@ -220,12 +219,6 @@ func (c *Conn) SeatAnswer(module, subject string, answer func(subject string, bo
return return
} }
out, err := answer(msg.Subject, body) out, err := answer(msg.Subject, body)
// A proof arriving after the runner's stop, or cut at its bound, is answered nothing, as answerCalledOn does
// (design 47 H2 §813 (12), H-A-369).
var unanswered interface{ Unanswered() bool }
if errors.As(err, &unanswered) && unanswered.Unanswered() {
return
}
if err != nil { if err != nil {
b, _ := json.Marshal(map[string]string{"error": err.Error()}) b, _ := json.Marshal(map[string]string{"error": err.Error()})
_ = msg.Respond(b) _ = msg.Respond(b)
@@ -286,8 +279,6 @@ func (c *Conn) SeatTake(module, consumer string, deliver func(Work) error) (func
if err != nil { if err != nil {
return nil, fmt.Errorf("binding %s's worker %s on %s: %w", module, w.Consumer, w.Stream, err) 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) { reading, err := bound.Consume(func(msg jetstream.Msg) {
if !json.Valid(msg.Data()) { if !json.Valid(msg.Data()) {
_ = msg.Term() _ = msg.Term()
@@ -301,7 +292,7 @@ func (c *Conn) SeatTake(module, consumer string, deliver func(Work) error) (func
// that died, not one that is slow. // that died, not one that is slow.
done := make(chan struct{}) done := make(chan struct{})
go func() { go func() {
tick := time.NewTicker(heartbeat) tick := time.NewTicker(WorkHeartbeat)
defer tick.Stop() defer tick.Stop()
for { for {
select { select {
@@ -436,7 +427,11 @@ func (c *Conn) stateWrite(module, name, key string, value json.RawMessage,
} }
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel() defer cancel()
rev, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (uint64, error) { return write(ctx, kv) }) kv, err := c.bucket(ctx, s)
if err != nil {
return 0, err
}
rev, err := write(ctx, kv)
if errors.Is(err, jetstream.ErrKeyExists) || isWrongSequence(err) { if errors.Is(err, jetstream.ErrKeyExists) || isWrongSequence(err) {
return 0, changed{name + "." + key} return 0, changed{name + "." + key}
} }
+20 -26
View File
@@ -33,10 +33,8 @@ type Pulled struct {
Delivered uint64 `json:"delivered"` 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 // pulls are the messages modules pulled and have not settled, by id; each kept with the module it was pulled for, so
// pulled for, so one module never settles another's; and the workers bound on that connection. They are the Conn's, not // one module never settles another's.
// 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 { type pulls struct {
mu sync.Mutex mu sync.Mutex
held map[string]pulledMsg held map[string]pulledMsg
@@ -48,6 +46,8 @@ type pulledMsg struct {
msg jetstream.Msg msg jetstream.Msg
} }
var seatPulls = &pulls{held: map[string]pulledMsg{}, cons: map[string]jetstream.Consumer{}}
func pullID() string { func pullID() string {
var b [8]byte var b [8]byte
_, _ = rand.Read(b[:]) _, _ = rand.Read(b[:])
@@ -111,20 +111,17 @@ 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()), p := &Pulled{ID: pullID(), Worker: w.Consumer, Subject: msg.Subject(), Body: json.RawMessage(msg.Data()),
Headers: headers, Delivered: delivered} Headers: headers, Delivered: delivered}
c.pulls.mu.Lock() seatPulls.mu.Lock()
if c.pulls.held == nil { seatPulls.held[p.ID] = pulledMsg{module: module, msg: msg}
c.pulls.held = map[string]pulledMsg{} seatPulls.mu.Unlock()
}
c.pulls.held[p.ID] = pulledMsg{module: module, msg: msg}
c.pulls.mu.Unlock()
return p, nil return p, nil
} }
func (c *Conn) pullConsumer(module string, w SeatWorker) (jetstream.Consumer, error) { func (c *Conn) pullConsumer(module string, w SeatWorker) (jetstream.Consumer, error) {
key := module + " " + w.Consumer key := module + " " + w.Consumer
c.pulls.mu.Lock() seatPulls.mu.Lock()
bound, ok := c.pulls.cons[key] bound, ok := seatPulls.cons[key]
c.pulls.mu.Unlock() seatPulls.mu.Unlock()
if ok { if ok {
return bound, nil return bound, nil
} }
@@ -138,12 +135,9 @@ func (c *Conn) pullConsumer(module string, w SeatWorker) (jetstream.Consumer, er
if err != nil { if err != nil {
return nil, fmt.Errorf("binding %s's worker %s on %s: %w", module, w.Consumer, w.Stream, err) return nil, fmt.Errorf("binding %s's worker %s on %s: %w", module, w.Consumer, w.Stream, err)
} }
c.pulls.mu.Lock() seatPulls.mu.Lock()
if c.pulls.cons == nil { seatPulls.cons[key] = bound
c.pulls.cons = map[string]jetstream.Consumer{} seatPulls.mu.Unlock()
}
c.pulls.cons[key] = bound
c.pulls.mu.Unlock()
return bound, nil return bound, nil
} }
@@ -174,15 +168,15 @@ func (c *Conn) SeatSettleAfter(module, id string, delay time.Duration) error {
} }
func (c *Conn) settle(module, id, fate string, delay time.Duration) error { func (c *Conn) settle(module, id, fate string, delay time.Duration) error {
c.pulls.mu.Lock() seatPulls.mu.Lock()
p, ok := c.pulls.held[id] p, ok := seatPulls.held[id]
if ok && p.module != module { if ok && p.module != module {
ok = false ok = false
} }
if ok && fate != SettleProgress { if ok && fate != SettleProgress {
delete(c.pulls.held, id) delete(seatPulls.held, id)
} }
c.pulls.mu.Unlock() seatPulls.mu.Unlock()
if !ok { if !ok {
return fmt.Errorf("%s holds no pulled message %s", module, id) return fmt.Errorf("%s holds no pulled message %s", module, id)
} }
@@ -198,8 +192,8 @@ func (c *Conn) settle(module, id, fate string, delay time.Duration) error {
case SettleNakAfter: case SettleNakAfter:
return p.msg.NakWithDelay(delay) return p.msg.NakWithDelay(delay)
} }
c.pulls.mu.Lock() seatPulls.mu.Lock()
c.pulls.held[id] = p // an unknown fate settles nothing seatPulls.held[id] = p // an unknown fate settles nothing
c.pulls.mu.Unlock() seatPulls.mu.Unlock()
return fmt.Errorf("a pulled message's fate is ack, nak, nak-after, term or progress, not %q", fate) return fmt.Errorf("a pulled message's fate is ack, nak, nak-after, term or progress, not %q", fate)
} }
+10 -16
View File
@@ -19,22 +19,17 @@ func TestAHolderPullsOneMessageWhenItHasRoom(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
} }
// A pull that wants a message waits for it: the worker learns of a stored message after the publish is answered, so first, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0)
// 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 { if err != nil || first == nil || string(first.Body) != `{"id":"a1"}` || first.Delivered != 1 {
t.Fatalf("the first pull = %+v, %v", first, err) t.Fatalf("the first pull = %+v, %v", first, err)
} }
// One pulled and in hand, the other never delivered: nothing was fetched ahead. What is in hand is the worker's own // One pulled, one still waiting on the stream: nothing was fetched ahead.
// 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") info, err := js.ConsumerInfo("SEAT_OPERATOR_CHANNEL", "SEAT_OPERATOR_CHANNEL_worker")
if err != nil || info.NumAckPending != 1 { if err != nil || info.NumPending != 1 || info.NumAckPending != 1 {
t.Fatalf("after one pull: in hand %d (%v); want 1", info.NumAckPending, err) t.Fatalf("after one pull: pending %d, in hand %d (%v); want 1 and 1", info.NumPending, info.NumAckPending, err)
} }
second, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 10*time.Second) second, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0)
if err != nil || second == nil || string(second.Body) != `{"id":"a2"}` || second.Delivered != 1 { if err != nil || second == nil || string(second.Body) != `{"id":"a2"}` {
t.Fatalf("the second pull = %+v, %v", second, err) t.Fatalf("the second pull = %+v, %v", second, err)
} }
if none, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0); err != nil || none != nil { if none, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0); err != nil || none != nil {
@@ -59,23 +54,22 @@ func TestAHolderPullsOneMessageWhenItHasRoom(t *testing.T) {
if err := conn.SeatSettle("messenger", second.ID, bus.SettleNak); err != nil { if err := conn.SeatSettle("messenger", second.ID, bus.SettleNak); err != nil {
t.Fatal(err) t.Fatal(err)
} }
again, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 10*time.Second) again, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", time.Second)
if err != nil || again == nil || string(again.Body) != `{"id":"a2"}` || again.Delivered != 2 { if err != nil || again == nil || string(again.Body) != `{"id":"a2"}` || again.Delivered != 2 {
t.Fatalf("the message handed back = %+v, %v", again, err) 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 // 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. The delay is what the next pull must come within to see nothing, so it is a second, not a // of 0 settles nothing.
// moment a loaded machine can spend between two calls.
if err := conn.SeatSettleAfter("messenger", again.ID, 0); err == nil { if err := conn.SeatSettleAfter("messenger", again.ID, 0); err == nil {
t.Error("a delay of 0 was accepted") t.Error("a delay of 0 was accepted")
} }
if err := conn.SeatSettleAfter("messenger", again.ID, time.Second); err != nil { if err := conn.SeatSettleAfter("messenger", again.ID, 300*time.Millisecond); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if early, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0); err != nil || early != nil { 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) 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", 10*time.Second) late, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 2*time.Second)
if err != nil || late == nil || late.Delivered != 3 { if err != nil || late == nil || late.Delivered != 3 {
t.Fatalf("the message given again after its delay = %+v, %v", late, err) t.Fatalf("the message given again after its delay = %+v, %v", late, err)
} }
+2 -33
View File
@@ -34,13 +34,11 @@ func seatMesh(t *testing.T) (*mt.Mesh, *bus.Conn, nats.JetStreamContext) {
t.Fatal(err) 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{ for stream, c := range map[string]*nats.ConsumerConfig{
"SEAT_OPERATOR_CHANNEL": {Durable: "SEAT_OPERATOR_CHANNEL_worker", AckPolicy: nats.AckExplicitPolicy, "SEAT_OPERATOR_CHANNEL": {Durable: "SEAT_OPERATOR_CHANNEL_worker", AckPolicy: nats.AckExplicitPolicy,
FilterSubject: "mesh.seat.operator-channel.accept.>", AckWait: 30 * time.Second}, FilterSubject: "mesh.seat.operator-channel.accept.>", AckWait: 2 * time.Second},
"SEAT_CHANNEL": {Durable: "SEAT_CHANNEL_TELEGRAM_worker", AckPolicy: nats.AckExplicitPolicy, "SEAT_CHANNEL": {Durable: "SEAT_CHANNEL_TELEGRAM_worker", AckPolicy: nats.AckExplicitPolicy,
FilterSubject: "mesh.seat.channel.accept.*.telegram", AckWait: 30 * time.Second}, FilterSubject: "mesh.seat.channel.accept.*.telegram", AckWait: 2 * time.Second},
} { } {
if _, err := js.AddConsumer(stream, c); err != nil { if _, err := js.AddConsumer(stream, c); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -166,21 +164,12 @@ func TestTheHolderTakesItsWorkOnceAndAFailureComesBack(t *testing.T) {
} }
} }
// unansweredProof is the error the runner's drain hands for a call after its stop or cut at its bound.
type unansweredProof struct{}
func (unansweredProof) Error() string { return "answered nothing" }
func (unansweredProof) Unanswered() bool { return true }
func TestAProofIsAskedAndAnsweredAndNeverKept(t *testing.T) { func TestAProofIsAskedAndAnsweredAndNeverKept(t *testing.T) {
_, conn, js := seatMesh(t) _, conn, js := seatMesh(t)
stop, err := conn.SeatAnswer("messenger", "mesh.seat.intake.proof.code.*", func(subject string, body json.RawMessage) (json.RawMessage, error) { stop, err := conn.SeatAnswer("messenger", "mesh.seat.intake.proof.code.*", func(subject string, body json.RawMessage) (json.RawMessage, error) {
if !strings.HasSuffix(subject, ".telegram") { if !strings.HasSuffix(subject, ".telegram") {
return nil, errors.New("asked by another kind") return nil, errors.New("asked by another kind")
} }
if string(body) == `{"cut":true}` {
return nil, unansweredProof{}
}
return json.RawMessage(`{"linked":true}`), nil return json.RawMessage(`{"linked":true}`), nil
}) })
if err != nil { if err != nil {
@@ -195,26 +184,6 @@ func TestAProofIsAskedAndAnsweredAndNeverKept(t *testing.T) {
if string(answer) != `{"linked":true}` { if string(answer) != `{"linked":true}` {
t.Fatalf("the proof was answered %s", answer) t.Fatalf("the proof was answered %s", answer)
} }
// A proof arriving after the stop, or cut at the bound, is answered nothing (design 47 H2 §813 (12), H-A-369): the
// answerer handles proofs in order, so the first reply on one inbox after a cut proof and a whole one is the whole one's.
raw, err := nats.Connect(mt.URL(t))
if err != nil {
t.Fatal(err)
}
defer raw.Close()
inbox := nats.NewInbox()
replies, err := raw.SubscribeSync(inbox)
if err != nil {
t.Fatal(err)
}
for _, body := range []string{`{"cut":true}`, `{"code":"123456"}`} {
if err := raw.PublishRequest("mesh.seat.intake.proof.code.telegram", inbox, []byte(body)); err != nil {
t.Fatal(err)
}
}
if first, err := replies.NextMsg(30 * time.Second); err != nil || string(first.Data) != `{"linked":true}` {
t.Fatalf("a proof cut at the stop was answered, or the whole one not: %v %v", first, err)
}
if _, err := conn.SeatProve("telegram", "mesh.seat.intake.proof.code.desktop", json.RawMessage(`{}`)); err == nil { if _, err := conn.SeatProve("telegram", "mesh.seat.intake.proof.code.desktop", json.RawMessage(`{}`)); err == nil {
t.Error("a channel asked a proof as another kind") t.Error("a channel asked a proof as another kind")
} }
+153 -306
View File
@@ -5,16 +5,16 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"maps"
"regexp" "regexp"
"slices"
"sort" "sort"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"git.novox.be/novox/mesh-sdk/go/membership" "git.novox.be/novox/mesh-sdk/go/membership"
"github.com/nats-io/nats.go" "git.novox.be/novox/mesh-sdk/go/pernode"
"github.com/nats-io/nats.go/jetstream" "github.com/nats-io/nats.go/jetstream"
) )
@@ -40,18 +40,11 @@ type StateIssued struct {
// StateEntry is one key's current value. // StateEntry is one key's current value.
type StateEntry struct { type StateEntry struct {
Key string `json:"key"` Key string `json:"key"`
// Value is none on a delete a page hands (Deleted). Value json.RawMessage `json:"value"`
Value json.RawMessage `json:"value,omitempty"`
Revision uint64 `json:"revision"` Revision uint64 `json:"revision"`
// At is when the bus wrote this value (the entry's created time), as stdio.StateEntry.At reads it. // At is when the bus wrote this value (the entry's created time), as stdio.StateEntry.At reads it.
At time.Time `json:"at,omitzero"` At time.Time `json:"at,omitzero"`
// SeenAgain is set in a page on a value the bus wrote after the read reached its bucket, so a reader knows it replaces
// any value it holds for the key (design 47 H2 §779, H-A-382).
SeenAgain bool `json:"seen-again,omitempty"`
// Deleted is set in a page on a key's kept delete (a purge reads as one), handed at its sequence with no value, so a
// reader following pages removes the key and a deleted key never comes back alive (design 47 H2 §779, H-A-451 (1)).
Deleted bool `json:"deleted,omitempty"`
} }
// StateChange is one change a watch delivers: a key put, deleted, or expired (its own time to live, or the // StateChange is one change a watch delivers: a key put, deleted, or expired (its own time to live, or the
@@ -99,107 +92,20 @@ func (c *Conn) issuedState(module, name string) (StateIssued, error) {
"issued: %s (novox/hq ADR 0201, ADR 0595 §1)", module, name, issued) "issued: %s (novox/hq ADR 0201, ADR 0595 §1)", module, name, issued)
} }
// binding is one bucket's binding, or the bind in flight for it: the first asker binds, an asker meanwhile waits for
// that bind (done) instead of asking the bus again.
type binding struct {
done chan struct{}
kv jetstream.KeyValue
err error
}
// bucket is the state's binding, bound once for the process (design 47 H lead answers H-A-251): binding a bucket is a
// stream-info request on the bus, and asked before every get it made each read two answers. A bind that fails is not
// kept, so the next ask binds again.
func (c *Conn) bucket(ctx context.Context, s StateIssued) (jetstream.KeyValue, error) { func (c *Conn) bucket(ctx context.Context, s StateIssued) (jetstream.KeyValue, error) {
c.bindMu.Lock()
b := c.bound[s.Bucket]
if b == nil {
if c.bound == nil {
c.bound = map[string]*binding{}
}
b = &binding{done: make(chan struct{})}
c.bound[s.Bucket] = b
c.bindMu.Unlock()
b.kv, b.err = c.bindBucket(ctx, s.Bucket)
if b.err != nil {
c.bindMu.Lock()
if c.bound[s.Bucket] == b {
delete(c.bound, s.Bucket)
}
c.bindMu.Unlock()
}
close(b.done)
} else {
c.bindMu.Unlock()
select {
case <-b.done:
case <-ctx.Done():
return nil, ctx.Err()
}
}
if b.err != nil {
if errors.Is(b.err, jetstream.ErrBucketNotFound) {
return nil, fmt.Errorf("the state %q is issued and its bucket is not on the bus yet: the mesh "+
"creates it from the catalogue on its next raise", s.Name)
}
return nil, b.err
}
return b.kv, nil
}
func (c *Conn) bindBucket(ctx context.Context, bucket string) (jetstream.KeyValue, error) {
if c.bind != nil {
return c.bind(ctx, bucket)
}
js, err := jetstream.New(c.nc) js, err := jetstream.New(c.nc)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return js.KeyValue(ctx, bucket) kv, err := js.KeyValue(ctx, s.Bucket)
}
// unbind drops a bucket's binding the bus said is gone, when it is still the one kept, so the next ask binds again.
func (c *Conn) unbind(bucket string, kv jetstream.KeyValue) {
c.bindMu.Lock()
defer c.bindMu.Unlock()
b := c.bound[bucket]
if b == nil {
return
}
select {
case <-b.done: // bound: its kv is written
default:
return // bound again already, in flight
}
if b.kv == kv {
delete(c.bound, bucket)
}
}
// bucketGone is the bus saying a kept binding's bucket is not there (deleted, or deleted and created again): no stream of
// the name, or nobody answers on its subjects.
func bucketGone(err error) bool {
return errors.Is(err, jetstream.ErrStreamNotFound) || errors.Is(err, jetstream.ErrBucketNotFound) ||
errors.Is(err, jetstream.ErrNoStreamResponse) || errors.Is(err, nats.ErrNoResponders)
}
// inBucket does one act on the state's kept binding; when the bus says its bucket is gone, the binding is dropped, the
// bucket bound again once and the act done once more on the new binding (H-A-251).
func inBucket[T any](c *Conn, ctx context.Context, s StateIssued, do func(jetstream.KeyValue) (T, error)) (T, error) {
var none T
kv, err := c.bucket(ctx, s)
if err != nil { if err != nil {
return none, err if errors.Is(err, jetstream.ErrBucketNotFound) {
return nil, fmt.Errorf("the state %q is issued and its bucket is not on the bus yet: the mesh "+
"creates it from the catalogue on its next raise", s.Name)
}
return nil, err
} }
got, err := do(kv) return kv, nil
if !bucketGone(err) {
return got, err
}
c.unbind(s.Bucket, kv)
if kv, err = c.bucket(ctx, s); err != nil {
return none, err
}
return do(kv)
} }
func checkKey(key string) error { func checkKey(key string) error {
@@ -224,7 +130,11 @@ func (c *Conn) StateGet(module, name, key string) (*StateEntry, error) {
} }
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel() defer cancel()
e, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (jetstream.KeyValueEntry, error) { return kv.Get(ctx, key) }) kv, err := c.bucket(ctx, s)
if err != nil {
return nil, err
}
e, err := kv.Get(ctx, key)
if errors.Is(err, jetstream.ErrKeyNotFound) { if errors.Is(err, jetstream.ErrKeyNotFound) {
return nil, nil return nil, nil
} }
@@ -234,8 +144,7 @@ func (c *Conn) StateGet(module, name, key string) (*StateEntry, error) {
return &StateEntry{Key: e.Key(), Value: valueOf(e.Value()), Revision: e.Revision(), At: e.Created().UTC()}, nil return &StateEntry{Key: e.Key(), Value: valueOf(e.Value()), Revision: e.Revision(), At: e.Created().UTC()}, nil
} }
// StatePage is one page of a read: the values the bus wrote after the cursor's sequence, in sequence order, and the // StatePage is the current values after a key, in key order, and the key to ask after for the rest.
// opaque cursor that continues the read, empty at its end (design 47 H2 §779).
type StatePage struct { type StatePage struct {
Entries []StateEntry `json:"entries"` Entries []StateEntry `json:"entries"`
Next string `json:"next,omitempty"` Next string `json:"next,omitempty"`
@@ -244,181 +153,100 @@ type StatePage struct {
// StatePageBudget is the time a page spends reading when the asker names none: well under the 30 s a reader waits. // StatePageBudget is the time a page spends reading when the asker names none: well under the 30 s a reader waits.
const StatePageBudget = 10 * time.Second const StatePageBudget = 10 * time.Second
// StatePageMost is the most a page holds, in keys and values, whatever the asker names (design 47 H2 §779).
const StatePageMost = 768 << 10
// PageClock is the time a page's budget counts by, replaced by a test. // PageClock is the time a page's budget counts by, replaced by a test.
var PageClock = time.Now var PageClock = time.Now
// pageCursor is where a read stands, written into the opaque cursor a page answers as next: the bucket's node for a state // StatePage reads the values in key order after `after` in one pass, as many as fit maxBytes (each key and value),
// kept one bucket per node (empty for one bucket), the sequence of the last message handed, and mark, the bucket's last // stopping when budget is spent, at least one value, so a bundle asks one request for many values, where StateGet
// sequence when the read reached it, after which every message is marked seen-again (H-A-382 (1)). The runner keeps // is one request each. Access is checked once and the bucket bound once. It is a read like StateGet: served to the
// nothing per read: the cursor carries it all. // owner and to every reader, and writes nothing. Next is the last key given when more follow.
type pageCursor struct { func (c *Conn) StatePage(module, name, after string, maxBytes int, budget time.Duration) (StatePage, error) {
node string
after, mark uint64
}
func (p pageCursor) String() string {
return fmt.Sprintf("%s.%d.%d", p.node, p.mark, p.after)
}
func cursorOf(raw string) (pageCursor, error) {
if raw == "" {
return pageCursor{}, nil
}
parts := strings.Split(raw, ".")
var p pageCursor
var err1, err2 error
if len(parts) == 3 {
p.node = parts[0]
p.mark, err1 = strconv.ParseUint(parts[1], 10, 64)
p.after, err2 = strconv.ParseUint(parts[2], 10, 64)
}
if len(parts) != 3 || err1 != nil || err2 != nil {
return pageCursor{}, fmt.Errorf("%q is not a cursor a page answered: hand back the next of the page before", raw)
}
return p, nil
}
// StatePage reads one page of a state in the order the bus wrote it (design 47 H2 §779, H-A-254, H-A-382): from an ordered
// consumer starting after the cursor's sequence, never a replay of the bucket per page, each kept message once across the
// pages of a read, a key's older kept revisions included; a message written after the read reached its bucket comes
// marked seen-again, and a deleted key gets no entry. A page holds as many values as fit maxBytes (each key and value; at
// most StatePageMost) or the budget allows, at least one, and next continues the read, empty at its end. A state kept one
// bucket per node is read one node's bucket after another, in node order. It is a read like StateGet: served to the owner
// and to every reader, and writes nothing.
func (c *Conn) StatePage(module, name, cursor string, maxBytes int, budget time.Duration) (StatePage, error) {
s, err := c.issuedState(module, name) s, err := c.issuedState(module, name)
if err != nil { if err != nil {
return StatePage{}, err return StatePage{}, err
} }
at, err := cursorOf(cursor)
if err != nil {
return StatePage{}, err
}
if budget <= 0 { if budget <= 0 {
budget = StatePageBudget budget = StatePageBudget
} }
if maxBytes <= 0 || maxBytes > StatePageMost { // The bind and the listing have a StateTimeout of their own, and each get another: the page's time budget is what
maxBytes = StatePageMost // ends a slow page (with Next), never a deadline spread over the whole of it.
} // ctx covers the bind and the listing alone; every bus request inside the loop takes each().
r := &pageRead{page: StatePage{Entries: []StateEntry{}}, maxBytes: maxBytes, budget: budget, started: PageClock()}
if !s.PerNode {
if at.node != "" {
return StatePage{}, fmt.Errorf("%q is not a cursor of %s's state %s: it names a node's bucket", cursor, module, name)
}
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel()
if _, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (struct{}, error) {
return struct{}{}, r.bucket(kv, at, cursor != "")
}); err != nil {
return StatePage{}, err
}
return r.page, nil
}
fam := c.family(s)
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
nodes, err := fam.Nodes(ctx)
cancel()
if err != nil {
return StatePage{}, err
}
sort.Strings(nodes)
for _, node := range nodes {
if node < at.node {
continue
}
from, reached := pageCursor{node: node}, cursor != "" && node == at.node
if reached {
from = at
}
octx, ocancel := context.WithTimeout(context.Background(), StateTimeout)
kv, err := fam.Open(octx, node)
if err == nil && kv != nil {
err = r.bucket(kv, from, reached)
}
ocancel()
if err != nil {
return StatePage{}, err
}
if r.page.Next != "" {
return r.page, nil
}
}
return r.page, nil
}
// pageRead is one page being filled.
type pageRead struct {
page StatePage
size int
maxBytes int
budget time.Duration
started time.Time
}
// bucket reads one bucket after from into the page, until the bucket is read to its end (the page then goes on with the
// next bucket, or ends with no next) or the page is full (next set). reached says an earlier page of the read already
// reached the bucket, so from carries its mark.
func (r *pageRead) bucket(kv jetstream.KeyValue, from pageCursor, reached bool) error {
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel() defer cancel()
if !reached { each := func() (context.Context, context.CancelFunc) {
// The read reaches this bucket: what the bus writes into it from now on is marked seen-again (H-A-382 (1)). return context.WithTimeout(context.Background(), StateTimeout)
status, err := kv.Status(ctx) }
// Every current value is read in one stream per bucket (currentOf), never one bus request per key: a page of the
// assignments (about 330 keys) read key by key took 13 s from a node far from the bus (2026-11-14).
current := map[string]*StateEntry{}
if s.PerNode {
fam := c.family(s)
keys, err := fam.Keys(ctx)
if err != nil { if err != nil {
return err return StatePage{}, err
} }
bs, ok := status.(*jetstream.KeyValueBucketStatus) nodes := map[string]bool{}
if !ok || bs.StreamInfo() == nil { for _, k := range keys {
return fmt.Errorf("%s's last sequence is not read, so no page of it can say what is seen again", kv.Bucket()) if node, err := pernode.NodeOf(k); err == nil {
} nodes[node] = true
from.mark = bs.StreamInfo().State.LastSeq
}
// Deletes are handed too: a page that dropped them would bring a deleted key with history back alive (H-A-451 (1)).
opts := []jetstream.WatchOpt{jetstream.IncludeHistory()}
if from.after > 0 {
opts = append(opts, jetstream.ResumeFromRevision(from.after+1))
}
w, err := kv.WatchAll(ctx, opts...)
if err != nil {
return err
}
defer func() {
_ = w.Stop()
// What the watch still hands after its stop is taken and dropped, so its delivery never blocks on a page read no more.
go func() {
for range w.Updates() {
} }
}() }
}() for node := range nodes {
for { octx, ocancel := each() // each node's bucket is a bus request of its own: its own deadline
var e jetstream.KeyValueEntry kv, err := fam.Open(octx, node)
select { ocancel()
case <-ctx.Done(): if err != nil {
return fmt.Errorf("a page of %s is not read: %w", kv.Bucket(), ctx.Err()) return StatePage{}, err
case got, ok := <-w.Updates():
if !ok || got == nil {
return nil // the bucket is read to its end
} }
e = got if kv == nil {
continue
}
wctx, wcancel := each()
got, err := currentOf(wctx, kv)
wcancel()
if err != nil {
return StatePage{}, err
}
maps.Copy(current, got)
} }
deleted := e.Operation() != jetstream.KeyValuePut } else {
var value json.RawMessage kv, err := c.bucket(ctx, s)
if !deleted { if err != nil {
value = valueOf(e.Value()) return StatePage{}, err
} }
full := len(r.page.Entries) > 0 && (r.size+len(e.Key())+len(value) > r.maxBytes || PageClock().Sub(r.started) >= r.budget) if current, err = currentOf(ctx, kv); err != nil {
if full { return StatePage{}, err
r.page.Next = from.String()
return nil
} }
r.page.Entries = append(r.page.Entries, StateEntry{Key: e.Key(), Value: value, Revision: e.Revision(), At: e.Created().UTC(),
SeenAgain: e.Revision() > from.mark, Deleted: deleted})
r.size += len(e.Key()) + len(value)
from.after = e.Revision()
} }
keys := slices.Collect(maps.Keys(current))
get := func(key string) (*StateEntry, error) { return current[key], nil }
sort.Strings(keys)
page := StatePage{Entries: []StateEntry{}}
started := PageClock()
size := 0
for _, k := range keys {
if after != "" && k <= after {
continue
}
if len(page.Entries) > 0 && PageClock().Sub(started) >= budget {
page.Next = page.Entries[len(page.Entries)-1].Key
break
}
e, err := get(k)
if err != nil {
return StatePage{}, err
}
if e == nil {
continue
}
if size > 0 && size+len(k)+len(e.Value) > maxBytes {
page.Next = page.Entries[len(page.Entries)-1].Key
break
}
page.Entries = append(page.Entries, *e)
size += len(k) + len(e.Value)
}
return page, nil
} }
// StateKept is one value a bucket still keeps for a key: a put, or a delete (a purge reads as one). // StateKept is one value a bucket still keeps for a key: a put, or a delete (a purge reads as one).
@@ -445,9 +273,11 @@ func (c *Conn) StateHistory(module, name, key string) ([]StateKept, error) {
} }
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel() defer cancel()
entries, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) ([]jetstream.KeyValueEntry, error) { kv, err := c.bucket(ctx, s)
return kv.History(ctx, key) if err != nil {
}) return nil, err
}
entries, err := kv.History(ctx, key)
kept := []StateKept{} kept := []StateKept{}
if errors.Is(err, jetstream.ErrKeyNotFound) { if errors.Is(err, jetstream.ErrKeyNotFound) {
return kept, nil return kept, nil
@@ -487,46 +317,31 @@ type StateInfo struct {
// StateInfo reads a state's bucket's fill and caps. It is a read like StateGet: served to the owner and every reader. // StateInfo reads a state's bucket's fill and caps. It is a read like StateGet: served to the owner and every reader.
func (c *Conn) StateInfo(module, name string) (*StateInfo, error) { func (c *Conn) StateInfo(module, name string) (*StateInfo, error) {
status, info, err := c.bucketStatus(module, name) s, err := c.issuedState(module, name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &StateInfo{State: name, Bucket: status.Bucket(), Bytes: info.State.Bytes, Keys: uint64(info.State.NumSubjects),
MaxBytes: info.Config.MaxBytes, MaxValueBytes: info.Config.MaxMsgSize, History: status.History(),
TTLSeconds: int64(status.TTL() / time.Second), KeyTTL: info.Config.AllowMsgTTL && status.LimitMarkerTTL() > 0}, nil
}
// StateFill is a state's bucket's fill against its cap, buscalls.Fill's form: the messages it keeps, their bytes and its
// cap in bytes (0 is none). A put answers it, read from the bound stream's info once per put, since the bus's key-value
// put answers no figures of its own (design 47 H2 DMC-14, H-A-386).
func (c *Conn) StateFill(module, name string) (buscalls.Fill, error) {
_, info, err := c.bucketStatus(module, name)
if err != nil {
return buscalls.Fill{}, err
}
return buscalls.Fill{Count: info.State.Msgs, Bytes: info.State.Bytes, MaxBytes: uint64(max(info.Config.MaxBytes, 0))}, nil
}
// bucketStatus is a state's bucket's status and the info of the stream behind it.
func (c *Conn) bucketStatus(module, name string) (jetstream.KeyValueStatus, *jetstream.StreamInfo, error) {
s, err := c.issuedState(module, name)
if err != nil {
return nil, nil, err
}
if s.PerNode { if s.PerNode {
return nil, nil, perNodeRefusal(module, name, "fill") return nil, perNodeRefusal(module, name, "fill")
} }
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel() defer cancel()
status, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (jetstream.KeyValueStatus, error) { return kv.Status(ctx) }) kv, err := c.bucket(ctx, s)
if err != nil { if err != nil {
return nil, nil, err return nil, err
}
status, err := kv.Status(ctx)
if err != nil {
return nil, err
} }
b, ok := status.(*jetstream.KeyValueBucketStatus) b, ok := status.(*jetstream.KeyValueBucketStatus)
if !ok || b.StreamInfo() == nil { if !ok || b.StreamInfo() == nil {
return nil, nil, fmt.Errorf("the bus answered no stream behind %s's state %s", module, name) return nil, fmt.Errorf("the bus answered no stream behind %s's state %s", module, name)
} }
return status, b.StreamInfo(), nil info := b.StreamInfo()
return &StateInfo{State: name, Bucket: status.Bucket(), Bytes: info.State.Bytes, Keys: uint64(info.State.NumSubjects),
MaxBytes: info.Config.MaxBytes, MaxValueBytes: info.Config.MaxMsgSize, History: status.History(),
TTLSeconds: int64(status.TTL() / time.Second), KeyTTL: info.Config.AllowMsgTTL && status.LimitMarkerTTL() > 0}, nil
} }
// StatePut writes one key, as the module, where the module keeps the state. It answers the revision. // StatePut writes one key, as the module, where the module keeps the state. It answers the revision.
@@ -548,7 +363,11 @@ func (c *Conn) StatePut(module, name, key string, value json.RawMessage) (uint64
} }
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel() defer cancel()
return inBucket(c, ctx, s, func(kv jetstream.KeyValue) (uint64, error) { return kv.Put(ctx, key, value) }) kv, err := c.bucket(ctx, s)
if err != nil {
return 0, err
}
return kv.Put(ctx, key, value)
} }
// MinKeyTTL is the shortest time to live a key may be given: the bus counts a key's age in whole seconds (mesh-sdk // MinKeyTTL is the shortest time to live a key may be given: the bus counts a key's age in whole seconds (mesh-sdk
@@ -618,8 +437,11 @@ func (c *Conn) StateDelete(module, name, key string) error {
} }
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel() defer cancel()
_, err = inBucket(c, ctx, s, func(kv jetstream.KeyValue) (struct{}, error) { return struct{}{}, kv.Delete(ctx, key) }) kv, err := c.bucket(ctx, s)
return err if err != nil {
return err
}
return kv.Delete(ctx, key)
} }
// StateKeys is every key with a current value, sorted. // StateKeys is every key with a current value, sorted.
@@ -633,7 +455,11 @@ func (c *Conn) StateKeys(module, name string) ([]string, error) {
} }
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel() defer cancel()
return inBucket(c, ctx, s, func(kv jetstream.KeyValue) ([]string, error) { return keysOf(ctx, kv) }) kv, err := c.bucket(ctx, s)
if err != nil {
return nil, err
}
return keysOf(ctx, kv)
} }
// keysOf is every key with a current value in one bucket, sorted. // keysOf is every key with a current value in one bucket, sorted.
@@ -703,16 +529,12 @@ func (c *Conn) StateWatch(module, name, pattern string, deliver func(StateChange
return c.perNodeWatch(module, s, pattern, deliver) return c.perNodeWatch(module, s, pattern, deliver)
} }
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout) ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel() kv, err := c.bucket(ctx, s)
type watching struct{ stop func() } cancel()
w, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (watching, error) {
stop, err := c.watchBucket(module, name, kv, filter, deliver)
return watching{stop}, err
})
if err != nil { if err != nil {
return nil, err return nil, err
} }
return w.stop, nil return c.watchBucket(module, name, kv, filter, deliver)
} }
// watchBucket is StateWatch over one bucket: the current values, then every change. // watchBucket is StateWatch over one bucket: the current values, then every change.
@@ -885,3 +707,28 @@ func providerReference(v any) bool {
// referenceName is a node's or a module's name as mesh-sdk names them: lower case, digits and dashes. // referenceName is a node's or a module's name as mesh-sdk names them: lower case, digits and dashes.
var referenceName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`) var referenceName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
// currentOf is every current value of a bucket, read in one stream (a watch of every key, deletes left out, ended at its
// first nil): the values a page answers, without a bus request per key.
func currentOf(ctx context.Context, kv jetstream.KeyValue) (map[string]*StateEntry, error) {
w, err := kv.WatchAll(ctx, jetstream.IgnoreDeletes())
if err != nil {
return nil, err
}
defer func() { _ = w.Stop() }()
out := map[string]*StateEntry{}
for {
select {
case <-ctx.Done():
return nil, fmt.Errorf("the values of %s are not all read: %w", kv.Bucket(), ctx.Err())
case e, ok := <-w.Updates():
if !ok {
return out, nil
}
if e == nil {
return out, nil
}
out[e.Key()] = &StateEntry{Key: e.Key(), Value: valueOf(e.Value()), Revision: e.Revision(), At: e.Created().UTC()}
}
}
}
@@ -1,83 +0,0 @@
//go:build integration
package bus_test
import (
"strings"
"testing"
"github.com/nats-io/nats.go"
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
)
// **On the bus, a read of a state is one answer: its bucket is bound once, and bound again when it was made afresh or
// is gone** (design 47 H lead answers H-A-251). The runtime asked the bucket's stream info before every get, so each
// read was two answers; a third of a night's bus flood came this way.
func TestAStateReadOnTheBusBindsItsBucketOnce(t *testing.T) {
conn, kv := owedWatcher(t)
const bucket = "mesh-delivery-assigner_pins"
if _, err := kv.Put("a", []byte(`{"v":1}`)); err != nil {
t.Fatal(err)
}
watcher, err := nats.Connect(mt.URL(t))
if err != nil {
t.Fatal(err)
}
t.Cleanup(watcher.Close)
// 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 {
t.Fatal(err)
}
read := func() {
t.Helper()
e, err := conn.StateGet("gitea", "mesh-delivery-assigner.pins", "a")
if err != nil || e == nil {
t.Fatalf("read: %+v, %v", e, err)
}
}
read()
read()
read()
if err := watcher.Flush(); err != nil {
t.Fatal(err)
}
if got := len(infos); got != 1 {
t.Fatalf("three reads asked the bucket's stream info %d times, want once", got)
}
// The bucket deleted under the runtime: the read binds again, once, and says the bucket is not on the bus.
js, _ := watcher.JetStream()
if err := js.DeleteKeyValue(bucket); err != nil {
t.Fatal(err)
}
_, err = conn.StateGet("gitea", "mesh-delivery-assigner.pins", "a")
if err == nil || !strings.Contains(err.Error(), "not on the bus yet") {
t.Fatalf("a read of a deleted bucket answered %v, want that its bucket is not on the bus", err)
}
// And made afresh: read again from the new bucket.
again, err := js.CreateKeyValue(&nats.KeyValueConfig{Bucket: bucket, History: 1})
if err != nil {
t.Fatal(err)
}
if _, err := again.Put("a", []byte(`{"v":2}`)); err != nil {
t.Fatal(err)
}
e, err := conn.StateGet("gitea", "mesh-delivery-assigner.pins", "a")
if err != nil || e == nil || string(e.Value) != `{"v":2}` {
t.Fatalf("a read of the bucket made afresh: %+v, %v", e, err)
}
read()
if err := watcher.Flush(); err != nil {
t.Fatal(err)
}
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)
}
}
-141
View File
@@ -1,141 +0,0 @@
package bus
import (
"context"
"encoding/json"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/nats-io/nats.go/jetstream"
)
// boundKV is a bucket's binding in a test: it answers every get with one value, or, once gone, as the bus answers a
// binding whose bucket was deleted.
type boundKV struct {
jetstream.KeyValue
gone atomic.Bool
puts atomic.Int32
}
type boundEntry struct {
jetstream.KeyValueEntry
key string
}
func (e boundEntry) Key() string { return e.key }
func (e boundEntry) Value() []byte { return []byte(`{"v":1}`) }
func (e boundEntry) Revision() uint64 { return 1 }
func (boundEntry) Created() time.Time { return time.Time{} }
func (*boundKV) Bucket() string { return "gitea_pins" }
func (kv *boundKV) Get(_ context.Context, key string) (jetstream.KeyValueEntry, error) {
if kv.gone.Load() {
return nil, jetstream.ErrStreamNotFound
}
return boundEntry{key: key}, nil
}
func (kv *boundKV) Put(context.Context, string, []byte) (uint64, error) {
if kv.gone.Load() {
return 0, jetstream.ErrNoStreamResponse
}
return uint64(kv.puts.Add(1)), nil
}
// **A state is bound once for the process, and bound again only when the bus says its bucket is gone** (design 47 H
// lead answers H-A-251): binding is a stream-info request on the bus, and asked before every get it made each read two
// answers on the bus.
func TestAStateIsBoundOnceAndBoundAgainWhenItsBucketIsGone(t *testing.T) {
setup := func() (*Conn, *atomic.Int32, *[]*boundKV) {
var binds atomic.Int32
var mu sync.Mutex
made := []*boundKV{}
c := &Conn{node: "anchor", issued: map[string]*Membership{"gitea": {Module: "gitea",
State: []StateIssued{{Name: "pins", Bucket: "gitea_pins", Writes: true}}}}}
c.bind = func(_ context.Context, bucket string) (jetstream.KeyValue, error) {
binds.Add(1)
if bucket != "gitea_pins" {
t.Errorf("bound %s, want gitea_pins", bucket)
}
kv := &boundKV{}
mu.Lock()
made = append(made, kv)
mu.Unlock()
return kv, nil
}
return c, &binds, &made
}
t.Run("two reads, one bind", func(t *testing.T) {
c, binds, _ := setup()
for range 2 {
if e, err := c.StateGet("gitea", "pins", "a"); err != nil || e == nil || e.Key != "a" {
t.Fatalf("read: %+v, %v", e, err)
}
}
if _, err := c.StatePut("gitea", "pins", "a", json.RawMessage(`{"v":2}`)); err != nil {
t.Fatal(err)
}
if got := binds.Load(); got != 1 {
t.Fatalf("two reads and a write bound the bucket %d times, want once", got)
}
})
t.Run("many readers at once, one bind", func(t *testing.T) {
c, binds, _ := setup()
var wg sync.WaitGroup
for range 16 {
wg.Go(func() {
if _, err := c.StateGet("gitea", "pins", "a"); err != nil {
t.Error(err)
}
})
}
wg.Wait()
if got := binds.Load(); got != 1 {
t.Fatalf("16 readers bound the bucket %d times, want once", got)
}
})
t.Run("a bucket gone under the runner is bound again once", func(t *testing.T) {
c, binds, made := setup()
if _, err := c.StateGet("gitea", "pins", "a"); err != nil {
t.Fatal(err)
}
(*made)[0].gone.Store(true)
if e, err := c.StateGet("gitea", "pins", "a"); err != nil || e == nil {
t.Fatalf("the read after the bucket was made again: %+v, %v", e, err)
}
if got := binds.Load(); got != 2 {
t.Fatalf("the bucket was bound %d times, want twice (once more after it was gone)", got)
}
if _, err := c.StateGet("gitea", "pins", "a"); err != nil {
t.Fatal(err)
}
(*made)[1].gone.Store(true)
if _, err := c.StatePut("gitea", "pins", "a", json.RawMessage(`{"v":2}`)); err != nil {
t.Fatal(err)
}
if got, puts := binds.Load(), (*made)[2].puts.Load(); got != 3 || puts != 1 {
t.Fatalf("a write to a gone bucket bound it %d times in all (want 3) and wrote %d times on the new binding (want 1)", got, puts)
}
})
t.Run("a bucket still gone after the bind again is said", func(t *testing.T) {
c, binds, made := setup()
if _, err := c.StateGet("gitea", "pins", "a"); err != nil {
t.Fatal(err)
}
(*made)[0].gone.Store(true)
c.bind = func(context.Context, string) (jetstream.KeyValue, error) {
binds.Add(1)
return nil, jetstream.ErrBucketNotFound
}
if _, err := c.StateGet("gitea", "pins", "a"); err == nil {
t.Fatal("a read of a bucket no longer on the bus answered no error")
}
if got := binds.Load(); got != 2 {
t.Fatalf("the bucket was bound %d times, want twice: the bind again is once", got)
}
})
}
+2 -18
View File
@@ -69,7 +69,6 @@ func TestAPerNodeStateIsServedAcrossEveryNodesBucket(t *testing.T) {
var mu sync.Mutex var mu sync.Mutex
var current, live []string var current, live []string
heard := make(chan struct{}, 1)
stop, err := conn.StateWatch("mesh-provisioner", "mesh-host.composed", "", func(ch bus.StateChange) error { stop, err := conn.StateWatch("mesh-provisioner", "mesh-host.composed", "", func(ch bus.StateChange) error {
mu.Lock() mu.Lock()
defer mu.Unlock() defer mu.Unlock()
@@ -78,10 +77,6 @@ func TestAPerNodeStateIsServedAcrossEveryNodesBucket(t *testing.T) {
} else { } else {
live = append(live, ch.Key) live = append(live, ch.Key)
} }
select {
case heard <- struct{}{}:
default:
}
return nil return nil
}) })
if err != nil { if err != nil {
@@ -103,10 +98,7 @@ func TestAPerNodeStateIsServedAcrossEveryNodesBucket(t *testing.T) {
if _, err := a.Put("a.m1.f5", []byte(`{"v":1}`)); err != nil { if _, err := a.Put("a.m1.f5", []byte(`{"v":1}`)); err != nil {
t.Fatal(err) t.Fatal(err)
} }
// Waited for as the watch hands each change over, not polled within a fixed five seconds: the new bucket is taken mt.Until(t, func() error {
// 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() mu.Lock()
defer mu.Unlock() defer mu.Unlock()
got := strings.Join(append(append([]string(nil), current...), live...), ",") got := strings.Join(append(append([]string(nil), current...), live...), ",")
@@ -116,13 +108,5 @@ func TestAPerNodeStateIsServedAcrossEveryNodesBucket(t *testing.T) {
} }
} }
return nil return nil
} })
bound := time.After(30 * time.Second)
for err := missing(); err != nil; err = missing() {
select {
case <-heard:
case <-bound:
t.Fatal(err)
}
}
} }
+30 -92
View File
@@ -3,7 +3,6 @@ package bus
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"sort" "sort"
"strings" "strings"
"sync" "sync"
@@ -11,9 +10,6 @@ import (
"time" "time"
"github.com/nats-io/nats.go/jetstream" "github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-sdk/go/membership"
"git.novox.be/novox/mesh-sdk/go/process"
) )
// A module's own stream, as the runtime publishes to it and hears it (novox/hq ADR 0363 §8, issue 725). // A module's own stream, as the runtime publishes to it and hears it (novox/hq ADR 0363 §8, issue 725).
@@ -33,54 +29,11 @@ type StreamIssued struct {
Subject string `json:"subject"` Subject string `json:"subject"`
} }
// HeardIssued is one stream an assignment hears, EVENTS like any other: the stream, the module's durable consumer the // HeardIssued is one module stream an assignment hears: the stream and the durable consumer on it the
// runner's twin on it is named from, and, from a grants part that writes it, the twin's whole spec (mesh-sdk's // runtime binds. The consumer is the mesh's to make, to filter and to delete.
// membership.HeardIssued; design 47 H2, H-A-472 seventh and eighth addenda). An entry with a spec is created or updated type HeardIssued struct {
// from it by the runner at a child's first subscribe; one without, an older writer's, is bound by name as before. Stream string `json:"stream"`
type HeardIssued = membership.HeardIssued Consumer string `json:"consumer"`
// heardKey is one consumer a hearing binds: the stream and the runner's twin on it. The spec rides beside it, never in
// it, so a map is keyed by the consumer alone.
type heardKey struct{ Stream, Consumer string }
// twinConfig is the configuration of the runner's twin of a heard entry with a spec: its filters, ack wait, max deliver,
// max ack pending and deliver policy as the grants part composed them, under the twin's own name. Every filter goes in
// FilterSubjects, one alone too, so the create is on the name alone, the form the reader is granted.
func twinConfig(h HeardIssued) (jetstream.ConsumerConfig, error) {
cfg := jetstream.ConsumerConfig{
Durable: h.Consumer + ToolsSuffix,
AckPolicy: jetstream.AckExplicitPolicy,
AckWait: time.Duration(h.AckWaitSeconds) * time.Second,
MaxDeliver: h.MaxDeliver,
MaxAckPending: h.MaxAckPending,
FilterSubjects: append([]string(nil), h.Filters...),
}
switch h.DeliverPolicy {
case membership.DeliverFromNow:
cfg.DeliverPolicy = jetstream.DeliverNewPolicy
case membership.DeliverLastPerSubject:
cfg.DeliverPolicy = jetstream.DeliverLastPerSubjectPolicy
case membership.DeliverAll, "":
cfg.DeliverPolicy = jetstream.DeliverAllPolicy
default:
return cfg, fmt.Errorf("the membership names the deliver policy %q, which the runner does not know", h.DeliverPolicy)
}
return cfg, nil
}
// makeTwin creates or updates the runner's twin of a heard entry from its spec (H-A-472 fifth to seventh addenda): what
// the bus lacks is made as a part's process makes it, and one held is brought to the spec, its delivery position kept.
// An entry without a spec makes nothing: its consumer is the grants part's, bound by name.
func makeTwin(ctx context.Context, js jetstream.JetStream, h HeardIssued) error {
if !h.HasSpec() {
return nil
}
cfg, err := twinConfig(h)
if err != nil {
return err
}
_, err = js.CreateOrUpdateConsumer(ctx, h.Stream, cfg)
return err
} }
// eventSubject is where a module's event is published: on the subject of the first of its membership's // eventSubject is where a module's event is published: on the subject of the first of its membership's
@@ -139,42 +92,31 @@ type hearing struct {
mu sync.Mutex mu sync.Mutex
stopped bool stopped bool
bound map[heardKey]jetstream.ConsumeContext bound map[HeardIssued]jetstream.ConsumeContext
// made is when the bus made each bound consumer: a consumer deleted and made again under its name has // made is when the bus made each bound consumer: a consumer deleted and made again under its name has
// another time, and a loop bound to the old one is not reading the new one. // another time, and a loop bound to the old one is not reading the new one.
made map[heardKey]time.Time made map[HeardIssued]time.Time
said map[heardKey]bool said map[HeardIssued]bool
// why is the last error the bus gave a consumer's loop, said when the loop ends on it. // why is the last error the bus gave a consumer's loop, said when the loop ends on it.
// Guarded by whyMu, not mu: the bus hands errors from its own goroutines, possibly while mu is held. // Guarded by whyMu, not mu: the bus hands errors from its own goroutines, possibly while mu is held.
whyMu sync.Mutex whyMu sync.Mutex
why map[heardKey]error why map[HeardIssued]error
kick chan struct{} kick chan struct{}
done chan struct{} done chan struct{}
unhear func() 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 { func newHearing(c *Conn, js jetstream.JetStream, module string, deliver func(Envelope) error) *hearing {
return &hearing{c: c, js: js, module: module, deliver: deliver, return &hearing{c: c, js: js, module: module, deliver: deliver,
bound: map[heardKey]jetstream.ConsumeContext{}, made: map[heardKey]time.Time{}, said: map[heardKey]bool{}, why: map[heardKey]error{}, 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 the runner's twin of one heard entry, made first from the entry's spec where it carries one (makeTwin), else // bind reads one durable consumer by name, and on failure says what it was doing. Errors the bus gives
// bound by name, and on failure says what it was doing. Errors the bus gives the loop afterwards are handed to onErr, when // the loop afterwards are handed to onErr, when given.
// given. func (h *hearing) bind(stream, durable string, onErr func(error)) (jetstream.ConsumeContext, time.Time, string, error) {
func (h *hearing) bind(heard HeardIssued, onErr func(error)) (jetstream.ConsumeContext, time.Time, string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel() defer cancel()
stream, durable := heard.Stream, heard.Consumer+ToolsSuffix
if err := makeTwin(ctx, h.js, heard); err != nil {
return nil, time.Time{}, "making", err
}
consumer, err := h.js.Consumer(ctx, stream, durable) consumer, err := h.js.Consumer(ctx, stream, durable)
if err != nil { if err != nil {
return nil, time.Time{}, "binding", err return nil, time.Time{}, "binding", err
@@ -187,10 +129,7 @@ func (h *hearing) bind(heard HeardIssued, onErr func(error)) (jetstream.ConsumeC
if onErr != nil { if onErr != nil {
opts = append(opts, jetstream.ConsumeErrHandler(func(_ jetstream.ConsumeContext, err error) { onErr(err) })) opts = append(opts, jetstream.ConsumeErrHandler(func(_ jetstream.ConsumeContext, err error) { onErr(err) }))
} }
// Claimed through the SDK's one guard as it is pulled (design 47 H, H-A-196, H-A-197): a second pull loop on a durable reading, err := consumer.Consume(h.handle, opts...)
// this process pulls already would take every other event from the first, so it is refused here, loud. The claim is
// released as the loop is stopped, or once the bus ended it, before its Closed is closed.
reading, err := process.ConsumeOnce(consumer, "the tool runner's hearing of "+h.module, h.handle, opts...)
if err != nil { if err != nil {
return nil, time.Time{}, "reading", err return nil, time.Time{}, "reading", err
} }
@@ -214,7 +153,7 @@ func (h *hearing) handle(msg jetstream.Msg) {
done, stopped := make(chan struct{}), make(chan struct{}) done, stopped := make(chan struct{}), make(chan struct{})
go func() { go func() {
defer close(stopped) defer close(stopped)
tick := time.NewTicker(h.heartbeat) tick := time.NewTicker(EventHeartbeat)
defer tick.Stop() defer tick.Stop()
for { for {
select { select {
@@ -242,7 +181,7 @@ func (h *hearing) handle(msg jetstream.Msg) {
return return
} }
if err != nil { if err != nil {
_ = msg.NakWithDelay(h.nakDelay) _ = msg.NakWithDelay(NakDelay)
return return
} }
_ = msg.Ack() _ = msg.Ack()
@@ -259,7 +198,7 @@ func (h *hearing) start() {
h.nudge() h.nudge()
}) })
go func() { go func() {
tick := time.NewTicker(h.rebind) tick := time.NewTicker(RebindEvery)
defer tick.Stop() defer tick.Stop()
for { for {
select { select {
@@ -274,7 +213,7 @@ func (h *hearing) start() {
} }
// forget drops the last error a consumer's loop was given. // forget drops the last error a consumer's loop was given.
func (h *hearing) forget(heard heardKey) { func (h *hearing) forget(heard HeardIssued) {
h.whyMu.Lock() h.whyMu.Lock()
delete(h.why, heard) delete(h.why, heard)
h.whyMu.Unlock() h.whyMu.Unlock()
@@ -310,7 +249,7 @@ func (h *hearing) stop() {
// replaced says whether the consumer a loop is bound to is gone from the bus or was made again since. A bus // replaced says whether the consumer a loop is bound to is gone from the bus or was made again since. A bus
// that cannot be asked right now says no: the loop is left as it is. // that cannot be asked right now says no: the loop is left as it is.
func (h *hearing) replaced(heard heardKey) bool { func (h *hearing) replaced(heard HeardIssued) bool {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() defer cancel()
consumer, err := h.js.Consumer(ctx, heard.Stream, heard.Consumer) consumer, err := h.js.Consumer(ctx, heard.Stream, heard.Consumer)
@@ -326,14 +265,13 @@ func (h *hearing) replaced(heard heardKey) bool {
// reconcile makes what is bound what the module's membership names now. // reconcile makes what is bound what the module's membership names now.
func (h *hearing) reconcile() { func (h *hearing) reconcile() {
want := map[heardKey]HeardIssued{} want := map[HeardIssued]bool{}
// A module whose membership was withdrawn hears nothing more here, and its twins are not made again (H-A-472 ninth addendum). if m := h.c.Membership(h.module); m != nil {
if m := h.c.Membership(h.module); m != nil && !h.c.Withdrawn(h.module) {
for _, heard := range m.Hears { for _, heard := range m.Hears {
// EVENTS is its caller's, bound beside the hearing (ConsumeAsBeatingWhen). if heard.Stream != "" && heard.Consumer != "" {
if heard.Stream != "" && heard.Consumer != "" && heard.Stream != EventsStream {
// The runner's own durable beside the program's (A-397). // The runner's own durable beside the program's (A-397).
want[heardKey{heard.Stream, heard.Consumer + ToolsSuffix}] = heard heard.Consumer += ToolsSuffix
want[heard] = true
} }
} }
} }
@@ -343,7 +281,7 @@ func (h *hearing) reconcile() {
return return
} }
for heard, reading := range h.bound { for heard, reading := range h.bound {
if _, still := want[heard]; !still { if !want[heard] {
reading.Stop() reading.Stop()
delete(h.bound, heard) delete(h.bound, heard)
delete(h.made, heard) delete(h.made, heard)
@@ -352,7 +290,7 @@ func (h *hearing) reconcile() {
} }
} }
for heard := range h.said { for heard := range h.said {
if _, still := want[heard]; !still { if !want[heard] {
delete(h.said, heard) delete(h.said, heard)
h.forget(heard) h.forget(heard)
} }
@@ -391,7 +329,7 @@ func (h *hearing) reconcile() {
default: default:
} }
} }
missing := make([]heardKey, 0, len(want)) missing := make([]HeardIssued, 0, len(want))
for heard := range want { for heard := range want {
if h.bound[heard] == nil { if h.bound[heard] == nil {
missing = append(missing, heard) missing = append(missing, heard)
@@ -401,7 +339,7 @@ func (h *hearing) reconcile() {
for _, heard := range missing { for _, heard := range missing {
heard := heard heard := heard
h.forget(heard) h.forget(heard)
reading, created, doing, err := h.bind(want[heard], func(err error) { reading, created, doing, err := h.bind(heard.Stream, heard.Consumer, func(err error) {
h.whyMu.Lock() h.whyMu.Lock()
h.why[heard] = err h.why[heard] = err
h.whyMu.Unlock() h.whyMu.Unlock()
@@ -410,7 +348,7 @@ func (h *hearing) reconcile() {
// Said once, not at every attempt; said again when it is bound. // Said once, not at every attempt; said again when it is bound.
if !h.said[heard] { 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.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, h.rebind) h.module, heard.Stream, doing, heard.Consumer, err, RebindEvery)
h.said[heard] = true h.said[heard] = true
} }
continue continue
@@ -5,7 +5,6 @@ import (
"testing" "testing"
"git.novox.be/novox/mesh-sdk/go/buscalls" "git.novox.be/novox/mesh-sdk/go/buscalls"
"github.com/nats-io/nats.go/jetstream"
) )
// novox/hq ADR 0363 §2, §3: an event goes to the stream whose pattern carries it, as the bus matches subjects. // novox/hq ADR 0363 §2, §3: an event goes to the stream whose pattern carries it, as the bus matches subjects.
@@ -70,19 +69,3 @@ func TestAnEventNoStreamCarriesIsPublishedOnEvents(t *testing.T) {
t.Errorf("a stream's event reaches its consumer as %q, not as on EVENTS", got) t.Errorf("a stream's event reaches its consumer as %q, not as on EVENTS", got)
} }
} }
// Design 47 H lead answers H-A-227: an object store's fill is the figures the bus keeps for its stream, its live
// subjects as the count, never a count of its descriptions: a store holding twenty thousand messages, deleted chunks'
// leftovers among them, answers its bytes, its cap and its four live subjects.
func TestAnObjectStoresFillIsItsStreamsOwnFigures(t *testing.T) {
info := &jetstream.StreamInfo{
Config: jetstream.StreamConfig{MaxBytes: 8 << 30},
State: jetstream.StreamState{Msgs: 20653, Bytes: 1 << 30, NumSubjects: 4, FirstSeq: 9, LastSeq: 20661},
}
if got, want := objectsFillOf(info), (buscalls.Fill{Count: 4, Bytes: 1 << 30, MaxBytes: 8 << 30}); got != want {
t.Fatalf("fill %+v, want %+v", got, want)
}
if got := objectsFillOf(&jetstream.StreamInfo{State: jetstream.StreamState{Bytes: 7}}); got != (buscalls.Fill{Bytes: 7}) {
t.Fatalf("a store with no cap and no live subject: fill %+v", got)
}
}
-146
View File
@@ -4,15 +4,11 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"slices"
"strings" "strings"
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/nats-io/nats.go"
"git.novox.be/novox/mesh-sdk/go/membership"
"github.com/novox/mesh-tools/node-tools/internal/bus" "github.com/novox/mesh-tools/node-tools/internal/bus"
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest" mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
) )
@@ -262,34 +258,6 @@ func TestAConsumerNamedBeforeItExistsIsBoundOnceItDoes(t *testing.T) {
} }
return nil return nil
}) })
// A second pull loop on the durable the runner pulls is refused, naming it and both binders (design 47 H, H-A-196,
// H-A-197); a re-serve that stops its loop first binds again without a refusal, its module stream's durable too.
if _, err := conn.ConsumeAs("reader", func(bus.Envelope) error { return nil }); err == nil ||
!strings.Contains(err.Error(), "pulled in this process already") || !strings.Contains(err.Error(), "anchor_reader") ||
strings.Count(err.Error(), "the tool runner's hearing of reader") != 2 {
t.Fatalf("a second pull loop on the durable the runner pulls was not refused naming it and both binders: %v", err)
}
stop()
again, err := conn.ConsumeAs("reader", func(env bus.Envelope) error {
mu.Lock()
heard[env.Key]++
mu.Unlock()
return nil
})
if err != nil {
t.Fatalf("the re-serve was refused after its old loop stopped: %v", err)
}
t.Cleanup(again)
mesh.Emit(t, "mesh.stream.mail.event.mail.home.message.added", map[string]any{})
mt.Until(t, func() error {
mu.Lock()
defer mu.Unlock()
if heard["mail.mail.home.message.added"] != 2 {
return fmt.Errorf("after the re-serve heard %v", heard)
}
return nil
})
} }
// novox/hq ADR 0363 §6 (issue 725): a consumer the controller deletes and makes again under the same name, its // novox/hq ADR 0363 §6 (issue 725): a consumer the controller deletes and makes again under the same name, its
@@ -372,117 +340,3 @@ func (l *syncLogs) Has(fragment string) bool {
} }
return false return false
} }
// Design 47 H2, H-A-472 fifth to ninth addenda: the runner makes its own twin `<node>_<module>_tools` of every stream its
// membership hears, EVENTS among them, from the spec the entry carries, at a child's first subscribe; a twin it holds is
// brought to the spec at the next; and when the grants part withdraws the membership, the runner removes the twins from
// the streams the entry named and makes none again.
func TestTheRunnersTwinIsMadeFromItsMembershipsSpecAndRemovedWhenWithdrawn(t *testing.T) {
reader := mt.MembershipOf("reader", "anchor", false, nil)
reader.Hears = []bus.HeardIssued{
{Stream: bus.EventsStream, Consumer: "anchor_reader", Filters: []string{"mesh.mod.alpha.event.>", "mesh.again.anchor_reader_tools.>"},
AckWaitSeconds: 7, MaxDeliver: 3, DeliverPolicy: membership.DeliverFromNow},
{Stream: "MAIL", Consumer: "anchor_reader", Filters: []string{"mesh.stream.mail.event.mail.>"}, AckWaitSeconds: 9,
MaxDeliver: 4, MaxAckPending: 2, DeliverPolicy: membership.DeliverAll},
}
mesh, conn := streamMesh(t, reader)
nc, err := nats.Connect(mt.URL(t))
if err != nil {
t.Fatal(err)
}
t.Cleanup(nc.Close)
js, _ := nc.JetStream()
// Waiting on MAIL before the twin exists: a twin that delivers all hears it.
mesh.Emit(t, "mesh.stream.mail.event.mail.home.message.added", map[string]any{"n": 1})
var mu sync.Mutex
heard := map[string]int{}
consume := func() (func(), error) {
return conn.ConsumeAs("reader", func(env bus.Envelope) error {
mu.Lock()
heard[env.Key]++
mu.Unlock()
return nil
})
}
stop, err := consume()
if err != nil {
t.Fatal(err)
}
mesh.Emit(t, "mesh.mod.alpha.event.happened", map[string]any{"n": 1})
mt.Until(t, func() error {
mu.Lock()
defer mu.Unlock()
if heard["alpha.happened"] != 1 || heard["mail.mail.home.message.added"] != 1 {
return fmt.Errorf("heard %v, want one on EVENTS and one on MAIL", heard)
}
return nil
})
for _, row := range []struct {
stream string
filters []string
ackWait time.Duration
maxDeliver int
maxAckPending int
deliver nats.DeliverPolicy
}{
{bus.EventsStream, []string{"mesh.mod.alpha.event.>", "mesh.again.anchor_reader_tools.>"}, 7 * time.Second, 3, 0, nats.DeliverNewPolicy},
{"MAIL", []string{"mesh.stream.mail.event.mail.>"}, 9 * time.Second, 4, 2, nats.DeliverAllPolicy},
} {
info, err := js.ConsumerInfo(row.stream, "anchor_reader_tools")
if err != nil {
t.Fatalf("the twin on %s: %v", row.stream, err)
}
c := info.Config
if !slices.Equal(c.FilterSubjects, row.filters) || c.AckWait != row.ackWait || c.MaxDeliver != row.maxDeliver ||
(row.maxAckPending != 0 && c.MaxAckPending != row.maxAckPending) || c.DeliverPolicy != row.deliver {
t.Errorf("the twin on %s is %+v, want the membership's spec", row.stream, c)
}
}
// A twin held is brought to the spec at the next first subscribe.
stop()
reader.Hears[1].MaxDeliver = 6
mesh.Issue(t, reader)
mt.Until(t, func() error {
if m := conn.Membership("reader"); m == nil || m.Hears[1].MaxDeliver != 6 {
return errors.New("the new spec is not issued yet")
}
return nil
})
if stop, err = consume(); err != nil {
t.Fatal(err)
}
mt.Until(t, func() error {
info, err := js.ConsumerInfo("MAIL", "anchor_reader_tools")
if err != nil || info.Config.MaxDeliver != 6 {
return fmt.Errorf("the twin on MAIL is not brought to the spec: %v", err)
}
return nil
})
// Withdrawn: the twins go from both streams, and a subscribe after makes none.
kv, err := js.KeyValue(membership.GrantsBucket)
if err != nil {
t.Fatal(err)
}
if err := kv.Delete(membership.GrantsKey("anchor", "reader")); err != nil {
t.Fatal(err)
}
mt.Until(t, func() error {
for _, stream := range []string{bus.EventsStream, "MAIL"} {
if _, err := js.ConsumerInfo(stream, "anchor_reader_tools"); !errors.Is(err, nats.ErrConsumerNotFound) {
return fmt.Errorf("the twin on %s is still there (%v)", stream, err)
}
}
return nil
})
stop()
if !conn.Withdrawn("reader") {
t.Error("the module is not marked withdrawn")
}
if again, err := consume(); err == nil {
again()
t.Error("a subscribe after the withdrawal made the twin again")
}
}
+1 -5
View File
@@ -202,14 +202,10 @@ func (s *Surface) emitters() (known knownEmitters, unchecked string) {
return known, "the catalog half is not yet read (" + err.Error() + "); its first view is in mesh_first_views" return known, "the catalog half is not yet read (" + err.Error() + "); its first view is in mesh_first_views"
} }
seatEvents := map[string][]string{} // a seat's events, as its definition in the seat list declares them seatEvents := map[string][]string{} // a seat's events, as its definition in the seat list declares them
known.seats, known.modules = map[string][]string{}, map[string][]string{}
// Every seat of the seat list is an emitter, by the events its definition declares under its events family, whichever
// repository defines it (design 47 H2 §821, H-A-343): a seat the catalog half's own definitions do not name, such as one the
// delivery repository's contracts module defines, is waited on by its seat and event name.
for _, st := range catalogue.Seats() { for _, st := range catalogue.Seats() {
seatEvents[st.Name] = st.Emits seatEvents[st.Name] = st.Emits
known.seats[st.Name] = st.Emits
} }
known.seats, known.modules = map[string][]string{}, map[string][]string{}
branches := make([]string, 0, len(halves)) branches := make([]string, 0, len(halves))
for b := range halves { for b := range halves {
branches = append(branches, b) branches = append(branches, b)
-2
View File
@@ -246,8 +246,6 @@ func TestMeshWaitRefusesLoudlyAndNeverLoops(t *testing.T) {
{"mesh-delivry-view.delivered", "mesh-delivry-view is neither a seat nor a module of the catalog half (mesh-catalog.revision, revision 7 of main)", true}, {"mesh-delivry-view.delivered", "mesh-delivry-view is neither a seat nor a module of the catalog half (mesh-catalog.revision, revision 7 of main)", true},
{"mesh-delivery-view.planned", "no declaration names mesh-delivery-view.planned", false}, {"mesh-delivery-view.planned", "no declaration names mesh-delivery-view.planned", false},
{"mesh-catalog.catalog-revision", "", false}, {"mesh-catalog.catalog-revision", "", false},
// a seat of the seat list the half's definitions do not name is waited on by its declared event (design 47 H2 §821)
{"mesh-wants.wanted", "", false},
} { } {
text, isErr := callWait(half, map[string]any{"subjects": []any{c.name}, "timeout": 1}) text, isErr := callWait(half, map[string]any{"subjects": []any{c.name}, "timeout": 1})
if isErr != c.refused || c.says != "" && !strings.Contains(text, c.says) || if isErr != c.refused || c.says != "" && !strings.Contains(text, c.says) ||
-132
View File
@@ -1,132 +0,0 @@
package launch
import (
"fmt"
"sort"
"sync"
"time"
)
// DrainBoundSetting is the tool runner module's setting of how long, once told to stop, it waits for the calls in flight in its
// bundles to finish, a duration text; DefaultDrainBound is its default (design 47 H2 §813 (12), H-A-342 (2), H-A-377).
const (
DrainBoundSetting = "drain-bound"
DefaultDrainBound = 30 * time.Second
)
// inFlight is one ask the runner made of a bundle and is still waiting on: the bundle, the verb (a tool's name, else the
// method), when it was asked, and closed when the drain cuts it.
type inFlight struct {
module, verb string
at time.Time
cut chan struct{}
}
// asks is every ask in flight in every bundle the runner launched, and whether the runner is draining: from then on it makes
// no new ask (design 47 H2 §813 (12)).
var asks = struct {
mu sync.Mutex
draining bool
next uint64
of map[uint64]*inFlight
// ended is signalled at each ask's end while draining, so the drain hears the last end instead of looking again.
ended chan struct{}
}{of: map[uint64]*inFlight{}}
// afterStop is an ask made after the stop began: it is not taken and its caller is answered nothing, never refused, so the
// caller's kept call paces and meets the new runner (design 47 H2 §813 (12) as H-A-369 amends it).
type afterStop struct{ module, verb string }
func (e *afterStop) Error() string {
return fmt.Sprintf("%s's %s was not taken: the tool runner is stopping, and a call after its stop is answered nothing", e.module, e.verb)
}
// Unanswered says the call is left without an answer, so its kept call asks again and meets the new runner.
func (e *afterStop) Unanswered() bool { return true }
// cutCall is a call the drain cut at its bound. Its caller is answered nothing, so it sees a transport fault (§813 (12)): the
// bus reads Unanswered and sends no reply.
type cutCall struct{ module, verb string }
func (e *cutCall) Error() string {
return fmt.Sprintf("%s's %s was cut: it outlived the tool runner's drain bound at its stop", e.module, e.verb)
}
// Unanswered says the call is left without an answer, so its caller sees a transport fault.
func (e *cutCall) Unanswered() bool { return true }
// begin records an ask about to be made; once the runner drains it takes none, and its caller is answered nothing.
func begin(module, verb string) (uint64, *inFlight, error) {
asks.mu.Lock()
defer asks.mu.Unlock()
if asks.draining {
return 0, nil, &afterStop{module: module, verb: verb}
}
asks.next++
f := &inFlight{module: module, verb: verb, at: time.Now(), cut: make(chan struct{})}
asks.of[asks.next] = f
return asks.next, f, nil
}
// end is an ask's end, answered or not.
func end(id uint64) {
asks.mu.Lock()
defer asks.mu.Unlock()
delete(asks.of, id)
if asks.draining {
select {
case asks.ended <- struct{}{}:
default:
}
}
}
// Drain is the runner's stop (design 47 H2 §813 (12), H-A-342 (2), H-A-353): from now on no new ask is made of any bundle, the
// asks in flight are waited for within bound, and each still in flight at the bound is cut, with a journal line naming the
// bundle, the verb and the call's age; its caller is answered nothing. It returns once no ask is in flight or the bound
// passed; the runner then stops its bundles itself.
func Drain(bound time.Duration, logf func(string, ...any)) {
asks.mu.Lock()
asks.draining = true
asks.ended = make(chan struct{}, 1)
ended := asks.ended
asks.mu.Unlock()
timer := time.NewTimer(bound)
defer timer.Stop()
for {
asks.mu.Lock()
left := len(asks.of)
asks.mu.Unlock()
if left == 0 {
return
}
select {
case <-ended:
case <-timer.C:
asks.mu.Lock()
ids := make([]uint64, 0, len(asks.of))
for id := range asks.of {
ids = append(ids, id)
}
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
now := time.Now()
for _, id := range ids {
f := asks.of[id]
logf("[mesh-tools] at its stop the tool runner cut %s's call %s, %s old: it outlived the drain bound of %s, and its "+
"caller is answered nothing (design 47 H2 §813 (12))", f.module, f.verb, now.Sub(f.at).Round(time.Millisecond), bound)
close(f.cut)
delete(asks.of, id)
}
asks.mu.Unlock()
return
}
}
}
// undrain is a test's: the runner serves again as before its stop.
func undrain() {
asks.mu.Lock()
asks.draining = false
asks.of = map[uint64]*inFlight{}
asks.mu.Unlock()
}
+2 -115
View File
@@ -1,13 +1,11 @@
package launch package launch
import ( import (
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"sync"
"syscall" "syscall"
"testing" "testing"
"time" "time"
@@ -53,11 +51,6 @@ done
// to stop, the power bundle among them dialling the system bus again, which restarted the bus during the // to stop, the power bundle among them dialling the system bus again, which restarted the bus during the
// shutdown and held it 29 minutes). A bundle that exits while it serves is started again; once the runtime // shutdown and held it 29 minutes). A bundle that exits while it serves is started again; once the runtime
// itself is stopping, none is, by a restart or by a call. // itself is stopping, none is, by a restart or by a call.
//
// **The tool runner drains at a stop** (design 47 H2 §813 (12), H-A-342 (2), H-A-353, H-A-369): once it drains, no new call is
// taken and its caller is answered nothing (Unanswered), never refused; a call
// in flight that ends within the drain bound is answered; one still in flight at the bound is cut, said with its bundle, its verb
// and its age, and left unanswered (Unanswered, so the bus sends its caller nothing: a transport fault).
func TestABundleIsStartedAgainUnlessTheRuntimeIsStopping(t *testing.T) { func TestABundleIsStartedAgainUnlessTheRuntimeIsStopping(t *testing.T) {
saved := RestartFirst saved := RestartFirst
RestartFirst = 10 * time.Millisecond RestartFirst = 10 * time.Millisecond
@@ -66,104 +59,12 @@ func TestABundleIsStartedAgainUnlessTheRuntimeIsStopping(t *testing.T) {
name string name string
stopping bool stopping bool
starts int starts int
drain time.Duration // a drain row: the runner drains its calls in flight within this bound
release bool // a drain row's held call ends within the bound
}{ }{
{"a bundle that dies while the runtime serves", false, 2, 0, false}, {"a bundle that dies while the runtime serves", false, 2},
{"a bundle signalled with the stopping runtime", true, 1, 0, false}, {"a bundle signalled with the stopping runtime", true, 1},
{"a call that ends within the drain bound is answered, and a call after the stop is answered nothing", false, 0, 10 * time.Second, true},
{"a call that outlives the drain bound is cut and said", false, 0, 50 * time.Millisecond, false},
} { } {
t.Run(row.name, func(t *testing.T) { t.Run(row.name, func(t *testing.T) {
shuttingDown.Store(false) shuttingDown.Store(false)
if row.drain > 0 {
t.Cleanup(undrain)
dir := t.TempDir()
entry, hold := filepath.Join(dir, "bundle"), filepath.Join(dir, "hold")
if err := os.WriteFile(entry, []byte(holdingBundle), 0o755); err != nil {
t.Fatal(err)
}
if err := syscall.Mkfifo(hold, 0o600); err != nil {
t.Fatal(err)
}
l, err := Start("holding", entry, append(os.Environ(), "HOLD="+hold), &subscribing{}, t.Logf)
if err != nil {
t.Fatal(err)
}
t.Cleanup(l.Stop)
run := l.Registrations[0].Tools[0].Run
type answer struct {
raw json.RawMessage
err error
}
first := make(chan answer, 1)
go func() { raw, err := run("", json.RawMessage(`{}`)); first <- answer{raw, err} }()
// The call is in flight once the runner counted it.
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(time.Millisecond) {
asks.mu.Lock()
n := len(asks.of)
asks.mu.Unlock()
if n == 1 {
break
}
if time.Now().After(deadline) {
t.Fatal("the call was never in flight")
}
}
var mu sync.Mutex
var said []string
drained := make(chan struct{})
began := time.Now()
go func() {
Drain(row.drain, func(f string, a ...any) { mu.Lock(); said = append(said, fmt.Sprintf(f, a...)); mu.Unlock() })
close(drained)
}()
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(time.Millisecond) {
asks.mu.Lock()
d := asks.draining
asks.mu.Unlock()
if d {
break
}
if time.Now().After(deadline) {
t.Fatal("the drain never began")
}
}
if row.release {
var unanswered interface{ Unanswered() bool }
if _, err := run("", json.RawMessage(`{}`)); !errors.As(err, &unanswered) || !unanswered.Unanswered() {
t.Errorf("a call made after the stop ended %v, want it answered nothing, never refused", err)
}
f, err := os.OpenFile(hold, os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
_, _ = f.WriteString("go\n")
_ = f.Close()
}
got := <-first
<-drained
mu.Lock()
defer mu.Unlock()
if row.release {
if got.err != nil || !strings.Contains(string(got.raw), "held") {
t.Errorf("the call in flight was answered %s, %v; want it finished", got.raw, got.err)
}
if time.Since(began) >= row.drain || len(said) != 0 {
t.Errorf("the drain took %s and said %q; want it ended at the call's end, saying nothing", time.Since(began), said)
}
return
}
var unanswered interface{ Unanswered() bool }
if !errors.As(got.err, &unanswered) || !unanswered.Unanswered() {
t.Errorf("the call past the bound ended %v, want it cut and unanswered", got.err)
}
if len(said) != 1 || !strings.Contains(said[0], "holding") || !strings.Contains(said[0], "hold,") ||
!strings.Contains(said[0], "old") {
t.Errorf("the cut was said %q, want one line naming the bundle, the verb and the call's age", said)
}
return
}
dir := t.TempDir() dir := t.TempDir()
entry, out := filepath.Join(dir, "bundle"), filepath.Join(dir, "out") entry, out := filepath.Join(dir, "bundle"), filepath.Join(dir, "out")
if err := os.WriteFile(entry, []byte(notingBundle), 0o755); err != nil { if err := os.WriteFile(entry, []byte(notingBundle), 0o755); err != nil {
@@ -213,17 +114,3 @@ func TestABundleIsStartedAgainUnlessTheRuntimeIsStopping(t *testing.T) {
}) })
} }
} }
// holdingBundle serves one tool, hold, which answers only once a line can be read from the fifo $HOLD: a call that lasts as long
// as the test keeps it.
const holdingBundle = `#!/bin/sh
while IFS= read -r line; do
id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\)[,}].*/\1/p')
case "$line" in
*'"method":"initialize"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;;
*'"method":"tools/list"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"tools":[{"name":"hold","inputSchema":{}}]}}\n' "$id" ;;
*'"method":"tools/call"'*) read -r go < "$HOLD"
printf '{"jsonrpc":"2.0","id":%s,"result":{"content":[{"type":"text","text":"{\\"held\\":true}"}]}}\n' "$id" ;;
esac
done
`
+7 -49
View File
@@ -48,19 +48,7 @@ type Tool struct {
Run func(caller string, args json.RawMessage) (json.RawMessage, error) Run func(caller string, args json.RawMessage) (json.RawMessage, error)
// RunWithin is Run that waits within for the bundle's answer, the `timeout` the verb's seat definition names (design 47 H §760, // RunWithin is Run that waits within for the bundle's answer, the `timeout` the verb's seat definition names (design 47 H §760,
// H-A-43); zero waits CallTimeout. A tool the runtime serves itself has none: Run is its call. // H-A-43); zero waits CallTimeout. A tool the runtime serves itself has none: Run is its call.
RunWithin func(caller, ask string, args json.RawMessage, within time.Duration) (json.RawMessage, error) RunWithin func(caller string, args json.RawMessage, within time.Duration) (json.RawMessage, error)
// within is the wait Within set, which Call hands RunWithin.
within time.Duration
}
// Call runs the tool for caller, handing a bundle the ask id the call carried in its request header (stdio.AskHeader; design 47 H2
// §775, H-A-351), which the runtime names in the call's `_meta` under stdio.MetaAsk; "" when it carried none. A tool the runtime
// serves itself is its Run.
func (t Tool) Call(caller, ask string, args json.RawMessage) (json.RawMessage, error) {
if t.RunWithin == nil {
return t.Run(caller, args)
}
return t.RunWithin(caller, ask, args, t.within)
} }
// Within is the tool as called for a verb whose definition names a timeout: its Run waits within for the bundle's answer. A zero // Within is the tool as called for a verb whose definition names a timeout: its Run waits within for the bundle's answer. A zero
@@ -70,10 +58,7 @@ func (t Tool) Within(within time.Duration) Tool {
return t return t
} }
run := t.RunWithin run := t.RunWithin
t.Run = func(caller string, args json.RawMessage) (json.RawMessage, error) { t.Run = func(caller string, args json.RawMessage) (json.RawMessage, error) { return run(caller, args, within) }
return run(caller, "", args, within)
}
t.within = within
return t return t
} }
@@ -85,9 +70,8 @@ const MetaCaller = "mesh/caller"
// callParams is a `tools/call`'s params: the tool, its arguments as the caller sent them, and in `_meta`, which the // callParams is a `tools/call`'s params: the tool, its arguments as the caller sent them, and in `_meta`, which the
// runtime writes and no caller can, the caller — only when the subject named one — and the id of the call in flight // runtime writes and no caller can, the caller — only when the subject named one — and the id of the call in flight
// (mesh-sdk buscalls.MetaCall), which a ledger's apply names so the runtime stamps the caller it proved (novox/hq ADR // (mesh-sdk buscalls.MetaCall), which a ledger's apply names so the runtime stamps the caller it proved (novox/hq ADR
// 0597 §7), and the ask id the call carried in its request header, only when it carried one (stdio.MetaAsk; design 47 H2 // 0597 §7).
// §775, H-A-351). func callParams(name, caller, call string, args json.RawMessage) map[string]any {
func callParams(name, caller, call, ask string, args json.RawMessage) map[string]any {
params := map[string]any{"name": name, "arguments": args} params := map[string]any{"name": name, "arguments": args}
meta := map[string]any{} meta := map[string]any{}
if caller != "" { if caller != "" {
@@ -96,9 +80,6 @@ func callParams(name, caller, call, ask string, args json.RawMessage) map[string
if call != "" { if call != "" {
meta[buscalls.MetaCall] = call meta[buscalls.MetaCall] = call
} }
if ask != "" {
meta[stdio.MetaAsk] = ask
}
if len(meta) > 0 { if len(meta) > 0 {
params["_meta"] = meta params["_meta"] = meta
} }
@@ -500,12 +481,6 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
if answered, err = mesh.Seat(strings.TrimPrefix(m.Method, "mesh/seat."), m.Params, nil); err == nil { if answered, err = mesh.Seat(strings.TrimPrefix(m.Method, "mesh/seat."), m.Params, nil); err == nil {
result = answered result = answered
} }
case "mesh/queue.waiting":
// The asks that wait on the holder's own queue of a seat (design 47 H2 H-A-410).
var answered json.RawMessage
if answered, err = mesh.Seat("waiting", m.Params, nil); err == nil {
result = answered
}
case "mesh/seat.take", "mesh/seat.answer": case "mesh/seat.take", "mesh/seat.answer":
mu.Lock() mu.Lock()
seatTaker = c seatTaker = c
@@ -838,7 +813,7 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
input = json.RawMessage("{}") input = json.RawMessage("{}")
} }
tool := Tool{Name: name, Description: t.Description, Input: input, tool := Tool{Name: name, Description: t.Description, Input: input,
Run: nil, RunWithin: func(caller, ask string, args json.RawMessage, within time.Duration) (json.RawMessage, error) { Run: nil, RunWithin: func(caller string, args json.RawMessage, within time.Duration) (json.RawMessage, error) {
if len(args) == 0 || string(args) == "null" { if len(args) == 0 || string(args) == "null" {
args = json.RawMessage("{}") args = json.RawMessage("{}")
} }
@@ -848,7 +823,7 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
if within > 0 { if within > 0 {
bound = within bound = within
} }
res, err := asking("tools/call", callParams(full, caller, call, ask, args), bound) res, err := asking("tools/call", callParams(full, caller, call, args), bound)
if err != nil { if err != nil {
if errors.Is(err, errNoAnswer) { if errors.Is(err, errNoAnswer) {
// Its caller is gone by now and nobody else would hear of it (issue 1966). // Its caller is gone by now and nobody else would hear of it (issue 1966).
@@ -885,7 +860,7 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
return b, nil return b, nil
}} }}
tool.Run = func(caller string, args json.RawMessage) (json.RawMessage, error) { tool.Run = func(caller string, args json.RawMessage) (json.RawMessage, error) {
return tool.RunWithin(caller, "", args, 0) return tool.RunWithin(caller, args, 0)
} }
if _, seen := groups[under]; !seen { if _, seen := groups[under]; !seen {
order = append(order, under) order = append(order, under)
@@ -915,18 +890,6 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
} }
func (c *child) ask(module, method string, params any, timeout time.Duration) (json.RawMessage, error) { func (c *child) ask(module, method string, params any, timeout time.Duration) (json.RawMessage, error) {
// Counted for the drain at a stop, and refused once it began (design 47 H2 §813 (12)).
verb := method
if p, ok := params.(map[string]any); ok && method == "tools/call" {
if name, ok := p["name"].(string); ok {
verb = name
}
}
asked, flight, err := begin(module, verb)
if err != nil {
return nil, err
}
defer end(asked)
c.mu.Lock() c.mu.Lock()
if c.why != nil { if c.why != nil {
c.mu.Unlock() c.mu.Unlock()
@@ -962,11 +925,6 @@ func (c *child) ask(module, method string, params any, timeout time.Duration) (j
return m.Result, nil return m.Result, nil
case <-c.dead: case <-c.dead:
return nil, c.deathReason() return nil, c.deathReason()
case <-flight.cut:
c.mu.Lock()
delete(c.pending, id)
c.mu.Unlock()
return nil, &cutCall{module: module, verb: verb}
case <-timer.C: case <-timer.C:
c.mu.Lock() c.mu.Lock()
delete(c.pending, id) delete(c.pending, id)
+29 -28
View File
@@ -128,34 +128,6 @@ func TestABundleTakesASeatsWorkThroughItsOwnChannel(t *testing.T) {
t.Errorf("a publish with ack went the unacknowledged way: %v", b.published) t.Errorf("a publish with ack went the unacknowledged way: %v", b.published)
} }
}) })
// 1887/A11: a bundle's pull reaches the runtime's bus from its own channel, as its other seat traffic does.
t.Run("ABundlesPullReachesTheRuntimeThroughItsOwnChannel", func(t *testing.T) {
entry := filepath.Join(t.TempDir(), "bundle")
if err := os.WriteFile(entry, []byte(pullingBundle), 0o755); err != nil {
t.Fatal(err)
}
b := &seating{}
l, err := Start("mesh-build-go", entry, os.Environ(), b, t.Logf)
if err != nil {
t.Fatal(err)
}
t.Cleanup(l.Stop)
for i := 0; ; i++ {
b.mu.Lock()
verb, params := b.verb, b.params
b.mu.Unlock()
if verb == "pull" {
if params != `{"worker":"SEAT_NODE_BUILD_GO_DELIVERY_worker","wait_ms":0}` {
t.Fatalf("pulled with %s", params)
}
return
}
if i > 100 {
t.Fatal("the bundle's pull never reached the runtime")
}
time.Sleep(20 * time.Millisecond)
}
})
} }
// A bundle that pulls one ask from its worker when it is listed. // A bundle that pulls one ask from its worker when it is listed.
@@ -170,3 +142,32 @@ while IFS= read -r line; do
esac esac
done done
` `
// 1887/A11: a bundle's pull reaches the runtime's bus from its own channel, as its other seat traffic does.
func TestABundlePullsASeatsWorkThroughItsOwnChannel(t *testing.T) {
entry := filepath.Join(t.TempDir(), "bundle")
if err := os.WriteFile(entry, []byte(pullingBundle), 0o755); err != nil {
t.Fatal(err)
}
b := &seating{}
l, err := Start("mesh-build-go", entry, os.Environ(), b, t.Logf)
if err != nil {
t.Fatal(err)
}
t.Cleanup(l.Stop)
for i := 0; ; i++ {
b.mu.Lock()
verb, params := b.verb, b.params
b.mu.Unlock()
if verb == "pull" {
if params != `{"worker":"SEAT_NODE_BUILD_GO_DELIVERY_worker","wait_ms":0}` {
t.Fatalf("pulled with %s", params)
}
return
}
if i > 100 {
t.Fatal("the bundle's pull never reached the runtime")
}
time.Sleep(20 * time.Millisecond)
}
}
+2 -4
View File
@@ -260,13 +260,11 @@ func Fixture(name string) string {
return filepath.Join(filepath.Dir(here), "..", "..", "test", "fixtures", name) return filepath.Join(filepath.Dir(here), "..", "..", "test", "fixtures", name)
} }
// Until retries while the bus answers "no responders" — something not yet served. Its bound only ends a wait that never // Until retries while the bus answers "no responders" — something not yet served.
// 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) { func Until(t *testing.T, try func() error) {
t.Helper() t.Helper()
var err error var err error
for i := 0; i < 300; i++ { for i := 0; i < 50; i++ {
if err = try(); err == nil { if err = try(); err == nil {
return return
} }
@@ -8,7 +8,6 @@ import (
"testing" "testing"
"time" "time"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/approval" "git.novox.be/novox/mesh-sdk/go/approval"
"git.novox.be/novox/mesh-sdk/go/seatdef" "git.novox.be/novox/mesh-sdk/go/seatdef"
"github.com/novox/mesh-tools/node-tools/internal/bus" "github.com/novox/mesh-tools/node-tools/internal/bus"
@@ -21,7 +20,6 @@ import (
type saidCaller struct { type saidCaller struct {
Caller string `json:"caller"` Caller string `json:"caller"`
Call string `json:"call"` Call string `json:"call"`
Ask *string `json:"ask"`
Arguments map[string]any `json:"arguments"` Arguments map[string]any `json:"arguments"`
} }
@@ -67,39 +65,7 @@ func TestACallOnTheCallerNamedSubjectReachesTheModuleWithItsCaller(t *testing.T)
if got.Arguments["caller"] != "novox.node-tools" { if got.Arguments["caller"] != "novox.node-tools" {
t.Errorf("%s: the arguments did not reach the module as sent: %v", key, got.Arguments) t.Errorf("%s: the arguments did not reach the module as sent: %v", key, got.Arguments)
} }
// A call that carries no ask id in its header names none in `_meta` (design 47 H2 §775, H-A-351).
if got.Ask != nil {
t.Errorf("%s reached the module with ask %q, want none for a call whose header carries none", key, *got.Ask)
}
} }
// **The ask id a kept call sets in its request header is copied into the call's `_meta` as mesh/ask** (design 47 H2 §775,
// H-A-351), for a module's tool and for a seat's verb.
url := mt.URL(t)
t.Run("TheAskIdOfTheHeaderReachesTheModule", func(t *testing.T) {
raw, err := nats.Connect(url)
if err != nil {
t.Fatal(err)
}
defer raw.Close()
for _, subject := range []string{"mesh.mod.ledger.tool.who", "mesh.seat.node-desk.tool.who.anchor"} {
msg := nats.NewMsg(subject)
msg.Header.Set(stdio.AskHeader, "ask-7f3a")
msg.Data = []byte(`{}`)
var reply struct {
Result saidCaller `json:"result"`
}
mt.Until(t, func() error {
answer, err := raw.RequestMsg(msg, 5*time.Second)
if err == nil {
err = json.Unmarshal(answer.Data, &reply)
}
return err
})
if reply.Result.Ask == nil || *reply.Result.Ask != "ask-7f3a" {
t.Errorf("%s reached the module with ask %v, want the header's ask-7f3a under mesh/ask", subject, reply.Result.Ask)
}
}
})
} }
// deskDefined is the seat list's definition of the fixture seat node-desk, its verb who. // deskDefined is the seat list's definition of the fixture seat node-desk, its verb who.
+3 -3
View File
@@ -25,11 +25,11 @@ type Gate interface {
} }
// gatedRun is how a handler calls a tool: through the gate where there is one. // gatedRun is how a handler calls a tool: through the gate where there is one.
type gatedRun func(call approval.Call, t launch.Tool, caller, ask string) (any, error) type gatedRun func(call approval.Call, t launch.Tool, caller string) (any, error)
// gated calls the tool through the gate, or straight where the runner has none. // gated calls the tool through the gate, or straight where the runner has none.
func (c *consumers) gated(call approval.Call, t launch.Tool, caller, ask string) (any, error) { func (c *consumers) gated(call approval.Call, t launch.Tool, caller string) (any, error) {
run := func() (any, error) { return t.Call(caller, ask, call.Args) } run := func() (any, error) { return t.Run(caller, call.Args) }
if c.gate == nil { if c.gate == nil {
return run() return run()
} }
+15 -28
View File
@@ -518,10 +518,10 @@ func (r *runner) serve(l *loadedModule) {
// Told who called, from the subject the call arrived on, never from its body (novox/hq issue 365). // Told who called, from the subject the call arrived on, never from its body (novox/hq issue 365).
// Through the approval gate, before the bundle or the runner's own tool (design 46 7-approval-mark §20). // Through the approval gate, before the bundle or the runner's own tool (design 46 7-approval-mark §20).
module, own := reg.module, reg.repairs module, own := reg.module, reg.repairs
stop, err := r.conn.HandleCalled(address, func(caller, ask string, body json.RawMessage) (any, error) { stop, err := r.conn.HandleCalled(address, func(caller string, body json.RawMessage) (any, error) {
return r.events.gated(approval.Call{Address: module + "." + t.Name, Module: module, Name: t.Name, Own: own, return r.events.gated(approval.Call{Address: module + "." + t.Name, Module: module, Name: t.Name, Own: own,
Fingerprint: r.fingerprintOf(module), Env: r.envOf(module), Caller: caller, Args: argsOf(body), Fingerprint: r.fingerprintOf(module), Env: r.envOf(module), Caller: caller, Args: argsOf(body),
Description: t.Description}, t, caller, ask) Description: t.Description}, t, caller)
}) })
if err != nil { if err != nil {
r.logf("[mesh-tools] cannot serve %s.%s: %v", reg.module, t.Name, err) r.logf("[mesh-tools] cannot serve %s.%s: %v", reg.module, t.Name, err)
@@ -815,7 +815,7 @@ func serveSeats(conn *bus.Conn, modules []string, current func() []registration,
// record of the calls its gate holds, by caller, and no bundle names it (lead answers A-265, A-266, A-271). // record of the calls its gate holds, by caller, and no bundle names it (lead answers A-265, A-266, A-271).
if v.Verb == seatdef.ApprovalsVerb && approvals != nil { if v.Verb == seatdef.ApprovalsVerb && approvals != nil {
seat := v.Seat seat := v.Seat
stop, err := conn.HandleSubjectCalled(v.Subject, func(caller, _ string, _ json.RawMessage) (any, error) { stop, err := conn.HandleSubjectCalled(v.Subject, func(caller string, _ json.RawMessage) (any, error) {
return approvals(caller) return approvals(caller)
}) })
if err != nil { if err != nil {
@@ -834,9 +834,9 @@ func serveSeats(conn *bus.Conn, modules []string, current func() []registration,
// Through the approval gate, for any caller, before the bundle (design 47 H §752; design 46 // Through the approval gate, for any caller, before the bundle (design 47 H §752; design 46
// 7-approval-mark §20). // 7-approval-mark §20).
module, v := module, v module, v := module, v
handle := func(caller, ask string, body json.RawMessage) (any, error) { handle := func(caller string, body json.RawMessage) (any, error) {
answer, err := gated(approval.Call{Address: v.Seat + "." + v.Verb, Module: module, Seat: v.Seat, Name: v.Verb, answer, err := gated(approval.Call{Address: v.Seat + "." + v.Verb, Module: module, Seat: v.Seat, Name: v.Verb,
Fingerprint: fingerprintOf(module), Caller: caller, Args: argsOf(body), Description: t.Description}, t.Within(within("seat:"+v.Seat+"."+v.Verb)), caller, ask) Fingerprint: fingerprintOf(module), Caller: caller, Args: argsOf(body), Description: t.Description}, t.Within(within("seat:"+v.Seat+"."+v.Verb)), caller)
if err != nil || !chunked("seat:"+v.Seat+"."+v.Verb) { if err != nil || !chunked("seat:"+v.Seat+"."+v.Verb) {
return answer, err return answer, err
} }
@@ -1206,9 +1206,8 @@ type stateAsked struct {
// TTLSeconds gives a created or put key its own time to live (issue 1952): create makes it only when it has no // TTLSeconds gives a created or put key its own time to live (issue 1952): create makes it only when it has no
// value, put renews it whole. Zero is none. // value, put renews it whole. Zero is none.
TTLSeconds int `json:"ttl_seconds"` TTLSeconds int `json:"ttl_seconds"`
// Cursor and MaxBytes are a `page`'s opaque cursor, the next of the page before (empty: from the start), and its size in // After and MaxBytes are a `page`'s start key and its size in keys and values (zero is a megabyte).
// keys and values (zero, or above 768 KB, is 768 KB; design 47 H2 §779). After string `json:"after"`
Cursor string `json:"cursor"`
MaxBytes int `json:"max_bytes"` MaxBytes int `json:"max_bytes"`
// BudgetMS is the time a `page` may spend reading, in milliseconds (zero is the runtime's own, well under 30 s). // BudgetMS is the time a `page` may spend reading, in milliseconds (zero is the runtime's own, well under 30 s).
BudgetMS int `json:"budget_ms"` BudgetMS int `json:"budget_ms"`
@@ -1240,8 +1239,11 @@ func (b *moduleBus) State(verb string, params json.RawMessage) (json.RawMessage,
} }
answer = entry answer = entry
case "page": case "page":
// One page of the state in the order the bus wrote it, after the cursor, one request for many (design 47 H2 §779). // The values after a key in key order, one request for many (a first view's page of a slow state).
page, err := conn.StatePage(b.module, asked.State, asked.Cursor, asked.MaxBytes, time.Duration(asked.BudgetMS)*time.Millisecond) if asked.MaxBytes <= 0 {
asked.MaxBytes = 1 << 20
}
page, err := conn.StatePage(b.module, asked.State, asked.After, asked.MaxBytes, time.Duration(asked.BudgetMS)*time.Millisecond)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -1264,12 +1266,7 @@ func (b *moduleBus) State(verb string, params json.RawMessage) (json.RawMessage,
if err != nil { if err != nil {
return nil, err return nil, err
} }
// With the bucket's fill, so a bundle's prune reads it from the put (design 47 H2 DMC-14, H-A-386). answer = map[string]any{"revision": revision}
fill, err := conn.StateFill(b.module, asked.State)
if err != nil {
return nil, fmt.Errorf("%s was put at revision %d, but its state's fill is not read: %w", asked.Key, revision, err)
}
answer = map[string]any{"revision": revision, "fill": fill}
case "delete": case "delete":
if err := conn.StateDelete(b.module, asked.State, asked.Key); err != nil { if err := conn.StateDelete(b.module, asked.State, asked.Key); err != nil {
return nil, err return nil, err
@@ -1441,10 +1438,8 @@ type seatAsked struct {
Body json.RawMessage `json:"body"` Body json.RawMessage `json:"body"`
ID string `json:"id"` ID string `json:"id"`
Worker string `json:"worker"` Worker string `json:"worker"`
// Seat is the seat whose work queue a waiting read reads (design 47 H2 H-A-410). Bucket string `json:"bucket"`
Seat string `json:"seat"` Key string `json:"key"`
Bucket string `json:"bucket"`
Key string `json:"key"`
// WaitMS is how long a pull waits for a message (none when 0); Fate what a settle gives one (issue 1887 A11). // WaitMS is how long a pull waits for a message (none when 0); Fate what a settle gives one (issue 1887 A11).
WaitMS int `json:"wait_ms"` WaitMS int `json:"wait_ms"`
// DelayMS is how long a settle with the fate nak-after waits before the bus gives the message again. // DelayMS is how long a settle with the fate nak-after waits before the bus gives the message again.
@@ -1483,14 +1478,6 @@ func (b *moduleBus) Seat(verb string, params json.RawMessage, handOn func(string
return json.RawMessage("null"), err return json.RawMessage("null"), err
} }
return json.Marshal(entry) return json.Marshal(entry)
case "waiting":
// mesh/queue.waiting: the asks that wait on the holder's own queue of a seat, read without consuming them (design 47
// H2 H-A-410, ADR 0596).
waiting, err := conn.QueueWaitingOf(b.module, asked.Seat)
if err != nil {
return nil, err
}
return json.Marshal(waiting)
case "pull": case "pull":
// One message from a worker the membership lists, never a prefetch: a build module pulls an ask only when it // One message from a worker the membership lists, never a prefetch: a build module pulls an ask only when it
// has room, from its workers in their order (novox/hq ADR 0525 §4; issue 1887 A11). // has room, from its workers in their order (novox/hq ADR 0525 §4; issue 1887 A11).
+1 -1
View File
@@ -328,7 +328,7 @@ func TestANodeScopedSeatVerbIsAlsoAnsweredWithNoMachine(t *testing.T) {
return []registration{{module: "node-shelf", owner: "theta", tools: []launch.Tool{{Name: "list", return []registration{{module: "node-shelf", owner: "theta", tools: []launch.Tool{{Name: "list",
Run: func(string, json.RawMessage) (json.RawMessage, error) { return json.RawMessage(`{"shelf":["x"]}`), nil }}}}} Run: func(string, json.RawMessage) (json.RawMessage, error) { return json.RawMessage(`{"shelf":["x"]}`), nil }}}}}
} }
gated := func(_ approval.Call, tool launch.Tool, caller, _ string) (any, error) { gated := func(_ approval.Call, tool launch.Tool, caller string) (any, error) {
return tool.Run(caller, nil) return tool.Run(caller, nil)
} }
nodeTools.Follow("theta") nodeTools.Follow("theta")
@@ -3,7 +3,6 @@ package runtime
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt"
"strings" "strings"
"sync" "sync"
"testing" "testing"
@@ -220,64 +219,4 @@ func TestABundlePullsAndSettlesThroughItsModulesBus(t *testing.T) {
if none, err := building.Seat("pull", json.RawMessage(`{"worker":"SEAT_NODE_BUILD_GO_DELIVERY_worker"}`), nil); err != nil || string(none) != "null" { if none, err := building.Seat("pull", json.RawMessage(`{"worker":"SEAT_NODE_BUILD_GO_DELIVERY_worker"}`), nil); err != nil || string(none) != "null" {
t.Fatalf("an empty worker answered %s, %v", none, err) t.Fatalf("an empty worker answered %s, %v", none, err)
} }
// Design 47 H2 H-A-410: the holder reads what waits on its own queue of the seat without consuming it (mesh/queue.waiting),
// each ask with its id, the module that put it and its age; another module is refused, as is a seat it holds no queue of.
waiting := func(want string, spelled ...string) {
t.Helper()
seat := "node-build-go"
if len(spelled) > 0 {
seat = spelled[0]
}
raw, err := building.Seat("waiting", json.RawMessage(`{"seat":"`+seat+`"}`), nil)
var w bus.QueueWaiting
if err != nil || json.Unmarshal(raw, &w) != nil || w.Capped {
t.Fatalf("waiting = %s, %v", raw, err)
}
var got []string
for _, a := range w.Asks {
got = append(got, fmt.Sprintf("%s:%s:%v", a.Module, a.ID, a.AgeSeconds < 60)+map[bool]string{true: ":again"}[a.Again])
}
if strings.Join(got, ",") != want {
t.Errorf("waiting is %s, want %s", raw, want)
}
}
waiting("")
for _, id := range []string{"ask2", "ask3"} {
m := nats.NewMsg("mesh.seat.node-build-go.accept.delivery")
m.Header.Set("x-source", "mesh-delivery-pipeline")
m.Header.Set("x-event-id", "mesh-delivery-pipeline."+id)
m.Data = []byte(`{"id":"` + id + `"}`)
if _, err := js.PublishMsg(m); err != nil {
t.Fatal(err)
}
}
waiting("mesh-delivery-pipeline:ask2:true,mesh-delivery-pipeline:ask3:true")
waiting("mesh-delivery-pipeline:ask2:true,mesh-delivery-pipeline:ask3:true") // read again: nothing was consumed
if _, err := elsewhere.Seat("waiting", json.RawMessage(`{"seat":"node-build-go"}`), nil); err == nil {
t.Error("another module read the Go build seat's queue")
}
if _, err := building.Seat("waiting", json.RawMessage(`{"seat":"operator-channel"}`), nil); err == nil {
t.Error("the holder read the queue of a seat it holds no worker on")
}
raw, err = building.Seat("pull", json.RawMessage(`{"worker":"SEAT_NODE_BUILD_GO_DELIVERY_worker","wait_ms":1000}`), nil)
if err != nil || json.Unmarshal(raw, &p) != nil {
t.Fatal(raw, err)
}
// a pulled ask, held or handed back, is listed again (the holder tells the two apart by its state taken); one acknowledged
// is gone
waiting("mesh-delivery-pipeline:ask2:true:again,mesh-delivery-pipeline:ask3:true")
if _, err := building.Seat("settle", json.RawMessage(`{"id":"`+p.ID+`","fate":"nak-after","delay_ms":60000}`), nil); err != nil {
t.Fatal(err)
}
waiting("mesh-delivery-pipeline:ask2:true:again,mesh-delivery-pipeline:ask3:true")
raw, err = building.Seat("pull", json.RawMessage(`{"worker":"SEAT_NODE_BUILD_GO_DELIVERY_worker","wait_ms":1000}`), nil)
if err != nil || json.Unmarshal(raw, &p) != nil {
t.Fatal(raw, err)
}
if _, err := building.Seat("settle", json.RawMessage(`{"id":"`+p.ID+`","fate":"ack"}`), nil); err != nil {
t.Fatal(err)
}
waiting("mesh-delivery-pipeline:ask2:true:again")
// the seat's stream is the one mesh-sdk's buscompose names, '.' as '_' too (H-A-410, P9)
waiting("mesh-delivery-pipeline:ask2:true:again", "node-build.go")
} }
@@ -7,8 +7,6 @@ import (
"testing" "testing"
"time" "time"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"github.com/novox/mesh-tools/node-tools/internal/bus" "github.com/novox/mesh-tools/node-tools/internal/bus"
"github.com/novox/mesh-tools/node-tools/internal/launch" "github.com/novox/mesh-tools/node-tools/internal/launch"
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest" mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
@@ -73,26 +71,16 @@ func TestAKeysHistoryIsEveryValueKeptOldestFirst(t *testing.T) {
owner, reader, _ := historyBuses(t) owner, reader, _ := historyBuses(t)
before := time.Now().Add(-time.Second) before := time.Now().Add(-time.Second)
var revisions []uint64 var revisions []uint64
// each put answers the bucket's fill with its revision, buscalls.Fill's form (design 47 H2 DMC-14, H-A-386): the messages for _, v := range []string{`{"state":"open"}`, `{"state":"fixing"}`, `{"state":"resolved"}`} {
// kept (every value of the key, the bucket keeping 8), their bytes, and no cap (0)
var bytes uint64
for i, v := range []string{`{"state":"open"}`, `{"state":"fixing"}`, `{"state":"resolved"}`} {
raw, err := ask(owner, "put", map[string]any{"state": "issues", "key": "502", "value": json.RawMessage(v)}) raw, err := ask(owner, "put", map[string]any{"state": "issues", "key": "502", "value": json.RawMessage(v)})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
var r struct { var r struct {
Revision uint64 `json:"revision"` Revision uint64 `json:"revision"`
Fill *buscalls.Fill `json:"fill"`
} }
_ = json.Unmarshal(raw, &r) _ = json.Unmarshal(raw, &r)
revisions = append(revisions, r.Revision) revisions = append(revisions, r.Revision)
if r.Fill == nil || r.Fill.Count != uint64(i+1) || r.Fill.Bytes <= bytes || r.Fill.MaxBytes != 0 {
t.Errorf("put %d answered %s, want its revision and the fill of %d messages, more bytes than %d, no cap", i, raw, i+1, bytes)
}
if r.Fill != nil {
bytes = r.Fill.Bytes
}
} }
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": "503", "value": 1}); err != nil { if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": "503", "value": 1}); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -162,79 +150,35 @@ func TestAKeysHistoryAndAPageOfAStateAreServedToOwnerAndReaderAndRefusedToAModul
!strings.Contains(err.Error(), "not a key") { !strings.Contains(err.Error(), "not a key") {
t.Errorf("history of a key the bus cannot hold: %v", err) t.Errorf("history of a key the bus cannot hold: %v", err)
} }
// A page is the values in the order the bus wrote them after the cursor, in one request, to the owner and to a reader, // A page is the values in key order after a key, in one request, to the owner and to a reader, never to a
// never to a module not issued the state; a page too small for two values still gives one and says where the read goes // module not issued the state; a page too small for two values still gives one and says where it goes on.
// on; a value written after the read began comes marked seen-again, and a fresh read hands each kept message, a key's for k, v := range map[string]string{"2": `"bb"`, "3": `"cc"`} {
// older kept revision included (design 47 H2 §779, H-A-382). if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": k, "value": json.RawMessage(v)}); err != nil {
for _, kv := range [][2]string{{"2", `"bb"`}, {"3", `"cc"`}} {
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": kv[0], "value": json.RawMessage(kv[1])}); err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
type entry struct {
Key string `json:"key"`
Value json.RawMessage `json:"value"`
SeenAgain bool `json:"seen-again"`
Deleted bool `json:"deleted"`
}
type page struct { type page struct {
Entries []entry `json:"entries"` Entries []kept `json:"entries"`
Next string `json:"next"` Next string `json:"next"`
} }
read := func(who launch.Bus, state, cursor string, most int) page { for _, c := range []struct {
t.Helper() who, state, after string
raw, err := ask(who, "page", map[string]any{"state": state, "cursor": cursor, "max_bytes": most}) max int
keys []string
next string
}{{"owner", "issues", "", 1 << 20, []string{"1", "2", "3"}, ""}, {"reader", "issues.issues", "1", 1 << 20, []string{"2", "3"}, ""},
{"owner", "issues", "", 1, []string{"1"}, "1"}, {"owner", "issues", "1", 9, []string{"2"}, "2"}} {
b := map[string]launch.Bus{"owner": owner, "reader": reader}[c.who]
raw, err := ask(b, "page", map[string]any{"state": c.state, "after": c.after, "max_bytes": c.max})
var p page var p page
if err != nil || json.Unmarshal(raw, &p) != nil { if err != nil || json.Unmarshal(raw, &p) != nil || p.Next != c.next || len(p.Entries) != len(c.keys) {
t.Fatalf("page of %s after %q = %s, %v", state, cursor, raw, err) t.Fatalf("page %+v = %s, %v", c, raw, err)
} }
return p for i, k := range c.keys {
} if p.Entries[i].Key != k {
said := func(p page) string { t.Errorf("page %+v: entry %d is %s, want %s", c, i, p.Entries[i].Key, k)
var out []string
for _, e := range p.Entries {
out = append(out, e.Key+map[bool]string{true: "+again"}[e.SeenAgain]+map[bool]string{true: "+deleted"}[e.Deleted])
if e.Deleted == (e.Value != nil) {
out = append(out, "(value "+string(e.Value)+")")
} }
} }
return strings.Join(out, ",") + map[bool]string{true: " (more)"}[p.Next != ""]
}
for who, b := range map[string]launch.Bus{"issues": owner, "issues.issues": reader} {
if got := said(read(b, who, "", 1<<20)); got != "1,2,3" {
t.Errorf("a whole page of %s is %s, want 1,2,3", who, got)
}
}
first := read(owner, "issues", "", 1)
second := read(owner, "issues", first.Next, 1)
if said(first) != "1 (more)" || said(second) != "2 (more)" {
t.Fatalf("pages of one value are %s and %s, want 1 (more) and 2 (more)", said(first), said(second))
}
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": "1", "value": 11}); err != nil {
t.Fatal(err)
}
if got := said(read(owner, "issues", second.Next, 1<<20)); got != "3,1+again" {
t.Errorf("the rest of the read is %s, want 3 and 1 written again since the read began, marked: 3,1+again", got)
}
if got := said(read(owner, "issues", "", 1<<20)); got != "1,2,3,1" {
t.Errorf("a fresh read is %s, want each kept message once, 1's older revision first: 1,2,3,1", got)
}
// A kept delete is handed as an entry deleted, with no value, at its sequence, so a deleted key never comes back alive
// from a bucket with history (H-A-451 (1)).
for _, v := range []int{1, 2} {
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": "gone", "value": v}); err != nil {
t.Fatal(err)
}
}
if _, err := ask(owner, "delete", map[string]any{"state": "issues", "key": "gone"}); err != nil {
t.Fatal(err)
}
if got := said(read(owner, "issues", "", 1<<20)); got != "1,2,3,1,gone,gone,gone+deleted" {
t.Errorf("a read past a delete is %s, want its two values and then the delete: 1,2,3,1,gone,gone,gone+deleted", got)
}
if _, err := ask(owner, "page", map[string]any{"state": "issues", "cursor": "2"}); err == nil ||
!strings.Contains(err.Error(), "not a cursor") {
t.Errorf("a page after a key, not a cursor, answered %v; want it refused", err)
} }
// A page stops when its time budget is spent, after one value at least, and says where it goes on. // A page stops when its time budget is spent, after one value at least, and says where it goes on.
step := time.Time{} step := time.Time{}
@@ -242,7 +186,7 @@ func TestAKeysHistoryAndAPageOfAStateAreServedToOwnerAndReaderAndRefusedToAModul
defer func() { bus.PageClock = time.Now }() defer func() { bus.PageClock = time.Now }()
raw, err := ask(owner, "page", map[string]any{"state": "issues", "max_bytes": 1 << 20, "budget_ms": 10000}) raw, err := ask(owner, "page", map[string]any{"state": "issues", "max_bytes": 1 << 20, "budget_ms": 10000})
var cut page var cut page
if err != nil || json.Unmarshal(raw, &cut) != nil || said(cut) != "1 (more)" { if err != nil || json.Unmarshal(raw, &cut) != nil || len(cut.Entries) != 1 || cut.Next != "1" {
t.Fatalf("a page past its budget = %s, %v", raw, err) t.Fatalf("a page past its budget = %s, %v", raw, err)
} }
if _, err := ask(other, "page", map[string]any{"state": "issues.issues"}); err == nil { if _, err := ask(other, "page", map[string]any{"state": "issues.issues"}); err == nil {
-23
View File
@@ -37,29 +37,6 @@
"why": "the mesh's tools for whoever is on this machine, over MCP on loopback; the machine's login is the authority (novox/hq ADR 0152, 0175)" "why": "the mesh's tools for whoever is on this machine, over MCP on loopback; the machine's login is the authority (novox/hq ADR 0152, 0175)"
} }
], ],
"config": {
"drain-bound": {
"type": "string",
"description": "how long the tool runner, once told to stop, finishes the calls in flight before it cuts them and stops its bundles, a Go duration such as 30s (design 47 H2 §813 (12), H-A-377).",
"trusted": false,
"runtime": true,
"default": "30s"
},
"kept-call-pace-first": {
"type": "string",
"description": "how long the tool runner's kept call waits after its first transport fault before it calls again, doubling to kept-call-pace-max, a Go duration such as 1s (design 47 H2 §775).",
"trusted": false,
"runtime": true,
"default": "1s"
},
"kept-call-pace-max": {
"type": "string",
"description": "the longest wait of the tool runner's kept call between two calls, a Go duration such as 30s (design 47 H2 §775).",
"trusted": false,
"runtime": true,
"default": "30s"
}
},
"resources": [ "resources": [
{ {
"id": "mesh-state", "id": "mesh-state",
+2 -3
View File
@@ -1,8 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# A tools bundle that says who the runtime said called it (novox/hq issue 365): MCP over stdio, no SDK. Its tool # A tools bundle that says who the runtime said called it (novox/hq issue 365): MCP over stdio, no SDK. Its tool
# and its seat verb answer the caller the call's `_meta` named — "" when it named none —, the id of the call in flight # and its seat verb answer the caller the call's `_meta` named — "" when it named none —, the id of the call in flight
# it named (novox/hq ADR 0597 §7), the ask id it named under mesh/ask — null when it named none (design 47 H2 §775, H-A-351) —, # it named (novox/hq ADR 0597 §7), and the arguments as given.
# and the arguments as given.
import json, sys import json, sys
def say(m): def say(m):
@@ -20,7 +19,7 @@ for line in sys.stdin:
say({"id": rid, "result": {"tools": TOOLS}}) say({"id": rid, "result": {"tools": TOOLS}})
elif m == "tools/call": elif m == "tools/call":
meta = p.get("_meta") or {} meta = p.get("_meta") or {}
said = {"caller": meta.get("mesh/caller", ""), "call": meta.get("mesh/call", ""), "ask": meta.get("mesh/ask"), "arguments": p.get("arguments") or {}} said = {"caller": meta.get("mesh/caller", ""), "call": meta.get("mesh/call", ""), "arguments": p.get("arguments") or {}}
say({"id": rid, "result": {"content": [{"type": "text", "text": json.dumps(said)}]}}) say({"id": rid, "result": {"content": [{"type": "text", "text": json.dumps(said)}]}})
elif rid is not None: elif rid is not None:
say({"id": rid, "result": {}}) say({"id": rid, "result": {}})
+3 -32
View File
@@ -1,17 +1,11 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# A tools bundle for the tool runner's whole test (design 47 H §774): MCP over stdio, no SDK. A tool `who`, the seat node-desk's verbs # A tools bundle for the tool runner's whole test (design 47 H §774): MCP over stdio, no SDK. A tool `who`, the seat node-desk's verbs
# `who` (answers at once) and `slow` (answers after three seconds), and a tool `reach` that asks the seat verb node-desk.fresh as the # `who` (answers at once) and `slow` (answers after three seconds), and a tool `reach` that asks the seat verb node-desk.fresh as the
# bundle does, through the runtime's `mesh/ask`, and says what came back; a tool `hold`, which answers after the seconds it is given, # bundle does, through the runtime's `mesh/ask`, and says what came back.
# beside other calls (design 47 H2 §813 (12)); a tool `page`, which reads one page of its state `pages` after the cursor it is given, import json, sys, time
# through the runtime's `mesh/state.page`, and says the keys, those seen again and the next cursor (design 47 H2 §779).
import json, os, sys, threading, time
LOCK = threading.Lock()
def say(m): def say(m):
m["jsonrpc"] = "2.0" m["jsonrpc"] = "2.0"; sys.stdout.write(json.dumps(m) + "\n"); sys.stdout.flush()
with LOCK:
sys.stdout.write(json.dumps(m) + "\n"); sys.stdout.flush()
def text(rid, value): def text(rid, value):
say({"id": rid, "result": {"content": [{"type": "text", "text": json.dumps(value)}]}}) say({"id": rid, "result": {"content": [{"type": "text", "text": json.dumps(value)}]}})
@@ -19,8 +13,6 @@ def text(rid, value):
TOOLS = [ TOOLS = [
{"name": "who", "description": "the module's own tool", "inputSchema": {"type": "object", "properties": {}}}, {"name": "who", "description": "the module's own tool", "inputSchema": {"type": "object", "properties": {}}},
{"name": "reach", "description": "asks the seat verb node-desk.fresh", "inputSchema": {"type": "object", "properties": {}}}, {"name": "reach", "description": "asks the seat verb node-desk.fresh", "inputSchema": {"type": "object", "properties": {}}},
{"name": "hold", "description": "answers after the seconds it is given, beside other calls", "inputSchema": {"type": "object", "properties": {"seconds": {"type": "number"}}}},
{"name": "page", "description": "one page of the state pages after a cursor", "inputSchema": {"type": "object", "properties": {"cursor": {"type": "string"}}}},
{"name": "node-desk.who", "description": "the seat's verb", "inputSchema": {"type": "object", "properties": {}}}, {"name": "node-desk.who", "description": "the seat's verb", "inputSchema": {"type": "object", "properties": {}}},
{"name": "node-desk.slow", "description": "the seat's verb that answers late", "inputSchema": {"type": "object", "properties": {}}}, {"name": "node-desk.slow", "description": "the seat's verb that answers late", "inputSchema": {"type": "object", "properties": {}}},
] ]
@@ -32,29 +24,8 @@ for line in sys.stdin:
say({"id": rid, "result": {"tools": TOOLS}}) say({"id": rid, "result": {"tools": TOOLS}})
elif m == "tools/call": elif m == "tools/call":
name = p.get("name") name = p.get("name")
if name == "hold":
seconds = (p.get("arguments") or {}).get("seconds", 0)
with open(os.environ["HELD_FILE"], "a") as noted:
noted.write("hold %s\n" % seconds)
threading.Thread(target=lambda r=rid, n=seconds: (time.sleep(n), text(r, {"held": n})), daemon=True).start()
continue
if name == "node-desk.slow": if name == "node-desk.slow":
time.sleep(3) time.sleep(3)
if name == "page":
cursor = (p.get("arguments") or {}).get("cursor", "")
say({"id": "p1", "method": "mesh/state.page", "params": {"state": "pages", "cursor": cursor}})
for answer in sys.stdin:
a = json.loads(answer)
if a.get("id") == "p1":
if "error" in a:
text(rid, {"error": a["error"]})
else:
r = a.get("result") or {}
es = r.get("entries") or []
text(rid, {"keys": [e["key"] for e in es if not e.get("seen-again")],
"again": [e["key"] for e in es if e.get("seen-again")], "next": r.get("next", "")})
break
continue
if name == "reach": if name == "reach":
say({"id": "q1", "method": "mesh/ask", "params": {"key": "seat:node-desk.fresh", "body": {}}}) say({"id": "q1", "method": "mesh/ask", "params": {"key": "seat:node-desk.fresh", "body": {}}})
for answer in sys.stdin: for answer in sys.stdin: