Skip to content
quarry Artifact [a7dd680b1b]
Login

Artifact [a7dd680b1b]

Artifact a7dd680b1b2608f9be736f83e0966e30a766712d2888a082cdd1a4a6b33c4d80:


package pickupclient

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/http/httptrace"
	"net/url"
	"strconv"
	"strings"
	"time"

	"craftdesign.group/quarry/internal/nextstep"
)

// A forge restarting for a minute or two answers late or not at all. A
// read costs nothing to ask again, so it is asked again; a write may
// have been applied, so it never is: the person is told the outcome is
// unknown and which read settles it.
const (
	attemptTimeout  = time.Minute
	retryAttempts   = 3
	retryAfterMax   = 30 * time.Second
	busyDefaultWait = 10
	forgeBusyCode   = "forge_busy"
	unknownCode     = "outcome_unknown"
)

var retryBackoff = [...]time.Duration{2 * time.Second, 5 * time.Second}

type noRetryKey struct{}

func isSafeMethod(m string) bool { return m == "" || m == http.MethodGet || m == http.MethodHead }

// netFailure is a transport error that knows whether the request had been
// written to the connection when it failed.
type netFailure struct {
	err    error
	sent   bool
	method string
}

func (f *netFailure) Error() string { return f.err.Error() }
func (f *netFailure) Unwrap() error { return f.err }

// retryTransport gives each attempt its own timeout and asks a safe
// request again after a timeout, a lost connection or a 502, 503 or 504.
type retryTransport struct {
	base    http.RoundTripper
	e       *Env
	timeout time.Duration // per attempt; 0 for none
}

type cancelBody struct {
	io.ReadCloser
	cancel context.CancelFunc
}

func (b cancelBody) Close() error { err := b.ReadCloser.Close(); b.cancel(); return err }

func (t *retryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	safe := isSafeMethod(req.Method) && req.Context().Value(noRetryKey{}) == nil
	for attempt := 1; ; attempt++ {
		sent := false
		ctx := httptrace.WithClientTrace(req.Context(), &httptrace.ClientTrace{
			WroteRequest: func(httptrace.WroteRequestInfo) { sent = true },
		})
		cancel := context.CancelFunc(func() {})
		if t.timeout > 0 {
			ctx, cancel = context.WithTimeout(ctx, t.timeout)
		}
		resp, err := t.base.RoundTrip(req.Clone(ctx))
		var wait time.Duration
		failed := err != nil
		if failed {
			if req.Context().Err() != nil {
				cancel()
				return nil, err
			}
			err = &netFailure{err: err, sent: sent, method: req.Method}
		} else if sc := resp.StatusCode; sc != 502 && sc != 503 && sc != 504 {
			resp.Body = cancelBody{resp.Body, cancel}
			return resp, nil
		}
		if attempt < retryAttempts {
			wait = retryBackoff[attempt-1]
			if !failed {
				if s := retryAfter(resp); s > 0 {
					wait = time.Duration(s) * time.Second
				}
			}
			if wait > retryAfterMax {
				wait = retryAfterMax
			}
		}
		dl, hasDL := req.Context().Deadline()
		if !safe || wait == 0 || (hasDL && time.Until(dl) <= wait) {
			if failed {
				cancel()
				return nil, err
			}
			resp.Body = cancelBody{resp.Body, cancel}
			return resp, nil
		}
		if !failed {
			resp.Body.Close()
		}
		cancel()
		fmt.Fprintf(t.e.Stderr, "the forge did not answer; retrying in %d s (attempt %d of %d)\n", int((wait+time.Second-1)/time.Second), attempt+1, retryAttempts)
		if serr := t.e.Sleep(req.Context(), wait); serr != nil {
			return nil, serr
		}
	}
}

// retryAfter is the seconds a Retry-After header gives, 0 when absent.
func retryAfter(resp *http.Response) int {
	if n, err := strconv.Atoi(strings.TrimSpace(resp.Header.Get("Retry-After"))); err == nil && n > 0 {
		return n
	}
	return 0
}

// netRefuse is the refusal for a request that got no answer. read names the
// read that shows whether a write was applied. After a failure that is not
// an unknown write outcome it asks the forge's version once, to tell a forge
// that is still starting from one that is down.
func (e *Env) netRefuse(ctx context.Context, v voice, base *url.URL, err error, read string) int {
	var nf *netFailure
	method := ""
	if errors.As(err, &nf) {
		method = nf.method
	}
	if nf != nil && nf.sent && !isSafeMethod(method) {
		return v.refuse(1, unknownCode, "the forge did not answer after the request was sent, so it may or may not have applied it: "+show(err.Error()), false,
			&nextstep.Next{Say: "Read it back before sending it again.", Cmd: read})
	}
	if base != nil && ctx.Err() == nil && e.forgeStarting(ctx, base) {
		return v.busy(0)
	}
	msg := "the forge could not be reached: " + show(err.Error())
	if !isSafeMethod(method) {
		msg += "; nothing was sent, so it is safe to run again"
	}
	return v.refuse(1, "unreachable", msg, false, nil)
}

// forgeStarting is true when /api/v1/version answers ready:false.
func (e *Env) forgeStarting(ctx context.Context, base *url.URL) bool {
	ctx, cancel := context.WithTimeout(context.WithValue(ctx, noRetryKey{}, true), 5*time.Second)
	defer cancel()
	req, err := http.NewRequestWithContext(ctx, "GET", base.ResolveReference(&url.URL{Path: "/api/v1/version"}).String(), nil)
	if err != nil {
		return false
	}
	resp, err := e.Client.Do(req)
	if err != nil {
		return false
	}
	defer resp.Body.Close()
	var b struct {
		Ready *bool `json:"ready"`
	}
	return json.NewDecoder(io.LimitReader(resp.Body, pickupBodyMax)).Decode(&b) == nil && b.Ready != nil && !*b.Ready
}

// busy refuses with forge_busy; secs is the forge's Retry-After, 0 when it
// gave none.
func (v voice) busy(secs int) int {
	if secs <= 0 {
		secs = busyDefaultWait
	}
	return v.refuse(1, forgeBusyCode, fmt.Sprintf("the forge is busy or still starting; wait about %d s and run this again", secs), false,
		&nextstep.Next{Say: fmt.Sprintf("Try again in %d s.", secs)})
}