package relay import ( "fmt" "net" "strings" "sync" "testing" "time" "git.smesh.lol/torly/pkg/tinyspawn" ) // These tests are the measuring stick for the shutdown invariant: every domain // must reach its breaker, and a domain that does not is named rather than // silently abandoned. The load tests that exercise individual domains live with // the change that fixes them. // withShortDeadline lowers the shutdown deadline for one test. func withShortDeadline(t *testing.T, d time.Duration) { t.Helper() old := shutdownDeadline shutdownDeadline = d t.Cleanup(func() { shutdownDeadline = old }) } // TestCloseNamesHungDomain: a domain that ignores its breaker must be reported // by name. This is what makes every later shutdown assertion meaningful. func TestCloseNamesHungDomain(t *testing.T) { withShortDeadline(t, 50*time.Millisecond) block := make(chan struct{}) tree := &Tree{stop: tinyspawn.NewBreaker()} tree.add("hung", tinyspawn.Spawn( func(_ struct{}, c struct{ Block <-chan struct{} }) { <-c.Block }, struct{}{}, struct{ Block <-chan struct{} }{Block: block}, )) defer close(block) start := time.Now() hung := tree.Close() elapsed := time.Since(start) if len(hung) != 1 || hung[0] != "hung" { t.Fatalf("Close reported %v, want [hung]", hung) } if elapsed > 2*time.Second { t.Fatalf("Close took %s with a 50ms deadline", elapsed) } } // TestCloseReportsNothingWhenEveryDomainStops: the common case must stay clean, // otherwise the signal is useless. func TestCloseReportsNothingWhenEveryDomainStops(t *testing.T) { withShortDeadline(t, time.Second) tree := &Tree{stop: tinyspawn.NewBreaker()} tree.add("quick", tinyspawn.Spawn( func(_ struct{}, _ struct{}) {}, struct{}{}, struct{}{}, )) if hung := tree.Close(); len(hung) != 0 { t.Fatalf("Close reported %v, want none", hung) } } // TestExitedNamesDomain: a domain that returns on its own must be named, so the // root can say which one died instead of "a relay domain exited". func TestExitedNamesDomain(t *testing.T) { withShortDeadline(t, time.Second) tree := &Tree{stop: tinyspawn.NewBreaker()} tree.add("quitter", tinyspawn.Spawn( func(_ struct{}, _ struct{}) {}, struct{}{}, struct{}{}, )) defer tree.Close() deadline := time.Now().Add(2 * time.Second) for { if name, dead := tree.Exited(); dead { if name != "quitter" { t.Fatalf("Exited named %q, want quitter", name) } return } if time.Now().After(deadline) { t.Fatal("Exited never saw the domain return") } time.Sleep(time.Millisecond) } } // TestTreeShutdownIdle: a real tree with no traffic must stop promptly. This is // the baseline the loaded cases are compared against. func TestTreeShutdownIdle(t *testing.T) { tr := startTestRelay(t, false) start := time.Now() hung := tr.tree.Close() elapsed := time.Since(start) if len(hung) != 0 { t.Fatalf("idle shutdown left domains running: %v", hung) } // The floor is the acceptor's 50ms poll slice plus the database's close. if elapsed > 150*time.Millisecond { t.Fatalf("idle shutdown took %s, want under 150ms", elapsed) } } // TestTreeShutdownUnderLoad: an end-to-end guard on shutdown latency while eight // clients publish and subscribe without reading their responses. The structural // half of the same invariant is TestDomainLoopsCheckTheBreaker. func TestTreeShutdownUnderLoad(t *testing.T) { tr := startTestRelay(t, false) // Two prebuilt frames per connection: one event, one subscription. Reusing // them keeps the client out of the measurement. ev := testEvent(t, 3, 1, nil, "load") eventFrame := append([]byte(`["EVENT",`), ev.AppendJSON(nil)...) eventFrame = append(eventFrame, ']') reqFrame := []byte(`["REQ","load",{"limit":50}]`) stop := make(chan struct{}) var wg sync.WaitGroup for i := 0; i < 8; i++ { c := dialWS(t, tr.addr) wg.Add(1) go func(c *testWS) { defer wg.Done() defer c.close() for n := 0; ; n++ { select { case <-stop: return default: } frame := eventFrame if n%2 == 1 { frame = reqFrame } if err := c.writeText(frame); err != nil { return } } }(c) } // Give the flood time to reach the domain loop before the breaker closes. time.Sleep(300 * time.Millisecond) start := time.Now() hung := tr.tree.Close() elapsed := time.Since(start) close(stop) wg.Wait() if len(hung) != 0 { t.Fatalf("shutdown under load left domains running: %v", hung) } if elapsed > 250*time.Millisecond { t.Fatalf("shutdown under load took %s, want under 250ms", elapsed) } } // TestTreeShutdownWithStalledClient: a peer that promises a body and never sends // it parks a reader in the body read. On this path the writer's teardown closes // the shared fd, which is what unblocks the reader; the test is an end-to-end // guard, not proof that the read wait is breaker-aware. The blocked-writer case // below is the one that needs the wait itself to notice. func TestTreeShutdownWithStalledClient(t *testing.T) { tr := startTestRelay(t, false) conn, err := net.Dial("tcp", tr.addr) if err != nil { t.Fatalf("dial: %v", err) } defer conn.Close() head := "POST /upload HTTP/1.1\r\nHost: " + tr.addr + "\r\nContent-Length: 1000\r\n\r\npartial" if _, err := conn.Write([]byte(head)); err != nil { t.Fatalf("write: %v", err) } // Let the reader consume the headers and park on the body. time.Sleep(100 * time.Millisecond) start := time.Now() hung := tr.tree.Close() elapsed := time.Since(start) if len(hung) != 0 { t.Fatalf("stalled client left domains running: %v", hung) } if elapsed > 400*time.Millisecond { t.Fatalf("shutdown with a stalled client took %s, want under 400ms", elapsed) } } // TestTreeShutdownWithBlockedWriter: a client that subscribes and never reads // blocks its writer in a socket write, while its reader sits idle. Neither side // can be unblocked by the other's teardown, so both waits have to notice the // breaker themselves, or shutdown waits out the write and read deadlines. func TestTreeShutdownWithBlockedWriter(t *testing.T) { tr := startTestRelay(t, false) // Enough stored data that one subscription response cannot fit in the socket // buffers, so the writer really blocks. pub := dialWS(t, tr.addr) content := strings.Repeat("x", 32<<10) for i := 0; i < 100; i++ { publish(t, pub, testEvent(t, byte(i+1), 1, nil, content)) } pub.close() c := dialWS(t, tr.addr) if err := c.writeText([]byte(`["REQ","big",{"limit":1000}]`)); err != nil { t.Fatalf("subscribe: %v", err) } // Let the writer fill the socket and block. time.Sleep(400 * time.Millisecond) start := time.Now() hung := tr.tree.Close() elapsed := time.Since(start) c.close() if len(hung) != 0 { t.Fatalf("blocked writer left domains running: %v", hung) } if elapsed > 500*time.Millisecond { t.Fatalf("shutdown with a blocked writer took %s, want under 500ms", elapsed) } } // TestTreeShutdownDuringQuery: a subscription result is delivered in chunks, so a // shutdown that lands between chunks must take effect there rather than after the // whole result. func TestTreeShutdownDuringQuery(t *testing.T) { tr := startTestRelay(t, false) // Enough events that one result spans several delivery turns. pub := dialWS(t, tr.addr) content := strings.Repeat("y", 2000) for i := 0; i < 200; i++ { publish(t, pub, testEvent(t, byte(i%200)+1, 1, nil, fmt.Sprintf("%s %d", content, i))) } pub.close() c := dialWS(t, tr.addr) if err := c.writeText([]byte(`["REQ","all",{"kinds":[1],"limit":1000}]`)); err != nil { t.Fatalf("subscribe: %v", err) } // Read a couple of frames so the reader is inside the result, then close. c.read() c.read() start := time.Now() hung := tr.tree.Close() elapsed := time.Since(start) c.close() if len(hung) != 0 { t.Fatalf("shutdown during a query left domains running: %v", hung) } if elapsed > 250*time.Millisecond { t.Fatalf("shutdown during a query took %s, want under 250ms", elapsed) } }