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:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user