http_runner.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // http_runner.go - metodos de medicion por HTTP directo (#976): alternativas
  2. // reales al runner Ookla para lineas donde speedtest.net mide mal (peering
  3. // pobre con los servidores cercanos, CGNAT, etc.).
  4. //
  5. // - cloudflare: speed.cloudflare.com, los endpoints publicos de su test
  6. // web (__down?bytes=N para bajada, __up para subida).
  7. // - librespeed: cualquier instancia LibreSpeed (autoalojada o publica);
  8. // serverURL es la URL base de la instancia y se usan sus endpoints
  9. // backend/garbage.php (bajada) y backend/empty.php (subida y ping).
  10. // - custom (#1001): endpoint HTTP libre; serverURL es la URL completa y
  11. // se usa tal cual para bajada (GET), subida (POST) y ping (GET).
  12. // Cualquier respuesta 2xx vale.
  13. //
  14. // Ambos miden con bucles de chunks acotados por tiempo y por bytes para no
  15. // castigar lineas lentas ni subestimar las rapidas.
  16. package speedtest
  17. import (
  18. "bytes"
  19. "context"
  20. "fmt"
  21. "io"
  22. "net/http"
  23. "net/url"
  24. "strings"
  25. "time"
  26. )
  27. // Proveedores soportados en settings.speedtest.provider (#976). "" equivale
  28. // a ProviderOokla (instalaciones anteriores sin la clave kv).
  29. const (
  30. ProviderOokla = "ookla" // speedtest.net via showwin/speedtest-go (default)
  31. ProviderCloudflare = "cloudflare" // speed.cloudflare.com por HTTP directo
  32. ProviderLibrespeed = "librespeed" // instancia LibreSpeed (serverURL = base)
  33. ProviderCustom = "custom" // endpoint HTTP libre (#1001): serverURL es la URL completa
  34. ProviderNDT = "ndt" // M-Lab NDT (#1037): locate automático, serverURL = FQDN opcional
  35. )
  36. func validProvider(v string) bool {
  37. return v == ProviderOokla || v == ProviderCloudflare || v == ProviderLibrespeed || v == ProviderCustom || v == ProviderNDT
  38. }
  39. // Limites de la medicion HTTP: al menos minDur midiendo (precision en
  40. // lineas rapidas) y como mucho maxBytes (techo en lineas lentas; el ctx del
  41. // scheduler -3 min- sigue siendo la ultima palabra).
  42. const (
  43. httpDownMinDur = 4 * time.Second
  44. httpDownMaxBytes = 128 << 20 // 128 MiB
  45. httpUpMinDur = 3 * time.Second
  46. httpUpMaxBytes = 64 << 20 // 64 MiB
  47. httpDownChunk = 8 << 20 // 8 MiB por peticion de bajada
  48. httpUpChunk = 4 << 20 // 4 MiB por peticion de subida
  49. httpPings = 5
  50. )
  51. // statusOK valida la respuesta del endpoint: los proveedores conocidos
  52. // exigen 200 exacto; custom acepta cualquier 2xx (endpoint libre, #1001).
  53. func statusOK(provider string, code int) bool {
  54. if provider == ProviderCustom {
  55. return code >= 200 && code < 300
  56. }
  57. return code == http.StatusOK
  58. }
  59. // HTTPRunner ejecuta el test contra endpoints HTTP directos. Cumple la
  60. // interfaz Runner: para cloudflare el serverURL se ignora (endpoints
  61. // fijos); para librespeed es la URL base de la instancia; para custom es
  62. // la URL completa del endpoint.
  63. type HTTPRunner struct {
  64. Provider string
  65. // DownURL/UpURL/PingURL pisan los endpoints por defecto (tests con
  66. // httptest); "" = los del proveedor.
  67. DownURL string
  68. UpURL string
  69. PingURL string
  70. // Client opcional (tests); nil = uno con timeouts razonables.
  71. Client *http.Client
  72. }
  73. func (r HTTPRunner) httpClient() *http.Client {
  74. if r.Client != nil {
  75. return r.Client
  76. }
  77. return &http.Client{Timeout: 60 * time.Second}
  78. }
  79. // endpoints resuelve las URLs de bajada, subida y ping del proveedor.
  80. func (r HTTPRunner) endpoints(serverURL string) (down, up, ping string, err error) {
  81. switch r.Provider {
  82. case ProviderCloudflare:
  83. down, up, ping = "https://speed.cloudflare.com/__down", "https://speed.cloudflare.com/__up", "https://speed.cloudflare.com/__down?bytes=0"
  84. case ProviderLibrespeed:
  85. base := strings.TrimRight(strings.TrimSpace(serverURL), "/")
  86. if base == "" {
  87. return "", "", "", fmt.Errorf("librespeed exige la URL base de la instancia")
  88. }
  89. u, perr := url.Parse(base)
  90. if perr != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
  91. return "", "", "", fmt.Errorf("URL de instancia librespeed invalida: %q", serverURL)
  92. }
  93. down, up, ping = base+"/backend/garbage.php", base+"/backend/empty.php", base+"/backend/empty.php"
  94. case ProviderCustom:
  95. // #1001: endpoint libre. La URL dada se usa TAL CUAL para bajada
  96. // (GET), subida (POST) y ping (GET): el endpoint debe aceptar ambos
  97. // metodos (estilo backend/empty.php de LibreSpeed o __down/__up de
  98. // Cloudflare). Cualquier 2xx vale: no imponemos el contrato exacto
  99. // de un proveedor concreto.
  100. u := strings.TrimSpace(serverURL)
  101. if u == "" {
  102. return "", "", "", fmt.Errorf("custom exige la URL del endpoint de medicion")
  103. }
  104. parsed, perr := url.Parse(u)
  105. if perr != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
  106. return "", "", "", fmt.Errorf("URL de endpoint custom invalida: %q", serverURL)
  107. }
  108. down, up, ping = u, u, u
  109. default:
  110. return "", "", "", fmt.Errorf("proveedor HTTP desconocido %q", r.Provider)
  111. }
  112. if r.DownURL != "" {
  113. down = r.DownURL
  114. }
  115. if r.UpURL != "" {
  116. up = r.UpURL
  117. }
  118. if r.PingURL != "" {
  119. ping = r.PingURL
  120. }
  121. return down, up, ping, nil
  122. }
  123. // Run mide ping, bajada y subida contra los endpoints del proveedor.
  124. func (r HTTPRunner) Run(ctx context.Context, serverURL string) (Result, error) {
  125. down, up, ping, err := r.endpoints(serverURL)
  126. if err != nil {
  127. return Result{}, err
  128. }
  129. c := r.httpClient()
  130. // Ping: minimo de N peticiones ligeras (como el runner Ookla, ping antes
  131. // de las mediciones pesadas).
  132. var best time.Duration
  133. for i := 0; i < httpPings; i++ {
  134. start := time.Now()
  135. req, _ := http.NewRequestWithContext(ctx, http.MethodGet, ping, nil)
  136. resp, perr := c.Do(req)
  137. if perr != nil {
  138. return Result{}, fmt.Errorf("ping: %w", perr)
  139. }
  140. _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1024))
  141. resp.Body.Close()
  142. if !statusOK(r.Provider, resp.StatusCode) {
  143. return Result{}, fmt.Errorf("ping: HTTP %d", resp.StatusCode)
  144. }
  145. if d := time.Since(start); best == 0 || d < best {
  146. best = d
  147. }
  148. }
  149. downMbps, err := r.measureDown(ctx, c, down)
  150. if err != nil {
  151. return Result{}, fmt.Errorf("download: %w", err)
  152. }
  153. upMbps, err := r.measureUp(ctx, c, up)
  154. if err != nil {
  155. return Result{}, fmt.Errorf("upload: %w", err)
  156. }
  157. res := Result{
  158. TS: time.Now(),
  159. DownMbps: downMbps,
  160. UpMbps: upMbps,
  161. }
  162. pingMs := float64(best.Microseconds()) / 1000.0
  163. res.PingMs = &pingMs
  164. if u, uerr := url.Parse(down); uerr == nil {
  165. res.ServerName = u.Host
  166. res.ServerID = r.Provider
  167. }
  168. return res, nil
  169. }
  170. // measureDown descarga chunks hasta cumplir la duracion minima o el techo de
  171. // bytes. Cloudflare acota por query (?bytes=N); librespeed por ckSize
  172. // (bloques de 1 KiB, max 1 MiB por peticion).
  173. func (r HTTPRunner) measureDown(ctx context.Context, c *http.Client, downURL string) (float64, error) {
  174. var total int64
  175. start := time.Now()
  176. for total < httpDownMaxBytes {
  177. u := downURL
  178. switch r.Provider {
  179. case ProviderLibrespeed:
  180. u += "?ckSize=1024"
  181. case ProviderCustom:
  182. // #1001: la URL se usa tal cual, sin inventar parametros.
  183. default:
  184. if !strings.Contains(u, "bytes=") {
  185. u = u + "?bytes=" + fmt.Sprint(httpDownChunk)
  186. }
  187. }
  188. req, _ := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
  189. resp, err := c.Do(req)
  190. if err != nil {
  191. return 0, err
  192. }
  193. var n int64
  194. if r.Provider == ProviderCustom {
  195. // Techo por peticion: un endpoint con stream infinito no debe
  196. // bloquear el bucle (el ctx del scheduler sigue mandando).
  197. n, err = io.Copy(io.Discard, io.LimitReader(resp.Body, httpDownChunk))
  198. } else {
  199. n, err = io.Copy(io.Discard, resp.Body)
  200. }
  201. resp.Body.Close()
  202. if err != nil {
  203. return 0, err
  204. }
  205. if !statusOK(r.Provider, resp.StatusCode) {
  206. return 0, fmt.Errorf("HTTP %d", resp.StatusCode)
  207. }
  208. if n == 0 {
  209. return 0, fmt.Errorf("endpoint de bajada devolvio 0 bytes")
  210. }
  211. total += n
  212. if time.Since(start) >= httpDownMinDur {
  213. break
  214. }
  215. }
  216. return mbps(total, time.Since(start)), nil
  217. }
  218. // measureUp sube chunks de ceros hasta cumplir la duracion minima o el
  219. // techo. Los cuerpos se reutilizan de un buffer unico (sin allocs por chunk).
  220. func (r HTTPRunner) measureUp(ctx context.Context, c *http.Client, upURL string) (float64, error) {
  221. chunk := make([]byte, httpUpChunk)
  222. var total int64
  223. start := time.Now()
  224. for total < httpUpMaxBytes {
  225. req, _ := http.NewRequestWithContext(ctx, http.MethodPost, upURL, bytes.NewReader(chunk))
  226. req.ContentLength = int64(len(chunk))
  227. req.Header.Set("Content-Type", "application/octet-stream")
  228. resp, err := c.Do(req)
  229. if err != nil {
  230. return 0, err
  231. }
  232. _, _ = io.Copy(io.Discard, resp.Body)
  233. resp.Body.Close()
  234. if !statusOK(r.Provider, resp.StatusCode) {
  235. return 0, fmt.Errorf("HTTP %d", resp.StatusCode)
  236. }
  237. total += int64(len(chunk))
  238. if time.Since(start) >= httpUpMinDur {
  239. break
  240. }
  241. }
  242. return mbps(total, time.Since(start)), nil
  243. }
  244. func mbps(n int64, d time.Duration) float64 {
  245. if d <= 0 {
  246. return 0
  247. }
  248. return float64(n) * 8 / d.Seconds() / 1e6
  249. }