client.go165 lines, 4.6 KB
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "math/rand/v2" |
| 10 | "net/http" |
| 11 | "sync/atomic" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/google/uuid" |
| 15 | ) |
| 16 | |
| 17 | // A client calls our API the way a careful client should: every write has an |
| 18 | // idempotency key, and a write without a clear answer is sent again, with the |
| 19 | // same key, until it gets one. |
| 20 | type client struct { |
| 21 | base string |
| 22 | http *http.Client |
| 23 | retries atomic.Int64 // every extra try, of every request |
| 24 | } |
| 25 | |
| 26 | func newClient(base string) *client { |
| 27 | // A request with no answer after five seconds is lost: it may or may not |
| 28 | // have happened. Only a retry, with the same key, can find out which. |
| 29 | return &client{base: base, http: &http.Client{Timeout: 5 * time.Second}} |
| 30 | } |
| 31 | |
| 32 | // An apiError is an answer that isn't a success: its status, and our code. |
| 33 | type apiError struct { |
| 34 | Status int |
| 35 | Code string |
| 36 | } |
| 37 | |
| 38 | func (e *apiError) Error() string { |
| 39 | return fmt.Sprintf("%d %s", e.Status, e.Code) |
| 40 | } |
| 41 | |
| 42 | // final reports whether err is an answer that asking again won't change. |
| 43 | func final(err error) bool { |
| 44 | e, ok := errors.AsType[*apiError](err) |
| 45 | if !ok { |
| 46 | return err == nil // no answer at all: try again |
| 47 | } |
| 48 | switch { |
| 49 | case e.Status >= 500, e.Status == http.StatusTooManyRequests: |
| 50 | return false // our fault, or slow down: try again |
| 51 | case e.Code == "request_in_progress": |
| 52 | return false // the first try is still running |
| 53 | } |
| 54 | return true |
| 55 | } |
| 56 | |
| 57 | // A request is one call to the API: as whom, with which key, and what. |
| 58 | type request struct { |
| 59 | path string |
| 60 | token string |
| 61 | key string |
| 62 | body any |
| 63 | } |
| 64 | |
| 65 | // post sends r once, and decodes a successful answer into out. replayed says |
| 66 | // whether the API answered from its record of an earlier try. |
| 67 | func (c *client) post(ctx context.Context, r request, out any) (replayed bool, err error) { |
| 68 | body, err := json.Marshal(r.body) |
| 69 | if err != nil { |
| 70 | return false, err |
| 71 | } |
| 72 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.base+r.path, bytes.NewReader(body)) |
| 73 | if err != nil { |
| 74 | return false, err |
| 75 | } |
| 76 | req.Header.Set("Content-Type", "application/json") |
| 77 | if r.token != "" { |
| 78 | req.Header.Set("Authorization", "Bearer "+r.token) |
| 79 | } |
| 80 | if r.key != "" { |
| 81 | req.Header.Set("Idempotency-Key", r.key) |
| 82 | } |
| 83 | resp, err := c.http.Do(req) |
| 84 | if err != nil { |
| 85 | return false, err |
| 86 | } |
| 87 | defer resp.Body.Close() |
| 88 | if resp.StatusCode >= 300 { |
| 89 | var e struct { |
| 90 | Error struct{ Code string } `json:"error"` |
| 91 | } |
| 92 | _ = json.NewDecoder(resp.Body).Decode(&e) // a proxy's error may have no body |
| 93 | return false, &apiError{resp.StatusCode, e.Error.Code} |
| 94 | } |
| 95 | return resp.Header.Get("Idempotent-Replayed") == "true", json.NewDecoder(resp.Body).Decode(out) |
| 96 | } |
| 97 | |
| 98 | // send posts r until the answer is final, or ctx is done, always with the |
| 99 | // same key: the client's half of exactly once. |
| 100 | func (c *client) send(ctx context.Context, r request, out any) (replayed bool, err error) { |
| 101 | wait := 250 * time.Millisecond |
| 102 | for { |
| 103 | replayed, err = c.post(ctx, r, out) |
| 104 | if final(err) || ctx.Err() != nil { |
| 105 | return replayed, err |
| 106 | } |
| 107 | c.retries.Add(1) |
| 108 | // A random wait, up to a limit that doubles: clients that failed |
| 109 | // together don't all come back at the same moment. |
| 110 | select { |
| 111 | case <-ctx.Done(): |
| 112 | return false, err |
| 113 | case <-time.After(rand.N(wait)): |
| 114 | } |
| 115 | wait = min(2*wait, 5*time.Second) |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | // A customer is a user who signed in, and their wallet. |
| 120 | type customer struct { |
| 121 | token string |
| 122 | wallet uuid.UUID |
| 123 | } |
| 124 | |
| 125 | // signUp registers a user, signs in, opens a wallet in currency, and deposits |
| 126 | // amount into it, unless it's zero. |
| 127 | func (c *client) signUp(ctx context.Context, email, currency string, amount int64) (customer, error) { |
| 128 | creds := map[string]string{"email": email, "password": "correct horse battery staple"} |
| 129 | var login struct { |
| 130 | Token string `json:"access_token"` |
| 131 | } |
| 132 | var wallet struct { |
| 133 | ID uuid.UUID `json:"id"` |
| 134 | } |
| 135 | err := c.call(ctx, request{path: "/v1/auth/register", body: creds}, nil) |
| 136 | if err == nil { |
| 137 | err = c.call(ctx, request{path: "/v1/auth/login", body: creds}, &login) |
| 138 | } |
| 139 | if err == nil { |
| 140 | body := map[string]string{"currency": currency} |
| 141 | err = c.call(ctx, request{path: "/v1/wallets", token: login.Token, body: body}, &wallet) |
| 142 | } |
| 143 | if err == nil && amount > 0 { |
| 144 | err = c.call(ctx, request{ |
| 145 | path: "/v1/wallets/" + wallet.ID.String() + "/deposits", |
| 146 | token: login.Token, |
| 147 | body: map[string]any{"amount": amount, "currency": currency}, |
| 148 | }, nil) |
| 149 | } |
| 150 | if err != nil { |
| 151 | return customer{}, fmt.Errorf("sign up %s: %w", email, err) |
| 152 | } |
| 153 | return customer{token: login.Token, wallet: wallet.ID}, nil |
| 154 | } |
| 155 | |
| 156 | // call sends r with a new idempotency key, and decodes the answer into out, |
| 157 | // unless out is nil. |
| 158 | func (c *client) call(ctx context.Context, r request, out any) error { |
| 159 | if out == nil { |
| 160 | out = &struct{}{} |
| 161 | } |
| 162 | r.key = uuid.NewString() |
| 163 | _, err := c.send(ctx, r, out) |
| 164 | return err |
| 165 | } |