client.go105 lines, 3.7 KB
| 1 | // Package walletclient calls the wallet service over gRPC. Other services use |
| 2 | // it instead of the bare generated client, so every caller gets deadlines, |
| 3 | // retries and request IDs right, in one place. |
| 4 | package walletclient |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "fmt" |
| 9 | "time" |
| 10 | |
| 11 | walletv1 "github.com/fiston-user/payments/gen/wallet/v1" |
| 12 | "github.com/fiston-user/payments/internal/platform/grpcx" |
| 13 | "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" |
| 14 | "google.golang.org/grpc" |
| 15 | "google.golang.org/grpc/credentials" |
| 16 | ) |
| 17 | |
| 18 | // serviceConfig is how gRPC calls the wallet: spread over all its addresses, |
| 19 | // and with automatic retries, but only where a retry can't do harm. Reads are |
| 20 | // always safe. Transfer is safe only because a retry sends the same message, |
| 21 | // with the same idempotency key, and holds because the hold ID is one. |
| 22 | // ABORTED is a transfer that's still running. |
| 23 | const serviceConfig = `{ |
| 24 | "loadBalancingConfig": [{"round_robin": {}}], |
| 25 | "methodConfig": [{ |
| 26 | "name": [ |
| 27 | {"service": "wallet.v1.WalletService", "method": "GetWallet"}, |
| 28 | {"service": "wallet.v1.WalletService", "method": "GetBalance"} |
| 29 | ], |
| 30 | "retryPolicy": { |
| 31 | "maxAttempts": 3, |
| 32 | "initialBackoff": "0.1s", |
| 33 | "maxBackoff": "1s", |
| 34 | "backoffMultiplier": 2, |
| 35 | "retryableStatusCodes": ["UNAVAILABLE"] |
| 36 | } |
| 37 | }, { |
| 38 | "name": [ |
| 39 | {"service": "wallet.v1.WalletService", "method": "Deposit"}, |
| 40 | {"service": "wallet.v1.WalletService", "method": "Transfer"}, |
| 41 | {"service": "wallet.v1.HoldService"} |
| 42 | ], |
| 43 | "retryPolicy": { |
| 44 | "maxAttempts": 3, |
| 45 | "initialBackoff": "0.2s", |
| 46 | "maxBackoff": "2s", |
| 47 | "backoffMultiplier": 2, |
| 48 | "retryableStatusCodes": ["UNAVAILABLE", "ABORTED"] |
| 49 | } |
| 50 | }], |
| 51 | "retryThrottling": {"maxTokens": 10, "tokenRatio": 0.1} |
| 52 | }` |
| 53 | |
| 54 | // Client calls the wallet service. It's safe for concurrent use: make one when |
| 55 | // your service starts, and share it. |
| 56 | type Client struct { |
| 57 | walletv1.WalletServiceClient |
| 58 | walletv1.HoldServiceClient |
| 59 | conn *grpc.ClientConn |
| 60 | } |
| 61 | |
| 62 | // New returns a Client for the wallet service at target, like |
| 63 | // dns:///wallet:9081, over a connection secured with creds: mTLS, or in |
| 64 | // tests, insecure.NewCredentials(). Every call gets a deadline of at most |
| 65 | // timeout, or an earlier one from its context. opts are added to ours, for tests. |
| 66 | func New( |
| 67 | target string, creds credentials.TransportCredentials, timeout time.Duration, opts ...grpc.DialOption, |
| 68 | ) (*Client, error) { |
| 69 | opts = append([]grpc.DialOption{ |
| 70 | grpc.WithTransportCredentials(creds), |
| 71 | grpc.WithDefaultServiceConfig(serviceConfig), |
| 72 | grpc.WithChainUnaryInterceptor(grpcx.PropagateRequestID, deadline(timeout)), |
| 73 | grpc.WithStatsHandler(otelgrpc.NewClientHandler()), // a span per call, and the context |
| 74 | }, opts...) |
| 75 | // NewClient doesn't connect yet: the first call does, and gRPC |
| 76 | // reconnects by itself whenever it has to. |
| 77 | conn, err := grpc.NewClient(target, opts...) |
| 78 | if err != nil { |
| 79 | return nil, fmt.Errorf("wallet client: %w", err) |
| 80 | } |
| 81 | return &Client{ |
| 82 | WalletServiceClient: walletv1.NewWalletServiceClient(conn), |
| 83 | HoldServiceClient: walletv1.NewHoldServiceClient(conn), |
| 84 | conn: conn, |
| 85 | }, nil |
| 86 | } |
| 87 | |
| 88 | // Close closes the connection to the wallet service. |
| 89 | func (c *Client) Close() error { |
| 90 | return c.conn.Close() |
| 91 | } |
| 92 | |
| 93 | // deadline gives every call a deadline, at most d from now. When the caller's |
| 94 | // context ends sooner, that deadline wins: a child context never outlives its |
| 95 | // parent. So a call made for a request never outlasts the request. |
| 96 | func deadline(d time.Duration) grpc.UnaryClientInterceptor { |
| 97 | return func( |
| 98 | ctx context.Context, method string, req, reply any, |
| 99 | cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption, |
| 100 | ) error { |
| 101 | ctx, cancel := context.WithTimeout(ctx, d) |
| 102 | defer cancel() |
| 103 | return invoker(ctx, method, req, reply, cc, opts...) |
| 104 | } |
| 105 | } |