idempotency.go93 lines, 3.0 KB
| 1 | // Package idempotency makes requests that move money safe to retry. Clients |
| 2 | // send a unique Idempotency-Key with each request. The first request with a |
| 3 | // key runs. A retry with the same key gets the first response back, byte for |
| 4 | // byte, instead of running again. |
| 5 | package idempotency |
| 6 | |
| 7 | import ( |
| 8 | "crypto/sha256" |
| 9 | "encoding/json" |
| 10 | "fmt" |
| 11 | "net/http" |
| 12 | |
| 13 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 14 | ) |
| 15 | |
| 16 | // The headers: the key a client sends, and the one that marks a replay. |
| 17 | const ( |
| 18 | KeyHeader = "Idempotency-Key" |
| 19 | ReplayedHeader = "Idempotent-Replayed" |
| 20 | ) |
| 21 | |
| 22 | // Errors for requests that can't run with the key they sent. |
| 23 | var ( |
| 24 | ErrKeyRequired = httpx.NewError(http.StatusBadRequest, "idempotency_key_required", |
| 25 | "requests that move money need an Idempotency-Key header, of 1 to 255 characters") |
| 26 | ErrKeyReused = httpx.NewError(http.StatusUnprocessableEntity, "idempotency_key_reused", |
| 27 | "this Idempotency-Key was already used for a different request") |
| 28 | ErrInProgress = httpx.NewError(http.StatusConflict, "request_in_progress", |
| 29 | "a request with this Idempotency-Key is still in progress, retry later") |
| 30 | ) |
| 31 | |
| 32 | // A Key names one operation: the key a client sent, the caller that sent it, |
| 33 | // and a fingerprint of the request it came with. |
| 34 | type Key struct { |
| 35 | Scope string |
| 36 | Value string |
| 37 | Fingerprint []byte |
| 38 | } |
| 39 | |
| 40 | // NewKey reads the Idempotency-Key header of r. scope is the caller, and req |
| 41 | // is the decoded request body, for the fingerprint. |
| 42 | func NewKey(r *http.Request, scope string, req any) (Key, error) { |
| 43 | value := r.Header.Get(KeyHeader) |
| 44 | if value == "" || len(value) > 255 { |
| 45 | return Key{}, ErrKeyRequired |
| 46 | } |
| 47 | fp, err := Fingerprint(r.Method, r.URL.Path, req) |
| 48 | if err != nil { |
| 49 | return Key{}, err |
| 50 | } |
| 51 | return Key{Scope: scope, Value: value, Fingerprint: fp}, nil |
| 52 | } |
| 53 | |
| 54 | // Fingerprint hashes a request's method, path and canonical body with SHA-256. |
| 55 | // The canonical body is req, the decoded body, encoded again: spaces and the |
| 56 | // order of fields don't change it, but any value does. |
| 57 | func Fingerprint(method, path string, req any) ([]byte, error) { |
| 58 | body, err := json.Marshal(req) |
| 59 | if err != nil { |
| 60 | return nil, fmt.Errorf("fingerprint: %w", err) |
| 61 | } |
| 62 | h := sha256.New() |
| 63 | fmt.Fprintf(h, "%s %s\n", method, path) |
| 64 | h.Write(body) |
| 65 | return h.Sum(nil), nil |
| 66 | } |
| 67 | |
| 68 | // Response is what we answered for a key. |
| 69 | type Response struct { |
| 70 | Status int |
| 71 | Body []byte |
| 72 | Replayed bool // sent before, and stored |
| 73 | } |
| 74 | |
| 75 | // JSON returns a response with v as its body, encoded as httpx.WriteJSON would. |
| 76 | func JSON(status int, v any) (Response, error) { |
| 77 | body, err := json.Marshal(v) |
| 78 | if err != nil { |
| 79 | return Response{}, fmt.Errorf("encode response: %w", err) |
| 80 | } |
| 81 | return Response{Status: status, Body: append(body, '\n')}, nil |
| 82 | } |
| 83 | |
| 84 | // Write sends the response. A replay says so in a header, and is otherwise |
| 85 | // exactly what the first request got. |
| 86 | func (resp Response) Write(w http.ResponseWriter) { |
| 87 | if resp.Replayed { |
| 88 | w.Header().Set(ReplayedHeader, "true") |
| 89 | } |
| 90 | w.Header().Set("Content-Type", "application/json") |
| 91 | w.WriteHeader(resp.Status) |
| 92 | w.Write(resp.Body) |
| 93 | } |