zeroshade commented on code in PR #2679:
URL: https://github.com/apache/iceberg-go/pull/2679#discussion_r4722059585


##########
catalog/rest/idempotency_test.go:
##########
@@ -249,3 +255,579 @@ func TestMutationTransportReplay(t *testing.T) {
                })
        }
 }
+
+type keyedAttempt struct {
+       method, path, key, body string
+}
+
+// newKeyedTestCatalog serves /v1/config with every endpoint plus config (a 
JSON
+// object fragment such as `"idempotency-key-lifetime":"PT30M"`) and sends all
+// other requests to h with their 1-based count.
+func newKeyedTestCatalog(t *testing.T, config string, h func(n int, w 
http.ResponseWriter, r *http.Request)) (*Catalog, func() []keyedAttempt) {
+       t.Helper()
+       var endpoints []string
+       for _, ep := range allEndpoints {
+               endpoints = append(endpoints, ep.String())
+       }
+       eps, err := json.Marshal(endpoints)
+       require.NoError(t, err)
+       if config != "" {
+               config = "," + config
+       }
+       var mu sync.Mutex
+       var got []keyedAttempt
+       server := httptest.NewServer(http.HandlerFunc(func(w 
http.ResponseWriter, r *http.Request) {
+               if r.URL.Path == "/v1/config" {
+                       _, _ = io.WriteString(w, 
`{"endpoints":`+string(eps)+config+`}`)
+
+                       return
+               }
+               body, _ := io.ReadAll(r.Body)
+               mu.Lock()
+               got = append(got, keyedAttempt{r.Method, r.URL.Path, 
r.Header.Get(headerIdempotencyKey), string(body)})
+               n := len(got)
+               mu.Unlock()
+               h(n, w, r)
+       }))
+       t.Cleanup(server.Close)
+       c, err := newCatalogFromProps(t.Context(), "test", server.URL, nil)
+       require.NoError(t, err)
+       t.Cleanup(func() { _ = c.Close() })
+
+       return c, func() []keyedAttempt {
+               mu.Lock()
+               defer mu.Unlock()
+
+               return append([]keyedAttempt(nil), got...)
+       }
+}
+
+func lifetimeConfig(v string) string { return `"idempotency-key-lifetime":"` + 
v + `"` }
+
+func dropConnection(w http.ResponseWriter) {
+       if conn, _, err := w.(http.Hijacker).Hijack(); err == nil {
+               _ = conn.Close()
+       }
+}
+
+func uuidV7At(created time.Time) string {
+       var id uuid.UUID
+       ms := created.UnixMilli()
+       for i := range 6 {
+               id[i] = byte(ms >> (8 * (5 - i)))
+       }
+       id[6], id[8] = 0x70, 0x80
+
+       return id.String()
+}
+
+func TestKeyedResendReusesKeyAndBody(t *testing.T) {
+       t.Parallel()
+       ns := table.Identifier{"ns"}
+       for _, status := range []int{500, 502, 503, 504} {
+               t.Run(strconv.Itoa(status), func(t *testing.T) {
+                       t.Parallel()
+                       c, attempts := newKeyedTestCatalog(t, 
lifetimeConfig("PT30M"), func(n int, w http.ResponseWriter, _ *http.Request) {
+                               if n == 1 {
+                                       w.WriteHeader(status)
+
+                                       return
+                               }
+                               _, _ = io.WriteString(w, `{}`)
+                       })
+                       require.NoError(t, c.CreateNamespace(t.Context(), ns, 
nil))
+                       got := attempts()
+                       require.Len(t, got, 2)
+                       require.NotEmpty(t, got[0].key)
+                       require.Equal(t, got[0], got[1])
+                       require.NotEmpty(t, got[0].body)
+               })
+       }
+       t.Run("delete", func(t *testing.T) {
+               t.Parallel()
+               c, attempts := newKeyedTestCatalog(t, lifetimeConfig("PT30M"), 
func(n int, w http.ResponseWriter, _ *http.Request) {
+                       if n == 1 {
+                               w.WriteHeader(http.StatusServiceUnavailable)
+
+                               return
+                       }
+                       w.WriteHeader(http.StatusNoContent)
+               })
+               require.NoError(t, c.DropNamespace(t.Context(), ns))
+               got := attempts()
+               require.Len(t, got, 2)
+               require.NotEmpty(t, got[0].key)
+               require.Equal(t, got[0], got[1])
+       })
+       t.Run("connection error", func(t *testing.T) {
+               t.Parallel()
+               // No warm connection, so net/http does not replay: this is the 
explicit resend.
+               c, attempts := newKeyedTestCatalog(t, lifetimeConfig("PT30M"), 
func(n int, w http.ResponseWriter, _ *http.Request) {
+                       if n == 1 {
+                               dropConnection(w)
+
+                               return
+                       }
+                       _, _ = io.WriteString(w, `{}`)
+               })
+               require.NoError(t, c.CreateNamespace(t.Context(), ns, nil))
+               got := attempts()
+               require.Len(t, got, 2)
+               require.NotEmpty(t, got[0].key)
+               require.Equal(t, got[0], got[1])
+       })
+}
+
+func TestKeyedSeparateCallsUseNewKeys(t *testing.T) {
+       t.Parallel()
+       id := table.Identifier{"ns", "name"}
+       c, attempts := newKeyedTestCatalog(t, lifetimeConfig("PT30M"), func(_ 
int, w http.ResponseWriter, _ *http.Request) {
+               w.WriteHeader(http.StatusConflict)
+       })
+       // A transaction refreshed after a 409 is a new call: it must not reuse 
the key.
+       for range 2 {
+               _, _, err := c.CommitTable(t.Context(), id, nil, nil)
+               require.ErrorIs(t, err, ErrCommitFailed)
+       }
+       got := attempts()
+       require.Len(t, got, 2)
+       require.NotEmpty(t, got[0].key)
+       require.NotEqual(t, got[0].key, got[1].key)
+}
+
+func TestCommitResendConflictAfterExpiry(t *testing.T) {
+       for _, tc := range []struct {
+               status int
+               body   string
+       }{
+               {http.StatusConflict, `{"error":{"message":"requirement 
failed","type":"CommitFailedException","code":409}}`},
+               {http.StatusBadRequest, `{"error":{"message":"requirement 
failed","type":"BadRequestException","code":400}}`},
+       } {
+               var applied atomic.Int32
+               c, attempts := newKeyedTestCatalog(t, lifetimeConfig("PT1S"), 
func(n int, w http.ResponseWriter, _ *http.Request) {
+                       if n == 1 {
+                               applied.Add(1)
+                               dropConnection(w)
+
+                               return
+                       }
+                       w.WriteHeader(tc.status)
+                       _, _ = io.WriteString(w, tc.body)
+               })
+               transport := c.cl.Transport
+               sends := 0
+               c.cl.Transport = roundTripFunc(func(r *http.Request) 
(*http.Response, error) {
+                       sends++
+                       if sends == 2 {
+                               time.Sleep(time.Second)
+                       }
+
+                       return transport.RoundTrip(r)
+               })
+               _, _, err := c.CommitTable(t.Context(), table.Identifier{"ns", 
"name"}, nil, nil)
+               require.ErrorIs(t, err, ErrCommitStateUnknown, tc.status)
+               // else the table commit loop replays the commit or cleans up 
its files
+               require.NotErrorIs(t, err, table.ErrCommitFailed, tc.status)
+               require.NotErrorIs(t, err, table.ErrCommitRejected, tc.status)
+               require.ErrorContains(t, err, "requirement failed")
+               got := attempts()
+               require.Len(t, got, 2)
+               require.EqualValues(t, 1, applied.Load())
+               require.NotEmpty(t, got[0].key)
+               require.Equal(t, got[0], got[1])
+       }
+}
+
+func TestKeyedResendTimerRechecksExpiry(t *testing.T) {
+       for _, commit := range []bool{true, false} {
+               start := time.Now()
+               clockReads := 0
+               kc := &keyedCall{
+                       policy: &idempotencyPolicy{}, commit: commit, key: 
"key", start: start, lifetime: time.Second,
+                       now: func() time.Time {
+                               clockReads++
+                               if clockReads > 1 {
+                                       return start.Add(time.Second)
+                               }
+
+                               return start
+                       },
+               }
+               attempts := 0
+               cl := &http.Client{Transport: roundTripFunc(func(*http.Request) 
(*http.Response, error) {
+                       attempts++
+
+                       return nil, io.EOF
+               })}
+               _, err := send(t.Context(), cl, kc, &reqConfig{}, nil, func() 
(*http.Request, error) {
+                       return http.NewRequestWithContext(t.Context(), 
http.MethodPost, "http://catalog.test";, nil)
+               })
+               require.ErrorIs(t, err, io.EOF)
+               if commit {
+                       require.ErrorIs(t, err, ErrCommitStateUnknown)
+               } else {
+                       require.NotErrorIs(t, err, ErrCommitStateUnknown)
+               }
+               require.Equal(t, 1, attempts, "commit=%v", commit)
+               require.Equal(t, 2, clockReads)
+       }
+}
+
+func TestKeyedNoResendOn4xx(t *testing.T) {
+       t.Parallel()
+       for _, status := range []int{400, 401, 403, 404, 408, 409, 429} {
+               t.Run(strconv.Itoa(status), func(t *testing.T) {
+                       t.Parallel()
+                       c, attempts := newKeyedTestCatalog(t, 
lifetimeConfig("PT30M"), func(_ int, w http.ResponseWriter, _ *http.Request) {
+                               w.WriteHeader(status)
+                       })
+                       require.Error(t, c.CreateNamespace(t.Context(), 
table.Identifier{"ns"}, nil))
+                       require.Len(t, attempts(), 1)
+               })
+       }
+}
+
+func TestKeyedNoResendWithoutUsableLifetime(t *testing.T) {
+       t.Parallel()
+       for _, tc := range []struct {
+               name, config string
+               keyed        bool
+       }{
+               {"absent", ``, false},
+               {"null", `"idempotency-key-lifetime":null`, false},
+               {"zero", lifetimeConfig("PT0S"), true},
+               {"negative", lifetimeConfig("-PT1S"), true},
+               {"malformed", lifetimeConfig("soon"), true},
+               {"out of range", lifetimeConfig("PT9223372036854775808S"), 
true},
+               {"empty", lifetimeConfig(""), true},
+       } {
+               t.Run(tc.name, func(t *testing.T) {
+                       t.Parallel()
+                       c, attempts := newKeyedTestCatalog(t, tc.config, func(_ 
int, w http.ResponseWriter, _ *http.Request) {
+                               w.WriteHeader(http.StatusServiceUnavailable)
+                       })
+                       require.Error(t, c.CreateNamespace(t.Context(), 
table.Identifier{"ns"}, nil))
+                       got := attempts()
+                       require.Len(t, got, 1)
+                       require.Equal(t, tc.keyed, got[0].key != "")
+               })
+       }
+}
+
+func TestKeyedResendBudget(t *testing.T) {
+       t.Parallel()
+       c, attempts := newKeyedTestCatalog(t, lifetimeConfig("PT30M"), func(_ 
int, w http.ResponseWriter, _ *http.Request) {
+               w.WriteHeader(http.StatusServiceUnavailable)
+       })
+       err := c.CreateNamespace(t.Context(), table.Identifier{"ns"}, nil)
+       require.ErrorIs(t, err, ErrServiceUnavailable)
+       require.Len(t, attempts(), 1+keyedMaxRetries)
+}
+
+func TestKeyedResendStopsAtExpiry(t *testing.T) {
+       t.Parallel()
+       ns, id := table.Identifier{"ns"}, table.Identifier{"ns", "name"}
+       t.Run("next delay would exceed the window", func(t *testing.T) {
+               t.Parallel()
+               c, attempts := newKeyedTestCatalog(t, lifetimeConfig("PT1S"), 
func(_ int, w http.ResponseWriter, _ *http.Request) {
+                       w.Header().Set("Retry-After", "2")
+                       w.WriteHeader(http.StatusServiceUnavailable)
+               })
+               start := time.Now()
+               err := c.CreateNamespace(t.Context(), ns, nil)
+               require.ErrorIs(t, err, ErrServiceUnavailable)
+               require.Len(t, attempts(), 1)
+               require.Less(t, time.Since(start), time.Second)
+       })
+       t.Run("slow first attempt", func(t *testing.T) {
+               t.Parallel()
+               c, attempts := newKeyedTestCatalog(t, lifetimeConfig("PT1S"), 
func(_ int, w http.ResponseWriter, _ *http.Request) {
+                       time.Sleep(1100 * time.Millisecond)
+                       w.WriteHeader(http.StatusServiceUnavailable)
+               })
+               err := c.CreateNamespace(t.Context(), ns, nil)
+               require.ErrorIs(t, err, ErrServiceUnavailable)
+               require.Len(t, attempts(), 1)
+       })
+       t.Run("commit reports unknown state", func(t *testing.T) {
+               t.Parallel()
+               c, attempts := newKeyedTestCatalog(t, lifetimeConfig("PT1S"), 
func(_ int, w http.ResponseWriter, _ *http.Request) {
+                       w.Header().Set("Retry-After", "2")
+                       w.WriteHeader(http.StatusServiceUnavailable)
+               })
+               _, _, err := c.CommitTable(t.Context(), id, nil, nil)
+               require.ErrorIs(t, err, ErrCommitStateUnknown)
+               require.Len(t, attempts(), 1)
+       })
+       t.Run("commit connection error reports unknown state", func(t 
*testing.T) {
+               t.Parallel()
+               for _, config := range []string{lifetimeConfig("PT0S"), 
lifetimeConfig("PT1S")} {
+                       c, attempts := newKeyedTestCatalog(t, config, func(_ 
int, w http.ResponseWriter, _ *http.Request) {
+                               dropConnection(w)
+                       })
+                       _, _, err := c.CommitTable(t.Context(), id, nil, nil)
+                       require.ErrorIs(t, err, ErrCommitStateUnknown)
+                       require.NotEmpty(t, attempts()[0].key)
+               }
+       })
+       t.Run("unkeyed commit connection error is unchanged", func(t 
*testing.T) {
+               t.Parallel()
+               c, attempts := newKeyedTestCatalog(t, ``, func(_ int, w 
http.ResponseWriter, _ *http.Request) {
+                       dropConnection(w)
+               })
+               _, _, err := c.CommitTable(t.Context(), id, nil, nil)
+               require.Error(t, err)
+               require.NotErrorIs(t, err, ErrCommitStateUnknown)
+               require.Len(t, attempts(), 1)
+       })
+}
+
+func TestKeyedResendHonorsCancellation(t *testing.T) {
+       t.Parallel()
+       ctx, cancel := context.WithCancel(t.Context())
+       defer cancel()
+       c, attempts := newKeyedTestCatalog(t, lifetimeConfig("PT2H"), func(_ 
int, w http.ResponseWriter, _ *http.Request) {
+               w.Header().Set("Retry-After", "3600")
+               w.WriteHeader(http.StatusServiceUnavailable)
+               cancel()
+       })
+       start := time.Now()
+       require.ErrorIs(t, c.CreateNamespace(ctx, table.Identifier{"ns"}, nil), 
context.Canceled)
+       require.Less(t, time.Since(start), time.Second)
+       require.Len(t, attempts(), 1)
+}
+
+func TestKeyedTransportReplayWindow(t *testing.T) {
+       t.Parallel()
+       ns := table.Identifier{"ns"}
+       // replayHandler drops the first POST on a warmed connection, which 
net/http
+       // replays by itself unless GetBody refuses.
+       replayHandler := func(delay time.Duration) func(int, 
http.ResponseWriter, *http.Request) {
+               return func(n int, w http.ResponseWriter, r *http.Request) {
+                       if r.Method == http.MethodGet {
+                               _, _ = io.WriteString(w, `{"namespaces":[]}`)
+
+                               return
+                       }
+                       if n == 2 { // n counts the warm-up GET
+                               time.Sleep(delay)
+                               dropConnection(w)
+
+                               return
+                       }
+                       _, _ = io.WriteString(w, `{}`)
+               }
+       }
+       run := func(t *testing.T, lifetime string, delay time.Duration) 
([]keyedAttempt, error) {
+               c, attempts := newKeyedTestCatalog(t, lifetimeConfig(lifetime), 
replayHandler(delay))
+               _, err := c.ListNamespaces(t.Context(), nil)
+               require.NoError(t, err)
+
+               err = c.CreateNamespace(t.Context(), ns, nil)
+
+               return attempts()[1:], err
+       }
+       t.Run("inside the window", func(t *testing.T) {
+               t.Parallel()
+               got, err := run(t, "PT30M", 0)
+               require.NoError(t, err)
+               require.Len(t, got, 2)
+               require.Equal(t, got[0], got[1])
+       })
+       t.Run("after a slow first attempt", func(t *testing.T) {
+               t.Parallel()
+               got, err := run(t, "PT1S", 1100*time.Millisecond)
+               require.Error(t, err)
+               require.Len(t, got, 1)
+       })
+       t.Run("zero lifetime", func(t *testing.T) {
+               t.Parallel()
+               got, err := run(t, "PT0S", 0)
+               require.Error(t, err)
+               require.Len(t, got, 1)
+       })
+}
+
+func TestKeyedRedirectReplayWindow(t *testing.T) {
+       t.Parallel()
+       for _, tc := range []struct {
+               lifetime string
+               followed bool
+       }{{"PT30M", true}, {"PT0S", false}} {

Review Comment:
   This still pins a 307/308 as refused when the window is closed, which was 
the second half of @laskoviymishka's SigV4 comment. A 307/308 means the server 
didn't process the request, so following it is safe whatever the lifetime, and 
`main` does. As it stands, a server that advertises `PT0S` and redirects makes 
`CreateNamespace` fail. Note that `net/http` calls `GetBody` for the redirect 
before `CheckRedirect`, so the `sent` flag alone can't tell a redirect from a 
transport replay. One option is to record that a response came back, in the 
session transport, and allow `GetBody` after that.



##########
catalog/rest/idempotency.go:
##########
@@ -0,0 +1,343 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package rest
+
+import (
+       "context"
+       "errors"
+       "fmt"
+       "io"
+       "math"
+       "math/big"
+       "net"
+       "net/http"
+       "net/url"
+       "regexp"
+       "strings"
+       "sync/atomic"
+       "time"
+
+       "github.com/apache/iceberg-go/table"
+       "github.com/google/uuid"
+)
+
+const (
+       keyedMaxRetries = 3
+       keyedMinDelay   = 100 * time.Millisecond
+       keyedMaxDelay   = 5 * time.Second
+)
+
+// errReplayWindowClosed is returned by a keyed request's GetBody once the key
+// lifetime no longer allows a resend, which stops net/http from replaying it.
+var errReplayWindowClosed = errors.New("rest: idempotency-key-lifetime does 
not allow a resend")
+
+// idempotencyPolicy marks a request as keyed: it carries an Idempotency-Key 
and
+// may be resent within the server's advertised key lifetime.
+type idempotencyPolicy struct {
+       lifetime *string // advertised idempotency-key-lifetime, nil if not 
advertised
+       key      *string // caller-supplied key (scan planning); nil generates 
one
+       onRetry  func()  // called before each explicit resend
+}
+
+// withIdempotency keys a request when the server advertised a lifetime or the
+// caller supplied a key.
+func withIdempotency(lifetime, key *string, onRetry func()) reqOption {
+       return func(c *reqConfig) {
+               if lifetime != nil || key != nil {
+                       c.idempotency = &idempotencyPolicy{lifetime: lifetime, 
key: key, onRetry: onRetry}
+               }
+       }
+}
+
+// withCommitState makes a keyed call that cannot be resent after an ambiguous
+// failure report ErrCommitStateUnknown, since the commit may have landed.
+func withCommitState() reqOption {
+       return func(c *reqConfig) { c.commit = true }
+}
+
+// keyedCall is one logical keyed call: its key and the window in which it may
+// be resent. A new call, including a transaction retry after a 409, gets a new
+// key.
+type keyedCall struct {
+       policy   *idempotencyPolicy
+       commit   bool
+       key      string
+       start    time.Time     // first attempt, or the caller key's creation 
if earlier
+       lifetime time.Duration // 0 when resends are not allowed
+       now      func() time.Time
+}
+
+func newKeyedCall(cfg *reqConfig) (*keyedCall, error) {
+       if cfg.idempotency == nil {
+               return nil, nil
+       }
+       key, err := idempotencyHeaderValue(cfg.idempotency.key)
+       if err != nil {
+               return nil, err
+       }
+       kc := &keyedCall{policy: cfg.idempotency, commit: cfg.commit, key: key, 
start: time.Now(), now: time.Now}
+       if cfg.idempotency.lifetime != nil {
+               kc.lifetime, _ = parseKeyLifetime(*cfg.idempotency.lifetime)
+       }
+       if cfg.idempotency.key != nil {
+               // A caller key's age counts against the window. The UUIDv7 
timestamp may
+               // predate the caller's first send, which only shortens the 
window; a
+               // future timestamp is clamped so it never lengthens it.
+               id, err := uuid.Parse(key)
+               if err != nil {
+                       return nil, err
+               }
+               ms := int64(id[0])<<40 | int64(id[1])<<32 | int64(id[2])<<24 | 
int64(id[3])<<16 | int64(id[4])<<8 | int64(id[5])
+               if created := time.UnixMilli(ms); created.Before(kc.start) {
+                       kc.start = created
+               }
+       }
+
+       return kc, nil
+}
+
+func (kc *keyedCall) open() bool { return kc.now().Sub(kc.start) < kc.lifetime 
}
+
+// observedBody distinguishes a signer's body read from a transport replay.
+type observedBody struct {
+       io.ReadCloser
+       sent *atomic.Bool
+}
+
+func (b observedBody) Read(p []byte) (int, error) {
+       b.sent.Store(true)
+
+       return b.ReadCloser.Read(p)
+}
+
+func (b observedBody) Close() error {
+       b.sent.Store(true)
+
+       return b.ReadCloser.Close()
+}
+
+// prepare adds the key and bounds transport replays and redirects with bodies.
+// Bodyless requests (keyed DELETE) never call GetBody and cannot be bounded 
here.
+func (kc *keyedCall) prepare(req *http.Request) {
+       req.Header.Set(headerIdempotencyKey, kc.key)
+       if body := req.GetBody; body != nil {
+               sent := &atomic.Bool{}
+               req.Body = observedBody{ReadCloser: req.Body, sent: sent}
+               req.GetBody = func() (io.ReadCloser, error) {
+                       if sent.Load() && !kc.open() {
+                               return nil, errReplayWindowClosed
+                       }
+
+                       return body()
+               }
+       }
+}
+
+func keyedRetryStatus(code int) bool {
+       switch code {
+       case http.StatusInternalServerError, http.StatusBadGateway,
+               http.StatusServiceUnavailable, http.StatusGatewayTimeout:
+               return true
+       }
+
+       return false
+}
+
+// keyedRetryError reports whether a transport error may be resent: a timeout
+// or connection error, but not the caller's own cancellation.
+func keyedRetryError(ctx context.Context, err error) bool {
+       if ctx.Err() != nil {
+               return false
+       }
+       if errors.Is(err, errReplayWindowClosed) || errors.Is(err, io.EOF) || 
errors.Is(err, io.ErrUnexpectedEOF) {
+               return true
+       }
+       if ue, ok := errors.AsType[*url.Error](err); ok {
+               err = ue.Err
+       }
+       _, ok := errors.AsType[net.Error](err)
+
+       return ok
+}
+
+// send performs one HTTP call. An unkeyed call (kc == nil) is a single cl.Do.
+// A keyed call resends the same request and key after a retryable 5xx, 
timeout or connection
+// error while the key lifetime allows it, and returns every other response as
+// is. It returns either a response to handle or the final error; a retryable
+// status that was not resent is returned as the error handleNon200 maps it to.
+func send(ctx context.Context, cl *http.Client, kc *keyedCall, cfg *reqConfig, 
override map[int]error, newReq func() (*http.Request, error)) (response 
*http.Response, finalErr error) {
+       resent := false
+       defer func() {
+               if !resent || !kc.commit || finalErr == nil || 
errors.Is(finalErr, ErrCommitStateUnknown) {
+                       return
+               }
+               // After a resend, a conflict or rejection may answer a commit 
that already
+               // landed; keep its text but not its chain, or the table commit 
loop would
+               // replay it (conflict) or clean up its files (rejection).
+               if errors.Is(finalErr, table.ErrCommitFailed) || 
errors.Is(finalErr, table.ErrCommitRejected) {
+                       finalErr = fmt.Errorf("%w: resend failed: %v", 
ErrCommitStateUnknown, finalErr)
+               } else {
+                       finalErr = fmt.Errorf("%w: resend failed: %w", 
ErrCommitStateUnknown, finalErr)
+               }
+       }()
+       _, hasDeadline := ctx.Deadline()
+       delay := keyedMinDelay
+       for attempt := 0; ; attempt++ {
+               req, err := newReq()
+               if err != nil {
+                       return nil, err
+               }
+               if kc == nil {
+                       return cl.Do(req)
+               }
+               kc.prepare(req)
+               if err := ctx.Err(); err != nil {
+                       if attempt > 0 && kc.commit {
+                               return nil, fmt.Errorf("%w: cancelled after an 
ambiguous attempt: %w", ErrCommitStateUnknown, err)
+                       }
+
+                       return nil, err
+               }
+               resent = attempt > 0
+               rsp, err := cl.Do(req)
+               var retryAfter time.Duration
+               switch {
+               case err == nil && resent && kc.commit && rsp.StatusCode >= 400 
&& !keyedRetryStatus(rsp.StatusCode):
+                       err = handleNon200(rsp, override, cfg.errorTypeOverride)
+                       _, _ = io.Copy(io.Discard, rsp.Body)
+                       _ = rsp.Body.Close()
+
+                       return nil, err
+               case err == nil && !keyedRetryStatus(rsp.StatusCode):
+                       return rsp, nil
+               case err == nil:
+                       retryAfter = 
parseRetryAfter(rsp.Header.Get("Retry-After"))
+                       err = handleNon200(rsp, override, cfg.errorTypeOverride)
+                       _, _ = io.Copy(io.Discard, rsp.Body)
+                       _ = rsp.Body.Close()
+               case !keyedRetryError(ctx, err):
+                       if kc.commit && ctx.Err() != nil {
+                               return nil, fmt.Errorf("%w: cancelled after an 
ambiguous attempt: %w: %w", ErrCommitStateUnknown, err, ctx.Err())
+                       }
+
+                       return nil, err
+               }
+
+               delay = nextScanPlanBackoff(delay, keyedMinDelay, keyedMaxDelay)
+               wait := applyRetryAfter(delay, retryAfter, keyedMinDelay, 
keyedMaxDelay, hasDeadline)
+               if attempt >= keyedMaxRetries || kc.lifetime <= 0 || 
kc.now().Sub(kc.start)+wait >= kc.lifetime {
+                       if kc.commit && !errors.Is(err, ErrCommitStateUnknown) {
+                               err = fmt.Errorf("%w: not resent within 
idempotency-key-lifetime: %w", ErrCommitStateUnknown, err)
+                       }
+
+                       return nil, err
+               }
+               timer := time.NewTimer(wait)
+               select {
+               case <-ctx.Done():
+                       timer.Stop()
+                       if kc.commit {
+                               return nil, fmt.Errorf("%w: cancelled after an 
ambiguous attempt: %w", ErrCommitStateUnknown, ctx.Err())
+                       }
+
+                       return nil, ctx.Err()
+               case <-timer.C:
+                       if !kc.open() {
+                               if kc.commit && !errors.Is(err, 
ErrCommitStateUnknown) {
+                                       err = fmt.Errorf("%w: not resent within 
idempotency-key-lifetime: %w", ErrCommitStateUnknown, err)
+                               }
+
+                               return nil, err
+                       }
+                       if kc.policy.onRetry != nil {
+                               kc.policy.onRetry()
+                       }
+               }
+       }
+}
+
+// keyLifetimeRE matches Java Duration.parse's day/time syntax.
+var keyLifetimeRE = 
regexp.MustCompile(`(?i)^([+-]?)P(?:([+-]?\d+)D)?(?:T(?:([+-]?\d+)H)?(?:([+-]?\d+)M)?(?:([+-]?\d+(?:[.,]\d{0,9})?)S)?)?$`)
+
+// parseKeyLifetime accepts positive durations; zero, negative and malformed
+// values disable resends. Java allows unbounded resends for malformed values.
+func parseKeyLifetime(s string) (time.Duration, bool) {
+       for i := range len(s) {
+               if s[i] >= 0x80 {
+                       return 0, false
+               }
+       }
+       m := keyLifetimeRE.FindStringSubmatch(s)
+       if m == nil || strings.EqualFold(s[len(s)-1:], "T") {
+               return 0, false
+       }
+       total := new(big.Rat)

Review Comment:
   Nit (non-blocking): reproducing Java's overflow order exactly with `big.Rat` 
is a lot of code for a value that only decides whether to resend. Clamping 
anything at or above `MaxInt64` ns to `MaxInt64` would cover the same cases 
with much less. Happy to leave it if you prefer the exact match.



##########
catalog/rest/idempotency.go:
##########
@@ -0,0 +1,343 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package rest
+
+import (
+       "context"
+       "errors"
+       "fmt"
+       "io"
+       "math"
+       "math/big"
+       "net"
+       "net/http"
+       "net/url"
+       "regexp"
+       "strings"
+       "sync/atomic"
+       "time"
+
+       "github.com/apache/iceberg-go/table"
+       "github.com/google/uuid"
+)
+
+const (
+       keyedMaxRetries = 3
+       keyedMinDelay   = 100 * time.Millisecond
+       keyedMaxDelay   = 5 * time.Second
+)
+
+// errReplayWindowClosed is returned by a keyed request's GetBody once the key
+// lifetime no longer allows a resend, which stops net/http from replaying it.
+var errReplayWindowClosed = errors.New("rest: idempotency-key-lifetime does 
not allow a resend")
+
+// idempotencyPolicy marks a request as keyed: it carries an Idempotency-Key 
and
+// may be resent within the server's advertised key lifetime.
+type idempotencyPolicy struct {
+       lifetime *string // advertised idempotency-key-lifetime, nil if not 
advertised
+       key      *string // caller-supplied key (scan planning); nil generates 
one
+       onRetry  func()  // called before each explicit resend
+}
+
+// withIdempotency keys a request when the server advertised a lifetime or the
+// caller supplied a key.
+func withIdempotency(lifetime, key *string, onRetry func()) reqOption {
+       return func(c *reqConfig) {
+               if lifetime != nil || key != nil {
+                       c.idempotency = &idempotencyPolicy{lifetime: lifetime, 
key: key, onRetry: onRetry}
+               }
+       }
+}
+
+// withCommitState makes a keyed call that cannot be resent after an ambiguous
+// failure report ErrCommitStateUnknown, since the commit may have landed.
+func withCommitState() reqOption {
+       return func(c *reqConfig) { c.commit = true }
+}
+
+// keyedCall is one logical keyed call: its key and the window in which it may
+// be resent. A new call, including a transaction retry after a 409, gets a new
+// key.
+type keyedCall struct {
+       policy   *idempotencyPolicy
+       commit   bool
+       key      string
+       start    time.Time     // first attempt, or the caller key's creation 
if earlier
+       lifetime time.Duration // 0 when resends are not allowed
+       now      func() time.Time
+}
+
+func newKeyedCall(cfg *reqConfig) (*keyedCall, error) {
+       if cfg.idempotency == nil {
+               return nil, nil
+       }
+       key, err := idempotencyHeaderValue(cfg.idempotency.key)
+       if err != nil {
+               return nil, err
+       }
+       kc := &keyedCall{policy: cfg.idempotency, commit: cfg.commit, key: key, 
start: time.Now(), now: time.Now}
+       if cfg.idempotency.lifetime != nil {
+               kc.lifetime, _ = parseKeyLifetime(*cfg.idempotency.lifetime)
+       }
+       if cfg.idempotency.key != nil {
+               // A caller key's age counts against the window. The UUIDv7 
timestamp may
+               // predate the caller's first send, which only shortens the 
window; a
+               // future timestamp is clamped so it never lengthens it.
+               id, err := uuid.Parse(key)
+               if err != nil {
+                       return nil, err
+               }
+               ms := int64(id[0])<<40 | int64(id[1])<<32 | int64(id[2])<<24 | 
int64(id[3])<<16 | int64(id[4])<<8 | int64(id[5])
+               if created := time.UnixMilli(ms); created.Before(kc.start) {
+                       kc.start = created
+               }
+       }
+
+       return kc, nil
+}
+
+func (kc *keyedCall) open() bool { return kc.now().Sub(kc.start) < kc.lifetime 
}
+
+// observedBody distinguishes a signer's body read from a transport replay.
+type observedBody struct {
+       io.ReadCloser
+       sent *atomic.Bool
+}
+
+func (b observedBody) Read(p []byte) (int, error) {
+       b.sent.Store(true)
+
+       return b.ReadCloser.Read(p)
+}
+
+func (b observedBody) Close() error {
+       b.sent.Store(true)
+
+       return b.ReadCloser.Close()
+}
+
+// prepare adds the key and bounds transport replays and redirects with bodies.
+// Bodyless requests (keyed DELETE) never call GetBody and cannot be bounded 
here.
+func (kc *keyedCall) prepare(req *http.Request) {
+       req.Header.Set(headerIdempotencyKey, kc.key)
+       if body := req.GetBody; body != nil {
+               sent := &atomic.Bool{}
+               req.Body = observedBody{ReadCloser: req.Body, sent: sent}
+               req.GetBody = func() (io.ReadCloser, error) {
+                       if sent.Load() && !kc.open() {
+                               return nil, errReplayWindowClosed
+                       }
+
+                       return body()
+               }
+       }
+}
+
+func keyedRetryStatus(code int) bool {
+       switch code {
+       case http.StatusInternalServerError, http.StatusBadGateway,
+               http.StatusServiceUnavailable, http.StatusGatewayTimeout:
+               return true
+       }
+
+       return false
+}
+
+// keyedRetryError reports whether a transport error may be resent: a timeout
+// or connection error, but not the caller's own cancellation.
+func keyedRetryError(ctx context.Context, err error) bool {
+       if ctx.Err() != nil {
+               return false
+       }
+       if errors.Is(err, errReplayWindowClosed) || errors.Is(err, io.EOF) || 
errors.Is(err, io.ErrUnexpectedEOF) {
+               return true
+       }
+       if ue, ok := errors.AsType[*url.Error](err); ok {
+               err = ue.Err
+       }
+       _, ok := errors.AsType[net.Error](err)
+
+       return ok
+}
+
+// send performs one HTTP call. An unkeyed call (kc == nil) is a single cl.Do.
+// A keyed call resends the same request and key after a retryable 5xx, 
timeout or connection
+// error while the key lifetime allows it, and returns every other response as
+// is. It returns either a response to handle or the final error; a retryable
+// status that was not resent is returned as the error handleNon200 maps it to.
+func send(ctx context.Context, cl *http.Client, kc *keyedCall, cfg *reqConfig, 
override map[int]error, newReq func() (*http.Request, error)) (response 
*http.Response, finalErr error) {
+       resent := false
+       defer func() {
+               if !resent || !kc.commit || finalErr == nil || 
errors.Is(finalErr, ErrCommitStateUnknown) {
+                       return
+               }
+               // After a resend, a conflict or rejection may answer a commit 
that already
+               // landed; keep its text but not its chain, or the table commit 
loop would
+               // replay it (conflict) or clean up its files (rejection).
+               if errors.Is(finalErr, table.ErrCommitFailed) || 
errors.Is(finalErr, table.ErrCommitRejected) {
+                       finalErr = fmt.Errorf("%w: resend failed: %v", 
ErrCommitStateUnknown, finalErr)
+               } else {
+                       finalErr = fmt.Errorf("%w: resend failed: %w", 
ErrCommitStateUnknown, finalErr)
+               }
+       }()
+       _, hasDeadline := ctx.Deadline()
+       delay := keyedMinDelay
+       for attempt := 0; ; attempt++ {
+               req, err := newReq()
+               if err != nil {
+                       return nil, err
+               }
+               if kc == nil {
+                       return cl.Do(req)
+               }
+               kc.prepare(req)
+               if err := ctx.Err(); err != nil {
+                       if attempt > 0 && kc.commit {
+                               return nil, fmt.Errorf("%w: cancelled after an 
ambiguous attempt: %w", ErrCommitStateUnknown, err)
+                       }
+
+                       return nil, err
+               }
+               resent = attempt > 0
+               rsp, err := cl.Do(req)
+               var retryAfter time.Duration
+               switch {
+               case err == nil && resent && kc.commit && rsp.StatusCode >= 400 
&& !keyedRetryStatus(rsp.StatusCode):
+                       err = handleNon200(rsp, override, cfg.errorTypeOverride)
+                       _, _ = io.Copy(io.Discard, rsp.Body)
+                       _ = rsp.Body.Close()
+
+                       return nil, err
+               case err == nil && !keyedRetryStatus(rsp.StatusCode):
+                       return rsp, nil
+               case err == nil:
+                       retryAfter = 
parseRetryAfter(rsp.Header.Get("Retry-After"))
+                       err = handleNon200(rsp, override, cfg.errorTypeOverride)
+                       _, _ = io.Copy(io.Discard, rsp.Body)
+                       _ = rsp.Body.Close()
+               case !keyedRetryError(ctx, err):
+                       if kc.commit && ctx.Err() != nil {
+                               return nil, fmt.Errorf("%w: cancelled after an 
ambiguous attempt: %w: %w", ErrCommitStateUnknown, err, ctx.Err())
+                       }
+
+                       return nil, err
+               }
+
+               delay = nextScanPlanBackoff(delay, keyedMinDelay, keyedMaxDelay)
+               wait := applyRetryAfter(delay, retryAfter, keyedMinDelay, 
keyedMaxDelay, hasDeadline)
+               if attempt >= keyedMaxRetries || kc.lifetime <= 0 || 
kc.now().Sub(kc.start)+wait >= kc.lifetime {
+                       if kc.commit && !errors.Is(err, ErrCommitStateUnknown) {
+                               err = fmt.Errorf("%w: not resent within 
idempotency-key-lifetime: %w", ErrCommitStateUnknown, err)
+                       }
+
+                       return nil, err
+               }
+               timer := time.NewTimer(wait)
+               select {
+               case <-ctx.Done():
+                       timer.Stop()
+                       if kc.commit {
+                               return nil, fmt.Errorf("%w: cancelled after an 
ambiguous attempt: %w", ErrCommitStateUnknown, ctx.Err())
+                       }
+
+                       return nil, ctx.Err()
+               case <-timer.C:
+                       if !kc.open() {
+                               if kc.commit && !errors.Is(err, 
ErrCommitStateUnknown) {
+                                       err = fmt.Errorf("%w: not resent within 
idempotency-key-lifetime: %w", ErrCommitStateUnknown, err)
+                               }
+
+                               return nil, err
+                       }
+                       if kc.policy.onRetry != nil {
+                               kc.policy.onRetry()
+                       }
+               }
+       }
+}
+
+// keyLifetimeRE matches Java Duration.parse's day/time syntax.
+var keyLifetimeRE = 
regexp.MustCompile(`(?i)^([+-]?)P(?:([+-]?\d+)D)?(?:T(?:([+-]?\d+)H)?(?:([+-]?\d+)M)?(?:([+-]?\d+(?:[.,]\d{0,9})?)S)?)?$`)
+
+// parseKeyLifetime accepts positive durations; zero, negative and malformed
+// values disable resends. Java allows unbounded resends for malformed values.
+func parseKeyLifetime(s string) (time.Duration, bool) {
+       for i := range len(s) {
+               if s[i] >= 0x80 {

Review Comment:
   Nit: worth a comment that this guards against `(?i)` matching U+017F (ſ) as 
`s`. Otherwise this loop reads as arbitrary.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to