Compare commits
7 Commits
be97d94ef6
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 055c8d8777 | |||
| 8e39fd4503 | |||
| 646575ff28 | |||
| 8bea266f03 | |||
| c6e2ce7fd5 | |||
| 099ec2150e | |||
| 9328556c28 |
@@ -3,6 +3,7 @@ ZARINHUB_API_PASSWORD=
|
|||||||
ZARINHUB_AUTH_ENDPOINT=https://zarin-hub.com/api/v5/Authentication/GetToken
|
ZARINHUB_AUTH_ENDPOINT=https://zarin-hub.com/api/v5/Authentication/GetToken
|
||||||
ZARINHUB_ENDPOINT=https://zarin-hub.com/api/v5/KYC/CardToIban
|
ZARINHUB_ENDPOINT=https://zarin-hub.com/api/v5/KYC/CardToIban
|
||||||
ZARINHUB_TIMEOUT=5s
|
ZARINHUB_TIMEOUT=5s
|
||||||
|
ZARINHUB_RETRIES=2
|
||||||
|
|
||||||
DATABASE_PATH=./card-to-iban.db
|
DATABASE_PATH=./card-to-iban.db
|
||||||
SERVER_ADDR=127.0.0.1:8080
|
SERVER_ADDR=127.0.0.1:8080
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ Open:
|
|||||||
|
|
||||||
- App: `http://127.0.0.1:3000`
|
- App: `http://127.0.0.1:3000`
|
||||||
- Health check: `http://127.0.0.1:8080/health`
|
- Health check: `http://127.0.0.1:8080/health`
|
||||||
- Swagger UI: `http://127.0.0.1:8080/docs`
|
- Swagger UI: `http://127.0.0.1:8080/docs/`
|
||||||
- OpenAPI document: `http://127.0.0.1:8080/openapi.json`
|
- OpenAPI document: `http://127.0.0.1:8080/openapi.json`
|
||||||
|
|
||||||
After backend changes, restart it or run `docker compose up --build` again so the running container uses the latest code.
|
After backend changes, restart it or run `docker compose up --build` again so the running container uses the latest code.
|
||||||
@@ -80,6 +80,7 @@ Errors use the same `requestId` returned in the `X-Request-ID` header. See Swagg
|
|||||||
- The backend validates card numbers and refreshes ZarinHub access tokens automatically.
|
- The backend validates card numbers and refreshes ZarinHub access tokens automatically.
|
||||||
- Every conversion attempt is audited in SQLite.
|
- Every conversion attempt is audited in SQLite.
|
||||||
- Card numbers and upstream responses are sanitized before storage; credentials and tokens are not persisted.
|
- Card numbers and upstream responses are sanitized before storage; credentials and tokens are not persisted.
|
||||||
|
- Unknown frontend routes display a branded 404 page with a link back to the application.
|
||||||
- SQLite data is stored in the `card_to_iban_data` Docker volume when using Compose.
|
- SQLite data is stored in the `card_to_iban_data` Docker volume when using Compose.
|
||||||
|
|
||||||
## Tests
|
## Tests
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package main
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -15,6 +16,7 @@ type config struct {
|
|||||||
ZarinHubUsername string
|
ZarinHubUsername string
|
||||||
ZarinHubPassword string
|
ZarinHubPassword string
|
||||||
ZarinHubTimeout time.Duration
|
ZarinHubTimeout time.Duration
|
||||||
|
ZarinHubRetries int
|
||||||
DatabasePath string
|
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{
|
return config{
|
||||||
ServerAddr: valueOrDefault(
|
ServerAddr: valueOrDefault(
|
||||||
getenv("SERVER_ADDR"),
|
getenv("SERVER_ADDR"),
|
||||||
@@ -64,6 +78,7 @@ func readConfig(getenv func(string) string) (config, error) {
|
|||||||
ZarinHubUsername: username,
|
ZarinHubUsername: username,
|
||||||
ZarinHubPassword: password,
|
ZarinHubPassword: password,
|
||||||
ZarinHubTimeout: timeout,
|
ZarinHubTimeout: timeout,
|
||||||
|
ZarinHubRetries: retries,
|
||||||
DatabasePath: valueOrDefault(
|
DatabasePath: valueOrDefault(
|
||||||
getenv("DATABASE_PATH"),
|
getenv("DATABASE_PATH"),
|
||||||
"./card-to-iban.db",
|
"./card-to-iban.db",
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ func TestReadConfigUsesDefaults(t *testing.T) {
|
|||||||
if config.ZarinHubTimeout != 5*time.Second {
|
if config.ZarinHubTimeout != 5*time.Second {
|
||||||
t.Errorf("ZarinHubTimeout = %v", config.ZarinHubTimeout)
|
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" {
|
if config.DatabasePath != "./card-to-iban.db" {
|
||||||
t.Errorf("DatabasePath = %q", config.DatabasePath)
|
t.Errorf("DatabasePath = %q", config.DatabasePath)
|
||||||
}
|
}
|
||||||
@@ -70,3 +73,22 @@ func TestReadConfigRejectsInvalidTimeout(t *testing.T) {
|
|||||||
t.Fatalf("readConfig() error = %v, want timeout error", err)
|
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)
|
return fmt.Errorf("load configuration: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
httpClient := &http.Client{Timeout: config.ZarinHubTimeout}
|
httpClient := zarinhub.NewHTTPClient(
|
||||||
|
config.ZarinHubTimeout,
|
||||||
|
config.ZarinHubRetries,
|
||||||
|
logger,
|
||||||
|
)
|
||||||
tokenManager := zarinhub.NewTokenManager(
|
tokenManager := zarinhub.NewTokenManager(
|
||||||
httpClient,
|
httpClient,
|
||||||
config.ZarinHubAuthEndpoint,
|
config.ZarinHubAuthEndpoint,
|
||||||
@@ -46,9 +50,10 @@ func run(logger *slog.Logger) error {
|
|||||||
config.ZarinHubPassword,
|
config.ZarinHubPassword,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
authTimeout := time.Duration(config.ZarinHubRetries+1)*config.ZarinHubTimeout + 10*time.Second
|
||||||
authContext, cancelAuth := context.WithTimeout(
|
authContext, cancelAuth := context.WithTimeout(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
config.ZarinHubTimeout,
|
authTimeout,
|
||||||
)
|
)
|
||||||
_, err = tokenManager.AccessToken(authContext)
|
_, err = tokenManager.AccessToken(authContext)
|
||||||
cancelAuth()
|
cancelAuth()
|
||||||
@@ -79,6 +84,8 @@ func run(logger *slog.Logger) error {
|
|||||||
httpClient,
|
httpClient,
|
||||||
config.ZarinHubEndpoint,
|
config.ZarinHubEndpoint,
|
||||||
tokenManager,
|
tokenManager,
|
||||||
|
config.ZarinHubRetries,
|
||||||
|
logger,
|
||||||
)
|
)
|
||||||
cardService := service.NewCardService(zarinHubClient)
|
cardService := service.NewCardService(zarinHubClient)
|
||||||
auditRepository := repository.NewAuditRepository(db)
|
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
|
||||||
|
}
|
||||||
|
|
||||||
@@ -34,8 +34,8 @@ const swaggerUI = `<!doctype html>
|
|||||||
// RegisterDocumentation registers the OpenAPI document and its Swagger UI.
|
// RegisterDocumentation registers the OpenAPI document and its Swagger UI.
|
||||||
func RegisterDocumentation(mux *http.ServeMux) {
|
func RegisterDocumentation(mux *http.ServeMux) {
|
||||||
mux.HandleFunc("GET /openapi.json", serveOpenAPI)
|
mux.HandleFunc("GET /openapi.json", serveOpenAPI)
|
||||||
mux.HandleFunc("GET /swagger/", serveSwaggerUI)
|
mux.HandleFunc("GET /docs/", serveSwaggerUI)
|
||||||
mux.HandleFunc("GET /docs", redirectToSwaggerUI)
|
mux.HandleFunc("GET /docs", redirectToDocumentation)
|
||||||
}
|
}
|
||||||
|
|
||||||
func serveOpenAPI(w http.ResponseWriter, _ *http.Request) {
|
func serveOpenAPI(w http.ResponseWriter, _ *http.Request) {
|
||||||
@@ -48,6 +48,6 @@ func serveSwaggerUI(w http.ResponseWriter, _ *http.Request) {
|
|||||||
_, _ = w.Write([]byte(swaggerUI))
|
_, _ = w.Write([]byte(swaggerUI))
|
||||||
}
|
}
|
||||||
|
|
||||||
func redirectToSwaggerUI(w http.ResponseWriter, r *http.Request) {
|
func redirectToDocumentation(w http.ResponseWriter, r *http.Request) {
|
||||||
http.Redirect(w, r, "/swagger/", http.StatusTemporaryRedirect)
|
http.Redirect(w, r, "/docs/", http.StatusTemporaryRedirect)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,16 +26,21 @@ func TestRegisterDocumentation(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Swagger UI",
|
name: "Swagger UI",
|
||||||
path: "/swagger/",
|
path: "/docs/",
|
||||||
wantStatus: http.StatusOK,
|
wantStatus: http.StatusOK,
|
||||||
wantContentType: "text/html; charset=utf-8",
|
wantContentType: "text/html; charset=utf-8",
|
||||||
wantBody: `url: "/openapi.json"`,
|
wantBody: `url: "/openapi.json"`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "documentation shortcut",
|
name: "documentation trailing slash",
|
||||||
path: "/docs",
|
path: "/docs",
|
||||||
wantStatus: http.StatusTemporaryRedirect,
|
wantStatus: http.StatusTemporaryRedirect,
|
||||||
wantLocation: "/swagger/",
|
wantLocation: "/docs/",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "removed Swagger route",
|
||||||
|
path: "/swagger/",
|
||||||
|
wantStatus: http.StatusNotFound,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ func NewHandler(
|
|||||||
func (h *Handler) Convert(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) Convert(w http.ResponseWriter, r *http.Request) {
|
||||||
startedAt := h.now()
|
startedAt := h.now()
|
||||||
requestID := h.newRequestID()
|
requestID := h.newRequestID()
|
||||||
|
clientIP := extractClientIP(r)
|
||||||
|
|
||||||
w.Header().Set("X-Request-ID", requestID)
|
w.Header().Set("X-Request-ID", requestID)
|
||||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||||
@@ -89,6 +90,7 @@ func (h *Handler) Convert(w http.ResponseWriter, r *http.Request) {
|
|||||||
RequestID: requestID,
|
RequestID: requestID,
|
||||||
CreatedAt: startedAt,
|
CreatedAt: startedAt,
|
||||||
Duration: duration,
|
Duration: duration,
|
||||||
|
ClientIP: clientIP,
|
||||||
Status: outcome.auditStatus,
|
Status: outcome.auditStatus,
|
||||||
MaskedCard: card.Mask(cardNumber),
|
MaskedCard: card.Mask(cardNumber),
|
||||||
ResponseJSON: audit.SanitizeResponse(
|
ResponseJSON: audit.SanitizeResponse(
|
||||||
@@ -102,11 +104,17 @@ func (h *Handler) Convert(w http.ResponseWriter, r *http.Request) {
|
|||||||
record.UpstreamHTTPStatus = &upstreamStatus
|
record.UpstreamHTTPStatus = &upstreamStatus
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var clientIPValue string
|
||||||
|
if clientIP != nil {
|
||||||
|
clientIPValue = *clientIP
|
||||||
|
}
|
||||||
|
|
||||||
if err := h.audits.Save(r.Context(), record); err != nil {
|
if err := h.audits.Save(r.Context(), record); err != nil {
|
||||||
h.logger.ErrorContext(
|
h.logger.ErrorContext(
|
||||||
r.Context(),
|
r.Context(),
|
||||||
"request audit failed",
|
"request audit failed",
|
||||||
"request_id", requestID,
|
"request_id", requestID,
|
||||||
|
"client_ip", clientIPValue,
|
||||||
"route", "/api/v1/card-to-iban",
|
"route", "/api/v1/card-to-iban",
|
||||||
"http_status", http.StatusInternalServerError,
|
"http_status", http.StatusInternalServerError,
|
||||||
"audit_status", audit.StatusInternalError,
|
"audit_status", audit.StatusInternalError,
|
||||||
@@ -128,6 +136,7 @@ func (h *Handler) Convert(w http.ResponseWriter, r *http.Request) {
|
|||||||
r.Context(),
|
r.Context(),
|
||||||
"request completed",
|
"request completed",
|
||||||
"request_id", requestID,
|
"request_id", requestID,
|
||||||
|
"client_ip", clientIPValue,
|
||||||
"route", "/api/v1/card-to-iban",
|
"route", "/api/v1/card-to-iban",
|
||||||
"http_status", outcome.httpStatus,
|
"http_status", outcome.httpStatus,
|
||||||
"audit_status", outcome.auditStatus,
|
"audit_status", outcome.auditStatus,
|
||||||
|
|||||||
@@ -248,6 +248,10 @@ func TestHandlerConvert(t *testing.T) {
|
|||||||
t.Errorf("masked card = %q, want %q", record.MaskedCard, tt.wantMaskedCard)
|
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") {
|
if strings.Contains(string(record.ResponseJSON), "6037997512345678") {
|
||||||
t.Error("audit response contains the full card number")
|
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())
|
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"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
"card-to-iban/internal/service"
|
"card-to-iban/internal/service"
|
||||||
)
|
)
|
||||||
|
|
||||||
const maxResponseBodySize = 1 << 20
|
const (
|
||||||
|
maxResponseBodySize = 1 << 20
|
||||||
|
|
||||||
|
retryBaseDelay = 200 * time.Millisecond
|
||||||
|
retryMaxDelay = 2 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
httpClient *http.Client
|
httpClient *http.Client
|
||||||
endpointURL string
|
endpointURL string
|
||||||
tokenProvider TokenProvider
|
tokenProvider TokenProvider
|
||||||
|
maxRetries int
|
||||||
|
retryWait func(ctx context.Context, delay time.Duration) bool
|
||||||
|
logger *slog.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ service.CardToIBANClient = (*Client)(nil)
|
var _ service.CardToIBANClient = (*Client)(nil)
|
||||||
@@ -32,17 +42,114 @@ func NewClient(
|
|||||||
httpClient *http.Client,
|
httpClient *http.Client,
|
||||||
endpointURL string,
|
endpointURL string,
|
||||||
tokenProvider TokenProvider,
|
tokenProvider TokenProvider,
|
||||||
|
maxRetries int,
|
||||||
|
loggers ...*slog.Logger,
|
||||||
) *Client {
|
) *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,
|
httpClient: httpClient,
|
||||||
endpointURL: endpointURL,
|
endpointURL: endpointURL,
|
||||||
tokenProvider: tokenProvider,
|
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(
|
func (c *Client) Convert(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
cardNumber string,
|
cardNumber string,
|
||||||
|
) (service.ConversionResult, error) {
|
||||||
|
return c.convertOnce(ctx, cardNumber)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) convertOnce(
|
||||||
|
ctx context.Context,
|
||||||
|
cardNumber string,
|
||||||
) (service.ConversionResult, error) {
|
) (service.ConversionResult, error) {
|
||||||
accessToken, err := c.tokenProvider.AccessToken(ctx)
|
accessToken, err := c.tokenProvider.AccessToken(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
package zarinhub
|
package zarinhub
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -98,6 +101,7 @@ func TestClientConvertSuccess(t *testing.T) {
|
|||||||
},
|
},
|
||||||
server.URL,
|
server.URL,
|
||||||
&fakeTokenProvider{tokens: []string{token}},
|
&fakeTokenProvider{tokens: []string{token}},
|
||||||
|
0,
|
||||||
)
|
)
|
||||||
|
|
||||||
result, err := client.Convert(
|
result, err := client.Convert(
|
||||||
@@ -172,6 +176,7 @@ func TestClientReturnsRejectedForApplicationFailure(
|
|||||||
},
|
},
|
||||||
server.URL,
|
server.URL,
|
||||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||||
|
0,
|
||||||
)
|
)
|
||||||
|
|
||||||
result, err := client.Convert(
|
result, err := client.Convert(
|
||||||
@@ -264,6 +269,7 @@ func TestClientMapsHTTPStatusErrors(t *testing.T) {
|
|||||||
},
|
},
|
||||||
server.URL,
|
server.URL,
|
||||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||||
|
0,
|
||||||
)
|
)
|
||||||
|
|
||||||
result, err := client.Convert(
|
result, err := client.Convert(
|
||||||
@@ -322,6 +328,7 @@ func TestClientReturnsInvalidResponseForMalformedJSON(
|
|||||||
},
|
},
|
||||||
server.URL,
|
server.URL,
|
||||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||||
|
0,
|
||||||
)
|
)
|
||||||
|
|
||||||
result, err := client.Convert(
|
result, err := client.Convert(
|
||||||
@@ -367,6 +374,7 @@ func TestClientReturnsTimeout(t *testing.T) {
|
|||||||
},
|
},
|
||||||
server.URL,
|
server.URL,
|
||||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||||
|
0,
|
||||||
)
|
)
|
||||||
|
|
||||||
_, err := client.Convert(
|
_, err := client.Convert(
|
||||||
@@ -403,6 +411,7 @@ func TestClientRejectsOversizedResponse(t *testing.T) {
|
|||||||
&http.Client{Timeout: time.Second},
|
&http.Client{Timeout: time.Second},
|
||||||
server.URL,
|
server.URL,
|
||||||
&fakeTokenProvider{tokens: []string{"test-token"}},
|
&fakeTokenProvider{tokens: []string{"test-token"}},
|
||||||
|
0,
|
||||||
)
|
)
|
||||||
|
|
||||||
_, err := client.Convert(
|
_, err := client.Convert(
|
||||||
@@ -442,7 +451,7 @@ func TestClientRefreshesAndRetriesUnauthorizedRequest(t *testing.T) {
|
|||||||
defer server.Close()
|
defer server.Close()
|
||||||
|
|
||||||
tokens := &fakeTokenProvider{tokens: []string{"expired-token", "fresh-token"}}
|
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")
|
result, err := client.Convert(context.Background(), "6037997512345678")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -478,3 +487,280 @@ func (p *fakeTokenProvider) AccessToken(context.Context) (string, error) {
|
|||||||
func (p *fakeTokenProvider) Invalidate(token string) {
|
func (p *fakeTokenProvider) Invalidate(token string) {
|
||||||
p.invalidated = append(p.invalidated, token)
|
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 (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -220,3 +221,120 @@ func writeTokenResponse(
|
|||||||
t.Fatalf("encode response: %v", err)
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,37 +1,3 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
const config = useRuntimeConfig()
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="min-h-dvh">
|
<NuxtPage />
|
||||||
<header class="border-border bg-surface h-14 border-b shadow-[0_1px_2px_rgba(0,0,0,.03)]">
|
|
||||||
<div class="mx-auto flex h-full w-full max-w-[1120px] items-center px-4 sm:px-6 lg:px-8">
|
|
||||||
<BrandLogo />
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<main class="mx-auto w-full max-w-[760px] px-4 py-10 sm:px-6 sm:py-14">
|
|
||||||
<section aria-labelledby="page-title">
|
|
||||||
<p class="text-brand mb-2 text-sm font-bold">سرویس تبدیل کارت به شبا</p>
|
|
||||||
<h1 id="page-title" class="text-foreground text-2xl leading-[1.5] font-extrabold sm:text-3xl">
|
|
||||||
شماره شبا را سریع و مطمئن پیدا کنید
|
|
||||||
</h1>
|
|
||||||
<p class="text-muted mt-3 max-w-[620px] text-sm leading-8 sm:text-[15px]">
|
|
||||||
استعلام مستقیماً از سرویس زرینهاب انجام میشود. شماره کامل کارت در گزارشها یا پاسخ عمومی نگهداری نمیشود.
|
|
||||||
</p>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<div class="mt-7 sm:mt-8">
|
|
||||||
<CardConverter :api-base-url="config.public.apiBaseUrl" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<p class="text-muted mt-5 flex items-start gap-2 text-xs leading-6">
|
|
||||||
<svg viewBox="0 0 24 24" class="mt-0.5 size-4 shrink-0" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true">
|
|
||||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z" />
|
|
||||||
<path d="m9 12 2 2 4-4" />
|
|
||||||
</svg>
|
|
||||||
برای حفاظت از اطلاعات بانکی، فقط نسخه پوشیدهشده شماره کارت در سوابق فنی ثبت میشود.
|
|
||||||
</p>
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -252,7 +252,7 @@ onBeforeUnmount(dismissToast)
|
|||||||
v-if="iban"
|
v-if="iban"
|
||||||
ref="resultElement"
|
ref="resultElement"
|
||||||
data-result="iban"
|
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"
|
tabindex="-1"
|
||||||
aria-live="polite"
|
aria-live="polite"
|
||||||
>
|
>
|
||||||
@@ -270,7 +270,7 @@ onBeforeUnmount(dismissToast)
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<output
|
<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"
|
dir="ltr"
|
||||||
>{{ formattedIBAN }}</output>
|
>{{ formattedIBAN }}</output>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
21
frontend/app/error.test.ts
Normal file
21
frontend/app/error.test.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { mount } from '@vue/test-utils'
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import ErrorPage from './error.vue'
|
||||||
|
|
||||||
|
describe('ErrorPage', () => {
|
||||||
|
it('renders a branded not-found page with a way home', () => {
|
||||||
|
const wrapper = mount(ErrorPage, {
|
||||||
|
props: {
|
||||||
|
error: {
|
||||||
|
statusCode: 404,
|
||||||
|
statusMessage: 'Page not found',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(wrapper.get('h1').text()).toBe('صفحه پیدا نشد')
|
||||||
|
expect(wrapper.get('a').attributes('href')).toBe('/')
|
||||||
|
expect(wrapper.get('[role="img"]').attributes('aria-label')).toBe('زرینپال')
|
||||||
|
})
|
||||||
|
})
|
||||||
55
frontend/app/error.vue
Normal file
55
frontend/app/error.vue
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { NuxtError } from '#app'
|
||||||
|
import { computed } from 'vue'
|
||||||
|
|
||||||
|
import BrandLogo from './components/BrandLogo.vue'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
error: NuxtError
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const isNotFound = computed(() => props.error.statusCode === 404)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="min-h-dvh">
|
||||||
|
<header class="border-border bg-surface h-14 border-b shadow-[0_1px_2px_rgba(0,0,0,.03)]">
|
||||||
|
<div class="mx-auto flex h-full w-full max-w-[1120px] items-center px-4 sm:px-6 lg:px-8">
|
||||||
|
<BrandLogo />
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main class="mx-auto flex w-full max-w-[760px] items-center px-4 py-12 sm:min-h-[calc(100dvh-3.5rem)] sm:px-6 sm:py-16">
|
||||||
|
<section
|
||||||
|
class="card border-border bg-surface w-full border p-6 sm:p-8"
|
||||||
|
aria-labelledby="error-title"
|
||||||
|
>
|
||||||
|
<div class="bg-accent text-brand mb-5 grid size-12 place-items-center rounded-lg" aria-hidden="true">
|
||||||
|
<svg viewBox="0 0 24 24" class="size-6" fill="none" stroke="currentColor" stroke-width="1.8">
|
||||||
|
<path d="M12 8v5m0 3.5v.01" stroke-linecap="round" />
|
||||||
|
<circle cx="12" cy="12" r="9" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="text-brand mb-2 text-sm font-bold">خطای {{ error.statusCode }}</p>
|
||||||
|
<h1 id="error-title" class="text-foreground text-2xl leading-[1.5] font-extrabold sm:text-3xl">
|
||||||
|
{{ isNotFound ? 'صفحه پیدا نشد' : 'خطایی رخ داده است' }}
|
||||||
|
</h1>
|
||||||
|
<p class="text-muted mt-3 max-w-[560px] text-sm leading-8 sm:text-[15px]">
|
||||||
|
{{
|
||||||
|
isNotFound
|
||||||
|
? 'نشانی واردشده معتبر نیست یا صفحه موردنظر جابهجا شده است.'
|
||||||
|
: 'در نمایش این صفحه مشکلی پیش آمد. لطفاً دوباره تلاش کنید.'
|
||||||
|
}}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<a
|
||||||
|
href="/"
|
||||||
|
class="bg-brand hover:bg-brand-hover text-on-brand mt-6 inline-flex min-h-11 items-center justify-center rounded-lg px-5 text-sm font-bold transition-colors"
|
||||||
|
>
|
||||||
|
بازگشت به صفحه اصلی
|
||||||
|
</a>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
37
frontend/app/pages/index.vue
Normal file
37
frontend/app/pages/index.vue
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
const config = useRuntimeConfig()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="min-h-dvh">
|
||||||
|
<header class="border-border bg-surface h-14 border-b shadow-[0_1px_2px_rgba(0,0,0,.03)]">
|
||||||
|
<div class="mx-auto flex h-full w-full max-w-[1120px] items-center px-4 sm:px-6 lg:px-8">
|
||||||
|
<BrandLogo />
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main class="mx-auto w-full max-w-[760px] px-4 py-10 sm:px-6 sm:py-14">
|
||||||
|
<section aria-labelledby="page-title">
|
||||||
|
<p class="text-brand mb-2 text-sm font-bold">سرویس تبدیل کارت به شبا</p>
|
||||||
|
<h1 id="page-title" class="text-foreground text-2xl leading-[1.5] font-extrabold sm:text-3xl">
|
||||||
|
شماره شبا را سریع و مطمئن پیدا کنید
|
||||||
|
</h1>
|
||||||
|
<p class="text-muted mt-3 max-w-[620px] text-sm leading-8 sm:text-[15px]">
|
||||||
|
استعلام مستقیماً از سرویس زرینهاب انجام میشود. شماره کامل کارت در گزارشها یا پاسخ عمومی نگهداری نمیشود.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="mt-7 sm:mt-8">
|
||||||
|
<CardConverter :api-base-url="config.public.apiBaseUrl" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="text-muted mt-5 flex items-start gap-2 text-xs leading-6">
|
||||||
|
<svg viewBox="0 0 24 24" class="mt-0.5 size-4 shrink-0" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true">
|
||||||
|
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z" />
|
||||||
|
<path d="m9 12 2 2 4-4" />
|
||||||
|
</svg>
|
||||||
|
برای حفاظت از اطلاعات بانکی، فقط نسخه پوشیدهشده شماره کارت در سوابق فنی ثبت میشود.
|
||||||
|
</p>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
Reference in New Issue
Block a user