grpc.go313 lines, 9.0 KB
| 1 | package wallet |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | |
| 7 | walletv1 "github.com/fiston-user/payments/gen/wallet/v1" |
| 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/idempotency" |
| 11 | "github.com/google/uuid" |
| 12 | "github.com/jackc/pgx/v5" |
| 13 | "google.golang.org/grpc" |
| 14 | "google.golang.org/grpc/codes" |
| 15 | "google.golang.org/grpc/metadata" |
| 16 | "google.golang.org/protobuf/proto" |
| 17 | "google.golang.org/protobuf/types/known/timestamppb" |
| 18 | ) |
| 19 | |
| 20 | // GRPCServer serves the wallet API over gRPC, for our other services. Like |
| 21 | // Handler, it only translates: protobuf in, calls to the Service, protobuf |
| 22 | // out. The rules live in the Service, so both APIs share them. |
| 23 | type GRPCServer struct { |
| 24 | walletv1.UnimplementedWalletServiceServer |
| 25 | svc *Service |
| 26 | keys *idempotency.Store |
| 27 | } |
| 28 | |
| 29 | // NewGRPCServer returns a GRPCServer that serves svc. Transfers run once per |
| 30 | // idempotency key, and keys keeps those. |
| 31 | func NewGRPCServer(svc *Service, keys *idempotency.Store) *GRPCServer { |
| 32 | return &GRPCServer{svc: svc, keys: keys} |
| 33 | } |
| 34 | |
| 35 | // parseID reads a wallet ID from a request field. Unlike a URL that doesn't |
| 36 | // exist, a malformed ID in a typed request is an invalid argument. |
| 37 | func parseID(field, id string) (uuid.UUID, error) { |
| 38 | wid, err := uuid.Parse(id) |
| 39 | if err != nil { |
| 40 | var v apperr.ValidationError |
| 41 | v.Add(field, "must be a UUID") |
| 42 | return uuid.Nil, v.Err() |
| 43 | } |
| 44 | return wid, nil |
| 45 | } |
| 46 | |
| 47 | func toMoney(m Money) *walletv1.Money { |
| 48 | return &walletv1.Money{AmountMinor: m.Amount, Currency: m.Currency} |
| 49 | } |
| 50 | |
| 51 | func fromMoney(m *walletv1.Money) Money { |
| 52 | return Money{Amount: m.GetAmountMinor(), Currency: m.GetCurrency()} |
| 53 | } |
| 54 | |
| 55 | // CreateWallet opens a wallet for the caller. |
| 56 | func (s *GRPCServer) CreateWallet( |
| 57 | ctx context.Context, req *walletv1.CreateWalletRequest, |
| 58 | ) (*walletv1.CreateWalletResponse, error) { |
| 59 | acc, err := s.svc.CreateWallet(ctx, caller(ctx).String(), req.GetCurrency()) |
| 60 | if err != nil { |
| 61 | return nil, err |
| 62 | } |
| 63 | return &walletv1.CreateWalletResponse{Wallet: walletPB(acc)}, nil |
| 64 | } |
| 65 | |
| 66 | // GetWallet returns a wallet. |
| 67 | func (s *GRPCServer) GetWallet( |
| 68 | ctx context.Context, req *walletv1.GetWalletRequest, |
| 69 | ) (*walletv1.GetWalletResponse, error) { |
| 70 | id, err := parseID("wallet_id", req.GetWalletId()) |
| 71 | if err != nil { |
| 72 | return nil, err |
| 73 | } |
| 74 | acc, err := s.svc.As(caller(ctx)).Wallet(ctx, id) |
| 75 | if err != nil { |
| 76 | return nil, err |
| 77 | } |
| 78 | return &walletv1.GetWalletResponse{Wallet: walletPB(acc)}, nil |
| 79 | } |
| 80 | |
| 81 | // walletPB converts a wallet to its protobuf message. |
| 82 | func walletPB(acc Account) *walletv1.Wallet { |
| 83 | w := &walletv1.Wallet{ |
| 84 | Id: acc.ID.String(), |
| 85 | Currency: acc.Currency, |
| 86 | CreateTime: timestamppb.New(acc.CreatedAt), |
| 87 | Frozen: acc.Frozen, |
| 88 | } |
| 89 | if acc.OwnerID != nil { |
| 90 | w.OwnerId = acc.OwnerID.String() |
| 91 | } |
| 92 | return w |
| 93 | } |
| 94 | |
| 95 | // GetBalance returns a wallet's balance. |
| 96 | func (s *GRPCServer) GetBalance( |
| 97 | ctx context.Context, req *walletv1.GetBalanceRequest, |
| 98 | ) (*walletv1.GetBalanceResponse, error) { |
| 99 | id, err := parseID("wallet_id", req.GetWalletId()) |
| 100 | if err != nil { |
| 101 | return nil, err |
| 102 | } |
| 103 | b, err := s.svc.As(caller(ctx)).Balance(ctx, id) |
| 104 | if err != nil { |
| 105 | return nil, err |
| 106 | } |
| 107 | return &walletv1.GetBalanceResponse{ |
| 108 | WalletId: b.AccountID.String(), |
| 109 | Balance: toMoney(Money{Amount: b.Balance, Currency: b.Currency}), |
| 110 | }, nil |
| 111 | } |
| 112 | |
| 113 | // Deposit adds money to one of the caller's wallets, once per key. |
| 114 | func (s *GRPCServer) Deposit( |
| 115 | ctx context.Context, req *walletv1.DepositRequest, |
| 116 | ) (*walletv1.DepositResponse, error) { |
| 117 | id, err := parseID("wallet_id", req.GetWalletId()) |
| 118 | if err != nil { |
| 119 | return nil, err |
| 120 | } |
| 121 | amount := fromMoney(req.GetAmount()) |
| 122 | resp := &walletv1.DepositResponse{} |
| 123 | err = s.once(ctx, req.GetIdempotencyKey(), req, resp, func(svc *Service) (proto.Message, error) { |
| 124 | tx, err := svc.Deposit(ctx, id, amount) |
| 125 | if err != nil { |
| 126 | return nil, err |
| 127 | } |
| 128 | return &walletv1.DepositResponse{ |
| 129 | TransactionId: tx.ID.String(), |
| 130 | WalletId: id.String(), |
| 131 | Amount: toMoney(amount), |
| 132 | CreateTime: timestamppb.New(tx.CreatedAt), |
| 133 | }, nil |
| 134 | }) |
| 135 | if err != nil { |
| 136 | return nil, err |
| 137 | } |
| 138 | return resp, nil |
| 139 | } |
| 140 | |
| 141 | // Transfer moves money from one of the caller's wallets, once per key. |
| 142 | func (s *GRPCServer) Transfer( |
| 143 | ctx context.Context, req *walletv1.TransferRequest, |
| 144 | ) (*walletv1.TransferResponse, error) { |
| 145 | amount := fromMoney(req.GetAmount()) |
| 146 | resp := &walletv1.TransferResponse{} |
| 147 | err := s.once(ctx, req.GetIdempotencyKey(), req, resp, func(svc *Service) (proto.Message, error) { |
| 148 | tr, err := svc.Transfer(ctx, req.GetFromWalletId(), req.GetToWalletId(), amount) |
| 149 | if err != nil { |
| 150 | return nil, err |
| 151 | } |
| 152 | return &walletv1.TransferResponse{ |
| 153 | TransactionId: tr.TransactionID.String(), |
| 154 | FromWalletId: tr.From.String(), |
| 155 | ToWalletId: tr.To.String(), |
| 156 | Amount: toMoney(tr.Amount), |
| 157 | CreateTime: timestamppb.New(tr.CreatedAt), |
| 158 | }, nil |
| 159 | }) |
| 160 | if err != nil { |
| 161 | return nil, err |
| 162 | } |
| 163 | return resp, nil |
| 164 | } |
| 165 | |
| 166 | // once runs do once per idempotency key, as the caller, and decodes the stored |
| 167 | // response into out: a first answer and a replay take the same path. |
| 168 | func (s *GRPCServer) once( |
| 169 | ctx context.Context, value string, req, out proto.Message, |
| 170 | do func(svc *Service) (proto.Message, error), |
| 171 | ) error { |
| 172 | key, err := requestKey(ctx, value, req) |
| 173 | if err != nil { |
| 174 | return err |
| 175 | } |
| 176 | stored, err := s.keys.Run(ctx, key, func(tx pgx.Tx) (idempotency.Response, error) { |
| 177 | resp, err := do(s.svc.As(caller(ctx)).WithTx(tx)) |
| 178 | if err != nil { |
| 179 | return idempotency.Response{}, err |
| 180 | } |
| 181 | body, err := proto.Marshal(resp) |
| 182 | return idempotency.Response{Status: int(codes.OK), Body: body}, err |
| 183 | }) |
| 184 | if err != nil { |
| 185 | return err |
| 186 | } |
| 187 | if stored.Replayed { |
| 188 | grpc.SetHeader(ctx, metadata.Pairs("idempotent-replayed", "true")) |
| 189 | } |
| 190 | if err := proto.Unmarshal(stored.Body, out); err != nil { |
| 191 | return fmt.Errorf("decode stored response: %w", err) |
| 192 | } |
| 193 | return nil |
| 194 | } |
| 195 | |
| 196 | // requestKey is an RPC's idempotency key, scoped to the user who sent it, with |
| 197 | // a fingerprint of the method and the whole request. |
| 198 | func requestKey(ctx context.Context, value string, req proto.Message) (idempotency.Key, error) { |
| 199 | user, ok := authn.UserID(ctx) |
| 200 | if !ok { |
| 201 | return idempotency.Key{}, authn.ErrMissingToken |
| 202 | } |
| 203 | if value == "" || len(value) > 255 { |
| 204 | var v apperr.ValidationError |
| 205 | v.Add("idempotency_key", "must be 1 to 255 characters") |
| 206 | return idempotency.Key{}, v.Err() |
| 207 | } |
| 208 | // Deterministic: the same request always encodes to the same bytes. |
| 209 | body, err := proto.MarshalOptions{Deterministic: true}.Marshal(req) |
| 210 | if err != nil { |
| 211 | return idempotency.Key{}, err |
| 212 | } |
| 213 | method, _ := grpc.Method(ctx) |
| 214 | fp, err := idempotency.Fingerprint("gRPC", method, body) |
| 215 | if err != nil { |
| 216 | return idempotency.Key{}, err |
| 217 | } |
| 218 | return idempotency.Key{Scope: user.String(), Value: value, Fingerprint: fp}, nil |
| 219 | } |
| 220 | |
| 221 | // HoldServer serves the HoldService. It trusts the caller to say which user |
| 222 | // it acts for: users never reach it, and in episode 21, mTLS proves who calls. |
| 223 | type HoldServer struct { |
| 224 | walletv1.UnimplementedHoldServiceServer |
| 225 | svc *Service |
| 226 | } |
| 227 | |
| 228 | // NewHoldServer returns a HoldServer that serves svc. |
| 229 | func NewHoldServer(svc *Service) *HoldServer { |
| 230 | return &HoldServer{svc: svc} |
| 231 | } |
| 232 | |
| 233 | // Hold sets money aside from the owner's wallet. |
| 234 | func (s *HoldServer) Hold( |
| 235 | ctx context.Context, req *walletv1.HoldRequest, |
| 236 | ) (*walletv1.HoldResponse, error) { |
| 237 | id, err := parseID("hold_id", req.GetHoldId()) |
| 238 | if err != nil { |
| 239 | return nil, err |
| 240 | } |
| 241 | owner, err := parseID("owner_id", req.GetOwnerId()) |
| 242 | if err != nil { |
| 243 | return nil, err |
| 244 | } |
| 245 | wid, err := parseID("wallet_id", req.GetWalletId()) |
| 246 | if err != nil { |
| 247 | return nil, err |
| 248 | } |
| 249 | h, err := s.svc.As(owner).Hold(ctx, id, wid, fromMoney(req.GetAmount())) |
| 250 | if err != nil { |
| 251 | return nil, err |
| 252 | } |
| 253 | return &walletv1.HoldResponse{Hold: holdPB(h)}, nil |
| 254 | } |
| 255 | |
| 256 | // Capture pays a hold into another wallet. |
| 257 | func (s *HoldServer) Capture( |
| 258 | ctx context.Context, req *walletv1.CaptureRequest, |
| 259 | ) (*walletv1.CaptureResponse, error) { |
| 260 | id, err := parseID("hold_id", req.GetHoldId()) |
| 261 | if err != nil { |
| 262 | return nil, err |
| 263 | } |
| 264 | to, err := parseID("to_wallet_id", req.GetToWalletId()) |
| 265 | if err != nil { |
| 266 | return nil, err |
| 267 | } |
| 268 | h, err := s.svc.Capture(ctx, id, to) |
| 269 | if err != nil { |
| 270 | return nil, err |
| 271 | } |
| 272 | return &walletv1.CaptureResponse{Hold: holdPB(h)}, nil |
| 273 | } |
| 274 | |
| 275 | // Release gives a hold back to its wallet. |
| 276 | func (s *HoldServer) Release( |
| 277 | ctx context.Context, req *walletv1.ReleaseRequest, |
| 278 | ) (*walletv1.ReleaseResponse, error) { |
| 279 | id, err := parseID("hold_id", req.GetHoldId()) |
| 280 | if err != nil { |
| 281 | return nil, err |
| 282 | } |
| 283 | h, err := s.svc.Release(ctx, id) |
| 284 | if err != nil { |
| 285 | return nil, err |
| 286 | } |
| 287 | return &walletv1.ReleaseResponse{Hold: holdPB(h)}, nil |
| 288 | } |
| 289 | |
| 290 | // DescribeWallet returns anyone's wallet: the Service, as nobody in |
| 291 | // particular, sees them all. |
| 292 | func (s *HoldServer) DescribeWallet( |
| 293 | ctx context.Context, req *walletv1.DescribeWalletRequest, |
| 294 | ) (*walletv1.DescribeWalletResponse, error) { |
| 295 | id, err := parseID("wallet_id", req.GetWalletId()) |
| 296 | if err != nil { |
| 297 | return nil, err |
| 298 | } |
| 299 | acc, err := s.svc.Wallet(ctx, id) |
| 300 | if err != nil { |
| 301 | return nil, err |
| 302 | } |
| 303 | return &walletv1.DescribeWalletResponse{Wallet: walletPB(acc)}, nil |
| 304 | } |
| 305 | |
| 306 | func holdPB(h Hold) *walletv1.Hold { |
| 307 | return &walletv1.Hold{ |
| 308 | Id: h.ID.String(), |
| 309 | WalletId: h.WalletID.String(), |
| 310 | Amount: toMoney(Money{Amount: h.Amount, Currency: h.Currency}), |
| 311 | Status: string(h.Status), |
| 312 | } |
| 313 | } |