fixup! derp/derpserver: add per-connection receive rate limiting

This commit is contained in:
Mike O'Driscoll
2026-04-03 13:39:39 +00:00
parent e739b5e104
commit abdbf07268

View File

@@ -954,11 +954,16 @@ func BenchmarkHyperLogLogEstimate(b *testing.B) {
}
func TestPerClientRateLimit(t *testing.T) {
newServer := func(t *testing.T, bytesPerSec, burst int) func(t *testing.T) *derp.Client {
// newTestServer creates a DERP server and returns a client factory.
// If bytesPerSec > 0, sets the rate limit fields directly (bypassing the
// MaxPacketSize burst floor in SetPerClientRateLimit) so tests can use
// small burst values.
newTestServer := func(t *testing.T, bytesPerSec, burst int) func(t *testing.T) *derp.Client {
t.Helper()
s := New(key.NewNode(), logger.Discard)
if bytesPerSec > 0 {
s.SetPerClientRateLimit(bytesPerSec, burst)
s.perClientRecvBytesPerSec = bytesPerSec
s.perClientRecvBurst = burst
}
t.Cleanup(func() { s.Close() })
@@ -1034,16 +1039,20 @@ func TestPerClientRateLimit(t *testing.T) {
t.Run("throttled", func(t *testing.T) {
// Compare transfer time with and without rate limiting.
// This avoids flaky absolute time thresholds.
//
// numPkts must stay within the send queue depth (32) to avoid
// drops in the unlimited case where there's no backpressure.
// Burst is set below numPkts*pktSize so the limiter engages.
const pktSize = 1000
const numPkts = 128 // 128KB total, exceeds the 64KB effective burst
const numPkts = 20
unlimited := sendRecv(t, newServer(t, 0, 0), pktSize, numPkts)
limited := sendRecv(t, newServer(t, 100_000, 100_000), pktSize, numPkts)
unlimited := sendRecv(t, newTestServer(t, 0, 0), pktSize, numPkts)
// 50KB/s with 5KB burst: 20KB transfer takes ~300ms.
limited := sendRecv(t, newTestServer(t, 50_000, 5_000), pktSize, numPkts)
t.Logf("unlimited=%v, limited=%v (ratio=%.0fx)", unlimited, limited, float64(limited)/float64(unlimited))
// Rate-limited transfer should take at least 10x longer.
// In practice: ~280ms vs ~200µs (~1400x).
if limited < 10*unlimited {
t.Errorf("rate-limited transfer not slower enough: unlimited=%v, limited=%v", unlimited, limited)
}