T2 drain at stop: finish the calls in flight within the drain bound, cut and say past it
Once told to stop, the tool runner makes no new ask of a bundle (a call after the stop is refused), waits for the asks in flight within the drain bound (30 s by default), cuts each still in flight at the bound with a journal line naming the bundle, the verb and the call's age, leaves its caller unanswered (a transport fault), and only then stops its bundles itself. Builds: design 47 H2 §813 (12), H-A-342 (2), H-A-353
This commit is contained in:
@@ -155,6 +155,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 +168,10 @@ func serve(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// drainBound is how long the runner, told to stop, waits for the calls in flight to finish: the setting drain-bound (design 47
|
||||
// H2 §813 (12)).
|
||||
var drainBound = 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,
|
||||
|
||||
@@ -5,6 +5,8 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -75,6 +77,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 +108,32 @@ 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) })
|
||||
savedBound := drainBound
|
||||
drainBound = 2 * time.Second
|
||||
t.Cleanup(func() { drainBound = savedBound })
|
||||
|
||||
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) {
|
||||
@@ -161,4 +177,57 @@ func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *te
|
||||
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()
|
||||
|
||||
// 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 refused
|
||||
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()
|
||||
mt.Until(t, func() error {
|
||||
_, err := ask("ledger.who")
|
||||
if err == nil || !strings.Contains(err.Error(), "takes no new call") {
|
||||
return fmt.Errorf("a call after the stop was answered %v, want it refused", 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())
|
||||
}
|
||||
mu.Lock()
|
||||
}
|
||||
|
||||
// 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) }
|
||||
|
||||
@@ -637,6 +637,12 @@ func (c *Conn) answerCalledOn(subject, queue string, h CalledHandler) (func(), e
|
||||
go func() {
|
||||
var r reply
|
||||
result, err := h(callerOn(subject, msg.Subject), 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 {
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package launch
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DefaultDrainBound is how long the tool runner, once told to stop, waits for the calls in flight in its bundles to finish:
|
||||
// the setting drain-bound's default (design 47 H2 §813 (12), H-A-342 (2)).
|
||||
const 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{}}
|
||||
|
||||
// errStopping is an ask made after the stop: refused, the call made after the stop is not taken (§813 (12)).
|
||||
var errStopping = &Refused{Method: "", Message: "the tool runner is stopping: it takes no new call (design 47 H2 §813 (12))"}
|
||||
|
||||
// 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, or refuses it once the runner drains.
|
||||
func begin(module, verb string) (uint64, *inFlight, error) {
|
||||
asks.mu.Lock()
|
||||
defer asks.mu.Unlock()
|
||||
if asks.draining {
|
||||
return 0, nil, errStopping
|
||||
}
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package launch
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 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
|
||||
`
|
||||
|
||||
// **The tool runner drains at a stop** (design 47 H2 §813 (12), H-A-342 (2), H-A-353): once it drains, no new call is taken; 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 TestTheToolRunnerDrainsItsCallsInFlightAtAStop(t *testing.T) {
|
||||
for _, row := range []struct {
|
||||
name string
|
||||
bound time.Duration
|
||||
release bool
|
||||
}{
|
||||
{"a call that ends within the bound is answered, and a call after the stop is refused", 10 * time.Second, true},
|
||||
{"a call that outlives the bound is cut and said", 50 * time.Millisecond, false},
|
||||
} {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
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.bound, 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 {
|
||||
if _, err := run("", json.RawMessage(`{}`)); err == nil || !strings.Contains(err.Error(), "takes no new call") {
|
||||
t.Errorf("a call made after the stop was answered %v, want it 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.bound || 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -890,6 +890,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 +937,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)
|
||||
|
||||
+15
-3
@@ -1,11 +1,16 @@
|
||||
#!/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)).
|
||||
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 +18,7 @@ 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": "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,6 +30,12 @@ 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 == "reach":
|
||||
|
||||
Reference in New Issue
Block a user