throttled_test.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. )
  30. const (
  31. serverAddress = "127.0.0.1:8081"
  32. testDataSize = 10 * 1024 * 1024 // 10 MB
  33. )
  34. func TestThrottledConnRates(t *testing.T) {
  35. runRateLimitsTest(t, RateLimits{
  36. ReadUnthrottledBytes: 0,
  37. ReadBytesPerSecond: 0,
  38. WriteUnthrottledBytes: 0,
  39. WriteBytesPerSecond: 0,
  40. })
  41. runRateLimitsTest(t, RateLimits{
  42. ReadUnthrottledBytes: 0,
  43. ReadBytesPerSecond: 5 * 1024 * 1024,
  44. WriteUnthrottledBytes: 0,
  45. WriteBytesPerSecond: 5 * 1024 * 1024,
  46. })
  47. runRateLimitsTest(t, RateLimits{
  48. ReadUnthrottledBytes: 0,
  49. ReadBytesPerSecond: 5 * 1024 * 1024,
  50. WriteUnthrottledBytes: 0,
  51. WriteBytesPerSecond: 1024 * 1024,
  52. })
  53. runRateLimitsTest(t, RateLimits{
  54. ReadUnthrottledBytes: 0,
  55. ReadBytesPerSecond: 2 * 1024 * 1024,
  56. WriteUnthrottledBytes: 0,
  57. WriteBytesPerSecond: 2 * 1024 * 1024,
  58. })
  59. runRateLimitsTest(t, RateLimits{
  60. ReadUnthrottledBytes: 0,
  61. ReadBytesPerSecond: 1024 * 1024,
  62. WriteUnthrottledBytes: 0,
  63. WriteBytesPerSecond: 1024 * 1024,
  64. })
  65. // This test takes > 1 min to run, so disabled for now
  66. /*
  67. runRateLimitsTest(t, RateLimits{
  68. ReadUnthrottledBytes: 0,
  69. ReadBytesPerSecond: 1024 * 1024 / 8,
  70. WriteUnthrottledBytes: 0,
  71. WriteBytesPerSecond: 1024 * 1024 / 8,
  72. })
  73. */
  74. }
  75. func runRateLimitsTest(t *testing.T, rateLimits RateLimits) {
  76. // Run a local HTTP server which serves large chunks of data
  77. go func() {
  78. handler := func(w http.ResponseWriter, r *http.Request) {
  79. _, _ = ioutil.ReadAll(r.Body)
  80. testData, _ := MakeSecureRandomBytes(testDataSize)
  81. w.Write(testData)
  82. }
  83. server := &http.Server{
  84. Addr: serverAddress,
  85. Handler: http.HandlerFunc(handler),
  86. }
  87. server.ListenAndServe()
  88. }()
  89. // TODO: properly synchronize with server startup
  90. time.Sleep(1 * time.Second)
  91. // Set up a HTTP client with a throttled connection
  92. throttledDial := func(network, addr string) (net.Conn, error) {
  93. conn, err := net.Dial(network, addr)
  94. if err != nil {
  95. return conn, err
  96. }
  97. return NewThrottledConn(conn, rateLimits), nil
  98. }
  99. client := &http.Client{
  100. Transport: &http.Transport{
  101. Dial: throttledDial,
  102. },
  103. }
  104. // Upload and download a large chunk of data, and time it
  105. testData, _ := MakeSecureRandomBytes(testDataSize)
  106. requestBody := bytes.NewReader(testData)
  107. startTime := time.Now()
  108. response, err := client.Post("http://"+serverAddress, "application/octet-stream", requestBody)
  109. if err == nil && response.StatusCode != http.StatusOK {
  110. response.Body.Close()
  111. err = fmt.Errorf("unexpected response code: %d", response.StatusCode)
  112. }
  113. if err != nil {
  114. t.Fatalf("request failed: %s", err)
  115. }
  116. defer response.Body.Close()
  117. // Test: elapsed upload time must reflect rate limit
  118. checkElapsedTime(t, testDataSize, rateLimits.WriteBytesPerSecond, time.Since(startTime))
  119. startTime = time.Now()
  120. body, err := ioutil.ReadAll(response.Body)
  121. if err != nil {
  122. t.Fatalf("read response failed: %s", err)
  123. }
  124. if len(body) != testDataSize {
  125. t.Fatalf("unexpected response size: %d", len(body))
  126. }
  127. // Test: elapsed download time must reflect rate limit
  128. checkElapsedTime(t, testDataSize, rateLimits.ReadBytesPerSecond, time.Since(startTime))
  129. }
  130. func checkElapsedTime(t *testing.T, dataSize int, rateLimit int64, duration time.Duration) {
  131. // With no rate limit, should finish under a couple seconds
  132. floorElapsedTime := 0 * time.Second
  133. ceilingElapsedTime := 2 * time.Second
  134. if rateLimit != 0 {
  135. // With rate limit, should finish within a couple seconds or so of data size / bytes-per-second;
  136. // won't be exact due to request overhead and approximations in "ratelimit" package
  137. expectedElapsedTime := float64(testDataSize) / float64(rateLimit)
  138. floorElapsedTime = time.Duration(int64(math.Floor(expectedElapsedTime))) * time.Second
  139. floorElapsedTime -= 1500 * time.Millisecond
  140. if floorElapsedTime < 0 {
  141. floorElapsedTime = 0
  142. }
  143. ceilingElapsedTime = time.Duration(int64(math.Ceil(expectedElapsedTime))) * time.Second
  144. ceilingElapsedTime += 1500 * time.Millisecond
  145. }
  146. t.Logf(
  147. "\ndata size: %d\nrate limit: %d\nelapsed time: %s\nexpected time: [%s,%s]\n\n",
  148. dataSize,
  149. rateLimit,
  150. duration,
  151. floorElapsedTime,
  152. ceilingElapsedTime)
  153. if duration < floorElapsedTime {
  154. t.Errorf("unexpected duration: %s < %s", duration, floorElapsedTime)
  155. }
  156. if duration > ceilingElapsedTime {
  157. t.Errorf("unexpected duration: %s > %s", duration, ceilingElapsedTime)
  158. }
  159. }
  160. func TestThrottledConnClose(t *testing.T) {
  161. rateLimits := RateLimits{
  162. ReadBytesPerSecond: 1,
  163. WriteBytesPerSecond: 1,
  164. }
  165. n := 4
  166. b := make([]byte, n+1)
  167. throttledConn := NewThrottledConn(&testConn{}, rateLimits)
  168. now := time.Now()
  169. _, err := throttledConn.Read(b)
  170. elapsed := time.Since(now)
  171. if err != nil || elapsed < time.Duration(n)*time.Second {
  172. t.Errorf("unexpected interrupted read: %s, %v", elapsed, err)
  173. }
  174. now = time.Now()
  175. go func() {
  176. time.Sleep(500 * time.Millisecond)
  177. throttledConn.Close()
  178. }()
  179. _, err = throttledConn.Read(b)
  180. elapsed = time.Since(now)
  181. if elapsed > 1*time.Second {
  182. t.Errorf("unexpected uninterrupted read: %s, %v", elapsed, err)
  183. }
  184. throttledConn = NewThrottledConn(&testConn{}, rateLimits)
  185. now = time.Now()
  186. _, err = throttledConn.Write(b)
  187. elapsed = time.Since(now)
  188. if err != nil || elapsed < time.Duration(n)*time.Second {
  189. t.Errorf("unexpected interrupted write: %s, %v", elapsed, err)
  190. }
  191. now = time.Now()
  192. go func() {
  193. time.Sleep(500 * time.Millisecond)
  194. throttledConn.Close()
  195. }()
  196. _, err = throttledConn.Write(b)
  197. elapsed = time.Since(now)
  198. if elapsed > 1*time.Second {
  199. t.Errorf("unexpected uninterrupted write: %s, %v", elapsed, err)
  200. }
  201. }
  202. type testConn struct {
  203. }
  204. func (conn *testConn) Read(b []byte) (n int, err error) {
  205. return len(b), nil
  206. }
  207. func (conn *testConn) Write(b []byte) (n int, err error) {
  208. return len(b), nil
  209. }
  210. func (conn *testConn) Close() error {
  211. return nil
  212. }
  213. func (conn *testConn) LocalAddr() net.Addr {
  214. return nil
  215. }
  216. func (conn *testConn) RemoteAddr() net.Addr {
  217. return nil
  218. }
  219. func (conn *testConn) SetDeadline(t time.Time) error {
  220. return nil
  221. }
  222. func (conn *testConn) SetReadDeadline(t time.Time) error {
  223. return nil
  224. }
  225. func (conn *testConn) SetWriteDeadline(t time.Time) error {
  226. return nil
  227. }