| 303 | } |
| 304 | |
| 305 | func (s) TestBufferBloat(t *testing.T) { |
| 306 | defer restoreHooks()() |
| 307 | |
| 308 | // Infinitely fast CPU: time doesn't pass unless sleep is called. |
| 309 | tn := time.Unix(123, 0) |
| 310 | now = func() time.Time { return tn } |
| 311 | // Capture sleep times for checking later. |
| 312 | var sleepTimes []time.Duration |
| 313 | sleep = func(d time.Duration) { |
| 314 | sleepTimes = append(sleepTimes, d) |
| 315 | tn = tn.Add(d) |
| 316 | } |
| 317 | |
| 318 | wantSleeps := func(want ...time.Duration) error { |
| 319 | if !reflect.DeepEqual(want, sleepTimes) { |
| 320 | return fmt.Errorf("sleepTimes = %v; want %v", sleepTimes, want) |
| 321 | } |
| 322 | sleepTimes = nil |
| 323 | return nil |
| 324 | } |
| 325 | |
| 326 | n := &Network{Kbps: 8 /* 1KBps */, Latency: time.Second, MTU: 8} |
| 327 | bdpBytes := (n.Kbps * 1024 / 8) * int(n.Latency/time.Second) // 1024 |
| 328 | c, err := n.Conn(bufConn{&bytes.Buffer{}}) |
| 329 | if err != nil { |
| 330 | t.Fatalf("Unexpected error creating connection: %v", err) |
| 331 | } |
| 332 | wantSleeps(n.Latency) // Connection creation delay. |
| 333 | |
| 334 | write := func(n int, sleeps ...time.Duration) { |
| 335 | if wt, err := c.Write(make([]byte, n)); err != nil || wt != n { |
| 336 | t.Fatalf("c.Write(<%v bytes>) = %v, %v; want %v, nil", n, wt, err, n) |
| 337 | } |
| 338 | if err := wantSleeps(sleeps...); err != nil { |
| 339 | t.Fatalf("After writing %v bytes: %v", n, err) |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | read := func(n int, sleeps ...time.Duration) { |
| 344 | if rd, err := c.Read(make([]byte, n)); err != nil || rd != n { |
| 345 | t.Fatalf("c.Read(_) = %v, %v; want %v, nil", rd, err, n) |
| 346 | } |
| 347 | if err := wantSleeps(sleeps...); err != nil { |
| 348 | t.Fatalf("After reading %v bytes: %v", n, err) |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | write(8) // No reads and buffer not full, so no sleeps yet. |
| 353 | read(8, time.Second+n.pktTime(8)) |
| 354 | |
| 355 | write(bdpBytes) // Fill the buffer. |
| 356 | write(1) // We can send one extra packet even when the buffer is full. |
| 357 | write(n.MTU, n.pktTime(1)) // Make sure we sleep to clear the previous write. |
| 358 | write(1, n.pktTime(n.MTU)) |
| 359 | write(n.MTU+1, n.pktTime(1), n.pktTime(n.MTU)) |
| 360 | |
| 361 | tn = tn.Add(10 * time.Second) // Wait long enough for the buffer to clear. |
| 362 | write(bdpBytes) // No sleeps required. |