package pickupclient
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
)
// flaky answers by path: /api/v1/version and everything else, each with a
// script of per-hit behaviours ("drop" closes the connection after the
// request was read; a number is a status; "" is 200).
type flaky struct {
srv *httptest.Server
mu sync.Mutex
hits map[string]int
script func(r *http.Request, n int) (drop bool, status int, retryAfter string, body string)
sleeps []time.Duration
version string
}
func newFlaky(t *testing.T, script func(r *http.Request, n int) (bool, int, string, string)) *flaky {
f := &flaky{hits: map[string]int{}, script: script}
f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
f.mu.Lock()
f.hits[r.URL.Path]++
n := f.hits[r.URL.Path]
f.mu.Unlock()
drop, status, ra, body := script(r, n)
if drop {
c, _, _ := w.(http.Hijacker).Hijack()
c.Close()
return
}
if ra != "" {
w.Header().Set("Retry-After", ra)
}
if status == 0 {
status = 200
}
w.WriteHeader(status)
io.WriteString(w, body)
}))
t.Cleanup(f.srv.Close)
return f
}
func (f *flaky) run(t *testing.T, args ...string) (int, map[string]any, string) {
var out, errw bytes.Buffer
st := &fakeStore{}
st.Put(strings.TrimPrefix(f.srv.URL, "http://"), Record{Token: apiTestToken, Account: "alex"})
e := loginEnv(t, &out, &errw, st)
e.Client = nil
e.Sleep = func(_ context.Context, d time.Duration) error { f.sleeps = append(f.sleeps, d); return nil }
code := API(context.Background(), append([]string{"--host", f.srv.URL, "--json"}, args...), e)
var j map[string]any
_ = json.Unmarshal(out.Bytes(), &j)
return code, j, errw.String()
}
func (f *flaky) count(path string) int {
f.mu.Lock()
defer f.mu.Unlock()
return f.hits[path]
}
const tPath = "/api/v1/r/x/ticket/1"
func TestRetryGetRecoversAfterDroppedConnections(t *testing.T) {
f := newFlaky(t, func(r *http.Request, n int) (bool, int, string, string) {
return n < 3, 200, "", `{"ok":true}`
})
code, j, errw := f.run(t, "GET", "/r/x/ticket/1")
if code != 0 || j["ok"] != true {
t.Errorf("FAIL: exit %d body %v", code, j)
}
if n := f.count(tPath); n != 3 {
t.Errorf("FAIL: %d requests, want 3", n)
}
if len(f.sleeps) != 2 || f.sleeps[0] != 2*time.Second || f.sleeps[1] != 5*time.Second {
t.Errorf("FAIL: backoff %v", f.sleeps)
}
if n := len(strings.Split(strings.TrimSpace(errw), "\n")); n != 2 {
t.Errorf("FAIL: %d retry lines on stderr, want 2", n)
}
if f.count("/api/v1/version") != 0 {
t.Errorf("FAIL: the version was asked for on a request that succeeded")
}
if !t.Failed() {
t.Log("ok")
}
}
func TestRetryGetGivesUpAfterThreeAndAsksVersionOnce(t *testing.T) {
f := newFlaky(t, func(r *http.Request, n int) (bool, int, string, string) {
return r.URL.Path == tPath, 200, "", `{"ready":true}`
})
code, j, _ := f.run(t, "GET", "/r/x/ticket/1")
if code != 1 || j["code"] != "unreachable" {
t.Errorf("FAIL: exit %d %v", code, j)
}
if n := f.count(tPath); n != 3 {
t.Errorf("FAIL: %d attempts, want 3", n)
}
if n := f.count("/api/v1/version"); n != 1 {
t.Errorf("FAIL: %d version calls, want 1", n)
}
if !t.Failed() {
t.Log("ok")
}
}
func TestRetryGetHonoursRetryAfterCappedAt30(t *testing.T) {
f := newFlaky(t, func(r *http.Request, n int) (bool, int, string, string) {
if n == 1 {
return false, 503, "7", ""
}
return false, 503, "99", ""
})
code, j, _ := f.run(t, "GET", "/r/x/ticket/1")
if code != 1 || j["code"] != "forge_busy" {
t.Errorf("FAIL: exit %d %v", code, j)
}
if n := f.count(tPath); n != 3 {
t.Errorf("FAIL: %d attempts, want 3", n)
}
if len(f.sleeps) != 2 || f.sleeps[0] != 7*time.Second || f.sleeps[1] != 30*time.Second {
t.Errorf("FAIL: waits %v", f.sleeps)
}
if f.count("/api/v1/version") != 0 {
t.Errorf("FAIL: version asked after an answered 503")
}
if !t.Failed() {
t.Log("ok")
}
}
func TestRetryNeverRepeatsAWrite(t *testing.T) {
for _, m := range []string{"POST", "PUT", "PATCH", "DELETE"} {
f := newFlaky(t, func(r *http.Request, n int) (bool, int, string, string) { return true, 0, "", "" })
code, j, errw := f.run(t, m, "/r/x/ticket/1", "-f", "a=b")
if code != 1 || j["code"] != "outcome_unknown" {
t.Errorf("FAIL: %s exit %d %v", m, code, j)
}
if n := f.count(tPath); n != 1 {
t.Errorf("FAIL: %s sent %d times", m, n)
}
if len(f.sleeps) != 0 || errw != "" {
t.Errorf("FAIL: %s retried: %v %q", m, f.sleeps, errw)
}
if f.count("/api/v1/version") != 0 {
t.Errorf("FAIL: %s asked the version on an unknown outcome", m)
}
next, _ := j["next"].(map[string]any)
if next["cmd"] != "quarry api GET /r/x/ticket/1" {
t.Errorf("FAIL: %s next %v", m, j["next"])
}
}
if !t.Failed() {
t.Log("ok")
}
}
func TestRetryWriteRefusedBeforeSendingIsPlainUnreachable(t *testing.T) {
f := newFlaky(t, func(r *http.Request, n int) (bool, int, string, string) { return false, 0, "", "" })
f.srv.Close()
code, j, _ := f.run(t, "POST", "/r/x/ticket/1", "-f", "a=b")
if code != 1 || j["code"] != "unreachable" {
t.Errorf("FAIL: exit %d %v", code, j)
}
if len(f.sleeps) != 0 {
t.Errorf("FAIL: a write was retried: %v", f.sleeps)
}
if !t.Failed() {
t.Log("ok")
}
}
func TestRetryWriteGets503AsBusyWithoutRepeating(t *testing.T) {
f := newFlaky(t, func(r *http.Request, n int) (bool, int, string, string) { return false, 503, "12", "" })
code, j, _ := f.run(t, "POST", "/r/x/ticket/1", "-f", "a=b")
if code != 1 || j["code"] != "forge_busy" {
t.Errorf("FAIL: exit %d %v", code, j)
}
if n := f.count(tPath); n != 1 || len(f.sleeps) != 0 {
t.Errorf("FAIL: %d sends, sleeps %v", n, f.sleeps)
}
if !t.Failed() {
t.Log("ok")
}
}
func TestRetryNotReadyVersionMeansBusy(t *testing.T) {
f := newFlaky(t, func(r *http.Request, n int) (bool, int, string, string) {
if r.URL.Path == "/api/v1/version" {
return false, 200, "", `{"version":"v1","ready":false}`
}
return true, 0, "", ""
})
code, j, _ := f.run(t, "GET", "/r/x/ticket/1")
if code != 1 || j["code"] != "forge_busy" {
t.Errorf("FAIL: exit %d %v", code, j)
}
if n := f.count("/api/v1/version"); n != 1 {
t.Errorf("FAIL: %d version calls, want 1", n)
}
if !t.Failed() {
t.Log("ok")
}
}