Merge pull request 'Design 47 H2: the tool runner drains at stop, pages by cursor and reads a seat's waiting asks' (#88) from feat/47-H2 into main

This commit was merged in pull request #88.
This commit is contained in:
2026-11-22 04:56:14 +00:00
25 changed files with 1140 additions and 219 deletions
+21
View File
@@ -29,7 +29,9 @@ import (
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"
stdio "git.novox.be/novox/mesh-sdk/go"
"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"
runnerapproval "github.com/novox/mesh-tools/node-tools/internal/approval"
@@ -65,6 +67,15 @@ 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
// starts, beside the process's own (design 47 H §774, H-A-61).
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)
cred := credential(until)
conn := connectPatiently(cred, until)
@@ -155,6 +166,9 @@ func serve(ctx context.Context) error {
// First of all: the service manager signalled every bundle with this process, and none is started again
// (issue 1126).
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()
stopProviding()
stop()
@@ -165,6 +179,13 @@ func serve(ctx context.Context) error {
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
// 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,
+34 -2
View File
@@ -13,11 +13,43 @@ import (
"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): one test, two cases, so
// design 46 7-approval-mark §22's whole test of the gate adds no test to the module (design 47 G §419, §626).
// The runner's start waits for its credential and its bus within the start's bound (issue 1496), and reads its settings
// 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
// module (design 47 G §419, §626).
func TestTheRunnersStartWaitsForItsCredentialAndItsBus(t *testing.T) {
t.Run("the credential", awaitsCredential)
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
@@ -5,6 +5,8 @@ package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"strings"
@@ -65,7 +67,17 @@ func (c *catalogStandIn) handle(body json.RawMessage) (any, error) {
// for a verb that sends chunks (design 47 G A-490m).
func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *testing.T) {
mesh := mt.New(t)
mesh.Issue(t, mt.MembershipOf("ledger", "anchor", true, map[string][]string{"node-desk": {"who", "slow"}}))
ledger := 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()
credential, _ := json.Marshal(bus.Credential{URL: mt.URL(t), Module: runtimeModule, Node: "anchor"})
file := filepath.Join(dir, "broker")
@@ -75,6 +87,8 @@ func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *te
t.Setenv("MESH_BROKER_FILE", file)
t.Setenv("MESH_TOOL_MODULES", "ledger="+mt.Fixture("whole-bundle.py"))
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 {
c, err := bus.Connect(bus.Credential{URL: mt.URL(t), Module: module, Node: node, User: node + "." + module, Password: "unused"})
@@ -104,20 +118,31 @@ func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *te
}
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())
ended := make(chan error, 1)
go func() { ended <- serve(ctx) }()
t.Cleanup(func() {
stop()
select {
case err := <-ended:
if err != nil {
t.Errorf("serve ended with %v", err)
var stopped sync.Once
stopServe := func() {
stopped.Do(func() {
stop()
select {
case err := <-ended:
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)
asker := open("shop", "workstation")
ask := func(key string) (string, error) {
@@ -157,8 +182,110 @@ func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *te
listings := catalog.listings
catalog.mu.Unlock()
mu.Lock()
defer mu.Unlock()
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)
}
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) }
+15 -4
View File
@@ -20,6 +20,7 @@ import (
"encoding/json"
"errors"
"fmt"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/membership"
"log"
"regexp"
@@ -632,7 +633,7 @@ type reply struct {
// 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) {
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:
@@ -642,7 +643,17 @@ func (c *Conn) answerCalledOn(subject, queue string, h CalledHandler) (func(), e
cb := func(msg *nats.Msg) {
go func() {
var r reply
result, err := h(callerOn(subject, msg.Subject), json.RawMessage(msg.Data))
ask := ""
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 {
r.Error = err.Error()
} else {
@@ -695,7 +706,7 @@ func nullable(v any) any {
// HandleSubject answers a subject outright: a seat's verb where the mesh issued it.
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
@@ -733,7 +744,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:
// 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) {
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
+3 -2
View File
@@ -106,8 +106,9 @@ func callerOn(pattern, subject string) string {
return UserOfToken(subject[dot+1:])
}
// CalledHandler answers one call, told who called: the bus user the subject named, or "" when it named none.
type CalledHandler func(caller string, body json.RawMessage) (any, error)
// CalledHandler answers one call, told who called: the bus user the subject named, or "" when it named none; and the ask id the
// call carried in its request header stdio.AskHeader, or "" (design 47 H2 §775, H-A-351).
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
// publish ends its call at once instead of after RequestTimeout.
+3 -3
View File
@@ -58,7 +58,7 @@ type heard struct {
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()
defer h.mu.Unlock()
h.callers = append(h.callers, caller)
@@ -79,7 +79,7 @@ func TestACallerFallsBackAtOnceWhereNothingServesTheCallerNamedSubject(t *testin
h := &heard{}
// An older runtime: the subject that names no caller, alone.
stop, err := server.HandleSubject("mesh.mod.ledger.tool.who", func(body json.RawMessage) (any, error) {
return h.handler("", body)
return h.handler("", "", body)
})
if err != nil {
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.>"}})
server := dial(t, url, "node-tools", "anchor", "anchor.node-tools")
release := make(chan struct{})
stop, err := server.HandleSubjectCalled("mesh.mod.ledger.tool.slow", func(string, json.RawMessage) (any, error) {
stop, err := server.HandleSubjectCalled("mesh.mod.ledger.tool.slow", func(string, string, json.RawMessage) (any, error) {
<-release
return map[string]any{}, nil
})
+101
View File
@@ -0,0 +1,101 @@
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
}
+8 -1
View File
@@ -195,7 +195,8 @@ 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
// answer returns. A returned error is answered as `{"error": "<words>"}`, never as silence.
// answer returns. A returned error is answered as `{"error": "<words>"}`, never as silence, but for one that says it is
// 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) {
t, err := c.trafficOf(module)
if err != nil {
@@ -219,6 +220,12 @@ func (c *Conn) SeatAnswer(module, subject string, answer func(subject string, bo
return
}
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 {
b, _ := json.Marshal(map[string]string{"error": err.Error()})
_ = msg.Respond(b)
+29
View File
@@ -166,12 +166,21 @@ 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) {
_, conn, js := seatMesh(t)
stop, err := conn.SeatAnswer("messenger", "mesh.seat.intake.proof.code.*", func(subject string, body json.RawMessage) (json.RawMessage, error) {
if !strings.HasSuffix(subject, ".telegram") {
return nil, errors.New("asked by another kind")
}
if string(body) == `{"cut":true}` {
return nil, unansweredProof{}
}
return json.RawMessage(`{"linked":true}`), nil
})
if err != nil {
@@ -186,6 +195,26 @@ func TestAProofIsAskedAndAnsweredAndNeverKept(t *testing.T) {
if string(answer) != `{"linked":true}` {
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 {
t.Error("a channel asked a proof as another kind")
}
+191 -108
View File
@@ -5,16 +5,15 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
"git.novox.be/novox/mesh-sdk/go/buscalls"
"git.novox.be/novox/mesh-sdk/go/membership"
"git.novox.be/novox/mesh-sdk/go/pernode"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
)
@@ -41,11 +40,18 @@ type StateIssued struct {
// StateEntry is one key's current value.
type StateEntry struct {
Key string `json:"key"`
Value json.RawMessage `json:"value"`
Key string `json:"key"`
// Value is none on a delete a page hands (Deleted).
Value json.RawMessage `json:"value,omitempty"`
Revision uint64 `json:"revision"`
// 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"`
// 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
@@ -228,7 +234,8 @@ 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.
// StatePage is one page of a read: the values the bus wrote after the cursor's sequence, in sequence order, and the
// opaque cursor that continues the read, empty at its end (design 47 H2 §779).
type StatePage struct {
Entries []StateEntry `json:"entries"`
Next string `json:"next,omitempty"`
@@ -237,99 +244,181 @@ type StatePage struct {
// 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
// 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.
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) {
// pageCursor is where a read stands, written into the opaque cursor a page answers as next: the bucket's node for a state
// kept one bucket per node (empty for one bucket), the sequence of the last message handed, and mark, the bucket's last
// sequence when the read reached it, after which every message is marked seen-again (H-A-382 (1)). The runner keeps
// nothing per read: the cursor carries it all.
type pageCursor struct {
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)
if err != nil {
return StatePage{}, err
}
at, err := cursorOf(cursor)
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)
if maxBytes <= 0 || maxBytes > StatePageMost {
maxBytes = StatePageMost
}
// 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 {
return StatePage{}, err
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)
}
nodes := map[string]bool{}
for _, k := range keys {
if node, err := pernode.NodeOf(k); err == nil {
nodes[node] = true
}
}
for node := range nodes {
octx, ocancel := each() // each node's bucket is a bus request of its own: its own deadline
kv, err := fam.Open(octx, node)
ocancel()
if err != nil {
return StatePage{}, err
}
if kv == nil {
continue
}
wctx, wcancel := each()
got, err := currentOf(wctx, kv)
wcancel()
if err != nil {
return StatePage{}, err
}
maps.Copy(current, got)
}
} else {
var err error
if current, err = inBucket(c, ctx, s, func(kv jetstream.KeyValue) (map[string]*StateEntry, error) {
return currentOf(ctx, kv)
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
}
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 {
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
}
if len(page.Entries) > 0 && PageClock().Sub(started) >= budget {
page.Next = page.Entries[len(page.Entries)-1].Key
break
from, reached := pageCursor{node: node}, cursor != "" && node == at.node
if reached {
from = at
}
e, err := get(k)
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 e == nil {
continue
if r.page.Next != "" {
return r.page, nil
}
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
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)
defer cancel()
if !reached {
// The read reaches this bucket: what the bus writes into it from now on is marked seen-again (H-A-382 (1)).
status, err := kv.Status(ctx)
if err != nil {
return err
}
bs, ok := status.(*jetstream.KeyValueBucketStatus)
if !ok || bs.StreamInfo() == nil {
return fmt.Errorf("%s's last sequence is not read, so no page of it can say what is seen again", kv.Bucket())
}
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 {
var e jetstream.KeyValueEntry
select {
case <-ctx.Done():
return fmt.Errorf("a page of %s is not read: %w", kv.Bucket(), ctx.Err())
case got, ok := <-w.Updates():
if !ok || got == nil {
return nil // the bucket is read to its end
}
e = got
}
deleted := e.Operation() != jetstream.KeyValuePut
var value json.RawMessage
if !deleted {
value = valueOf(e.Value())
}
full := len(r.page.Entries) > 0 && (r.size+len(e.Key())+len(value) > r.maxBytes || PageClock().Sub(r.started) >= r.budget)
if full {
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()
}
}
// StateKept is one value a bucket still keeps for a key: a put, or a delete (a purge reads as one).
@@ -398,27 +487,46 @@ 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.
func (c *Conn) StateInfo(module, name string) (*StateInfo, error) {
s, err := c.issuedState(module, name)
status, info, err := c.bucketStatus(module, name)
if err != nil {
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 {
return nil, perNodeRefusal(module, name, "fill")
return nil, nil, perNodeRefusal(module, name, "fill")
}
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
defer cancel()
status, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (jetstream.KeyValueStatus, error) { return kv.Status(ctx) })
if err != nil {
return nil, err
return nil, nil, err
}
b, ok := status.(*jetstream.KeyValueBucketStatus)
if !ok || b.StreamInfo() == nil {
return nil, fmt.Errorf("the bus answered no stream behind %s's state %s", module, name)
return nil, nil, fmt.Errorf("the bus answered no stream behind %s's state %s", module, name)
}
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
return status, b.StreamInfo(), nil
}
// StatePut writes one key, as the module, where the module keeps the state. It answers the revision.
@@ -777,28 +885,3 @@ 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.
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()}
}
}
}
+5 -1
View File
@@ -202,10 +202,14 @@ 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"
}
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() {
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))
for b := range halves {
branches = append(branches, b)
+2
View File
@@ -246,6 +246,8 @@ 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-delivery-view.planned", "no declaration names mesh-delivery-view.planned", 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})
if isErr != c.refused || c.says != "" && !strings.Contains(text, c.says) ||
+132
View File
@@ -0,0 +1,132 @@
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()
}
+115 -2
View File
@@ -1,11 +1,13 @@
package launch
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
"testing"
"time"
@@ -51,6 +53,11 @@ done
// 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
// 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) {
saved := RestartFirst
RestartFirst = 10 * time.Millisecond
@@ -59,12 +66,104 @@ func TestABundleIsStartedAgainUnlessTheRuntimeIsStopping(t *testing.T) {
name string
stopping bool
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},
{"a bundle signalled with the stopping runtime", true, 1},
{"a bundle that dies while the runtime serves", false, 2, 0, false},
{"a bundle signalled with the stopping runtime", true, 1, 0, false},
{"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) {
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()
entry, out := filepath.Join(dir, "bundle"), filepath.Join(dir, "out")
if err := os.WriteFile(entry, []byte(notingBundle), 0o755); err != nil {
@@ -114,3 +213,17 @@ 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
`
+49 -7
View File
@@ -48,7 +48,19 @@ type Tool struct {
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,
// H-A-43); zero waits CallTimeout. A tool the runtime serves itself has none: Run is its call.
RunWithin func(caller string, args json.RawMessage, within time.Duration) (json.RawMessage, error)
RunWithin func(caller, ask 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
@@ -58,7 +70,10 @@ func (t Tool) Within(within time.Duration) Tool {
return t
}
run := t.RunWithin
t.Run = func(caller string, args json.RawMessage) (json.RawMessage, error) { return run(caller, args, within) }
t.Run = func(caller string, args json.RawMessage) (json.RawMessage, error) {
return run(caller, "", args, within)
}
t.within = within
return t
}
@@ -70,8 +85,9 @@ 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
// 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
// 0597 §7).
func callParams(name, caller, call string, args json.RawMessage) map[string]any {
// 0597 §7), and the ask id the call carried in its request header, only when it carried one (stdio.MetaAsk; design 47 H2
// §775, H-A-351).
func callParams(name, caller, call, ask string, args json.RawMessage) map[string]any {
params := map[string]any{"name": name, "arguments": args}
meta := map[string]any{}
if caller != "" {
@@ -80,6 +96,9 @@ func callParams(name, caller, call string, args json.RawMessage) map[string]any
if call != "" {
meta[buscalls.MetaCall] = call
}
if ask != "" {
meta[stdio.MetaAsk] = ask
}
if len(meta) > 0 {
params["_meta"] = meta
}
@@ -481,6 +500,12 @@ 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 {
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":
mu.Lock()
seatTaker = c
@@ -813,7 +838,7 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
input = json.RawMessage("{}")
}
tool := Tool{Name: name, Description: t.Description, Input: input,
Run: nil, RunWithin: func(caller string, args json.RawMessage, within time.Duration) (json.RawMessage, error) {
Run: nil, RunWithin: func(caller, ask string, args json.RawMessage, within time.Duration) (json.RawMessage, error) {
if len(args) == 0 || string(args) == "null" {
args = json.RawMessage("{}")
}
@@ -823,7 +848,7 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
if within > 0 {
bound = within
}
res, err := asking("tools/call", callParams(full, caller, call, args), bound)
res, err := asking("tools/call", callParams(full, caller, call, ask, args), bound)
if err != nil {
if errors.Is(err, errNoAnswer) {
// Its caller is gone by now and nobody else would hear of it (issue 1966).
@@ -860,7 +885,7 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
return b, nil
}}
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 {
order = append(order, under)
@@ -890,6 +915,18 @@ 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) {
// 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()
if c.why != nil {
c.mu.Unlock()
@@ -925,6 +962,11 @@ func (c *child) ask(module, method string, params any, timeout time.Duration) (j
return m.Result, nil
case <-c.dead:
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:
c.mu.Lock()
delete(c.pending, id)
+28 -29
View File
@@ -128,6 +128,34 @@ func TestABundleTakesASeatsWorkThroughItsOwnChannel(t *testing.T) {
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.
@@ -142,32 +170,3 @@ while IFS= read -r line; do
esac
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)
}
}
@@ -8,6 +8,7 @@ import (
"testing"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/approval"
"git.novox.be/novox/mesh-sdk/go/seatdef"
"github.com/novox/mesh-tools/node-tools/internal/bus"
@@ -20,6 +21,7 @@ import (
type saidCaller struct {
Caller string `json:"caller"`
Call string `json:"call"`
Ask *string `json:"ask"`
Arguments map[string]any `json:"arguments"`
}
@@ -65,7 +67,39 @@ func TestACallOnTheCallerNamedSubjectReachesTheModuleWithItsCaller(t *testing.T)
if got.Arguments["caller"] != "novox.node-tools" {
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.
+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.
type gatedRun func(call approval.Call, t launch.Tool, caller string) (any, error)
type gatedRun func(call approval.Call, t launch.Tool, caller, ask string) (any, error)
// 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 string) (any, error) {
run := func() (any, error) { return t.Run(caller, call.Args) }
func (c *consumers) gated(call approval.Call, t launch.Tool, caller, ask string) (any, error) {
run := func() (any, error) { return t.Call(caller, ask, call.Args) }
if c.gate == nil {
return run()
}
+28 -15
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).
// 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
stop, err := r.conn.HandleCalled(address, func(caller string, body json.RawMessage) (any, error) {
stop, err := r.conn.HandleCalled(address, func(caller, ask string, body json.RawMessage) (any, error) {
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),
Description: t.Description}, t, caller)
Description: t.Description}, t, caller, ask)
})
if err != nil {
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).
if v.Verb == seatdef.ApprovalsVerb && approvals != nil {
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)
})
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
// 7-approval-mark §20).
module, v := module, v
handle := func(caller string, body json.RawMessage) (any, error) {
handle := func(caller, ask string, body json.RawMessage) (any, error) {
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)
Fingerprint: fingerprintOf(module), Caller: caller, Args: argsOf(body), Description: t.Description}, t.Within(within("seat:"+v.Seat+"."+v.Verb)), caller, ask)
if err != nil || !chunked("seat:"+v.Seat+"."+v.Verb) {
return answer, err
}
@@ -1206,8 +1206,9 @@ 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"`
// Cursor and MaxBytes are a `page`'s opaque cursor, the next of the page before (empty: from the start), and its size in
// keys and values (zero, or above 768 KB, is 768 KB; design 47 H2 §779).
Cursor string `json:"cursor"`
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"`
@@ -1239,11 +1240,8 @@ func (b *moduleBus) State(verb string, params json.RawMessage) (json.RawMessage,
}
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)
// One page of the state in the order the bus wrote it, after the cursor, one request for many (design 47 H2 §779).
page, err := conn.StatePage(b.module, asked.State, asked.Cursor, asked.MaxBytes, time.Duration(asked.BudgetMS)*time.Millisecond)
if err != nil {
return nil, err
}
@@ -1266,7 +1264,12 @@ func (b *moduleBus) State(verb string, params json.RawMessage) (json.RawMessage,
if err != nil {
return nil, err
}
answer = map[string]any{"revision": revision}
// With the bucket's fill, so a bundle's prune reads it from the put (design 47 H2 DMC-14, H-A-386).
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":
if err := conn.StateDelete(b.module, asked.State, asked.Key); err != nil {
return nil, err
@@ -1438,8 +1441,10 @@ type seatAsked struct {
Body json.RawMessage `json:"body"`
ID string `json:"id"`
Worker string `json:"worker"`
Bucket string `json:"bucket"`
Key string `json:"key"`
// Seat is the seat whose work queue a waiting read reads (design 47 H2 H-A-410).
Seat string `json:"seat"`
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"`
// DelayMS is how long a settle with the fate nak-after waits before the bus gives the message again.
@@ -1478,6 +1483,14 @@ func (b *moduleBus) Seat(verb string, params json.RawMessage, handOn func(string
return json.RawMessage("null"), err
}
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":
// 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).
+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",
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)
}
nodeTools.Follow("theta")
@@ -3,6 +3,7 @@ package runtime
import (
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"testing"
@@ -219,4 +220,64 @@ 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" {
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,6 +7,8 @@ import (
"testing"
"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/launch"
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
@@ -71,16 +73,26 @@ func TestAKeysHistoryIsEveryValueKeptOldestFirst(t *testing.T) {
owner, reader, _ := historyBuses(t)
before := time.Now().Add(-time.Second)
var revisions []uint64
for _, v := range []string{`{"state":"open"}`, `{"state":"fixing"}`, `{"state":"resolved"}`} {
// each put answers the bucket's fill with its revision, buscalls.Fill's form (design 47 H2 DMC-14, H-A-386): the messages
// 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)})
if err != nil {
t.Fatal(err)
}
var r struct {
Revision uint64 `json:"revision"`
Revision uint64 `json:"revision"`
Fill *buscalls.Fill `json:"fill"`
}
_ = json.Unmarshal(raw, &r)
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 {
t.Fatal(err)
@@ -150,35 +162,79 @@ func TestAKeysHistoryAndAPageOfAStateAreServedToOwnerAndReaderAndRefusedToAModul
!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 {
// 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,
// never to a module not issued the state; a page too small for two values still gives one and says where the read goes
// on; a value written after the read began comes marked seen-again, and a fresh read hands each kept message, a key's
// older kept revision included (design 47 H2 §779, H-A-382).
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)
}
}
type page struct {
Entries []kept `json:"entries"`
Next string `json:"next"`
type entry struct {
Key string `json:"key"`
Value json.RawMessage `json:"value"`
SeenAgain bool `json:"seen-again"`
Deleted bool `json:"deleted"`
}
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})
type page struct {
Entries []entry `json:"entries"`
Next string `json:"next"`
}
read := func(who launch.Bus, state, cursor string, most int) page {
t.Helper()
raw, err := ask(who, "page", map[string]any{"state": state, "cursor": cursor, "max_bytes": most})
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)
if err != nil || json.Unmarshal(raw, &p) != nil {
t.Fatalf("page of %s after %q = %s, %v", state, cursor, 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)
return p
}
said := func(p page) string {
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.
step := time.Time{}
@@ -186,7 +242,7 @@ func TestAKeysHistoryAndAPageOfAStateAreServedToOwnerAndReaderAndRefusedToAModul
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" {
if err != nil || json.Unmarshal(raw, &cut) != nil || said(cut) != "1 (more)" {
t.Fatalf("a page past its budget = %s, %v", raw, err)
}
if _, err := ask(other, "page", map[string]any{"state": "issues.issues"}); err == nil {
+23
View File
@@ -37,6 +37,29 @@
"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": [
{
"id": "mesh-state",
+3 -2
View File
@@ -1,7 +1,8 @@
#!/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
# 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), and the arguments as given.
# 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) —,
# and the arguments as given.
import json, sys
def say(m):
@@ -19,7 +20,7 @@ for line in sys.stdin:
say({"id": rid, "result": {"tools": TOOLS}})
elif m == "tools/call":
meta = p.get("_meta") or {}
said = {"caller": meta.get("mesh/caller", ""), "call": meta.get("mesh/call", ""), "arguments": p.get("arguments") or {}}
said = {"caller": meta.get("mesh/caller", ""), "call": meta.get("mesh/call", ""), "ask": meta.get("mesh/ask"), "arguments": p.get("arguments") or {}}
say({"id": rid, "result": {"content": [{"type": "text", "text": json.dumps(said)}]}})
elif rid is not None:
say({"id": rid, "result": {}})
+32 -3
View File
@@ -1,11 +1,17 @@
#!/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
# `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.
import json, sys, time
# bundle does, through the runtime's `mesh/ask`, and says what came back; a tool `hold`, which answers after the seconds it is given,
# 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,
# 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):
m["jsonrpc"] = "2.0"; sys.stdout.write(json.dumps(m) + "\n"); sys.stdout.flush()
m["jsonrpc"] = "2.0"
with LOCK:
sys.stdout.write(json.dumps(m) + "\n"); sys.stdout.flush()
def text(rid, value):
say({"id": rid, "result": {"content": [{"type": "text", "text": json.dumps(value)}]}})
@@ -13,6 +19,8 @@ def text(rid, value):
TOOLS = [
{"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": "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.slow", "description": "the seat's verb that answers late", "inputSchema": {"type": "object", "properties": {}}},
]
@@ -24,8 +32,29 @@ for line in sys.stdin:
say({"id": rid, "result": {"tools": TOOLS}})
elif m == "tools/call":
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":
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":
say({"id": "q1", "method": "mesh/ask", "params": {"key": "seat:node-desk.fresh", "body": {}}})
for answer in sys.stdin: