AGENTS.md: a refused tool call is not a reason to end the turn; v2 plan (props, ctx guard, wake, identity, wiring) as acceptance tests; v1.1 run note

v2 given tests compiled against a panic-only skeleton (go vet clean); no reference
implementation.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
2026-09-25 08:37:38 -07:00
co-authored by Claude Fable 5.1
parent 9ba04b16e0
commit 74b8af4ce0
18 changed files with 1257 additions and 0 deletions
@@ -0,0 +1,75 @@
package config_test
import (
"strings"
"testing"
"time"
"git.wntrmute.dev/kyle/crossbar/internal/config"
)
const v2Base = `
listen = "127.0.0.1:1"
[hosts.a]
base_url = "http://a:1"
models = { "m" = { } }
[hosts.b]
base_url = "http://b:1"
models = { "m" = { } }
[hosts.b.wake]
mac = "aa:bb:cc:dd:ee:ff"
broadcast = "192.168.1.255:9"
wait = "45s"
[routes.r]
hosts = ["a", "b"]
peers = ["talos", "imladris"]
`
func TestV2Defaults(t *testing.T) {
c, err := config.Parse(strings.NewReader(v2Base))
if err != nil {
t.Fatal(err)
}
if c.Identity != "off" {
t.Errorf("identity default = %q, want off", c.Identity)
}
if c.Hosts["a"].Wake != nil {
t.Errorf("host without [wake] must have nil Wake")
}
w := c.Hosts["b"].Wake
if w == nil || w.MAC != "aa:bb:cc:dd:ee:ff" || w.Broadcast != "192.168.1.255:9" || w.Wait.Duration != 45*time.Second {
t.Errorf("wake = %+v", w)
}
if p := c.Routes["r"].Peers; len(p) != 2 || p[0] != "talos" {
t.Errorf("peers = %v", p)
}
}
func TestV2Validation(t *testing.T) {
good := v2Base
for _, tc := range []struct{ name, text, field string }{
{"bad identity", "identity = \"maybe\"\n" + good, "identity"},
{"peers without identity", "identity = \"off\"\n" + good, "routes.r.peers"},
{"bad mac", strings.Replace(good, `mac = "aa:bb:cc:dd:ee:ff"`, `mac = "nope"`, 1), "hosts.b.wake.mac"},
{"no broadcast", strings.Replace(good, `broadcast = "192.168.1.255:9"`, `broadcast = ""`, 1), "hosts.b.wake.broadcast"},
{"wait too short", strings.Replace(good, `wait = "45s"`, `wait = "2s"`, 1), "hosts.b.wake.wait"},
{"peers on unknown route field", "identity = \"tailscale\"\n" + strings.Replace(good, `peers = ["talos", "imladris"]`, `peers = []`, 1), "routes.r.peers"},
} {
_, err := config.Parse(strings.NewReader(tc.text))
e, ok := config.IsError(err)
if !ok || e.Field != tc.field {
t.Errorf("%s: %v, want *Error on %s", tc.name, err, tc.field)
}
}
// identity = "header" is the test/smoke mode; "tailscale" the real one; both accept peers.
for _, mode := range []string{"header", "tailscale"} {
if _, err := config.Parse(strings.NewReader("identity = \"" + mode + "\"\n" + good)); err != nil {
t.Errorf("identity=%s with peers: %v", mode, err)
}
}
// wait defaults to 45s when the [wake] table omits it
c, err := config.Parse(strings.NewReader("identity = \"header\"\n" + strings.Replace(good, "wait = \"45s\"\n", "", 1)))
if err != nil || c.Hosts["b"].Wake == nil || c.Hosts["b"].Wake.Wait.Duration != 45*time.Second {
t.Errorf("wake.wait default: %v %+v", err, c.Hosts["b"].Wake)
}
}
@@ -0,0 +1,75 @@
package health_test
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"git.wntrmute.dev/kyle/crossbar/internal/health"
)
// propsFake answers /health, /v1/models and a configurable /props.
func propsFake(t *testing.T, props string, status int) *httptest.Server {
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"status":"ok"}`) })
mux.HandleFunc("/v1/models", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"data":[{"id":"m"}]}`) })
mux.HandleFunc("/props", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(status)
fmt.Fprint(w, props)
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv
}
func TestPropsLearned(t *testing.T) {
srv := propsFake(t, `{"default_generation_settings":{"n_ctx":131072,"params":{}},"total_slots":4,"model_path":"/x/m.gguf","chat_template":"..."}`, 200)
tbl := health.New(map[string]string{"a": srv.URL}, time.Hour, nil)
tbl.PollOnce(context.Background())
s, _ := tbl.Get("a")
if !s.Healthy || s.NCtx != 131072 || s.Slots != 4 {
t.Fatalf("status = %+v, want healthy with NCtx 131072 and Slots 4", s)
}
if got := s.PerSlotCtx(); got != 32768 {
t.Errorf("PerSlotCtx = %d, want 131072/4", got)
}
}
func TestPropsAbsentOrBrokenIsNotAFailure(t *testing.T) {
for name, tc := range map[string]struct {
props string
status int
}{
"404": {`not found`, 404},
"not json": {`<html>`, 200},
"no fields": {`{"model_path":"/x"}`, 200},
"zero ctx": {`{"default_generation_settings":{"n_ctx":0},"total_slots":0}`, 200},
} {
t.Run(name, func(t *testing.T) {
srv := propsFake(t, tc.props, tc.status)
tbl := health.New(map[string]string{"a": srv.URL}, time.Hour, nil)
tbl.PollOnce(context.Background())
s, _ := tbl.Get("a")
if !s.Healthy {
t.Fatalf("a bad /props must not make the host unhealthy: %+v", s)
}
if s.NCtx != 0 || s.Slots != 0 || s.PerSlotCtx() != 0 {
t.Errorf("unknown context must read as 0: %+v", s)
}
})
}
}
func TestPerSlotCtxWithUnknownSlots(t *testing.T) {
s := health.Status{NCtx: 8192, Slots: 0}
if s.PerSlotCtx() != 8192 {
t.Errorf("with Slots unknown the whole context is the per-slot value; got %d", s.PerSlotCtx())
}
s = health.Status{NCtx: 8192, Slots: 3}
if s.PerSlotCtx() != 2730 {
t.Errorf("integer division: got %d, want 2730", s.PerSlotCtx())
}
}
@@ -0,0 +1,90 @@
package identity_test
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"git.wntrmute.dev/kyle/crossbar/internal/identity"
)
func TestParseWhois(t *testing.T) {
raw, err := os.ReadFile(filepath.Join("testdata", "whois.json"))
if err != nil {
t.Fatal(err)
}
id, err := identity.ParseWhois(raw)
if err != nil {
t.Fatal(err)
}
if id.Node != "titan" || id.Login == "" {
t.Errorf("parsed %+v, want Node titan and a login", id)
}
if _, err := identity.ParseWhois([]byte(`{"Node":{}}`)); err == nil {
t.Error("a whois answer without a node name must be an error")
}
if _, err := identity.ParseWhois([]byte(`nope`)); err == nil {
t.Error("non-JSON must be an error")
}
}
// fakeResolver answers from a map; "" means not a tailnet peer.
type fakeResolver map[string]string
func (f fakeResolver) Identity(ctx context.Context, ip string) (identity.ID, error) {
n, ok := f[ip]
if !ok {
return identity.ID{}, identity.ErrNotAPeer
}
return identity.ID{Node: n, Login: n + "@example"}, nil
}
func TestChecker(t *testing.T) {
c := identity.NewChecker(fakeResolver{"100.64.0.5": "talos", "100.64.0.9": "titan"})
for _, tc := range []struct {
name string
peers []string
addr string
want error
}{
{"open route", nil, "203.0.113.7:1", nil},
{"allowed peer", []string{"talos", "titan"}, "100.64.0.5:44444", nil},
{"other peer", []string{"talos"}, "100.64.0.9:1", identity.ErrForbidden},
{"not a peer", []string{"talos"}, "203.0.113.7:1", identity.ErrForbidden},
{"loopback", []string{"talos"}, "127.0.0.1:1", identity.ErrForbidden},
{"garbage addr", []string{"talos"}, "nonsense", identity.ErrForbidden},
} {
t.Run(tc.name, func(t *testing.T) {
got := c.Allow(context.Background(), tc.peers, tc.addr)
if !errors.Is(got, tc.want) && !(got == nil && tc.want == nil) {
t.Errorf("Allow(%v, %q) = %v, want %v", tc.peers, tc.addr, got, tc.want)
}
})
}
}
func TestCheckerCachesPerAddress(t *testing.T) {
calls := 0
r := countingResolver{f: fakeResolver{"100.64.0.5": "talos"}, calls: &calls}
c := identity.NewChecker(r)
for i := 0; i < 5; i++ {
if err := c.Allow(context.Background(), []string{"talos"}, "100.64.0.5:1"); err != nil {
t.Fatal(err)
}
}
if calls != 1 {
t.Errorf("resolver called %d times for one address, want 1 (cache)", calls)
}
}
type countingResolver struct {
f fakeResolver
calls *int
}
func (c countingResolver) Identity(ctx context.Context, ip string) (identity.ID, error) {
*c.calls++
return c.f.Identity(ctx, ip)
}
@@ -0,0 +1,74 @@
package identity_test
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.wntrmute.dev/kyle/crossbar/internal/identity"
)
// The middleware sits in front of the proxy: it names the route the same way the proxy does
// (X-Crossbar-Route header, else first path segment) and refuses callers a route does not list.
func TestMiddleware(t *testing.T) {
peers := map[string][]string{"locked": {"talos"}, "open": nil}
inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) })
h := identity.Middleware(identity.NewChecker(fakeResolver{"100.64.0.5": "talos", "100.64.0.9": "titan"}),
func(route string) ([]string, bool) { p, ok := peers[route]; return p, ok }, inner)
for _, tc := range []struct {
name, path, hdr, addr string
want int
}{
{"open route, anyone", "/open/v1/models", "", "203.0.113.1:5", 204},
{"locked, right peer", "/locked/v1/models", "", "100.64.0.5:5", 204},
{"locked, wrong peer", "/locked/v1/models", "", "100.64.0.9:5", 403},
{"locked, not a peer", "/locked/v1/models", "", "203.0.113.1:5", 403},
{"locked via header", "/v1/models", "locked", "100.64.0.9:5", 403},
{"header wins over path", "/open/v1/models", "locked", "203.0.113.1:5", 403},
{"unknown route passes through to the proxy's own 404", "/nope/v1/models", "", "203.0.113.1:5", 204},
{"admin path is never gated here", "/_crossbar/hosts", "", "203.0.113.1:5", 204},
} {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, tc.path, nil)
req.RemoteAddr = tc.addr
if tc.hdr != "" {
req.Header.Set("X-Crossbar-Route", tc.hdr)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != tc.want {
t.Errorf("%s = %d, want %d (%s)", tc.path, rec.Code, tc.want, rec.Body.String())
}
if rec.Code == 403 && (!strings.HasPrefix(rec.Header().Get("Content-Type"), "application/json") || !strings.Contains(rec.Body.String(), `"forbidden route"`)) {
t.Errorf("403 must be JSON {\"error\":\"forbidden route\"}: %q", rec.Body.String())
}
})
}
}
// HeaderResolver is the test/smoke identity source: it trusts X-Crossbar-Peer. It exists so the
// smoke run can exercise the gate without a tailnet; config must call it out as insecure.
func TestHeaderResolver(t *testing.T) {
inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) })
h := identity.Middleware(identity.NewHeaderChecker(), func(route string) ([]string, bool) { return []string{"talos"}, true }, inner)
req := httptest.NewRequest(http.MethodGet, "/r/v1/models", nil)
req.Header.Set("X-Crossbar-Peer", "talos")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 204 {
t.Errorf("header peer talos: %d", rec.Code)
}
req.Header.Set("X-Crossbar-Peer", "titan")
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 403 {
t.Errorf("header peer titan: %d, want 403", rec.Code)
}
req.Header.Del("X-Crossbar-Peer")
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 403 {
t.Errorf("no header: %d, want 403", rec.Code)
}
}
@@ -0,0 +1,24 @@
{
"Node": {
"ID": 1,
"StableID": "nEXAMPLE",
"Name": "titan.example.ts.net.",
"User": 2,
"Addresses": [
"100.64.0.9/32",
"fd7a:115c:a1e0::9/128"
],
"HomeDERP": 2,
"Created": "2026-01-01T00:00:00Z",
"Cap": 138,
"Online": true,
"ComputedName": "titan",
"ComputedNameWithHost": "titan"
},
"UserProfile": {
"ID": 2,
"LoginName": "user@example.com",
"DisplayName": "Example User"
},
"CapMap": null
}
@@ -0,0 +1,142 @@
package proxy_test
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.wntrmute.dev/kyle/crossbar/internal/proxy"
)
// ctxUpstream is a fake router that reports a context size in /props and echoes completions.
func ctxUpstream(t *testing.T, name string, nCtx, slots int) *upstream {
u := &upstream{name: name}
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"status":"ok"}`) })
mux.HandleFunc("/v1/models", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"data":[{"id":"shared"}]}`) })
mux.HandleFunc("/props", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, `{"default_generation_settings":{"n_ctx":%d},"total_slots":%d}`, nCtx, slots)
})
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
u.hits.Add(1)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"choices":[{"message":{"role":"assistant","content":"ok"}}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)
})
u.srv = httptest.NewServer(mux)
t.Cleanup(u.srv.Close)
return u
}
const ctxHosts = `
listen = "127.0.0.1:1"
queue_max = 2
[hosts.small]
base_url = %q
weight = 10.0
models = { "shared" = { parallel = 2 } }
[hosts.big]
base_url = %q
weight = 1.0
models = { "shared" = { parallel = 1 } }
[routes.r]
hosts = ["small", "big"]
default_model = "shared"
`
// bodyOfTokens builds a chat body whose byte size implies roughly n tokens under the guard's
// estimate (bytes/4 × 1.2): n tokens ≈ 3.33 n bytes ≈ 2n/3 five-byte words.
func bodyOfTokens(n int) string {
text := strings.Repeat("word ", n*2/3)
return fmt.Sprintf(`{"model":"shared","stream":false,"messages":[{"role":"user","content":"%s"}]}`, text)
}
func TestOversizedPromptMovesToAHostWhereItFits(t *testing.T) {
small := ctxUpstream(t, "small", 8192, 2) // 4096 per slot
big := ctxUpstream(t, "big", 131072, 1) // 131072 per slot
r := newRig(t, ctxHosts, small, big)
// A small prompt starts on `small` (weight 10).
resp := r.post("/r/v1/chat/completions", bodyOfTokens(100))
drain(resp)
if resp.Header.Get(proxy.HostHeader) != "small" {
t.Fatalf("small prompt went to %q, want small", resp.Header.Get(proxy.HostHeader))
}
// A new conversation with ~10k tokens does not fit small's 4096-token slot: it must be
// placed on big, with the reason visible in a header.
resp = r.post("/r/v1/chat/completions", bodyOfTokens(10000))
drain(resp)
if resp.StatusCode != 200 || resp.Header.Get(proxy.HostHeader) != "big" {
t.Fatalf("oversized prompt: %d from %q, want 200 from big", resp.StatusCode, resp.Header.Get(proxy.HostHeader))
}
if got := resp.Header.Get(proxy.CtxHeader); !strings.HasPrefix(got, "moved") {
t.Errorf("%s = %q, want moved:… ", proxy.CtxHeader, got)
}
}
func TestOversizedPromptWithNoFitIs400(t *testing.T) {
small := ctxUpstream(t, "small", 8192, 2)
tiny := ctxUpstream(t, "big", 4096, 2) // also too small
r := newRig(t, ctxHosts, small, tiny)
resp := r.post("/r/v1/chat/completions", bodyOfTokens(10000))
body := drain(resp)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status %d body %s, want 400", resp.StatusCode, body)
}
var e map[string]any
if err := json.Unmarshal([]byte(body), &e); err != nil || e["error"] != "prompt too large" {
t.Fatalf("body = %s, want error 'prompt too large'", body)
}
if est, _ := e["estimate"].(float64); est < 8000 || est > 13000 {
t.Errorf("estimate = %v, want roughly 10000 tokens", e["estimate"])
}
if max, _ := e["max"].(float64); max != 4096 {
t.Errorf("max = %v, want the largest per-slot context among the route's hosts (4096)", e["max"])
}
if small.hits.Load()+tiny.hits.Load() != 0 {
t.Errorf("a refused prompt must not reach any upstream")
}
}
func TestUnknownContextNeverBlocks(t *testing.T) {
// /props missing on both hosts: NCtx 0 means "unknown", and the guard must stay out of the way.
alpha, beta := newUpstream(t, "alpha"), newUpstream(t, "beta")
r := newRig(t, twoHosts, alpha, beta)
resp := r.post("/r/v1/chat/completions", bodyOfTokens(50000))
drain(resp)
if resp.StatusCode != 200 || resp.Header.Get(proxy.CtxHeader) != "" {
t.Errorf("unknown context: %d %q, want 200 and no ctx header", resp.StatusCode, resp.Header.Get(proxy.CtxHeader))
}
}
func TestStickyLeaseSurvivesGrowthUntilItDoesNotFit(t *testing.T) {
small := ctxUpstream(t, "small", 8192, 2)
big := ctxUpstream(t, "big", 131072, 1)
r := newRig(t, ctxHosts, small, big)
body := bodyOfTokens(100)
resp := r.post("/r/v1/chat/completions", body)
drain(resp)
if resp.Header.Get(proxy.HostHeader) != "small" {
t.Fatal("setup: first turn must be on small")
}
// Same conversation (same first user message), later turn well under 4096: stays.
longer := strings.Replace(body, `"content":"`, `"content":"`+strings.Repeat("x ", 500), 1)
resp = r.post("/r/v1/chat/completions", longer)
drain(resp)
if resp.Header.Get(proxy.HostHeader) != "small" || resp.Header.Get(proxy.LeaseHeader) != "reused" {
t.Errorf("turn 2: %q %q, want small reused", resp.Header.Get(proxy.HostHeader), resp.Header.Get(proxy.LeaseHeader))
}
// A turn that outgrows the slot moves the lease — once — and the move is recorded as an event.
huge := strings.Replace(body, `"content":"`, `"content":"`+strings.Repeat("x ", 30000), 1)
resp = r.post("/r/v1/chat/completions", huge)
drain(resp)
if resp.StatusCode != 200 || resp.Header.Get(proxy.HostHeader) != "big" {
t.Fatalf("outgrown turn: %d %q, want 200 from big", resp.StatusCode, resp.Header.Get(proxy.HostHeader))
}
resp = r.post("/r/v1/chat/completions", huge)
drain(resp)
if resp.Header.Get(proxy.HostHeader) != "big" || resp.Header.Get(proxy.LeaseHeader) != "reused" {
t.Errorf("after the move the lease is on big: %q %q", resp.Header.Get(proxy.HostHeader), resp.Header.Get(proxy.LeaseHeader))
}
}
@@ -0,0 +1,114 @@
package wake_test
import (
"bytes"
"context"
"net"
"testing"
"time"
"git.wntrmute.dev/kyle/crossbar/internal/wake"
)
func listen(t *testing.T) (*net.UDPConn, string) {
conn, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.Close() })
return conn, conn.LocalAddr().String()
}
func TestMagicPacket(t *testing.T) {
pkt, err := wake.MagicPacket("aa:bb:cc:dd:ee:ff")
if err != nil {
t.Fatal(err)
}
if len(pkt) != 102 || !bytes.Equal(pkt[:6], bytes.Repeat([]byte{0xff}, 6)) {
t.Fatalf("packet = % x", pkt)
}
mac := []byte{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}
for i := 0; i < 16; i++ {
if !bytes.Equal(pkt[6+6*i:12+6*i], mac) {
t.Fatalf("repetition %d wrong: % x", i, pkt[6+6*i:12+6*i])
}
}
for _, bad := range []string{"", "aa:bb", "zz:bb:cc:dd:ee:ff", "aabbccddeeff00"} {
if _, err := wake.MagicPacket(bad); err == nil {
t.Errorf("MagicPacket(%q) must fail", bad)
}
}
if p2, _ := wake.MagicPacket("AA-BB-CC-DD-EE-FF"); !bytes.Equal(p2, pkt) {
t.Errorf("dash-separated upper-case MAC must give the same packet")
}
}
func TestSendReachesTheBroadcastAddress(t *testing.T) {
conn, addr := listen(t)
if err := wake.Send("aa:bb:cc:dd:ee:ff", addr); err != nil {
t.Fatal(err)
}
buf := make([]byte, 200)
_ = conn.SetReadDeadline(time.Now().Add(time.Second))
n, _, err := conn.ReadFromUDP(buf)
if err != nil || n != 102 {
t.Fatalf("received %d bytes, err %v", n, err)
}
if err := wake.Send("aa:bb:cc:dd:ee:ff", "256.1.1.1:9"); err == nil {
t.Error("an unresolvable broadcast address must be an error")
}
}
// fakeHealth flips to healthy after `after` calls to Healthy.
type fakeHealth struct{ calls, after int }
func (f *fakeHealth) Healthy(name string) bool { f.calls++; return f.calls > f.after }
func TestWakerSendsOncePerWindowAndWaitsForHealth(t *testing.T) {
conn, addr := listen(t)
h := &fakeHealth{after: 3}
w := wake.New(map[string]wake.Target{"titan": {MAC: "aa:bb:cc:dd:ee:ff", Broadcast: addr, Wait: 2 * time.Second}}, h)
w.PollEvery(20 * time.Millisecond) // test hook: how often Wake re-checks health
start := time.Now()
ok := w.Wake(context.Background(), "titan")
if !ok {
t.Fatal("Wake must return true once the host reports healthy")
}
if time.Since(start) > time.Second {
t.Errorf("Wake waited %v for a host that came up after 3 checks", time.Since(start))
}
_ = conn.SetReadDeadline(time.Now().Add(200 * time.Millisecond))
buf := make([]byte, 200)
if n, _, err := conn.ReadFromUDP(buf); err != nil || n != 102 {
t.Fatalf("no magic packet received: %d %v", n, err)
}
// A second Wake inside the same window does not send again (the host is booting).
_ = w.Wake(context.Background(), "titan")
_ = conn.SetReadDeadline(time.Now().Add(150 * time.Millisecond))
if n, _, err := conn.ReadFromUDP(buf); err == nil {
t.Errorf("a second packet (%d bytes) was sent inside the wait window", n)
}
if w.Wake(context.Background(), "nobody") {
t.Errorf("unknown host: Wake must return false")
}
}
func TestWakeGivesUpAfterWait(t *testing.T) {
_, addr := listen(t)
h := &fakeHealth{after: 1 << 30}
w := wake.New(map[string]wake.Target{"titan": {MAC: "aa:bb:cc:dd:ee:ff", Broadcast: addr, Wait: 300 * time.Millisecond}}, h)
w.PollEvery(20 * time.Millisecond)
start := time.Now()
if w.Wake(context.Background(), "titan") {
t.Fatal("Wake must return false when the host never comes up")
}
if d := time.Since(start); d < 250*time.Millisecond || d > 900*time.Millisecond {
t.Errorf("Wake returned after %v, want about the 300ms wait", d)
}
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
start = time.Now()
if w.Wake(ctx, "titan") || time.Since(start) > 200*time.Millisecond {
t.Errorf("a cancelled context must end the wait early (took %v)", time.Since(start))
}
}