http.go160 lines, 4.7 KB
| 1 | package transfer |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "net/http" |
| 6 | "regexp" |
| 7 | |
| 8 | "github.com/fiston-user/payments/internal/platform/apperr" |
| 9 | "github.com/fiston-user/payments/internal/platform/authn" |
| 10 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 11 | "github.com/fiston-user/payments/internal/platform/idempotency" |
| 12 | "github.com/google/uuid" |
| 13 | ) |
| 14 | |
| 15 | // Handler serves the transfer API. It's asynchronous: a new transfer gets a |
| 16 | // 202 Accepted at once, and a URL to follow it. |
| 17 | type Handler struct { |
| 18 | store *Store |
| 19 | wake func() |
| 20 | } |
| 21 | |
| 22 | // NewHandler returns a Handler for store. |
| 23 | func NewHandler(store *Store, wake func()) *Handler { |
| 24 | return &Handler{store: store, wake: wake} |
| 25 | } |
| 26 | |
| 27 | // Register adds the transfer routes to mux. |
| 28 | func (h *Handler) Register(mux *http.ServeMux) { |
| 29 | mux.Handle("POST /v1/transfers", httpx.HandlerFunc(h.create)) |
| 30 | mux.Handle("GET /v1/transfers/{id}", httpx.HandlerFunc(h.get)) |
| 31 | } |
| 32 | |
| 33 | var currencyCode = regexp.MustCompile(`^[A-Z]{3}$`) |
| 34 | |
| 35 | // MaxAmount is the most one transfer can move, in minor units: the wallet's |
| 36 | // limit, a million dollars. Checked here, such a transfer fails at once, with |
| 37 | // a 422, instead of later, in its saga. |
| 38 | const MaxAmount = 100_000_000 |
| 39 | |
| 40 | func (h *Handler) create(w http.ResponseWriter, r *http.Request) error { |
| 41 | var req struct { |
| 42 | From string `json:"from"` |
| 43 | To string `json:"to"` |
| 44 | Amount int64 `json:"amount"` |
| 45 | Currency string `json:"currency"` |
| 46 | } |
| 47 | if err := httpx.DecodeJSON(w, r, &req); err != nil { |
| 48 | return err |
| 49 | } |
| 50 | key := r.Header.Get(idempotency.KeyHeader) |
| 51 | if key == "" || len(key) > 255 { |
| 52 | return idempotency.ErrKeyRequired |
| 53 | } |
| 54 | // Only what we can check alone: the rest is the wallet's call. |
| 55 | var v apperr.ValidationError |
| 56 | from, err := uuid.Parse(req.From) |
| 57 | if err != nil { |
| 58 | v.Add("from", "must be a wallet ID") |
| 59 | } |
| 60 | to, err := uuid.Parse(req.To) |
| 61 | if err != nil { |
| 62 | v.Add("to", "must be a wallet ID") |
| 63 | } else if to == from { |
| 64 | v.Add("to", "must be a different wallet") |
| 65 | } |
| 66 | switch { |
| 67 | case req.Amount <= 0: |
| 68 | v.Add("amount", "must be a positive number of minor units, like 1050 for 10.50") |
| 69 | case req.Amount > MaxAmount: |
| 70 | v.Add("amount", fmt.Sprintf("must be at most %d", MaxAmount)) |
| 71 | } |
| 72 | if !currencyCode.MatchString(req.Currency) { |
| 73 | v.Add("currency", "must be a three-letter ISO 4217 code, like USD") |
| 74 | } |
| 75 | if err := v.Err(); err != nil { |
| 76 | return err |
| 77 | } |
| 78 | user, _ := authn.UserID(r.Context()) |
| 79 | nt := NewTransfer{UserID: user, IdempotencyKey: key, FromWalletID: from, ToWalletID: to, |
| 80 | Amount: req.Amount, Currency: req.Currency} |
| 81 | t, created, err := h.store.Create(r.Context(), nt) |
| 82 | if err != nil { |
| 83 | return err |
| 84 | } |
| 85 | if !created { |
| 86 | // A retry: the same request gets the same transfer. |
| 87 | if t.From != from || t.To != to || t.Amount != req.Amount || t.Currency != req.Currency { |
| 88 | return idempotency.ErrKeyReused |
| 89 | } |
| 90 | w.Header().Set(idempotency.ReplayedHeader, "true") |
| 91 | } |
| 92 | w.Header().Set("Location", "/v1/transfers/"+t.ID.String()) |
| 93 | httpx.WriteJSON(w, r, http.StatusAccepted, t) |
| 94 | if created { |
| 95 | h.wake() |
| 96 | } |
| 97 | return nil |
| 98 | } |
| 99 | |
| 100 | func (h *Handler) get(w http.ResponseWriter, r *http.Request) error { |
| 101 | id, err := uuid.Parse(r.PathValue("id")) |
| 102 | if err != nil { |
| 103 | return ErrTransferNotFound |
| 104 | } |
| 105 | t, err := h.store.Get(r.Context(), id) |
| 106 | if err != nil { |
| 107 | return err |
| 108 | } |
| 109 | // Other people's transfers don't exist. |
| 110 | if user, _ := authn.UserID(r.Context()); t.UserID != user { |
| 111 | return ErrTransferNotFound |
| 112 | } |
| 113 | httpx.WriteJSON(w, r, http.StatusOK, t) |
| 114 | return nil |
| 115 | } |
| 116 | |
| 117 | // RegisterInternal adds the review API to mux, for our risk team's tools. |
| 118 | // The gateway never routes /internal/: only our ops tools can reach it, with |
| 119 | // their certificate, for a reviewer who signed in. |
| 120 | func (h *Handler) RegisterInternal(mux *http.ServeMux) { |
| 121 | mux.Handle("POST /internal/transfers/{id}/approve", httpx.HandlerFunc(h.review(true))) |
| 122 | mux.Handle("POST /internal/transfers/{id}/reject", httpx.HandlerFunc(h.review(false))) |
| 123 | } |
| 124 | |
| 125 | // review records a reviewer's verdict, and wakes the orchestrator to carry |
| 126 | // it out: the capture, or the release. The reviewer is whoever signed in: |
| 127 | // never a name in the body, which anyone could type. |
| 128 | func (h *Handler) review(approve bool) httpx.HandlerFunc { |
| 129 | return func(w http.ResponseWriter, r *http.Request) error { |
| 130 | var req struct { |
| 131 | Note string `json:"note"` |
| 132 | } |
| 133 | if err := httpx.DecodeJSON(w, r, &req); err != nil { |
| 134 | return err |
| 135 | } |
| 136 | var v apperr.ValidationError |
| 137 | if req.Note == "" { |
| 138 | v.Add("note", "is required: say why") |
| 139 | } |
| 140 | if err := v.Err(); err != nil { |
| 141 | return err |
| 142 | } |
| 143 | id, err := uuid.Parse(r.PathValue("id")) |
| 144 | if err != nil { |
| 145 | return ErrTransferNotFound |
| 146 | } |
| 147 | t, err := h.store.Get(r.Context(), id) |
| 148 | if err != nil { |
| 149 | return err |
| 150 | } |
| 151 | reviewer, _ := authn.UserID(r.Context()) |
| 152 | t, err = h.store.Review(r.Context(), t, Verdict{approve, reviewer.String(), req.Note}) |
| 153 | if err != nil { |
| 154 | return err |
| 155 | } |
| 156 | h.wake() |
| 157 | httpx.WriteJSON(w, r, http.StatusOK, t) |
| 158 | return nil |
| 159 | } |
| 160 | } |