Author SHA1 Message Date
mesh-tools 447a8d0359 Merge pull request 'The tool runner settles a seat ask with a delay and states seat-settle-delay (issue 1748; group fix/1748-transport-retry)' (#68) from fix/1748-transport-retry into main 2026-11-09 22:58:39 +00:00
jschoubben 62dce9fec7 T1: the seat settle applies a delayed nak with the bus's own delay (ADR 0664 §1, issue 1748)
mesh/delivery merged: source.main moved to novox/mesh-tools@447a8d035935
mesh/delivery-group group fix/1748-transport-retry merged: every member is merged
mesh/check checking 62dce9fec7a4 on 447a8d035935 | novox/mesh-tools#68 in group fix/1748-transport-retry
Claude-Session: https://claude.ai/code/session_01JG73KEq4zoDfM9WtYpcQgZ
2026-11-09 22:53:21 +01:00
jschoubben 7e4f86253e T2: the tool runner states the capability seat-settle-delay (ADR 0664 §5, issue 1748)
Claude-Session: https://claude.ai/code/session_01JG73KEq4zoDfM9WtYpcQgZ
2026-11-09 22:53:21 +01:00
mesh-tools 20979201eb Merge pull request 'The tool runner ends and restarts a bundle that writes an over-long line, and says an unanswered call and a refused answer (issue 1966 S8)' (#67) from fix/1966-s8-runner-frozen into main 2026-11-09 17:55:17 +00:00
jschoubben 4ee3cc0c7f Runner: the line cap is read once in Start, not per line from a goroutine (issue 1966, review round 3)
mesh/delivery merged: source.main moved to novox/mesh-tools@20979201eb56
mesh/check being carried to 4ee3cc0c7f4c on 20979201eb56 | from 2ea4f019e594
Claude-Session: https://claude.ai/code/session_01NcbgfFfQ4Z9UE5jK32PmE5
2026-11-09 13:59:13 +01:00
jschoubben a25c2b4d89 Launch test: the restart is heard as a second start line in the log, not polled from a file (issue 1966, review round 2)
Claude-Session: https://claude.ai/code/session_01NcbgfFfQ4Z9UE5jK32PmE5
2026-11-09 13:59:13 +01:00
jschoubben 312e29478e Tool runner: the cap's reason fails the call; the test proves the ending; the refused-answer limit keys on the caller's prefix and forgets old entries (issue 1966, review round 1)
Claude-Session: https://claude.ai/code/session_01NcbgfFfQ4Z9UE5jK32PmE5
2026-11-09 13:59:13 +01:00
jschoubben f3a9cc276e Tool runner: a bundle's over-long line ends the bundle and is said; an unanswered call and a refused answer are logged (issue 1966)
The reader of a bundle's stdout stopped at a line over 16 MiB without a word and the bundle's next write
blocked for good: every call of the module then timed out, unheard of. Now the line is said, the bundle ended
and started again by the exit path. A call the bundle does not answer in time is logged with tool and caller,
and a refused publish of an answer (to a caller's inbox) is said once per subject per minute.

Quick fix: only the bundle that met it (mesh-hand-acts' answer is cut by its own module). Thorough fix, chosen:
the runner guards every bundle, so the kind (a silent freeze of a module runtime) cannot recur for any module.

Claude-Session: https://claude.ai/code/session_01NcbgfFfQ4Z9UE5jK32PmE5
2026-11-09 13:59:13 +01:00
mesh-tools 2ea4f019e5 Merge pull request 'Issue a key-value entry asked in requires as a state, by its local name (issue 1966, recovery)' (#66) from fix/1966-requires-state into main 2026-11-09 12:56:37 +00:00
jschoubben 8052fd14f4 Issue a key-value entry asked in requires as a state, by its local name
mesh/delivery merged: source.main moved to novox/mesh-tools@2ea4f019e594
mesh/delivery-group group fix/1966-requires-state merged: every member is merged
mesh/check checking 8052fd14f4fd on 2ea4f019e594 | novox/mesh-tools#66 in group fix/1966-requires-state
A bundle's state call on a key-value entry its module asks for in requires
(ADR 0595 §1) was refused "keeps and reads no state called", because the
tool runner read the old state list alone (issue 1966). It now reads mesh-sdk's
one rule, membership.StateIssued.

Claude-Session: https://claude.ai/code/session_01NcbgfFSnn24M3GcqttoU7i
2026-11-09 12:39:04 +01:00
mesh-tools 9f61975c50 Merge pull request 'Gate record of mesh-tools' forge-made merges (issue 1966, recovery)' (#65) from fix/1966-forge-made-merge into main 2026-11-09 08:45:59 +00:00
jschoubben b82054d930 Record this repository's forge-made merges in the delivery gate, so the indexer takes them in (issue 1966, recovery)
mesh/delivery merged: source.main moved to novox/mesh-tools@9f61975c50a0
mesh/delivery-group group fix/1966-forge-made-merge merged: every member is merged
mesh/check checking b82054d9300a on 9f61975c50a0 | novox/mesh-tools#65 in group fix/1966-forge-made-merge
Merges made on the forge directly since 2026-11-09 07:04 UTC have no gate merge record,
and the indexer holds them; an empty merge through the gate covers this repository's head.
Second of its kind: the group's mesh-delivery member removes the need (the forge bridge
reads a forge-made merge's pull request from the forge).

Claude-Session: https://claude.ai/code/session_01NcbgfFSnn24M3GcqttoU7i
2026-11-09 09:17:01 +01:00
mesh-tools 164547645a Merge pull request 'The runtime answers a page of a kept state in one request, bounded by time (issue 1966, recovery)' (#64) from fix/1966-views-page-time into main 2026-11-09 08:13:13 +00:00
jschoubben 2135fed6cf A node's bucket opens under its own deadline, so a per-node page is ended by its budget too (issue 1966)
mesh/delivery merged: source.main moved to novox/mesh-tools@164547645aed
mesh/delivery-group group fix/1966-views-page-time merged: every member is merged
mesh/check checking 2135fed6cf1f on 9f61975c50a0 | novox/mesh-tools#64 in group fix/1966-views-page-time
Review round 3: the open on the first key of a node ran on the listing's context,
whose deadline is spent before the page's budget.

Claude-Session: https://claude.ai/code/session_01NcbgfFSnn24M3GcqttoU7i
2026-11-09 09:04:39 +01:00
jschoubben aba2c11a27 A page's gets each have their own deadline, so its budget always ends it; a node's bucket is bound once (issue 1966)
Claude-Session: https://claude.ai/code/session_01NcbgfFSnn24M3GcqttoU7i
2026-11-09 09:02:34 +01:00
jschoubben 568140f667 A page reads the bucket bound once and stops at its time budget, one value at least; an unknown verb is told by its code (issue 1966)
Claude-Session: https://claude.ai/code/session_01NcbgfFSnn24M3GcqttoU7i
2026-11-09 09:00:20 +01:00
jschoubben 1a9190774d The runtime answers a bulk read of kept state: the values after a key in one request (issue 1966)
Claude-Session: https://claude.ai/code/session_01NcbgfFSnn24M3GcqttoU7i
2026-11-09 08:51:19 +01:00
mesh-tools 27710ccabd Merge pull request 'The runtime says a bundle's state or log operation that failed or timed out, with its time (issue 1966, recovery)' (#63) from fix/1966-hand-acts-answers into main 2026-11-09 07:03:42 +00:00
jschoubben 634c77f90f The runtime says no lost compare-and-set as a failed operation, and its test waits on a channel, never a sleep (review round 1)
mesh/delivery merged: source.main moved to novox/mesh-tools@27710ccabd53
mesh/check checking 634c77f90f98 on 27710ccabd53
Claude-Session: https://claude.ai/code/session_01NcbgfFSnn24M3GcqttoU7i
2026-11-09 02:21:55 +01:00
jschoubben 1fc006b7dd The runtime says a state or log operation of a bundle that failed or timed out, with its time (issue 1966)
Claude-Session: https://claude.ai/code/session_01NcbgfFSnn24M3GcqttoU7i
2026-11-09 02:17:35 +01:00
mesh-tools f4b4fb908f Merge pull request 'The console passes arguments to a seat verb whose definition it does not hold (issue 1966, recovery)' (#62) from fix/1966-seat-reads-bootstrap into main 2026-11-08 03:45:19 +00:00
jschoubben 7572627aff The console passes a seat verb's arguments on when it holds no definition of the seat (issue 1966)
mesh/delivery merged: source.main moved to novox/mesh-tools@f4b4fb908f37
mesh/delivery-group group fix/1966-seat-reads-bootstrap merged: every member is merged
mesh/check failed (2): mesh-delivery-checker: no published of the tagged version of go-sdk of mesh-delivery…; and 1 more | 7572627affde on f4b4fb908f37
A seat verb whose holder announced an empty schema was judged as taking
nothing: shanks' tool runner refused "mesh-module-assigner.propose takes no
argument changes, why — it takes nothing". The console now judges such a
call by the verb's input in the seat's definition this runner holds; where
it holds none (it waits for the seat list, holding only the bootstrapped
definitions), the arguments go to the holder, which judges its own input,
and mesh_describe says the definition is not held instead of showing an
empty schema.

Claude-Session: https://claude.ai/code/session_01NcbgfFfQ4Z9UE5jK32PmE5
2026-11-08 02:45:30 +01:00
mesh-tools d184862b1a Merge pull request 'Registry milestone: mesh-tools (issue 1966)' (#61) from feat/registry-milestone into main 2026-11-07 14:19:59 +00:00
16 changed files with 629 additions and 29 deletions
+40
View File
@@ -195,6 +195,8 @@ type Conn struct {
calls callers
// waits are the waits in flight by subject, each told when the bus refuses its subscription (wait.go).
waits map[string]map[chan string]bool
// inboxSaid is when a refused answer publish was last said, by subject (answerRefused).
inboxSaid map[string]time.Time
}
// answered is one subject the runtime answers on: what to subscribe again with, and how often it was
@@ -232,6 +234,9 @@ func (c *Conn) refused(err error) {
if c.publishRefused(err) {
return
}
if c.answerRefused(err) {
return
}
if subject := subjectRefused(err); subject != "" && c.waitRefused(subject) {
return
}
@@ -1215,3 +1220,38 @@ func keyOf(subject string) string {
}
return event
}
// answerRefused says a refused publish of an answer (to a caller's inbox: a permission, or the single-use
// allowance of a reply expired) once per subject per minute, never silently (issue 1966: a caller waited out its
// time for an answer the bus had refused). It reports whether the refusal was one.
func (c *Conn) answerRefused(err error) bool {
m := refusedPublish.FindStringSubmatch(err.Error())
if len(m) < 2 || !strings.HasPrefix(strings.Trim(m[1], `"`), "_INBOX.") {
return false
}
// Keyed without the reply's last token (a new one per request), so a caller's burst is one line.
subject := strings.Trim(m[1], `"`)
if dot := strings.LastIndex(subject, "."); dot > len("_INBOX.") {
subject = subject[:dot]
}
c.mu.Lock()
if c.inboxSaid == nil {
c.inboxSaid = map[string]time.Time{}
}
now := time.Now()
for k, at := range c.inboxSaid {
if now.Sub(at) >= time.Minute {
delete(c.inboxSaid, k)
}
}
_, seen := c.inboxSaid[subject]
say := !seen
if say {
c.inboxSaid[subject] = now
}
c.mu.Unlock()
if say && c.Logf != nil {
c.Logf("[mesh-tools] the bus refused this account an answer to %s (%v); the caller gets none", subject, err)
}
return true
}
+30
View File
@@ -84,3 +84,33 @@ func TestARefusedSubscriptionIsAskedForAgain(t *testing.T) {
t.Error("a stopped subject is still tracked")
}
}
// Issue 1966: a refused publish of an answer (to a caller's inbox) is said, once per subject per minute, never dropped
// in silence while the caller waits out its time.
func TestARefusedAnswerIsSaidOncePerMinute(t *testing.T) {
c := &Conn{}
var said []string
c.Logf = func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) }
refuse := func(subject string) bool {
return c.answerRefused(fmt.Errorf("%w: Permissions Violation for Publish to %q", nats.ErrPermissionViolation, subject))
}
// A reply subject ends in a token new to every request: a burst under one prefix is one line.
if !refuse("_INBOX.user.abc.t1") || !refuse("_INBOX.user.abc.t2") || !refuse("_INBOX.user.def.t1") {
t.Fatal("a refused answer was not taken for one")
}
if len(said) != 2 {
t.Fatalf("want one line per caller, got %v", said)
}
c.inboxSaid["_INBOX.user.abc"] = time.Now().Add(-2 * time.Minute)
c.inboxSaid["_INBOX.user.old"] = time.Now().Add(-2 * time.Minute)
refuse("_INBOX.user.abc.t3")
if len(said) != 3 || !strings.Contains(said[2], "_INBOX.user.abc") {
t.Fatalf("a minute later it is said again, got %v", said)
}
if _, kept := c.inboxSaid["_INBOX.user.old"]; kept || len(c.inboxSaid) != 2 {
t.Fatalf("entries older than a minute are dropped on write, kept %v", c.inboxSaid)
}
if refuse("mesh.mod.x.tool.y") {
t.Fatal("a refused publish that is no answer was taken for one")
}
}
+19 -1
View File
@@ -147,11 +147,27 @@ const (
SettleNak = "nak" // handed back, to be delivered again at once
SettleTerm = "term" // dropped
SettleProgress = "progress" // still being worked: its acknowledgement wait starts again
// SettleNakAfter hands the message back to be delivered again after a delay: the bus's own redelivery, so no part
// keeps a timer for a step given again (novox/hq ADR 0664 §1; issue 1748). SeatSettleAfter gives it.
SettleNakAfter = "nak-after"
)
// SeatSettle gives the message module pulled under id its fate. A message pulled for another module, or settled
// already, is refused.
func (c *Conn) SeatSettle(module, id, fate string) error {
return c.settle(module, id, fate, 0)
}
// SeatSettleAfter hands the message module pulled under id back to be delivered again after delay (SettleNakAfter),
// counting one more delivery. A delay of 0 or below is refused and settles nothing.
func (c *Conn) SeatSettleAfter(module, id string, delay time.Duration) error {
if delay <= 0 {
return fmt.Errorf("a message given again after a delay needs a delay above 0, not %s", delay)
}
return c.settle(module, id, SettleNakAfter, delay)
}
func (c *Conn) settle(module, id, fate string, delay time.Duration) error {
seatPulls.mu.Lock()
p, ok := seatPulls.held[id]
if ok && p.module != module {
@@ -173,9 +189,11 @@ func (c *Conn) SeatSettle(module, id, fate string) error {
return p.msg.Term()
case SettleProgress:
return p.msg.InProgress()
case SettleNakAfter:
return p.msg.NakWithDelay(delay)
}
seatPulls.mu.Lock()
seatPulls.held[id] = p // an unknown fate settles nothing
seatPulls.mu.Unlock()
return fmt.Errorf("a pulled message's fate is ack, nak, 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)
}
+15
View File
@@ -58,6 +58,21 @@ func TestAHolderPullsOneMessageWhenItHasRoom(t *testing.T) {
if err != nil || again == nil || string(again.Body) != `{"id":"a2"}` || again.Delivered != 2 {
t.Fatalf("the message handed back = %+v, %v", again, err)
}
// Issue 1748: a message settled with a delay is not given again at once, is after it, one delivery higher; a delay
// of 0 settles nothing.
if err := conn.SeatSettleAfter("messenger", again.ID, 0); err == nil {
t.Error("a delay of 0 was accepted")
}
if err := conn.SeatSettleAfter("messenger", again.ID, 300*time.Millisecond); err != nil {
t.Fatal(err)
}
if early, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0); err != nil || early != nil {
t.Fatalf("a message given again after a delay came at once: %+v, %v", early, err)
}
late, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 2*time.Second)
if err != nil || late == nil || late.Delivered != 3 {
t.Fatalf("the message given again after its delay = %+v, %v", late, err)
}
if _, err := conn.SeatPull("telegram", "SEAT_OPERATOR_CHANNEL_worker", 0); err == nil || !strings.Contains(err.Error(), "membership lists") {
t.Errorf("a channel pulled the router's work: %v", err)
}
+131 -9
View File
@@ -11,6 +11,8 @@ import (
"sync"
"time"
"git.novox.be/novox/mesh-sdk/go/membership"
"git.novox.be/novox/mesh-sdk/go/pernode"
"github.com/nats-io/nats.go/jetstream"
)
@@ -70,21 +72,22 @@ func (c *Conn) issuedState(module, name string) (StateIssued, error) {
return StateIssued{}, fmt.Errorf("%s has no membership issued on %s yet, so no state of it is reachable "+
"until the mesh issues one (novox/hq ADR 0201)", module, c.node)
}
var names []string
// What a membership issues by a local name is mesh-sdk's one rule (membership.StateIssued, issue 1966): the old
// `state` list, then a key-value entry the module asks for in `requires` (ADR 0595 §1), by its local name.
issuing := membership.Membership{Bindings: m.Bindings}
for _, s := range m.State {
if s.Name == name {
return s, nil
}
names = append(names, s.Name)
issuing.State = append(issuing.State, membership.StateIssued{Name: s.Name, Bucket: s.Bucket, Writes: s.Writes, PerNode: s.PerNode})
}
if s, ok := issuing.StateIssued(name); ok {
return StateIssued{Name: s.Name, Bucket: s.Bucket, Writes: s.Writes, PerNode: s.PerNode}, nil
}
sort.Strings(names)
issued := "none"
if len(names) > 0 {
if names := issuing.StateNames(); len(names) > 0 {
issued = strings.Join(names, ", ")
}
return StateIssued{}, fmt.Errorf("%s keeps and reads no state called %q: it declares what it keeps under "+
"`state` and what it reads under `reads` as <module>.<name>, and was issued: %s (novox/hq ADR 0201)",
module, name, issued)
"`state` or as a key-value entry in `requires`, and what it reads under `reads` as <module>.<name>, and was "+
"issued: %s (novox/hq ADR 0201, ADR 0595 §1)", module, name, issued)
}
func (c *Conn) bucket(ctx context.Context, s StateIssued) (jetstream.KeyValue, error) {
@@ -139,6 +142,125 @@ 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
}
// StatePage is the current values after a key, in key order, and the key to ask after for the rest.
type StatePage struct {
Entries []StateEntry `json:"entries"`
Next string `json:"next,omitempty"`
}
// 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
// PageClock is the time a page's budget counts by, replaced by a test.
var PageClock = time.Now
// StatePage reads the values in key order after `after` in one pass, as many as fit maxBytes (each key and value),
// stopping when budget is spent, at least one value, so a bundle asks one request for many values, where StateGet
// is one request each. Access is checked once and the bucket bound once. It is a read like StateGet: served to the
// owner and to every reader, and writes nothing. Next is the last key given when more follow.
func (c *Conn) StatePage(module, name, after string, maxBytes int, budget time.Duration) (StatePage, error) {
s, err := c.issuedState(module, name)
if err != nil {
return StatePage{}, err
}
if budget <= 0 {
budget = StatePageBudget
}
// The bind and the listing have a StateTimeout of their own, and each get another: the page's time budget is what
// 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().
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel()
each := func() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), StateTimeout)
}
var keys []string
var get func(key string) (*StateEntry, error)
if s.PerNode {
fam := c.family(s)
if keys, err = fam.Keys(ctx); err != nil {
return StatePage{}, err
}
buckets := map[string]jetstream.KeyValue{} // each node's bucket bound once
get = func(key string) (*StateEntry, error) {
node, err := pernode.NodeOf(key)
if err != nil {
return nil, err
}
kv, bound := buckets[node]
if !bound {
octx, ocancel := each() // the open is a bus request in the loop: its own deadline, never ctx's
kv, err = fam.Open(octx, node)
ocancel()
if err != nil {
return nil, err
}
buckets[node] = kv
}
if kv == nil {
return nil, nil
}
gctx, gcancel := each()
defer gcancel()
e, err := kv.Get(gctx, key)
if errors.Is(err, jetstream.ErrKeyNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
return &StateEntry{Key: e.Key(), Value: valueOf(e.Value()), Revision: e.Revision(), At: e.Created().UTC()}, nil
}
} else {
kv, err := c.bucket(ctx, s)
if err != nil {
return StatePage{}, err
}
if keys, err = keysOf(ctx, kv); err != nil {
return StatePage{}, err
}
get = func(key string) (*StateEntry, error) {
gctx, gcancel := each()
defer gcancel()
e, err := kv.Get(gctx, key)
if errors.Is(err, jetstream.ErrKeyNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
return &StateEntry{Key: e.Key(), Value: valueOf(e.Value()), Revision: e.Revision(), At: e.Created().UTC()}, 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).
type StateKept struct {
Key string `json:"key"`
+42
View File
@@ -866,6 +866,11 @@ func argumentsAsSent(t target, given map[string]any) (map[string]any, error) {
if !t.Seat {
return args, nil
}
t, held := seatDefinitionHeld(t)
if !held {
// Nothing here says what the verb takes: its holder judges the arguments (issue 1966).
return args, nil
}
declared := map[string]bool{}
var names []string
if p, ok := schemaAsPassed(t)["properties"].(map[string]any); ok {
@@ -893,6 +898,36 @@ func argumentsAsSent(t target, given map[string]any) (map[string]any, error) {
return args, nil
}
// seatDefinitionHeld is a seat verb's target with the input the console judges a call by, and whether anything here
// says what the verb takes (issue 1966): the schema its holder announced when it declares an argument, else the verb's
// input in the seat's definition this runner holds. Neither holds while the runner waits for the seat list holding
// only the bootstrapped definitions and the holder announced an empty schema: then a call's arguments are passed on to
// the holder, which judges its own input, and mesh_describe says the definition is not held.
func seatDefinitionHeld(t target) (target, bool) {
if p, ok := asSchema(t.Tool.Input)["properties"].(map[string]any); ok && len(p) > 0 {
return t, true
}
seat, ok := catalogue.SeatNamed(t.Tool.Module)
if !ok {
return t, false
}
for _, v := range seat.Serves {
if v.Name == t.Tool.Name && v.Input != nil {
if raw, err := json.Marshal(v.Input); err == nil {
t.Tool.Input = raw
}
}
}
return t, true
}
// notHeld is what mesh_describe says of a seat verb whose definition this runner does not hold.
func notHeld(seat string) string {
return "the seat list this tool runner holds has no definition of " + seat + " yet (it holds the bootstrapped ones " +
"until it reads the list): what the verb takes is not known here, so the arguments of a call are passed to " +
"its holder, which judges them"
}
// schemaWithoutNode is a tool's schema with `node` taken out, for an address that names the machine.
func schemaWithoutNode(raw json.RawMessage) map[string]any {
schema := asSchema(raw)
@@ -1092,7 +1127,14 @@ func (s *Surface) discover(ctx context.Context, name string, args map[string]any
if description == "" {
description = t.Name
}
held := true
if t.Seat {
t, held = seatDefinitionHeld(t)
}
described := map[string]any{"address": t.Address, "description": description, "arguments": schemaAsPassed(t)}
if !held {
described["arguments"] = notHeld(t.Tool.Module)
}
key := t.Tool.Module + "." + t.Tool.Name
if t.Seat {
key = "seat:" + key
@@ -44,6 +44,27 @@ func TestAMeshSeatsNodeIsItsOwnArgument(t *testing.T) {
t.Fatalf("another machine in the arguments than in the address was dropped: %v", err)
}
// Issue 1966: a seat verb its holder announced with an empty schema is judged by the definition this runner holds;
// where it holds none (it waits for the seat list, holding the bootstrapped ones), the arguments go to the holder,
// which judges them, and mesh_describe says the definition is not held.
empty := json.RawMessage(`{"type":"object","properties":{}}`)
propose := target{Address: "mesh-module-assigner.propose", Seat: true,
Tool: Tool{Module: "mesh-module-assigner", Name: "propose", Seat: true, Scope: "mesh", Input: empty}}
if sent, err := argumentsAsSent(propose, map[string]any{"changes": []any{}, "why": "w"}); err != nil || sent["why"] != "w" {
t.Fatalf("a held definition's arguments were refused: %v %v", sent, err)
}
if _, err := argumentsAsSent(propose, map[string]any{"chnages": 1}); err == nil || !strings.Contains(err.Error(), "chnages") {
t.Fatalf("an argument the held definition does not declare was sent: %v", err)
}
unheld := target{Address: "mesh-not-yet-read.act", Seat: true,
Tool: Tool{Module: "mesh-not-yet-read", Name: "act", Seat: true, Scope: "mesh", Input: empty}}
if sent, err := argumentsAsSent(unheld, map[string]any{"changes": 1}); err != nil || sent["changes"] != 1 {
t.Fatalf("a seat whose definition is not held refused its arguments: %v %v", sent, err)
}
if _, held := seatDefinitionHeld(unheld); held || !strings.Contains(notHeld("mesh-not-yet-read"), "no definition of mesh-not-yet-read") {
t.Fatal("a definition not held is said to be held")
}
// A module's tool is its own: what it takes beyond node is the module's to judge.
beta := target{Address: "desk/beta.three", Node: "desk", Tool: Tool{Module: "beta", Name: "three"}}
if sent, err := argumentsAsSent(beta, map[string]any{"node": "desk", "verbose": true}); err != nil || sent["verbose"] != true || sent["node"] != nil {
+60 -6
View File
@@ -206,11 +206,33 @@ type child struct {
// restart decided — which Stop waits for (novox/hq issue 476).
handled chan struct{}
why error
// endedFor is why the runner itself ended the bundle (a line over the cap); its calls fail with it.
endedFor string
// watches are the state watches this child asked for, stopped when it exits (ADR 0201): a child
// that starts again watches again, as its code runs again.
watches []func()
}
// maxLine is the longest line the runner reads from a bundle; a variable so a test need not write megabytes.
var maxLine = 16 << 20
// errNoAnswer is a call the bundle did not answer within its bound.
var errNoAnswer = errors.New("the bundle did not answer in time")
// readCapped reads one line of at most max bytes. tooLong says it was longer; the rest is not read.
func readCapped(r *bufio.Reader, max int) (line []byte, tooLong bool, err error) {
for {
part, isPrefix, e := r.ReadLine()
line = append(line, part...)
if len(line) > max {
return nil, true, nil
}
if e != nil || !isPrefix {
return line, false, e
}
}
}
func (c *child) write(m any) error {
b, err := wire.Marshal(m)
if err != nil {
@@ -279,6 +301,7 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
// The restart pauses are read once, here: the exit handling runs on its own goroutine and must not
// read the package's settings while a caller (a test) changes them (novox/hq issue 476).
pauseFirst, pauseMost, settle := RestartFirst, RestartMost, RestartSettle
lineCap := maxLine
pause := pauseFirst
start := func() (*child, error) {
@@ -324,10 +347,25 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
}()
go func() {
defer close(c.handled)
scan := bufio.NewScanner(stdout)
scan.Buffer(make([]byte, 64*1024), 16<<20)
for scan.Scan() {
line := strings.TrimSpace(scan.Text())
rd := bufio.NewReaderSize(stdout, 64*1024)
for {
raw, tooLong, rerr := readCapped(rd, lineCap)
if tooLong {
// Never left frozen (issue 1966): a reader that stops while the bundle lives leaves the bundle's
// next write blocked for good. Said, and the bundle ended; the exit path below fails what waits
// on it and starts it again.
reason := fmt.Sprintf("%s's bundle wrote a line over %d bytes (a tool's answer the bus cannot carry)", module, lineCap)
logf("[mesh-tools] %s; ending the bundle", reason)
c.mu.Lock()
c.endedFor = reason
c.mu.Unlock()
_ = cmd.Process.Kill()
break
}
if rerr != nil && len(raw) == 0 {
break
}
line := strings.TrimSpace(string(raw))
if line == "" {
continue
}
@@ -345,6 +383,7 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
go func(m message) {
var result any = map[string]any{}
var err error
asked := time.Now()
switch m.Method {
case "mesh/publish":
err = mesh.Publish(m.Params)
@@ -372,7 +411,7 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
result = answered
}
case "mesh/state.get", "mesh/state.put", "mesh/state.delete", "mesh/state.keys",
"mesh/state.create", "mesh/state.update", "mesh/state.history", "mesh/state.info":
"mesh/state.create", "mesh/state.update", "mesh/state.history", "mesh/state.info", "mesh/state.page":
var answered json.RawMessage
if answered, err = mesh.State(strings.TrimPrefix(m.Method, "mesh/state."), m.Params); err == nil {
result = answered
@@ -479,6 +518,14 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
}
return
}
// A state or log operation the bus refused or let time out reaches a caller as a call that
// does not answer: say it here, with how long it took, so the next hang is readable.
// A lost compare-and-set is the normal answer of two writers to one key, retried by its caller: not said.
if err != nil && errorCode(err) != CodeChanged && (strings.HasPrefix(m.Method, "mesh/state.") ||
strings.HasPrefix(m.Method, "mesh/log.") || busStateCalls[m.Method]) {
logf("[mesh-tools] %s's bundle asked %s and it failed after %s: %v", module, m.Method,
time.Since(asked).Round(time.Millisecond), err)
}
if len(m.ID) == 0 {
return
}
@@ -520,6 +567,9 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
}
saidMu.Unlock()
c.mu.Lock()
if c.endedFor != "" {
why = c.endedFor + "; the bundle was ended (" + code + ")"
}
c.why = errors.New(why)
watches := c.watches
c.watches = nil
@@ -688,6 +738,10 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
defer end()
res, err := asking("tools/call", callParams(full, caller, call, args), CallTimeout)
if err != nil {
if errors.Is(err, errNoAnswer) {
// Its caller is gone by now and nobody else would hear of it (issue 1966).
logf("[mesh-tools] %s.%s called by %q: %v", module, full, caller, err)
}
return nil, err
}
var called struct {
@@ -785,7 +839,7 @@ func (c *child) ask(module, method string, params any, timeout time.Duration) (j
c.mu.Lock()
delete(c.pending, id)
c.mu.Unlock()
return nil, fmt.Errorf("%s's bundle did not answer %s in %ds", module, method, int(timeout/time.Second))
return nil, fmt.Errorf("%s's bundle did not answer %s in %ds: %w", module, method, int(timeout/time.Second), errNoAnswer)
}
}
@@ -0,0 +1,152 @@
package launch
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// changedError is a lost compare-and-set as the bus answers it: told by its code (novox/hq ADR 0259).
type changedError struct{}
func (changedError) Error() string { return "the key changed since revision 3" }
func (changedError) ErrorCode() int { return CodeChanged }
// refusingState answers the state "lost" with a lost compare-and-set and every other state with a time-out.
type refusingState struct{ subscribing }
func (*refusingState) State(_ string, params json.RawMessage) (json.RawMessage, error) {
if strings.Contains(string(params), `"state":"lost"`) {
return nil, changedError{}
}
return nil, errors.New("the bus did not answer in 10s")
}
// A bundle that asks the runtime for the state "lost" once it is started, and for the state "copied" once that is
// answered, so the first answer's handling has ended before the second is asked.
const askingBundle = `#!/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":[]}}\n' "$id"
printf '{"jsonrpc":"2.0","id":"q1","method":"mesh/state.update","params":{"state":"lost","key":"k"}}\n' ;;
*'"id":"q1"'*) printf '{"jsonrpc":"2.0","id":"q2","method":"mesh/state.get","params":{"state":"copied","key":"k"}}\n' ;;
esac
done
`
// A state operation the bus refuses or lets time out is said in the runtime's log with its method, its bundle and its
// time (issue 1966: a hand-act seat whose calls hung said nothing); a lost compare-and-set, asked first, is not.
func TestAFailedStateOperationIsSaidInTheRuntimesLog(t *testing.T) {
dir := t.TempDir()
entry := filepath.Join(dir, "bundle")
if err := os.WriteFile(entry, []byte(askingBundle), 0o755); err != nil {
t.Fatal(err)
}
said := make(chan string, 16)
logf := func(f string, a ...any) { said <- fmt.Sprintf(f, a...) }
l, err := Start("asker", entry, os.Environ(), &refusingState{}, logf)
if err != nil {
t.Fatal(err)
}
t.Cleanup(l.Stop)
var heard []string
timeout := time.After(5 * time.Second)
for {
select {
case line := <-said:
heard = append(heard, line)
if strings.Contains(line, "mesh/state.update") {
t.Fatalf("a lost compare-and-set was said as a failure: %q", line)
}
if strings.Contains(line, "asker's bundle asked mesh/state.get and it failed after") && strings.Contains(line, "did not answer in 10s") {
return
}
case <-timeout:
t.Fatalf("the failed state operation was not said; the log: %v", heard)
}
}
}
// A bundle that lists one tool, "t", and answers a call to it as its MODE says: "long" with a line over the runner's cap,
// "silent" with nothing at all.
const callingBundle = `#!/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"'*) echo started >&2; printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;;
*'"method":"tools/list"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"tools":[{"name":"t","description":"d"}]}}\n' "$id" ;;
*'"method":"tools/call"'*) [ "$MODE" = long ] && printf '%4096s\n' x ;;
esac
done
`
// Issue 1966: a bundle's line over the runner's cap, and a call the bundle never answers, are said in the runtime's log;
// the over-long line ends the bundle and fails the call at once, never leaving the runner reading nothing while the
// bundle's next write blocks.
func TestAnOverlongLineAndAnUnansweredCallAreSaid(t *testing.T) {
oldMax, oldCall, oldFirst := maxLine, CallTimeout, RestartFirst
maxLine, RestartFirst = 1024, 10*time.Millisecond
t.Cleanup(func() { maxLine, CallTimeout, RestartFirst = oldMax, oldCall, oldFirst })
for _, row := range []struct {
mode string
timeout time.Duration
}{
// The call's own bound is long: only the runner ending the bundle fails it within a second.
{"long", 10 * time.Second},
{"silent", 300 * time.Millisecond},
} {
t.Run(row.mode, func(t *testing.T) {
CallTimeout = row.timeout
dir := t.TempDir()
entry := filepath.Join(dir, "bundle")
if err := os.WriteFile(entry, []byte(callingBundle), 0o755); err != nil {
t.Fatal(err)
}
said := make(chan string, 32)
logf := func(f string, a ...any) { said <- fmt.Sprintf(f, a...) }
l, err := Start("caller", entry, append(os.Environ(), "MODE="+row.mode), &refusingState{}, logf)
if err != nil {
t.Fatal(err)
}
t.Cleanup(l.Stop)
begun := time.Now()
_, err = l.Registrations[0].Tools[0].Run("caller-1", nil)
if err == nil {
t.Fatal("the call was answered")
}
var heard []string
timeout := time.After(5 * time.Second)
want := "caller.t called by \"caller-1\""
if row.mode == "long" {
want = "ending the bundle"
if took := time.Since(begun); took > time.Second {
t.Fatalf("the call hung for %s", took)
}
if !strings.Contains(err.Error(), "over 1024 bytes") || strings.Contains(err.Error(), "did not answer") {
t.Fatalf("the call failed with %q, not the cap's reason", err)
}
}
// For "long" the bundle is also started again: it says "started" on each start, so twice in all.
started, found := 0, false
for !found || (row.mode == "long" && started < 2) {
select {
case line := <-said:
heard = append(heard, line)
found = found || strings.Contains(line, want)
if line == "[caller] started" {
started++
}
case <-timeout:
t.Fatalf("not said, or the bundle not started again; the log: %v", heard)
}
}
})
}
}
+1 -1
View File
@@ -139,7 +139,7 @@ func TestTheRunnerStatesTheCapabilitiesOfItsCallsInItsPing(t *testing.T) {
t.Fatalf("ping of the instance: %v", err)
}
var ping micro.Ping
if err := json.Unmarshal(msg.Data, &ping); err != nil || ping.Metadata[announce.Capabilities] != "bus-state-calls,ledger-calls" {
if err := json.Unmarshal(msg.Data, &ping); err != nil || ping.Metadata[announce.Capabilities] != "bus-state-calls,ledger-calls,seat-settle-delay" {
t.Errorf("the runner states %q (%v), want its bus-state and ledger calls", ping.Metadata[announce.Capabilities], err)
}
}
+4 -2
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"sort"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/buscalls"
)
@@ -25,9 +26,10 @@ var callFamilies = map[string][]string{
buscalls.LedgerRebuild, buscalls.LedgerReindex, buscalls.LedgerSnapshot, buscalls.LedgerLag},
}
// CallCapabilities is every capability of the calls this runner answers, sorted.
// CallCapabilities is every capability of the calls this runner answers, sorted. The delayed settle of a pulled seat
// message names a fate, not a method, so it stands beside the method families (novox/hq ADR 0664 §5).
func CallCapabilities() []string {
out := make([]string, 0, len(callFamilies))
out := []string{stdio.CapSeatSettleDelay}
for c := range callFamilies {
out = append(out, c)
}
+1 -1
View File
@@ -204,7 +204,7 @@ func TestABundleToolNamedAsALedgerRepairIsRefused(t *testing.T) {
// no other name; none answers "the runtime answers no ...".
func TestEveryCallOfAStatedCapabilityIsAnswered(t *testing.T) {
m, _, _ := aLedger(t)
if got := strings.Join(CallCapabilities(), ","); got != "bus-state-calls,ledger-calls" {
if got := strings.Join(CallCapabilities(), ","); got != "bus-state-calls,ledger-calls,seat-settle-delay" {
t.Fatalf("the runner states %s", got)
}
for capability, methods := range callFamilies {
+33 -5
View File
@@ -1021,9 +1021,19 @@ 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
// value, put renews it whole. Zero is none.
TTLSeconds int `json:"ttl_seconds"`
// After and MaxBytes are a `page`'s start key and its size in keys and values (zero is a megabyte).
After string `json:"after"`
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 int `json:"budget_ms"`
}
// State answers a bundle's `get`, `put`, `delete`, `keys`, `create`, `update`, `history` and `info` on its
// unknownVerb is an answer with the JSON-RPC code of a method not found, which a bundle tells by its code.
type unknownVerb struct{ error }
func (unknownVerb) ErrorCode() int { return -32601 }
// State answers a bundle's `get`, `put`, `delete`, `keys`, `page`, `create`, `update`, `history` and `info` on its
// module's state (ADR 0201, ADR 0259, ADR 0307); `create` and `put` take `ttl_seconds`, a key's own time to live,
// whose end every watch hears as an `expire` (issue 1952). The runtime refuses, with the reason, a state the module was not issued and a write to one it only reads.
func (b *moduleBus) State(verb string, params json.RawMessage) (json.RawMessage, error) {
@@ -1043,6 +1053,16 @@ func (b *moduleBus) State(verb string, params json.RawMessage) (json.RawMessage,
return json.RawMessage("null"), nil
}
answer = entry
case "page":
// The values after a key in key order, one request for many (a first view's page of a slow state).
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 {
return nil, err
}
answer = page
case "history":
// Every value the bucket still keeps for the key, oldest first (novox/hq ADR 0307).
kept, err := conn.StateHistory(b.module, asked.State, asked.Key)
@@ -1105,7 +1125,7 @@ func (b *moduleBus) State(verb string, params json.RawMessage) (json.RawMessage,
}
answer = map[string]any{"revision": revision}
default:
return nil, fmt.Errorf("the runtime answers no mesh/state.%s", verb)
return nil, unknownVerb{fmt.Errorf("the runtime answers no mesh/state.%s", verb)}
}
return json.Marshal(answer)
}
@@ -1236,8 +1256,10 @@ type seatAsked struct {
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 int `json:"wait_ms"`
Fate string `json:"fate"`
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 int64 `json:"delay_ms"`
Fate string `json:"fate"`
}
// Seat answers a bundle's seat traffic, each as the module and only as far as its membership lists:
@@ -1280,7 +1302,13 @@ func (b *moduleBus) Seat(verb string, params json.RawMessage, handOn func(string
}
return json.Marshal(p)
case "settle":
if err := conn.SeatSettle(b.module, asked.ID, asked.Fate); err != nil {
settle := func() error { return conn.SeatSettle(b.module, asked.ID, asked.Fate) }
if asked.Fate == bus.SettleNakAfter {
settle = func() error {
return conn.SeatSettleAfter(b.module, asked.ID, time.Duration(asked.DelayMS)*time.Millisecond)
}
}
if err := settle(); err != nil {
return nil, err
}
return json.RawMessage(`{}`), nil
@@ -202,6 +202,17 @@ func TestABundlePullsAndSettlesThroughItsModulesBus(t *testing.T) {
if _, err := elsewhere.Seat("settle", json.RawMessage(`{"id":"`+p.ID+`","fate":"ack"}`), nil); err == nil {
t.Fatal("another module settled the pulled ask")
}
// Issue 1748: a settle with the fate nak-after and no delay settles nothing; with a delay the ask comes again.
if _, err := building.Seat("settle", json.RawMessage(`{"id":"`+p.ID+`","fate":"nak-after"}`), nil); err == nil {
t.Fatal("a delayed nak without a delay was accepted")
}
if _, err := building.Seat("settle", json.RawMessage(`{"id":"`+p.ID+`","fate":"nak-after","delay_ms":100}`), nil); err != nil {
t.Fatal(err)
}
raw, err = building.Seat("pull", json.RawMessage(`{"worker":"SEAT_NODE_BUILD_GO_DELIVERY_worker","wait_ms":2000}`), nil)
if err != nil || json.Unmarshal(raw, &p) != nil || p.Delivered != 2 {
t.Fatalf("the ask given again after its delay = %s, %v", raw, err)
}
if _, err := building.Seat("settle", json.RawMessage(`{"id":"`+p.ID+`","fate":"ack"}`), nil); err != nil {
t.Fatal(err)
}
@@ -132,9 +132,10 @@ func TestAKeysHistoryIsEveryValueKeptOldestFirst(t *testing.T) {
}
}
// A module the bucket was not issued to is refused its history with the reason, as it is a get.
func TestAKeysHistoryIsRefusedToAModuleNotIssuedTheState(t *testing.T) {
owner, _, other := historyBuses(t)
// A module the bucket was not issued to is refused its history, and a page, with the reason, as it is a get; the
// owner and a reader are served a page.
func TestAKeysHistoryAndAPageOfAStateAreServedToOwnerAndReaderAndRefusedToAModuleNotIssuedIt(t *testing.T) {
owner, reader, other := historyBuses(t)
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": "1", "value": 1}); err != nil {
t.Fatal(err)
}
@@ -149,4 +150,46 @@ func TestAKeysHistoryIsRefusedToAModuleNotIssuedTheState(t *testing.T) {
!strings.Contains(err.Error(), "not a key") {
t.Errorf("history of a key the bus cannot hold: %v", err)
}
// A page is the values in key order after a key, in one request, to the owner and to a reader, never to a
// module not issued the state; a page too small for two values still gives one and says where it goes on.
for k, v := range map[string]string{"2": `"bb"`, "3": `"cc"`} {
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": k, "value": json.RawMessage(v)}); err != nil {
t.Fatal(err)
}
}
type page struct {
Entries []kept `json:"entries"`
Next string `json:"next"`
}
for _, c := range []struct {
who, state, after string
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
if err != nil || json.Unmarshal(raw, &p) != nil || p.Next != c.next || len(p.Entries) != len(c.keys) {
t.Fatalf("page %+v = %s, %v", c, raw, err)
}
for i, k := range c.keys {
if p.Entries[i].Key != k {
t.Errorf("page %+v: entry %d is %s, want %s", c, i, p.Entries[i].Key, k)
}
}
}
// A page stops when its time budget is spent, after one value at least, and says where it goes on.
step := time.Time{}
bus.PageClock = func() time.Time { step = step.Add(11 * time.Second); return step }
defer func() { bus.PageClock = time.Now }()
raw, err := ask(owner, "page", map[string]any{"state": "issues", "max_bytes": 1 << 20, "budget_ms": 10000})
var cut page
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)
}
if _, err := ask(other, "page", map[string]any{"state": "issues.issues"}); err == nil {
t.Errorf("a page given to a module not issued the state")
}
}
+23 -1
View File
@@ -6,6 +6,8 @@ import (
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/membership"
"github.com/novox/mesh-tools/node-tools/internal/bus"
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
)
@@ -35,16 +37,24 @@ func TestABundleKeepsAndWatchesItsStateThroughTheRuntime(t *testing.T) {
peeker.State = []bus.StateIssued{{Name: "keeper.servers", Bucket: "keeper_servers"}}
mesh.Issue(t, keeper)
mesh.Issue(t, peeker)
// Issue 1966 (F1): a module that asks for its state as a key-value entry of `requires` (ADR 0595 §1) is issued it by
// its binding alone, under its local name, as its own; no other module is.
mesh.Bucket(t, "binder_holds")
binder := mt.MembershipOf("binder", "anchor", false, nil)
binder.Bindings = []membership.BusBinding{{Local: "holds", Storage: catalogue.StorageKeyValue, Template: catalogue.TemplateState, Bucket: "binder_holds"}}
mesh.Issue(t, binder)
nodeTools := connect(t, "node-tools", "anchor")
asker := connect(t, "console", "workstation")
dir := t.TempDir()
keeperLog, peekerLog := filepath.Join(dir, "keeper.log"), filepath.Join(dir, "peeker.log")
keeperLog, peekerLog, binderLog := filepath.Join(dir, "keeper.log"), filepath.Join(dir, "peeker.log"), filepath.Join(dir, "binder.log")
said := &lines{}
stop, err := Run(nodeTools, []Served{
{Module: "keeper", Entrypoints: []string{mt.Fixture("state-keeper.mjs")}},
{Module: "peeker", Entrypoints: []string{mt.Fixture("state-keeper.mjs")}},
{Module: "binder", Entrypoints: []string{mt.Fixture("state-keeper.mjs")}},
}, map[string]map[string]string{
"binder": {"STATE_NAME": "holds", "STATE_LOG": binderLog},
"keeper": {"STATE_NAME": "servers", "STATE_LOG": keeperLog},
"peeker": {"STATE_NAME": "keeper.servers", "STATE_LOG": peekerLog},
}, said.logf)
@@ -91,6 +101,16 @@ func TestABundleKeepsAndWatchesItsStateThroughTheRuntime(t *testing.T) {
}
same(t, got, `["all.one","anchor.two"]`)
// The bound module puts, gets and watches its key-value entry by its local name.
waitFor(t, binderLog, "current")
if _, err := call(t, asker, "binder.put@anchor", map[string]any{"state": "holds", "key": "h1", "value": 1}); err != nil {
t.Fatalf("a put on a bound key-value entry: %v", err)
}
waitFor(t, binderLog, "now put h1 1")
if got, err := call(t, asker, "binder.get@anchor", map[string]any{"state": "holds", "key": "h1"}); err != nil || !strings.Contains(got, `"value":1`) {
t.Fatalf("a get on a bound key-value entry answered %s, %v", got, err)
}
// Refused, with the reason, before anything is sent.
for _, c := range []struct {
key, why string
@@ -100,6 +120,8 @@ func TestABundleKeepsAndWatchesItsStateThroughTheRuntime(t *testing.T) {
map[string]any{"state": "keeper.servers", "key": "x", "value": 1}},
{"keeper.get@anchor", `keeper keeps and reads no state called "other"`,
map[string]any{"state": "other", "key": "x"}},
{"keeper.get@anchor", `keeper keeps and reads no state called "holds"`,
map[string]any{"state": "holds", "key": "h1"}},
{"keeper.put@anchor", `carries a field "accessToken", which names a credential`,
map[string]any{"state": "servers", "key": "x", "value": map[string]any{"headers": map[string]any{"accessToken": "s"}}}},
{"keeper.put@anchor", "is not a key the bus can hold",