throttled_test.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package common
  20. import (
  21. "bytes"
  22. "fmt"
  23. "io/ioutil"
  24. "math"
  25. "net"
  26. "net/http"
  27. "testing"
  28. "time"
  29. "github.com/Psiphon-Inc/goarista/monotime"
  30. )
  31. const (
  32. serverAddress = "127.0.0.1:8081"
  33. testDataSize = 10 * 1024 * 1024 // 10 MB
  34. )
  35. func TestThrottledConn(t *testing.T) {
  36. run(t, RateLimits{
  37. ReadUnthrottledBytes: 0,
  38. ReadBytesPerSecond: 0,
  39. WriteUnthrottledBytes: 0,
  40. WriteBytesPerSecond: 0,
  41. })
  42. run(t, RateLimits{
  43. ReadUnthrottledBytes: 0,
  44. ReadBytesPerSecond: 5 * 1024 * 1024,
  45. WriteUnthrottledBytes: 0,
  46. WriteBytesPerSecond: 5 * 1024 * 1024,
  47. })
  48. run(t, RateLimits{
  49. ReadUnthrottledBytes: 0,
  50. ReadBytesPerSecond: 5 * 1024 * 1024,
  51. WriteUnthrottledBytes: 0,
  52. WriteBytesPerSecond: 1024 * 1024,
  53. })
  54. run(t, RateLimits{
  55. ReadUnthrottledBytes: 0,
  56. ReadBytesPerSecond: 2 * 1024 * 1024,
  57. WriteUnthrottledBytes: 0,
  58. WriteBytesPerSecond: 2 * 1024 * 1024,
  59. })
  60. run(t, RateLimits{
  61. ReadUnthrottledBytes: 0,
  62. ReadBytesPerSecond: 1024 * 1024,
  63. WriteUnthrottledBytes: 0,
  64. WriteBytesPerSecond: 1024 * 1024,
  65. })
  66. // This test takes > 1 min to run, so disabled for now
  67. /*
  68. run(t, RateLimits{
  69. ReadUnthrottledBytes: 0,
  70. ReadBytesPerSecond: 1024 * 1024 / 8,
  71. WriteUnthrottledBytes: 0,
  72. WriteBytesPerSecond: 1024 * 1024 / 8,
  73. })
  74. */
  75. }
  76. func run(t *testing.T, rateLimits RateLimits) {
  77. // Run a local HTTP server which serves large chunks of data
  78. go func() {
  79. handler := func(w http.ResponseWriter, r *http.Request) {
  80. _, _ = ioutil.ReadAll(r.Body)
  81. testData, _ := MakeSecureRandomBytes(testDataSize)
  82. w.Write(testData)
  83. }
  84. server := &http.Server{
  85. Addr: serverAddress,
  86. Handler: http.HandlerFunc(handler),
  87. }
  88. server.ListenAndServe()
  89. }()
  90. // TODO: properly synchronize with server startup
  91. time.Sleep(1 * time.Second)
  92. // Set up a HTTP client with a throttled connection
  93. throttledDial := func(network, addr string) (net.Conn, error) {
  94. conn, err := net.Dial(network, addr)
  95. if err != nil {
  96. return conn, err
  97. }
  98. return NewThrottledConn(conn, rateLimits), nil
  99. }
  100. client := &http.Client{
  101. Transport: &http.Transport{
  102. Dial: throttledDial,
  103. },
  104. }
  105. // Upload and download a large chunk of data, and time it
  106. testData, _ := MakeSecureRandomBytes(testDataSize)
  107. requestBody := bytes.NewReader(testData)
  108. startTime := monotime.Now()
  109. response, err := client.Post("http://"+serverAddress, "application/octet-stream", requestBody)
  110. if err == nil && response.StatusCode != http.StatusOK {
  111. response.Body.Close()
  112. err = fmt.Errorf("unexpected response code: %d", response.StatusCode)
  113. }
  114. if err != nil {
  115. t.Fatalf("request failed: %s", err)
  116. }
  117. defer response.Body.Close()
  118. // Test: elapsed upload time must reflect rate limit
  119. checkElapsedTime(t, testDataSize, rateLimits.WriteBytesPerSecond, monotime.Since(startTime))
  120. startTime = monotime.Now()
  121. body, err := ioutil.ReadAll(response.Body)
  122. if err != nil {
  123. t.Fatalf("read response failed: %s", err)
  124. }
  125. if len(body) != testDataSize {
  126. t.Fatalf("unexpected response size: %d", len(body))
  127. }
  128. // Test: elapsed download time must reflect rate limit
  129. checkElapsedTime(t, testDataSize, rateLimits.ReadBytesPerSecond, monotime.Since(startTime))
  130. }
  131. func checkElapsedTime(t *testing.T, dataSize int, rateLimit int64, duration time.Duration) {
  132. // With no rate limit, should finish under a couple seconds
  133. floorElapsedTime := 0 * time.Second
  134. ceilingElapsedTime := 2 * time.Second
  135. if rateLimit != 0 {
  136. // With rate limit, should finish within a couple seconds or so of data size / bytes-per-second;
  137. // won't be exact due to request overhead and approximations in "ratelimit" package
  138. expectedElapsedTime := float64(testDataSize) / float64(rateLimit)
  139. floorElapsedTime = time.Duration(int64(math.Floor(expectedElapsedTime))) * time.Second
  140. floorElapsedTime -= 1500 * time.Millisecond
  141. if floorElapsedTime < 0 {
  142. floorElapsedTime = 0
  143. }
  144. ceilingElapsedTime = time.Duration(int64(math.Ceil(expectedElapsedTime))) * time.Second
  145. ceilingElapsedTime += 1500 * time.Millisecond
  146. }
  147. t.Logf(
  148. "\ndata size: %d\nrate limit: %d\nelapsed time: %s\nexpected time: [%s,%s]\n\n",
  149. dataSize,
  150. rateLimit,
  151. duration,
  152. floorElapsedTime,
  153. ceilingElapsedTime)
  154. if duration < floorElapsedTime {
  155. t.Errorf("unexpected duration: %s < %s", duration, floorElapsedTime)
  156. }
  157. if duration > ceilingElapsedTime {
  158. t.Errorf("unexpected duration: %s > %s", duration, ceilingElapsedTime)
  159. }
  160. }