Repository navigation
fix: Example: Safe Mutation with Idempotent POST Requests #68
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
webbrain-one
wants to merge
1
commit into
cinar:main
Choose a base branch
from
webbrain-one:webbrain/issue-49
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,180 @@ | ||
| // Copyright (c) 2026 Onur Cinar. | ||
| // The source code is provided under MIT License. | ||
| // https://github.com/cinar/resile | ||
|
|
||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "crypto/rand" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/cinar/resile" | ||
| ) | ||
|
|
||
| // HTTPError represents a non-2xx HTTP response. | ||
| type HTTPError struct { | ||
| StatusCode int | ||
| Body string | ||
| } | ||
|
|
||
| func (e *HTTPError) Error() string { | ||
| return fmt.Sprintf("HTTP request failed with status %d: %s", e.StatusCode, e.Body) | ||
| } | ||
|
|
||
| // shouldRetry restricts retries to transient server errors and transport errors. | ||
| // It explicitly aborts on 400 Bad Request, 401 Unauthorized, and other client errors. | ||
| func shouldRetry(err error) bool { | ||
| if err == nil { | ||
| return false | ||
| } | ||
|
|
||
| if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { | ||
| return false | ||
| } | ||
|
|
||
| var httpErr *HTTPError | ||
| if errors.As(err, &httpErr) { | ||
| switch httpErr.StatusCode { | ||
| case http.StatusInternalServerError, http.StatusBadGateway, http.StatusGatewayTimeout: | ||
| return true | ||
| default: | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| // Network-level failures (reset connections, DNS, TLS) are safe to retry | ||
| // because the server never processed the mutation. | ||
| return true | ||
| } | ||
|
|
||
| func newUUID() (string, error) { | ||
| var b [16]byte | ||
| if _, err := rand.Read(b[:]); err != nil { | ||
| return "", err | ||
| } | ||
|
|
||
| b[6] = (b[6] & 0x0f) | 0x40 | ||
| b[8] = (b[8] & 0x3f) | 0x80 | ||
|
|
||
| return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil | ||
| } | ||
|
|
||
| func main() { | ||
| var mu sync.Mutex | ||
| attempts := make(map[string]int) | ||
|
|
||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| body, _ := io.ReadAll(r.Body) | ||
| key := r.Header.Get("Idempotency-Key") | ||
|
|
||
| // Terminal business-logic error: invalid payload. Never retried. | ||
| if strings.Contains(string(body), "terminal") { | ||
| w.WriteHeader(http.StatusBadRequest) | ||
| fmt.Fprintln(w, "invalid order: quantity must be positive") | ||
| return | ||
| } | ||
|
|
||
| mu.Lock() | ||
| attempts[key]++ | ||
| n := attempts[key] | ||
| mu.Unlock() | ||
|
|
||
| switch n { | ||
| case 1: | ||
| w.WriteHeader(http.StatusInternalServerError) | ||
| fmt.Fprintln(w, "order service temporarily unavailable") | ||
| case 2: | ||
| w.WriteHeader(http.StatusBadGateway) | ||
| fmt.Fprintln(w, "upstream gateway unavailable") | ||
| case 3: | ||
| w.WriteHeader(http.StatusGatewayTimeout) | ||
| fmt.Fprintln(w, "upstream gateway timed out") | ||
| default: | ||
| w.Header().Set("Content-Type", "application/json") | ||
| fmt.Fprintf(w, `{"status":"accepted","idempotency_key":"%s"}`, key) | ||
| } | ||
| })) | ||
| defer server.Close() | ||
|
|
||
| client := &http.Client{Timeout: 2 * time.Second} | ||
| ctx := context.Background() | ||
|
|
||
| fmt.Println("--- Safe Mutation with Idempotent POST Requests ---") | ||
| fmt.Println("Transient 5xx responses are retried with the SAME Idempotency-Key.") | ||
| fmt.Println("Terminal 400 responses are pushed back to the caller and abort.") | ||
|
|
||
| // Transient scenario: 500, 502, 504, then success. | ||
| if err := executeSafePOST(ctx, client, server.URL, `{"order":"transient"}`, 4); err != nil { | ||
| fmt.Printf("Unexpected failure in transient scenario: %v\n", err) | ||
| return | ||
| } | ||
|
|
||
| // Terminal scenario: 400 Bad Request, no retry. | ||
| if err := executeSafePOST(ctx, client, server.URL, `{"order":"terminal"}`, 4); err != nil { | ||
| var httpErr *HTTPError | ||
| if errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusBadRequest { | ||
| fmt.Println("\nTerminal 400 Bad Request was not retried (as expected).") | ||
| return | ||
| } | ||
| fmt.Printf("Unexpected failure in terminal scenario: %v\n", err) | ||
| return | ||
| } | ||
|
|
||
| fmt.Println("\nUnexpected: terminal scenario succeeded instead of returning 400.") | ||
| } | ||
|
|
||
| func executeSafePOST(ctx context.Context, client *http.Client, url string, payload string, maxAttempts int) error { | ||
| // Generate the idempotency key once, before the resile.Do retry loop begins. | ||
| key, err := newUUID() | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| fmt.Printf("\nNew mutation request key: %s\n", key) | ||
| attempt := 0 | ||
|
|
||
| _, err = resile.Do(ctx, func(ctx context.Context) (string, error) { | ||
| attempt++ | ||
| fmt.Printf(" [Attempt %d] POST /orders with Idempotency-Key: %s\n", attempt, key) | ||
|
|
||
| req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(payload)) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Idempotency-Key", key) | ||
|
|
||
| resp, err := client.Do(req) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| respBody, err := io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
|
|
||
| if resp.StatusCode < 200 || resp.StatusCode >= 300 { | ||
| return "", &HTTPError{StatusCode: resp.StatusCode, Body: string(respBody)} | ||
| } | ||
|
|
||
| fmt.Printf(" [Attempt %d] Mutation accepted: %s\n", attempt, string(respBody)) | ||
| return string(respBody), nil | ||
| }, | ||
| resile.WithName("safe-mutation-post"), | ||
| resile.WithMaxAttempts(maxAttempts), | ||
| resile.WithBaseDelay(50*time.Millisecond), | ||
| resile.WithRetryIfFunc(shouldRetry), | ||
| ) | ||
|
|
||
| return err | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| // Copyright (c) 2026 Onur Cinar. | ||
| // The source code is provided under MIT License. | ||
| // https://github.com/cinar/resile | ||
|
|
||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "net/http" | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestShouldRetry(t *testing.T) { | ||
| t.Parallel() | ||
|
|
||
| tests := []struct { | ||
| name string | ||
| err error | ||
| want bool | ||
| }{ | ||
| {"nil", nil, false}, | ||
| {"canceled", context.Canceled, false}, | ||
| {"deadline", context.DeadlineExceeded, false}, | ||
| {"transport", errors.New("connection reset by peer"), true}, | ||
| {"wrapped transport", fmt.Errorf("request failed: %w", errors.New("connection reset by peer")), true}, | ||
| {"500", &HTTPError{StatusCode: http.StatusInternalServerError}, true}, | ||
| {"502", &HTTPError{StatusCode: http.StatusBadGateway}, true}, | ||
| {"504", &HTTPError{StatusCode: http.StatusGatewayTimeout}, true}, | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is skipping 503 (Service Unavailable) intentional? Would you like to include it here? |
||
| {"wrapped 500", fmt.Errorf("do: %w", &HTTPError{StatusCode: http.StatusInternalServerError}), true}, | ||
| {"400", &HTTPError{StatusCode: http.StatusBadRequest}, false}, | ||
| {"401", &HTTPError{StatusCode: http.StatusUnauthorized}, false}, | ||
| {"404", &HTTPError{StatusCode: http.StatusNotFound}, false}, | ||
| {"503", &HTTPError{StatusCode: http.StatusServiceUnavailable}, false}, | ||
| } | ||
|
|
||
| for _, tc := range tests { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| t.Parallel() | ||
| if got := shouldRetry(tc.err); got != tc.want { | ||
| t.Errorf("shouldRetry(%v) = %v, want %v", tc.err, got, tc.want) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The executeSafePOST declares maxAttempts as int but passes it directly to resile.WithMaxAttempts, which requires uint. Perhaps you can change it here as well?