wallet.go79 lines, 2.1 KB
| 1 | package transfer |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | |
| 6 | walletv1 "github.com/fiston-user/payments/gen/wallet/v1" |
| 7 | "google.golang.org/genproto/googleapis/rpc/errdetails" |
| 8 | "google.golang.org/grpc/codes" |
| 9 | "google.golang.org/grpc/status" |
| 10 | ) |
| 11 | |
| 12 | // Wallet is what the saga needs from the wallet service. Every step is |
| 13 | // idempotent: a transfer's hold ID is its own ID. |
| 14 | type Wallet interface { |
| 15 | Hold(ctx context.Context, t Transfer) error |
| 16 | Capture(ctx context.Context, t Transfer) error |
| 17 | Release(ctx context.Context, t Transfer) error |
| 18 | } |
| 19 | |
| 20 | // A Rejection is a step the wallet refused for good, like insufficient |
| 21 | // funds. Any other error might go away. |
| 22 | type Rejection struct { |
| 23 | Reason string |
| 24 | } |
| 25 | |
| 26 | func (r *Rejection) Error() string { |
| 27 | return "rejected: " + r.Reason |
| 28 | } |
| 29 | |
| 30 | // NewWallet returns the wallet service's HoldService, as a Wallet. |
| 31 | func NewWallet(client walletv1.HoldServiceClient) Wallet { |
| 32 | return holds{client} |
| 33 | } |
| 34 | |
| 35 | type holds struct { |
| 36 | client walletv1.HoldServiceClient |
| 37 | } |
| 38 | |
| 39 | func (h holds) Hold(ctx context.Context, t Transfer) error { |
| 40 | _, err := h.client.Hold(ctx, &walletv1.HoldRequest{ |
| 41 | HoldId: t.ID.String(), |
| 42 | OwnerId: t.UserID.String(), |
| 43 | WalletId: t.From.String(), |
| 44 | Amount: &walletv1.Money{AmountMinor: t.Amount, Currency: t.Currency}, |
| 45 | }) |
| 46 | return rejection(err) |
| 47 | } |
| 48 | |
| 49 | func (h holds) Capture(ctx context.Context, t Transfer) error { |
| 50 | _, err := h.client.Capture(ctx, &walletv1.CaptureRequest{ |
| 51 | HoldId: t.ID.String(), |
| 52 | ToWalletId: t.To.String(), |
| 53 | }) |
| 54 | return rejection(err) |
| 55 | } |
| 56 | |
| 57 | func (h holds) Release(ctx context.Context, t Transfer) error { |
| 58 | _, err := h.client.Release(ctx, &walletv1.ReleaseRequest{HoldId: t.ID.String()}) |
| 59 | return rejection(err) |
| 60 | } |
| 61 | |
| 62 | // rejection turns the wallet's final answers into a Rejection. |
| 63 | func rejection(err error) error { |
| 64 | s := status.Convert(err) |
| 65 | switch s.Code() { |
| 66 | case codes.FailedPrecondition: |
| 67 | for _, d := range s.Details() { |
| 68 | if info, ok := d.(*errdetails.ErrorInfo); ok { |
| 69 | return &Rejection{Reason: info.GetReason()} |
| 70 | } |
| 71 | } |
| 72 | return &Rejection{Reason: "failed_precondition"} |
| 73 | case codes.NotFound: |
| 74 | return &Rejection{Reason: "wallet_not_found"} |
| 75 | case codes.InvalidArgument: |
| 76 | return &Rejection{Reason: "invalid_request"} |
| 77 | } |
| 78 | return err |
| 79 | } |