Compare commits
5 Commits
099ec2150e
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 055c8d8777 | |||
| 8e39fd4503 | |||
| 646575ff28 | |||
| 8bea266f03 | |||
| c6e2ce7fd5 |
@@ -3,6 +3,7 @@ ZARINHUB_API_PASSWORD=
|
||||
ZARINHUB_AUTH_ENDPOINT=https://zarin-hub.com/api/v5/Authentication/GetToken
|
||||
ZARINHUB_ENDPOINT=https://zarin-hub.com/api/v5/KYC/CardToIban
|
||||
ZARINHUB_TIMEOUT=5s
|
||||
ZARINHUB_RETRIES=2
|
||||
|
||||
DATABASE_PATH=./card-to-iban.db
|
||||
SERVER_ADDR=127.0.0.1:8080
|
||||
|
||||
@@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -15,6 +16,7 @@ type config struct {
|
||||
ZarinHubUsername string
|
||||
ZarinHubPassword string
|
||||
ZarinHubTimeout time.Duration
|
||||
ZarinHubRetries int
|
||||
DatabasePath string
|
||||
}
|
||||
|
||||
@@ -44,6 +46,18 @@ func readConfig(getenv func(string) string) (config, error) {
|
||||
)
|
||||
}
|
||||
|
||||
retriesText := valueOrDefault(
|
||||
getenv("ZARINHUB_RETRIES"),
|
||||
"2",
|
||||
)
|
||||
|
||||
retries, err := strconv.Atoi(retriesText)
|
||||
if err != nil || retries < 0 {
|
||||
return config{}, fmt.Errorf(
|
||||
"ZARINHUB_RETRIES must be a non-negative integer",
|
||||
)
|
||||
}
|
||||
|
||||
return config{
|
||||
ServerAddr: valueOrDefault(
|
||||
getenv("SERVER_ADDR"),
|
||||
@@ -64,6 +78,7 @@ func readConfig(getenv func(string) string) (config, error) {
|
||||
ZarinHubUsername: username,
|
||||
ZarinHubPassword: password,
|
||||
ZarinHubTimeout: timeout,
|
||||
ZarinHubRetries: retries,
|
||||
DatabasePath: valueOrDefault(
|
||||
getenv("DATABASE_PATH"),
|
||||
"./card-to-iban.db",
|
||||
|
||||
@@ -31,6 +31,9 @@ func TestReadConfigUsesDefaults(t *testing.T) {
|
||||
if config.ZarinHubTimeout != 5*time.Second {
|
||||
t.Errorf("ZarinHubTimeout = %v", config.ZarinHubTimeout)
|
||||
}
|
||||
if config.ZarinHubRetries != 2 {
|
||||
t.Errorf("ZarinHubRetries = %d, want 2", config.ZarinHubRetries)
|
||||
}
|
||||
if config.DatabasePath != "./card-to-iban.db" {
|
||||
t.Errorf("DatabasePath = %q", config.DatabasePath)
|
||||
}
|
||||
@@ -70,3 +73,22 @@ func TestReadConfigRejectsInvalidTimeout(t *testing.T) {
|
||||
t.Fatalf("readConfig() error = %v, want timeout error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadConfigRejectsInvalidRetries(t *testing.T) {
|
||||
testCases := []string{"-1", "invalid", "2.5"}
|
||||
|
||||
for _, tc := range testCases {
|
||||
values := map[string]string{
|
||||
"ZARINHUB_API_USERNAME": "test-username",
|
||||
"ZARINHUB_API_PASSWORD": "test-password",
|
||||
"ZARINHUB_RETRIES": tc,
|
||||
}
|
||||
|
||||
_, err := readConfig(func(key string) string {
|
||||
return values[key]
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "ZARINHUB_RETRIES") {
|
||||
t.Errorf("retries=%q: want error mentioning ZARINHUB_RETRIES, got %v", tc, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,11 @@ func run(logger *slog.Logger) error {
|
||||
return fmt.Errorf("load configuration: %w", err)
|
||||
}
|
||||
|
||||
httpClient := &http.Client{Timeout: config.ZarinHubTimeout}
|
||||
httpClient := zarinhub.NewHTTPClient(
|
||||
config.ZarinHubTimeout,
|
||||
config.ZarinHubRetries,
|
||||
logger,
|
||||
)
|
||||
tokenManager := zarinhub.NewTokenManager(
|
||||
httpClient,
|
||||
config.ZarinHubAuthEndpoint,
|
||||
@@ -46,9 +50,10 @@ func run(logger *slog.Logger) error {
|
||||
config.ZarinHubPassword,
|
||||
)
|
||||
|
||||
authTimeout := time.Duration(config.ZarinHubRetries+1)*config.ZarinHubTimeout + 10*time.Second
|
||||
authContext, cancelAuth := context.WithTimeout(
|
||||
context.Background(),
|
||||
config.ZarinHubTimeout,
|
||||
authTimeout,
|
||||
)
|
||||
_, err = tokenManager.AccessToken(authContext)
|
||||
cancelAuth()
|
||||
@@ -79,6 +84,8 @@ func run(logger *slog.Logger) error {
|
||||
httpClient,
|
||||
config.ZarinHubEndpoint,
|
||||
tokenManager,
|
||||
config.ZarinHubRetries,
|
||||
logger,
|
||||
)
|
||||
cardService := service.NewCardService(zarinHubClient)
|
||||
auditRepository := repository.NewAuditRepository(db)
|
||||
|
||||
63
backend/internal/httpapi/client_ip.go
Normal file
63
backend/internal/httpapi/client_ip.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func extractClientIP(r *http.Request) *string {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Priority headers commonly set by reverse proxies, load balancers, and CDNs.
|
||||
headers := []string{
|
||||
"CF-Connecting-IP", // Cloudflare
|
||||
"True-Client-IP", // Cloudflare Enterprise, Akamai
|
||||
"X-Real-IP", // Nginx, Traefik
|
||||
}
|
||||
|
||||
for _, header := range headers {
|
||||
if val := strings.TrimSpace(r.Header.Get(header)); val != "" {
|
||||
if ip := parseIP(val); ip != "" {
|
||||
return &ip
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// X-Forwarded-For can contain multiple comma-separated IPs: client, proxy1, proxy2. The original client IP is the first entry.
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
for _, part := range strings.Split(xff, ",") {
|
||||
if ip := parseIP(part); ip != "" {
|
||||
return &ip
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to RemoteAddr (typically "host:port" or "[ipv6]:port").
|
||||
if r.RemoteAddr != "" {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
host = r.RemoteAddr
|
||||
}
|
||||
if ip := parseIP(host); ip != "" {
|
||||
return &ip
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseIP(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.TrimPrefix(raw, "[")
|
||||
raw = strings.TrimSuffix(raw, "]")
|
||||
|
||||
ip := net.ParseIP(raw)
|
||||
if ip == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return ip.String()
|
||||
}
|
||||
143
backend/internal/httpapi/client_ip_test.go
Normal file
143
backend/internal/httpapi/client_ip_test.go
Normal file
@@ -0,0 +1,143 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExtractClientIP(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
request *http.Request
|
||||
headers map[string]string
|
||||
remoteAddr string
|
||||
wantIP *string
|
||||
}{
|
||||
{
|
||||
name: "nil request",
|
||||
request: nil,
|
||||
wantIP: nil,
|
||||
},
|
||||
{
|
||||
name: "CF-Connecting-IP takes precedence",
|
||||
headers: map[string]string{
|
||||
"CF-Connecting-IP": "203.0.113.10",
|
||||
"X-Real-IP": "198.51.100.20",
|
||||
"X-Forwarded-For": "192.0.2.30",
|
||||
},
|
||||
remoteAddr: "10.0.0.1:54321",
|
||||
wantIP: ptr("203.0.113.10"),
|
||||
},
|
||||
{
|
||||
name: "True-Client-IP takes precedence over X-Real-IP",
|
||||
headers: map[string]string{
|
||||
"True-Client-IP": "203.0.113.11",
|
||||
"X-Real-IP": "198.51.100.20",
|
||||
"X-Forwarded-For": "192.0.2.30",
|
||||
},
|
||||
remoteAddr: "10.0.0.1:54321",
|
||||
wantIP: ptr("203.0.113.11"),
|
||||
},
|
||||
{
|
||||
name: "X-Real-IP takes precedence over X-Forwarded-For",
|
||||
headers: map[string]string{
|
||||
"X-Real-IP": "198.51.100.20",
|
||||
"X-Forwarded-For": "192.0.2.30",
|
||||
},
|
||||
remoteAddr: "10.0.0.1:54321",
|
||||
wantIP: ptr("198.51.100.20"),
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-For first entry is extracted",
|
||||
headers: map[string]string{
|
||||
"X-Forwarded-For": "192.0.2.30, 10.0.0.2, 172.16.0.5",
|
||||
},
|
||||
remoteAddr: "10.0.0.1:54321",
|
||||
wantIP: ptr("192.0.2.30"),
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-For single entry",
|
||||
headers: map[string]string{
|
||||
"X-Forwarded-For": " 192.0.2.31 ",
|
||||
},
|
||||
remoteAddr: "10.0.0.1:54321",
|
||||
wantIP: ptr("192.0.2.31"),
|
||||
},
|
||||
{
|
||||
name: "X-Forwarded-For skips invalid first entry to find valid IP",
|
||||
headers: map[string]string{
|
||||
"X-Forwarded-For": "unknown, 192.0.2.32",
|
||||
},
|
||||
remoteAddr: "10.0.0.1:54321",
|
||||
wantIP: ptr("192.0.2.32"),
|
||||
},
|
||||
{
|
||||
name: "Fallback to RemoteAddr with port",
|
||||
headers: map[string]string{},
|
||||
remoteAddr: "192.168.1.100:12345",
|
||||
wantIP: ptr("192.168.1.100"),
|
||||
},
|
||||
{
|
||||
name: "Fallback to RemoteAddr without port",
|
||||
headers: map[string]string{},
|
||||
remoteAddr: "192.168.1.101",
|
||||
wantIP: ptr("192.168.1.101"),
|
||||
},
|
||||
{
|
||||
name: "IPv6 in RemoteAddr with port",
|
||||
headers: map[string]string{},
|
||||
remoteAddr: "[2001:db8::1]:8080",
|
||||
wantIP: ptr("2001:db8::1"),
|
||||
},
|
||||
{
|
||||
name: "IPv6 in header",
|
||||
headers: map[string]string{
|
||||
"X-Real-IP": "2001:db8::2",
|
||||
},
|
||||
remoteAddr: "10.0.0.1:54321",
|
||||
wantIP: ptr("2001:db8::2"),
|
||||
},
|
||||
{
|
||||
name: "Invalid headers fall back to RemoteAddr",
|
||||
headers: map[string]string{
|
||||
"X-Real-IP": "not-an-ip",
|
||||
"X-Forwarded-For": "also-not-an-ip",
|
||||
},
|
||||
remoteAddr: "192.168.1.102:443",
|
||||
wantIP: ptr("192.168.1.102"),
|
||||
},
|
||||
{
|
||||
name: "No headers and empty RemoteAddr",
|
||||
headers: map[string]string{},
|
||||
remoteAddr: "",
|
||||
wantIP: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var req *http.Request
|
||||
if tt.name != "nil request" {
|
||||
req = httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
for k, v := range tt.headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
req.RemoteAddr = tt.remoteAddr
|
||||
}
|
||||
|
||||
got := extractClientIP(req)
|
||||
if (got == nil) != (tt.wantIP == nil) {
|
||||
t.Fatalf("extractClientIP() = %v, want %v", got, tt.wantIP)
|
||||
}
|
||||
if got != nil && tt.wantIP != nil && *got != *tt.wantIP {
|
||||
t.Errorf("extractClientIP() = %q, want %q", *got, *tt.wantIP)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func ptr(s string) *string {
|
||||
return &s
|
||||
}
|
||||
|
||||
@@ -60,6 +60,7 @@ func NewHandler(
|
||||
func (h *Handler) Convert(w http.ResponseWriter, r *http.Request) {
|
||||
startedAt := h.now()
|
||||
requestID := h.newRequestID()
|
||||
clientIP := extractClientIP(r)
|
||||
|
||||
w.Header().Set("X-Request-ID", requestID)
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
@@ -89,6 +90,7 @@ func (h *Handler) Convert(w http.ResponseWriter, r *http.Request) {
|
||||
RequestID: requestID,
|
||||
CreatedAt: startedAt,
|
||||
Duration: duration,
|
||||
ClientIP: clientIP,
|
||||
Status: outcome.auditStatus,
|
||||
MaskedCard: card.Mask(cardNumber),
|
||||
ResponseJSON: audit.SanitizeResponse(
|
||||
@@ -102,11 +104,17 @@ func (h *Handler) Convert(w http.ResponseWriter, r *http.Request) {
|
||||
record.UpstreamHTTPStatus = &upstreamStatus
|
||||
}
|
||||
|
||||
var clientIPValue string
|
||||
if clientIP != nil {
|
||||
clientIPValue = *clientIP
|
||||
}
|
||||
|
||||
if err := h.audits.Save(r.Context(), record); err != nil {
|
||||
h.logger.ErrorContext(
|
||||
r.Context(),
|
||||
"request audit failed",
|
||||
"request_id", requestID,
|
||||
"client_ip", clientIPValue,
|
||||
"route", "/api/v1/card-to-iban",
|
||||
"http_status", http.StatusInternalServerError,
|
||||
"audit_status", audit.StatusInternalError,
|
||||
@@ -128,6 +136,7 @@ func (h *Handler) Convert(w http.ResponseWriter, r *http.Request) {
|
||||
r.Context(),
|
||||
"request completed",
|
||||
"request_id", requestID,
|
||||
"client_ip", clientIPValue,
|
||||
"route", "/api/v1/card-to-iban",
|
||||
"http_status", outcome.httpStatus,
|
||||
"audit_status", outcome.auditStatus,
|
||||
|
||||
@@ -248,6 +248,10 @@ func TestHandlerConvert(t *testing.T) {
|
||||
t.Errorf("masked card = %q, want %q", record.MaskedCard, tt.wantMaskedCard)
|
||||
}
|
||||
|
||||
if record.ClientIP == nil || *record.ClientIP != "192.0.2.1" {
|
||||
t.Errorf("client IP = %v, want 192.0.2.1", record.ClientIP)
|
||||
}
|
||||
|
||||
if strings.Contains(string(record.ResponseJSON), "6037997512345678") {
|
||||
t.Error("audit response contains the full card number")
|
||||
}
|
||||
@@ -291,3 +295,75 @@ func TestHandlerFailsClosedWhenAuditSaveFails(t *testing.T) {
|
||||
t.Errorf("response body = %s, want internal_error", response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerExtractsClientIP(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
headerKey string
|
||||
headerVal string
|
||||
remoteAddr string
|
||||
wantIP string
|
||||
}{
|
||||
{
|
||||
name: "prefers CF-Connecting-IP",
|
||||
headerKey: "CF-Connecting-IP",
|
||||
headerVal: "203.0.113.88",
|
||||
remoteAddr: "10.0.0.1:1234",
|
||||
wantIP: "203.0.113.88",
|
||||
},
|
||||
{
|
||||
name: "prefers X-Forwarded-For over RemoteAddr",
|
||||
headerKey: "X-Forwarded-For",
|
||||
headerVal: "198.51.100.77, 10.0.0.2",
|
||||
remoteAddr: "10.0.0.1:1234",
|
||||
wantIP: "198.51.100.77",
|
||||
},
|
||||
{
|
||||
name: "uses RemoteAddr host without port",
|
||||
remoteAddr: "192.168.10.5:9999",
|
||||
wantIP: "192.168.10.5",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
audits := &fakeAuditSaver{}
|
||||
handler := NewHandler(
|
||||
&fakeConverter{
|
||||
result: service.ConversionResult{
|
||||
IBAN: "IR820540102680020817909002",
|
||||
UpstreamHTTPStatus: http.StatusOK,
|
||||
},
|
||||
},
|
||||
audits,
|
||||
slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
)
|
||||
|
||||
req := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/v1/card-to-iban",
|
||||
strings.NewReader(`{"card":"6037997512345678"}`),
|
||||
)
|
||||
if tt.headerKey != "" {
|
||||
req.Header.Set(tt.headerKey, tt.headerVal)
|
||||
}
|
||||
req.RemoteAddr = tt.remoteAddr
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
handler.Convert(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
|
||||
if len(audits.records) != 1 {
|
||||
t.Fatalf("audit records count = %d, want 1", len(audits.records))
|
||||
}
|
||||
|
||||
recIP := audits.records[0].ClientIP
|
||||
if recIP == nil || *recIP != tt.wantIP {
|
||||
t.Errorf("ClientIP = %v, want %q", recIP, tt.wantIP)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,18 +7,28 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"card-to-iban/internal/service"
|
||||
)
|
||||
|
||||
const maxResponseBodySize = 1 << 20
|
||||
const (
|
||||
maxResponseBodySize = 1 << 20
|
||||
|
||||
retryBaseDelay = 200 * time.Millisecond
|
||||
retryMaxDelay = 2 * time.Second
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
httpClient *http.Client
|
||||
endpointURL string
|
||||
tokenProvider TokenProvider
|
||||
maxRetries int
|
||||
retryWait func(ctx context.Context, delay time.Duration) bool
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
var _ service.CardToIBANClient = (*Client)(nil)
|
||||
@@ -32,17 +42,114 @@ func NewClient(
|
||||
httpClient *http.Client,
|
||||
endpointURL string,
|
||||
tokenProvider TokenProvider,
|
||||
maxRetries int,
|
||||
loggers ...*slog.Logger,
|
||||
) *Client {
|
||||
return &Client{
|
||||
if maxRetries < 0 {
|
||||
maxRetries = 0
|
||||
}
|
||||
|
||||
var logger *slog.Logger
|
||||
if len(loggers) > 0 && loggers[0] != nil {
|
||||
logger = loggers[0]
|
||||
}
|
||||
|
||||
if httpClient == nil {
|
||||
httpClient = http.DefaultClient
|
||||
}
|
||||
|
||||
client := &Client{
|
||||
httpClient: httpClient,
|
||||
endpointURL: endpointURL,
|
||||
tokenProvider: tokenProvider,
|
||||
maxRetries: maxRetries,
|
||||
logger: logger,
|
||||
}
|
||||
|
||||
if _, ok := httpClient.Transport.(*RetryTransport); !ok && maxRetries > 0 {
|
||||
rt := NewRetryTransport(
|
||||
httpClient.Transport,
|
||||
httpClient.Timeout,
|
||||
maxRetries,
|
||||
logger,
|
||||
)
|
||||
rt.retryWait = func(ctx context.Context, delay time.Duration) bool {
|
||||
if client.retryWait != nil {
|
||||
return client.retryWait(ctx, delay)
|
||||
}
|
||||
return waitForRetry(ctx, delay)
|
||||
}
|
||||
client.httpClient = &http.Client{
|
||||
Transport: rt,
|
||||
}
|
||||
} else if rt, ok := httpClient.Transport.(*RetryTransport); ok {
|
||||
origWait := rt.retryWait
|
||||
rt.retryWait = func(ctx context.Context, delay time.Duration) bool {
|
||||
if client.retryWait != nil {
|
||||
return client.retryWait(ctx, delay)
|
||||
}
|
||||
if origWait != nil {
|
||||
return origWait(ctx, delay)
|
||||
}
|
||||
return waitForRetry(ctx, delay)
|
||||
}
|
||||
}
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
func (c *Client) log() *slog.Logger {
|
||||
if c.logger != nil {
|
||||
return c.logger
|
||||
}
|
||||
return slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
}
|
||||
|
||||
func isRetryable(err error) bool {
|
||||
return errors.Is(err, ErrTimeout) ||
|
||||
errors.Is(err, ErrUnavailable)
|
||||
}
|
||||
|
||||
func retryDelay(attempt int) time.Duration {
|
||||
delay := retryBaseDelay
|
||||
|
||||
for i := 0; i < attempt; i++ {
|
||||
delay *= 2
|
||||
|
||||
if delay >= retryMaxDelay {
|
||||
return retryMaxDelay
|
||||
}
|
||||
}
|
||||
|
||||
return delay
|
||||
}
|
||||
|
||||
func waitForRetry(
|
||||
ctx context.Context,
|
||||
delay time.Duration,
|
||||
) bool {
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
|
||||
case <-timer.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Convert(
|
||||
ctx context.Context,
|
||||
cardNumber string,
|
||||
) (service.ConversionResult, error) {
|
||||
return c.convertOnce(ctx, cardNumber)
|
||||
}
|
||||
|
||||
func (c *Client) convertOnce(
|
||||
ctx context.Context,
|
||||
cardNumber string,
|
||||
) (service.ConversionResult, error) {
|
||||
accessToken, err := c.tokenProvider.AccessToken(ctx)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
package zarinhub
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -98,6 +101,7 @@ func TestClientConvertSuccess(t *testing.T) {
|
||||
},
|
||||
server.URL,
|
||||
&fakeTokenProvider{tokens: []string{token}},
|
||||
0,
|
||||
)
|
||||
|
||||
result, err := client.Convert(
|
||||
@@ -172,6 +176,7 @@ func TestClientReturnsRejectedForApplicationFailure(
|
||||
},
|
||||
server.URL,
|
||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||
0,
|
||||
)
|
||||
|
||||
result, err := client.Convert(
|
||||
@@ -264,6 +269,7 @@ func TestClientMapsHTTPStatusErrors(t *testing.T) {
|
||||
},
|
||||
server.URL,
|
||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||
0,
|
||||
)
|
||||
|
||||
result, err := client.Convert(
|
||||
@@ -322,6 +328,7 @@ func TestClientReturnsInvalidResponseForMalformedJSON(
|
||||
},
|
||||
server.URL,
|
||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||
0,
|
||||
)
|
||||
|
||||
result, err := client.Convert(
|
||||
@@ -367,6 +374,7 @@ func TestClientReturnsTimeout(t *testing.T) {
|
||||
},
|
||||
server.URL,
|
||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||
0,
|
||||
)
|
||||
|
||||
_, err := client.Convert(
|
||||
@@ -403,6 +411,7 @@ func TestClientRejectsOversizedResponse(t *testing.T) {
|
||||
&http.Client{Timeout: time.Second},
|
||||
server.URL,
|
||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||
0,
|
||||
)
|
||||
|
||||
_, err := client.Convert(
|
||||
@@ -442,7 +451,7 @@ func TestClientRefreshesAndRetriesUnauthorizedRequest(t *testing.T) {
|
||||
defer server.Close()
|
||||
|
||||
tokens := &fakeTokenProvider{tokens: []string{"expired-token", "fresh-token"}}
|
||||
client := NewClient(server.Client(), server.URL, tokens)
|
||||
client := NewClient(server.Client(), server.URL, tokens, 0)
|
||||
|
||||
result, err := client.Convert(context.Background(), "6037997512345678")
|
||||
if err != nil {
|
||||
@@ -478,3 +487,280 @@ func (p *fakeTokenProvider) AccessToken(context.Context) (string, error) {
|
||||
func (p *fakeTokenProvider) Invalidate(token string) {
|
||||
p.invalidated = append(p.invalidated, token)
|
||||
}
|
||||
|
||||
func TestRetryDelay(t *testing.T) {
|
||||
tests := []struct {
|
||||
attempt int
|
||||
want time.Duration
|
||||
}{
|
||||
{attempt: -1, want: 200 * time.Millisecond},
|
||||
{attempt: 0, want: 200 * time.Millisecond},
|
||||
{attempt: 1, want: 400 * time.Millisecond},
|
||||
{attempt: 2, want: 800 * time.Millisecond},
|
||||
{attempt: 3, want: 1600 * time.Millisecond},
|
||||
{attempt: 4, want: 2 * time.Second},
|
||||
{attempt: 10, want: 2 * time.Second},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := retryDelay(tt.attempt)
|
||||
if got != tt.want {
|
||||
t.Errorf("retryDelay(%d) = %v, want %v", tt.attempt, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewClientSanitizesNegativeRetries(t *testing.T) {
|
||||
client := NewClient(nil, "", nil, -1)
|
||||
if client.maxRetries != 0 {
|
||||
t.Errorf("maxRetries = %d, want 0", client.maxRetries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRetriesOnTransientErrorsUntilSuccess(t *testing.T) {
|
||||
const expectedIBAN = "IR820540102680020817909002"
|
||||
requestCount := 0
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestCount++
|
||||
if requestCount == 1 {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
fmt.Fprint(w, `{"error":"temporary outage"}`)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, `{
|
||||
"data":{"iban":%q},
|
||||
"meta":{"isSuccess":true,"errors":[]}
|
||||
}`, expectedIBAN)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
var recordedDelays []time.Duration
|
||||
client := NewClient(
|
||||
&http.Client{Timeout: time.Second},
|
||||
server.URL,
|
||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||
2,
|
||||
)
|
||||
client.retryWait = func(ctx context.Context, delay time.Duration) bool {
|
||||
recordedDelays = append(recordedDelays, delay)
|
||||
return true
|
||||
}
|
||||
|
||||
result, err := client.Convert(context.Background(), "6037997512345678")
|
||||
if err != nil {
|
||||
t.Fatalf("Convert() unexpected error = %v", err)
|
||||
}
|
||||
if result.IBAN != expectedIBAN {
|
||||
t.Errorf("IBAN = %q, want %q", result.IBAN, expectedIBAN)
|
||||
}
|
||||
if requestCount != 2 {
|
||||
t.Errorf("request count = %d, want 2", requestCount)
|
||||
}
|
||||
if len(recordedDelays) != 1 {
|
||||
t.Fatalf("len(recordedDelays) = %d, want 1", len(recordedDelays))
|
||||
}
|
||||
if recordedDelays[0] != 200*time.Millisecond {
|
||||
t.Errorf("delay[0] = %v, want 200ms", recordedDelays[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRetriesExhausted(t *testing.T) {
|
||||
requestCount := 0
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestCount++
|
||||
w.WriteHeader(http.StatusGatewayTimeout)
|
||||
fmt.Fprint(w, `{"error":"gateway timeout"}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
var recordedDelays []time.Duration
|
||||
client := NewClient(
|
||||
&http.Client{Timeout: time.Second},
|
||||
server.URL,
|
||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||
2,
|
||||
)
|
||||
client.retryWait = func(ctx context.Context, delay time.Duration) bool {
|
||||
recordedDelays = append(recordedDelays, delay)
|
||||
return true
|
||||
}
|
||||
|
||||
_, err := client.Convert(context.Background(), "6037997512345678")
|
||||
if !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("error = %v, want ErrUnavailable", err)
|
||||
}
|
||||
if requestCount != 3 {
|
||||
t.Errorf("request count = %d, want 3", requestCount)
|
||||
}
|
||||
if len(recordedDelays) != 2 {
|
||||
t.Fatalf("len(recordedDelays) = %d, want 2", len(recordedDelays))
|
||||
}
|
||||
if recordedDelays[0] != 200*time.Millisecond {
|
||||
t.Errorf("delay[0] = %v, want 200ms", recordedDelays[0])
|
||||
}
|
||||
if recordedDelays[1] != 400*time.Millisecond {
|
||||
t.Errorf("delay[1] = %v, want 400ms", recordedDelays[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientDoesNotRetryNonTransientErrors(t *testing.T) {
|
||||
requestCount := 0
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestCount++
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprint(w, `{"error":"invalid card format"}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := NewClient(
|
||||
&http.Client{Timeout: time.Second},
|
||||
server.URL,
|
||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||
2,
|
||||
)
|
||||
client.retryWait = func(ctx context.Context, delay time.Duration) bool {
|
||||
t.Error("retryWait should not be called for non-transient errors")
|
||||
return true
|
||||
}
|
||||
|
||||
_, err := client.Convert(context.Background(), "6037997512345678")
|
||||
if !errors.Is(err, ErrRejected) {
|
||||
t.Fatalf("error = %v, want ErrRejected", err)
|
||||
}
|
||||
if requestCount != 1 {
|
||||
t.Errorf("request count = %d, want 1", requestCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientStopsRetryOnContextCancellation(t *testing.T) {
|
||||
requestCount := 0
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestCount++
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
client := NewClient(
|
||||
&http.Client{Timeout: time.Second},
|
||||
server.URL,
|
||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||
2,
|
||||
)
|
||||
client.retryWait = func(c context.Context, delay time.Duration) bool {
|
||||
cancel()
|
||||
return waitForRetry(ctx, delay)
|
||||
}
|
||||
|
||||
_, err := client.Convert(ctx, "6037997512345678")
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("error = %v, want context.Canceled", err)
|
||||
}
|
||||
if requestCount != 1 {
|
||||
t.Errorf("request count = %d, want 1", requestCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRetryLogging(t *testing.T) {
|
||||
const expectedIBAN = "IR820540102680020817909002"
|
||||
requestCount := 0
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestCount++
|
||||
if requestCount == 1 {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
fmt.Fprint(w, `{"error":"temporary outage"}`)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, `{
|
||||
"data":{"iban":%q},
|
||||
"meta":{"isSuccess":true,"errors":[]}
|
||||
}`, expectedIBAN)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
var logBuf bytes.Buffer
|
||||
logger := slog.New(slog.NewJSONHandler(&logBuf, nil))
|
||||
|
||||
client := NewClient(
|
||||
&http.Client{Timeout: time.Second},
|
||||
server.URL,
|
||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||
2,
|
||||
logger,
|
||||
)
|
||||
client.retryWait = func(ctx context.Context, delay time.Duration) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
result, err := client.Convert(context.Background(), "6037997512345678")
|
||||
if err != nil {
|
||||
t.Fatalf("Convert() unexpected error = %v", err)
|
||||
}
|
||||
if result.IBAN != expectedIBAN {
|
||||
t.Errorf("IBAN = %q, want %q", result.IBAN, expectedIBAN)
|
||||
}
|
||||
|
||||
logs := logBuf.String()
|
||||
|
||||
if !strings.Contains(logs, "[INITIAL] zarinhub request") {
|
||||
t.Errorf("expected logs to contain '[INITIAL] zarinhub request', got:\n%s", logs)
|
||||
}
|
||||
if !strings.Contains(logs, `"is_retry":false`) {
|
||||
t.Errorf("expected logs to contain '\"is_retry\":false', got:\n%s", logs)
|
||||
}
|
||||
|
||||
if !strings.Contains(logs, "[RETRY] zarinhub request attempt 1") {
|
||||
t.Errorf("expected logs to contain '[RETRY] zarinhub request attempt 1', got:\n%s", logs)
|
||||
}
|
||||
if !strings.Contains(logs, "[RETRY] zarinhub request failed, retrying in") {
|
||||
t.Errorf("expected logs to contain '[RETRY] zarinhub request failed, retrying in', got:\n%s", logs)
|
||||
}
|
||||
if !strings.Contains(logs, `"is_retry":true`) {
|
||||
t.Errorf("expected logs to contain '\"is_retry\":true', got:\n%s", logs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRetryLoggingExhausted(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
fmt.Fprint(w, `{"error":"down"}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
var logBuf bytes.Buffer
|
||||
logger := slog.New(slog.NewJSONHandler(&logBuf, nil))
|
||||
|
||||
client := NewClient(
|
||||
&http.Client{Timeout: time.Second},
|
||||
server.URL,
|
||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||
1,
|
||||
logger,
|
||||
)
|
||||
client.retryWait = func(ctx context.Context, delay time.Duration) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
_, err := client.Convert(context.Background(), "6037997512345678")
|
||||
if !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("error = %v, want ErrUnavailable", err)
|
||||
}
|
||||
|
||||
logs := logBuf.String()
|
||||
if !strings.Contains(logs, "[RETRY] zarinhub request failed: all retries exhausted") {
|
||||
t.Errorf("expected logs to contain exhausted retries message, got:\n%s", logs)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package zarinhub
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
@@ -220,3 +221,120 @@ func writeTokenResponse(
|
||||
t.Fatalf("encode response: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenManagerRetriesOnTransientErrorsUntilSuccess(t *testing.T) {
|
||||
var calls int
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
writeTokenResponse(t, w, "retried-access", "retried-refresh", 28800)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
var recordedDelays []time.Duration
|
||||
transport := NewRetryTransport(
|
||||
server.Client().Transport,
|
||||
time.Second,
|
||||
2,
|
||||
)
|
||||
transport.retryWait = func(ctx context.Context, delay time.Duration) bool {
|
||||
recordedDelays = append(recordedDelays, delay)
|
||||
return true
|
||||
}
|
||||
httpClient := &http.Client{Transport: transport}
|
||||
|
||||
manager := NewTokenManager(httpClient, server.URL, "test-user", "test-pass")
|
||||
token, err := manager.AccessToken(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("AccessToken() error = %v", err)
|
||||
}
|
||||
if token != "retried-access" {
|
||||
t.Errorf("token = %q, want retried-access", token)
|
||||
}
|
||||
if calls != 2 {
|
||||
t.Errorf("calls = %d, want 2", calls)
|
||||
}
|
||||
if len(recordedDelays) != 1 {
|
||||
t.Fatalf("len(recordedDelays) = %d, want 1", len(recordedDelays))
|
||||
}
|
||||
if recordedDelays[0] != 200*time.Millisecond {
|
||||
t.Errorf("delay[0] = %v, want 200ms", recordedDelays[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenManagerRetriesOnTimeoutUntilSuccess(t *testing.T) {
|
||||
var calls int
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
writeTokenResponse(t, w, "timeout-recovered-access", "timeout-recovered-refresh", 28800)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
var recordedDelays []time.Duration
|
||||
transport := NewRetryTransport(
|
||||
server.Client().Transport,
|
||||
50*time.Millisecond,
|
||||
2,
|
||||
)
|
||||
transport.retryWait = func(ctx context.Context, delay time.Duration) bool {
|
||||
recordedDelays = append(recordedDelays, delay)
|
||||
return true
|
||||
}
|
||||
httpClient := &http.Client{Transport: transport}
|
||||
|
||||
manager := NewTokenManager(httpClient, server.URL, "test-user", "test-pass")
|
||||
token, err := manager.AccessToken(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("AccessToken() error = %v", err)
|
||||
}
|
||||
if token != "timeout-recovered-access" {
|
||||
t.Errorf("token = %q, want timeout-recovered-access", token)
|
||||
}
|
||||
if calls != 2 {
|
||||
t.Errorf("calls = %d, want 2", calls)
|
||||
}
|
||||
if len(recordedDelays) != 1 {
|
||||
t.Fatalf("len(recordedDelays) = %d, want 1", len(recordedDelays))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenManagerRetriesExhausted(t *testing.T) {
|
||||
var calls int
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
var recordedDelays []time.Duration
|
||||
transport := NewRetryTransport(
|
||||
server.Client().Transport,
|
||||
time.Second,
|
||||
2,
|
||||
)
|
||||
transport.retryWait = func(ctx context.Context, delay time.Duration) bool {
|
||||
recordedDelays = append(recordedDelays, delay)
|
||||
return true
|
||||
}
|
||||
httpClient := &http.Client{Transport: transport}
|
||||
|
||||
manager := NewTokenManager(httpClient, server.URL, "test-user", "test-pass")
|
||||
_, err := manager.AccessToken(context.Background())
|
||||
if !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("error = %v, want ErrUnavailable", err)
|
||||
}
|
||||
if calls != 3 {
|
||||
t.Errorf("calls = %d, want 3", calls)
|
||||
}
|
||||
if len(recordedDelays) != 2 {
|
||||
t.Fatalf("len(recordedDelays) = %d, want 2", len(recordedDelays))
|
||||
}
|
||||
}
|
||||
|
||||
239
backend/internal/zarinhub/transport.go
Normal file
239
backend/internal/zarinhub/transport.go
Normal file
@@ -0,0 +1,239 @@
|
||||
package zarinhub
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type RetryTransport struct {
|
||||
base http.RoundTripper
|
||||
timeout time.Duration
|
||||
maxRetries int
|
||||
retryWait func(ctx context.Context, delay time.Duration) bool
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func NewRetryTransport(
|
||||
base http.RoundTripper,
|
||||
timeout time.Duration,
|
||||
maxRetries int,
|
||||
loggers ...*slog.Logger,
|
||||
) *RetryTransport {
|
||||
if base == nil {
|
||||
base = http.DefaultTransport
|
||||
}
|
||||
if maxRetries < 0 {
|
||||
maxRetries = 0
|
||||
}
|
||||
|
||||
var logger *slog.Logger
|
||||
if len(loggers) > 0 && loggers[0] != nil {
|
||||
logger = loggers[0]
|
||||
}
|
||||
|
||||
return &RetryTransport{
|
||||
base: base,
|
||||
timeout: timeout,
|
||||
maxRetries: maxRetries,
|
||||
retryWait: waitForRetry,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func NewHTTPClient(
|
||||
timeout time.Duration,
|
||||
maxRetries int,
|
||||
loggers ...*slog.Logger,
|
||||
) *http.Client {
|
||||
transport := NewRetryTransport(
|
||||
http.DefaultTransport,
|
||||
timeout,
|
||||
maxRetries,
|
||||
loggers...,
|
||||
)
|
||||
|
||||
return &http.Client{
|
||||
Transport: transport,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *RetryTransport) log() *slog.Logger {
|
||||
if t.logger != nil {
|
||||
return t.logger
|
||||
}
|
||||
return slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
}
|
||||
|
||||
func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
waitFn := t.retryWait
|
||||
if waitFn == nil {
|
||||
waitFn = waitForRetry
|
||||
}
|
||||
|
||||
if req.Body != nil && req.GetBody == nil {
|
||||
bodyBytes, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = req.Body.Close()
|
||||
req.GetBody = func() (io.ReadCloser, error) {
|
||||
return io.NopCloser(bytes.NewReader(bodyBytes)), nil
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
resp *http.Response
|
||||
err error
|
||||
)
|
||||
|
||||
for attempt := 0; attempt <= t.maxRetries; attempt++ {
|
||||
if attempt > 0 {
|
||||
t.log().InfoContext(
|
||||
req.Context(),
|
||||
fmt.Sprintf("[RETRY] zarinhub request attempt %d", attempt),
|
||||
"is_retry", true,
|
||||
"retry_count", attempt,
|
||||
)
|
||||
} else {
|
||||
t.log().InfoContext(
|
||||
req.Context(),
|
||||
"[INITIAL] zarinhub request",
|
||||
"is_retry", false,
|
||||
"retry_count", 0,
|
||||
)
|
||||
}
|
||||
|
||||
var (
|
||||
attemptCtx context.Context
|
||||
cancelAttempt context.CancelFunc
|
||||
)
|
||||
if t.timeout > 0 {
|
||||
attemptCtx, cancelAttempt = context.WithTimeout(req.Context(), t.timeout)
|
||||
} else {
|
||||
attemptCtx = req.Context()
|
||||
cancelAttempt = func() {}
|
||||
}
|
||||
|
||||
attemptReq := req.Clone(attemptCtx)
|
||||
if req.GetBody != nil {
|
||||
body, bodyErr := req.GetBody()
|
||||
if bodyErr != nil {
|
||||
cancelAttempt()
|
||||
return nil, bodyErr
|
||||
}
|
||||
attemptReq.Body = body
|
||||
}
|
||||
|
||||
resp, err = t.base.RoundTrip(attemptReq)
|
||||
|
||||
if req.Context().Err() != nil {
|
||||
cancelAttempt()
|
||||
if resp != nil && resp.Body != nil {
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
if errors.Is(req.Context().Err(), context.Canceled) {
|
||||
return nil, fmt.Errorf("zarinhub request canceled: %w", req.Context().Err())
|
||||
}
|
||||
return nil, req.Context().Err()
|
||||
}
|
||||
|
||||
isErrRetryable := false
|
||||
var retryReason error
|
||||
|
||||
if err != nil {
|
||||
isErrRetryable = isTransportErrorRetryable(err)
|
||||
retryReason = err
|
||||
} else if isStatusCodeRetryable(resp.StatusCode) {
|
||||
isErrRetryable = true
|
||||
retryReason = fmt.Errorf("upstream returned status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
if !isErrRetryable {
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body = &bodyWithCancel{
|
||||
ReadCloser: resp.Body,
|
||||
cancel: cancelAttempt,
|
||||
}
|
||||
} else {
|
||||
cancelAttempt()
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
if attempt == t.maxRetries {
|
||||
if attempt > 0 {
|
||||
t.log().ErrorContext(
|
||||
req.Context(),
|
||||
"[RETRY] zarinhub request failed: all retries exhausted",
|
||||
"is_retry", true,
|
||||
"retry_count", attempt,
|
||||
"error", retryReason,
|
||||
)
|
||||
}
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body = &bodyWithCancel{
|
||||
ReadCloser: resp.Body,
|
||||
cancel: cancelAttempt,
|
||||
}
|
||||
} else {
|
||||
cancelAttempt()
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
if resp != nil && resp.Body != nil {
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
cancelAttempt()
|
||||
|
||||
delay := retryDelay(attempt)
|
||||
t.log().WarnContext(
|
||||
req.Context(),
|
||||
fmt.Sprintf("[RETRY] zarinhub request failed, retrying in %v (retry %d)", delay, attempt+1),
|
||||
"is_retry", true,
|
||||
"next_retry", attempt+1,
|
||||
"delay_ms", delay.Milliseconds(),
|
||||
"error", retryReason,
|
||||
)
|
||||
|
||||
if !waitFn(req.Context(), delay) {
|
||||
if req.Context().Err() != nil {
|
||||
if errors.Is(req.Context().Err(), context.Canceled) {
|
||||
return nil, fmt.Errorf("zarinhub request canceled: %w", req.Context().Err())
|
||||
}
|
||||
return nil, req.Context().Err()
|
||||
}
|
||||
return nil, context.Canceled
|
||||
}
|
||||
}
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func isTransportErrorRetryable(err error) bool {
|
||||
return !errors.Is(err, context.Canceled)
|
||||
}
|
||||
|
||||
func isStatusCodeRetryable(statusCode int) bool {
|
||||
return statusCode == http.StatusRequestTimeout ||
|
||||
statusCode == http.StatusTooManyRequests ||
|
||||
statusCode >= http.StatusInternalServerError
|
||||
}
|
||||
|
||||
type bodyWithCancel struct {
|
||||
io.ReadCloser
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (b *bodyWithCancel) Close() error {
|
||||
err := b.ReadCloser.Close()
|
||||
b.cancel()
|
||||
return err
|
||||
}
|
||||
211
backend/internal/zarinhub/transport_test.go
Normal file
211
backend/internal/zarinhub/transport_test.go
Normal file
@@ -0,0 +1,211 @@
|
||||
package zarinhub
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRetryTransportPreservesAndRewindsBody(t *testing.T) {
|
||||
var attempts int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
att := atomic.AddInt32(&attempts, 1)
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Errorf("read body error: %v", err)
|
||||
}
|
||||
if string(body) != `{"payload":"important"}` {
|
||||
t.Errorf("unexpected body on attempt %d: %q", att, string(body))
|
||||
}
|
||||
if att < 3 {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"status":"ok"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
transport := NewRetryTransport(server.Client().Transport, time.Second, 3)
|
||||
transport.retryWait = func(ctx context.Context, delay time.Duration) bool {
|
||||
return true
|
||||
}
|
||||
client := &http.Client{Transport: transport}
|
||||
|
||||
req, err := http.NewRequestWithContext(
|
||||
context.Background(),
|
||||
http.MethodPost,
|
||||
server.URL,
|
||||
bytes.NewReader([]byte(`{"payload":"important"}`)),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRequest error: %v", err)
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("client.Do error: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusOK)
|
||||
}
|
||||
if attempts != 3 {
|
||||
t.Errorf("attempts = %d, want 3", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryTransportDoesNotRetryClientErrors(t *testing.T) {
|
||||
tests := []int{
|
||||
http.StatusBadRequest,
|
||||
http.StatusUnauthorized,
|
||||
http.StatusForbidden,
|
||||
http.StatusNotFound,
|
||||
http.StatusUnprocessableEntity,
|
||||
}
|
||||
|
||||
for _, statusCode := range tests {
|
||||
t.Run(fmt.Sprintf("status_%d", statusCode), func(t *testing.T) {
|
||||
var attempts int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
atomic.AddInt32(&attempts, 1)
|
||||
w.WriteHeader(statusCode)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
transport := NewRetryTransport(server.Client().Transport, time.Second, 2)
|
||||
client := &http.Client{Transport: transport}
|
||||
|
||||
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, server.URL, nil)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("client.Do error: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != statusCode {
|
||||
t.Errorf("statusCode = %d, want %d", resp.StatusCode, statusCode)
|
||||
}
|
||||
if attempts != 1 {
|
||||
t.Errorf("attempts = %d, want 1", attempts)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryTransportPerAttemptTimeout(t *testing.T) {
|
||||
var attempts int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
att := atomic.AddInt32(&attempts, 1)
|
||||
if att == 1 {
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
transport := NewRetryTransport(server.Client().Transport, 40*time.Millisecond, 2)
|
||||
transport.retryWait = func(ctx context.Context, delay time.Duration) bool {
|
||||
return true
|
||||
}
|
||||
client := &http.Client{Transport: transport}
|
||||
|
||||
// Parent context has plenty of time (5s)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("client.Do error: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Errorf("status = %d, want 200", resp.StatusCode)
|
||||
}
|
||||
if attempts != 2 {
|
||||
t.Errorf("attempts = %d, want 2", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryTransportParentContextCancellation(t *testing.T) {
|
||||
var attempts int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
atomic.AddInt32(&attempts, 1)
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
transport := NewRetryTransport(server.Client().Transport, time.Second, 3)
|
||||
transport.retryWait = func(c context.Context, delay time.Duration) bool {
|
||||
cancel() // cancel parent context during backoff
|
||||
return waitForRetry(ctx, delay)
|
||||
}
|
||||
client := &http.Client{Transport: transport}
|
||||
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil)
|
||||
_, err := client.Do(req)
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("error = %v, want context.Canceled", err)
|
||||
}
|
||||
if attempts != 1 {
|
||||
t.Errorf("attempts = %d, want 1", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryTransportLoggingFormat(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
var buf bytes.Buffer
|
||||
logger := slog.New(slog.NewJSONHandler(&buf, nil))
|
||||
|
||||
transport := NewRetryTransport(server.Client().Transport, time.Second, 1, logger)
|
||||
transport.retryWait = func(ctx context.Context, delay time.Duration) bool {
|
||||
return true
|
||||
}
|
||||
client := &http.Client{Transport: transport}
|
||||
|
||||
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, server.URL, nil)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
logStr := buf.String()
|
||||
if !strings.Contains(logStr, "[INITIAL] zarinhub request") {
|
||||
t.Errorf("expected logs to contain '[INITIAL] zarinhub request', got: %s", logStr)
|
||||
}
|
||||
if !strings.Contains(logStr, `"is_retry":false`) {
|
||||
t.Errorf("expected logs to contain '\"is_retry\":false', got: %s", logStr)
|
||||
}
|
||||
if !strings.Contains(logStr, "[RETRY] zarinhub request attempt 1") {
|
||||
t.Errorf("expected logs to contain '[RETRY] zarinhub request attempt 1', got: %s", logStr)
|
||||
}
|
||||
if !strings.Contains(logStr, "[RETRY] zarinhub request failed, retrying in") {
|
||||
t.Errorf("expected logs to contain retry warning, got: %s", logStr)
|
||||
}
|
||||
if !strings.Contains(logStr, "[RETRY] zarinhub request failed: all retries exhausted") {
|
||||
t.Errorf("expected logs to contain exhausted message, got: %s", logStr)
|
||||
}
|
||||
}
|
||||
@@ -252,7 +252,7 @@ onBeforeUnmount(dismissToast)
|
||||
v-if="iban"
|
||||
ref="resultElement"
|
||||
data-result="iban"
|
||||
class="border-border bg-accent/55 border-t p-5 outline-none sm:p-6"
|
||||
class="border-border bg-accent/55 border-t px-4 py-5 outline-none sm:p-6"
|
||||
tabindex="-1"
|
||||
aria-live="polite"
|
||||
>
|
||||
@@ -270,7 +270,7 @@ onBeforeUnmount(dismissToast)
|
||||
</div>
|
||||
|
||||
<output
|
||||
class="border-brand/15 bg-surface block overflow-x-auto rounded-lg border px-4 py-5 text-center font-mono text-lg font-bold tracking-[0.04em] whitespace-nowrap sm:text-xl"
|
||||
class="border-brand/15 bg-surface block overflow-x-auto rounded-lg border px-2.5 py-4 text-center font-mono text-xs font-bold tracking-normal whitespace-nowrap min-[390px]:text-sm sm:px-4 sm:py-5 sm:text-xl sm:tracking-[0.04em]"
|
||||
dir="ltr"
|
||||
>{{ formattedIBAN }}</output>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user