shutdown_test.go raw

   1  package relay
   2  
   3  import (
   4  	"fmt"
   5  	"net"
   6  	"strings"
   7  	"sync"
   8  	"testing"
   9  	"time"
  10  
  11  	"git.smesh.lol/torly/pkg/tinyspawn"
  12  )
  13  
  14  // These tests are the measuring stick for the shutdown invariant: every domain
  15  // must reach its breaker, and a domain that does not is named rather than
  16  // silently abandoned. The load tests that exercise individual domains live with
  17  // the change that fixes them.
  18  
  19  // withShortDeadline lowers the shutdown deadline for one test.
  20  func withShortDeadline(t *testing.T, d time.Duration) {
  21  	t.Helper()
  22  	old := shutdownDeadline
  23  	shutdownDeadline = d
  24  	t.Cleanup(func() { shutdownDeadline = old })
  25  }
  26  
  27  // TestCloseNamesHungDomain: a domain that ignores its breaker must be reported
  28  // by name. This is what makes every later shutdown assertion meaningful.
  29  func TestCloseNamesHungDomain(t *testing.T) {
  30  	withShortDeadline(t, 50*time.Millisecond)
  31  
  32  	block := make(chan struct{})
  33  	tree := &Tree{stop: tinyspawn.NewBreaker()}
  34  	tree.add("hung", tinyspawn.Spawn(
  35  		func(_ struct{}, c struct{ Block <-chan struct{} }) { <-c.Block },
  36  		struct{}{},
  37  		struct{ Block <-chan struct{} }{Block: block},
  38  	))
  39  	defer close(block)
  40  
  41  	start := time.Now()
  42  	hung := tree.Close()
  43  	elapsed := time.Since(start)
  44  
  45  	if len(hung) != 1 || hung[0] != "hung" {
  46  		t.Fatalf("Close reported %v, want [hung]", hung)
  47  	}
  48  	if elapsed > 2*time.Second {
  49  		t.Fatalf("Close took %s with a 50ms deadline", elapsed)
  50  	}
  51  }
  52  
  53  // TestCloseReportsNothingWhenEveryDomainStops: the common case must stay clean,
  54  // otherwise the signal is useless.
  55  func TestCloseReportsNothingWhenEveryDomainStops(t *testing.T) {
  56  	withShortDeadline(t, time.Second)
  57  
  58  	tree := &Tree{stop: tinyspawn.NewBreaker()}
  59  	tree.add("quick", tinyspawn.Spawn(
  60  		func(_ struct{}, _ struct{}) {},
  61  		struct{}{},
  62  		struct{}{},
  63  	))
  64  	if hung := tree.Close(); len(hung) != 0 {
  65  		t.Fatalf("Close reported %v, want none", hung)
  66  	}
  67  }
  68  
  69  // TestExitedNamesDomain: a domain that returns on its own must be named, so the
  70  // root can say which one died instead of "a relay domain exited".
  71  func TestExitedNamesDomain(t *testing.T) {
  72  	withShortDeadline(t, time.Second)
  73  
  74  	tree := &Tree{stop: tinyspawn.NewBreaker()}
  75  	tree.add("quitter", tinyspawn.Spawn(
  76  		func(_ struct{}, _ struct{}) {},
  77  		struct{}{},
  78  		struct{}{},
  79  	))
  80  	defer tree.Close()
  81  
  82  	deadline := time.Now().Add(2 * time.Second)
  83  	for {
  84  		if name, dead := tree.Exited(); dead {
  85  			if name != "quitter" {
  86  				t.Fatalf("Exited named %q, want quitter", name)
  87  			}
  88  			return
  89  		}
  90  		if time.Now().After(deadline) {
  91  			t.Fatal("Exited never saw the domain return")
  92  		}
  93  		time.Sleep(time.Millisecond)
  94  	}
  95  }
  96  
  97  // TestTreeShutdownIdle: a real tree with no traffic must stop promptly. This is
  98  // the baseline the loaded cases are compared against.
  99  func TestTreeShutdownIdle(t *testing.T) {
 100  	tr := startTestRelay(t, false)
 101  
 102  	start := time.Now()
 103  	hung := tr.tree.Close()
 104  	elapsed := time.Since(start)
 105  
 106  	if len(hung) != 0 {
 107  		t.Fatalf("idle shutdown left domains running: %v", hung)
 108  	}
 109  	// The floor is the acceptor's 50ms poll slice plus the database's close.
 110  	if elapsed > 150*time.Millisecond {
 111  		t.Fatalf("idle shutdown took %s, want under 150ms", elapsed)
 112  	}
 113  }
 114  
 115  // TestTreeShutdownUnderLoad: an end-to-end guard on shutdown latency while eight
 116  // clients publish and subscribe without reading their responses. The structural
 117  // half of the same invariant is TestDomainLoopsCheckTheBreaker.
 118  func TestTreeShutdownUnderLoad(t *testing.T) {
 119  	tr := startTestRelay(t, false)
 120  
 121  	// Two prebuilt frames per connection: one event, one subscription. Reusing
 122  	// them keeps the client out of the measurement.
 123  	ev := testEvent(t, 3, 1, nil, "load")
 124  	eventFrame := append([]byte(`["EVENT",`), ev.AppendJSON(nil)...)
 125  	eventFrame = append(eventFrame, ']')
 126  	reqFrame := []byte(`["REQ","load",{"limit":50}]`)
 127  
 128  	stop := make(chan struct{})
 129  	var wg sync.WaitGroup
 130  	for i := 0; i < 8; i++ {
 131  		c := dialWS(t, tr.addr)
 132  		wg.Add(1)
 133  		go func(c *testWS) {
 134  			defer wg.Done()
 135  			defer c.close()
 136  			for n := 0; ; n++ {
 137  				select {
 138  				case <-stop:
 139  					return
 140  				default:
 141  				}
 142  				frame := eventFrame
 143  				if n%2 == 1 {
 144  					frame = reqFrame
 145  				}
 146  				if err := c.writeText(frame); err != nil {
 147  					return
 148  				}
 149  			}
 150  		}(c)
 151  	}
 152  	// Give the flood time to reach the domain loop before the breaker closes.
 153  	time.Sleep(300 * time.Millisecond)
 154  
 155  	start := time.Now()
 156  	hung := tr.tree.Close()
 157  	elapsed := time.Since(start)
 158  	close(stop)
 159  	wg.Wait()
 160  
 161  	if len(hung) != 0 {
 162  		t.Fatalf("shutdown under load left domains running: %v", hung)
 163  	}
 164  	if elapsed > 250*time.Millisecond {
 165  		t.Fatalf("shutdown under load took %s, want under 250ms", elapsed)
 166  	}
 167  }
 168  
 169  // TestTreeShutdownWithStalledClient: a peer that promises a body and never sends
 170  // it parks a reader in the body read. On this path the writer's teardown closes
 171  // the shared fd, which is what unblocks the reader; the test is an end-to-end
 172  // guard, not proof that the read wait is breaker-aware. The blocked-writer case
 173  // below is the one that needs the wait itself to notice.
 174  func TestTreeShutdownWithStalledClient(t *testing.T) {
 175  	tr := startTestRelay(t, false)
 176  
 177  	conn, err := net.Dial("tcp", tr.addr)
 178  	if err != nil {
 179  		t.Fatalf("dial: %v", err)
 180  	}
 181  	defer conn.Close()
 182  
 183  	head := "POST /upload HTTP/1.1\r\nHost: " + tr.addr +
 184  		"\r\nContent-Length: 1000\r\n\r\npartial"
 185  	if _, err := conn.Write([]byte(head)); err != nil {
 186  		t.Fatalf("write: %v", err)
 187  	}
 188  	// Let the reader consume the headers and park on the body.
 189  	time.Sleep(100 * time.Millisecond)
 190  
 191  	start := time.Now()
 192  	hung := tr.tree.Close()
 193  	elapsed := time.Since(start)
 194  
 195  	if len(hung) != 0 {
 196  		t.Fatalf("stalled client left domains running: %v", hung)
 197  	}
 198  	if elapsed > 400*time.Millisecond {
 199  		t.Fatalf("shutdown with a stalled client took %s, want under 400ms", elapsed)
 200  	}
 201  }
 202  
 203  // TestTreeShutdownWithBlockedWriter: a client that subscribes and never reads
 204  // blocks its writer in a socket write, while its reader sits idle. Neither side
 205  // can be unblocked by the other's teardown, so both waits have to notice the
 206  // breaker themselves, or shutdown waits out the write and read deadlines.
 207  func TestTreeShutdownWithBlockedWriter(t *testing.T) {
 208  	tr := startTestRelay(t, false)
 209  
 210  	// Enough stored data that one subscription response cannot fit in the socket
 211  	// buffers, so the writer really blocks.
 212  	pub := dialWS(t, tr.addr)
 213  	content := strings.Repeat("x", 32<<10)
 214  	for i := 0; i < 100; i++ {
 215  		publish(t, pub, testEvent(t, byte(i+1), 1, nil, content))
 216  	}
 217  	pub.close()
 218  
 219  	c := dialWS(t, tr.addr)
 220  	if err := c.writeText([]byte(`["REQ","big",{"limit":1000}]`)); err != nil {
 221  		t.Fatalf("subscribe: %v", err)
 222  	}
 223  	// Let the writer fill the socket and block.
 224  	time.Sleep(400 * time.Millisecond)
 225  
 226  	start := time.Now()
 227  	hung := tr.tree.Close()
 228  	elapsed := time.Since(start)
 229  	c.close()
 230  
 231  	if len(hung) != 0 {
 232  		t.Fatalf("blocked writer left domains running: %v", hung)
 233  	}
 234  	if elapsed > 500*time.Millisecond {
 235  		t.Fatalf("shutdown with a blocked writer took %s, want under 500ms", elapsed)
 236  	}
 237  }
 238  
 239  // TestTreeShutdownDuringQuery: a subscription result is delivered in chunks, so a
 240  // shutdown that lands between chunks must take effect there rather than after the
 241  // whole result.
 242  func TestTreeShutdownDuringQuery(t *testing.T) {
 243  	tr := startTestRelay(t, false)
 244  
 245  	// Enough events that one result spans several delivery turns.
 246  	pub := dialWS(t, tr.addr)
 247  	content := strings.Repeat("y", 2000)
 248  	for i := 0; i < 200; i++ {
 249  		publish(t, pub, testEvent(t, byte(i%200)+1, 1, nil, fmt.Sprintf("%s %d", content, i)))
 250  	}
 251  	pub.close()
 252  
 253  	c := dialWS(t, tr.addr)
 254  	if err := c.writeText([]byte(`["REQ","all",{"kinds":[1],"limit":1000}]`)); err != nil {
 255  		t.Fatalf("subscribe: %v", err)
 256  	}
 257  	// Read a couple of frames so the reader is inside the result, then close.
 258  	c.read()
 259  	c.read()
 260  
 261  	start := time.Now()
 262  	hung := tr.tree.Close()
 263  	elapsed := time.Since(start)
 264  	c.close()
 265  
 266  	if len(hung) != 0 {
 267  		t.Fatalf("shutdown during a query left domains running: %v", hung)
 268  	}
 269  	if elapsed > 250*time.Millisecond {
 270  		t.Fatalf("shutdown during a query took %s, want under 250ms", elapsed)
 271  	}
 272  }
 273