wgtmac commented on code in PR #1060:
URL: https://github.com/apache/iceberg-cpp/pull/1060#discussion_r4638247327


##########
mkdocs/docs/rest-catalog.md:
##########
@@ -0,0 +1,83 @@
+<!--
+  ~ 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.
+-->
+
+# REST catalog transport
+
+The transport and retry properties follow the Java `HTTPClient` and
+`ExponentialHttpRequestRetryStrategy`. They apply to configuration discovery,
+OAuth token requests, catalog operations, and storage credential refresh 
requests.
+Initial requests use client properties; subsequent requests use merged catalog
+properties.
+
+| Property | Default | Notes |
+| --- | --- | --- |
+| `rest.client.connection-timeout-ms` | 180000 | Non-negative integer; zero 
disables the configured deadline |
+| `rest.client.socket-timeout-ms` | Unbounded | Non-negative integer; zero 
disables the response inactivity timeout |
+| `rest.client.max-retries` | 5 | Positive integer; excludes the first 
attempt; does not bound total wait time |
+| `rest.client.user-agent` | `iceberg-cpp/<version>` | Used when the request 
has no explicit `User-Agent` header |
+| `rest.client.idempotency-key-lifetime` | Unbounded | ISO-8601 duration, for 
example `PT30M`; zero or negative durations disable keyed retries; malformed or 
out-of-range values are ignored |
+
+The socket timeout measures response inactivity rather than average transfer
+speed or total request duration. It does not bound request-body uploads. The
+legacy `HttpClient` constructor's third argument remains a total timeout per
+attempt. Transfers run synchronously in the calling thread; no executor is
+required for HTTP retries.
+
+HTTP response retries are decided after receiving the headers, before reading
+the response body:
+
+- HTTP 429, and HTTP 503 carrying `Retry-After`, permit retries for any method.
+- GET, HEAD and DELETE, and requests carrying an `Idempotency-Key` header, also
+  permit retries on HTTP 408, 500, 502, 503 and 504.
+- Positive numeric and HTTP-date `Retry-After` values are honored. Otherwise 
the
+  wait doubles from 1 second up to 64 seconds, with up to 10% jitter. Invalid 
or
+  non-positive values use this backoff; numeric durations beyond the 
millisecond
+  range saturate at the maximum representable duration.
+
+Recoverable I/O failures before response headers are received permit retries
+for idempotent methods or requests carrying `Idempotency-Key`. As in Java's
+I/O-exception retry path, these retries have no delay. Name resolution,
+connection, TLS, timeout, cancellation and premature-response-closure failures
+are not retried. Failures while reading a final response body are propagated,
+including when its HTTP status was successful.
+
+For keyed requests, the lifetime starts at the first send. A retry is abandoned
+when elapsed time plus the maximum next retry interval reaches the configured
+lifetime. The bound includes `Retry-After` or the largest possible HTTP backoff
+jitter. As in Java, the I/O-error lifetime check uses the exponential interval
+even though the exception retry itself has no delay. Unkeyed requests are not
+constrained by this property.
+
+Authentication runs once before the first send. Retries replay the same
+headers, body and idempotency key. A subsequent logical request authenticates
+again and can use an updated token.
+
+The client does not generate idempotency keys. Supply a distinct key for each
+logical mutation through per-request headers or an `AuthSession`. A static
+`header.Idempotency-Key` is unsuitable for unrelated mutations.
+
+Errors are classified from the `code` reported in the error body, falling back
+to the HTTP status when the body cannot be parsed. Service diagnostics remain
+available.
+
+Other Java transport options, including `rest.client.max-connections`,
+`rest.client.connections-per-route`, `rest.client.proxy.*` and
+`rest.client.tls.configurer-impl`, are not yet supported by this transport.
+
+For temporary storage credentials and their lifetime, see 
[FileIO](file-io.md#refreshing-temporary-s3-credentials).

Review Comment:
   This anchor does not exist in file-io.md. Please link to 
#storage-credentials or add the referenced section.



##########
src/iceberg/catalog/rest/http_client.cc:
##########
@@ -72,6 +231,319 @@ std::unordered_map<std::string, std::string> 
HttpResponse::headers() const {
 
 namespace {
 
+// The retry rules below mirror
+// org.apache.iceberg.rest.ExponentialHttpRequestRetryStrategy.
+
+constexpr std::string_view kHeaderRetryAfter = "Retry-After";
+
+/// \brief HTTP methods whose repetition is safe (RFC 9110 idempotent methods).
+bool IsIdempotent(HttpMethod method) {
+  switch (method) {
+    case HttpMethod::kGet:
+    case HttpMethod::kHead:
+    case HttpMethod::kDelete:
+    case HttpMethod::kPut:
+      return true;
+    default:
+      return false;
+  }
+}
+
+/// \brief Request-execution I/O failures eligible for Java-style retries.
+/// An empty reply corresponds to NoHttpResponseException. Premature entity
+/// closure, malformed responses, DNS, connect, TLS and timeout errors are 
excluded.
+bool IsRetriableTransportError(cpr::ErrorCode code) {
+  switch (code) {
+    case cpr::ErrorCode::GOT_NOTHING:
+    case cpr::ErrorCode::SEND_ERROR:
+    case cpr::ErrorCode::RECV_ERROR:
+    case cpr::ErrorCode::HTTP2:
+    case cpr::ErrorCode::HTTP2_STREAM:
+      return true;
+    default:
+      return false;
+  }
+}
+
+}  // namespace
+
+namespace {
+
+std::chrono::milliseconds Backoff(int64_t exec_count) {
+  if (exec_count <= 0) return std::chrono::milliseconds::zero();
+  return std::chrono::milliseconds(
+      1000 * (exec_count > 7 ? int64_t{64} : int64_t{1} << (exec_count - 1)));
+}
+
+std::optional<std::chrono::milliseconds> RetryAfter(
+    const cpr::Response& response, std::chrono::system_clock::time_point now) {
+  auto it = response.header.find(std::string(kHeaderRetryAfter));
+  if (it == response.header.end()) return std::nullopt;
+  auto value = std::string_view(it->second);
+  if (value.starts_with('+')) value.remove_prefix(1);
+  int64_t seconds = 0;
+  auto [end, ec] = std::from_chars(value.data(), value.data() + value.size(), 
seconds);
+  if (ec == std::errc{} && end == value.data() + value.size()) {
+    if (seconds <= 0) return std::nullopt;
+    constexpr auto kMaxSeconds = (std::chrono::milliseconds::max)().count() / 
1000;
+    if (seconds > kMaxSeconds) return (std::chrono::milliseconds::max)();
+    return std::chrono::milliseconds(seconds * 1000);
+  }
+  const auto date = curl_getdate(it->second.c_str(), nullptr);
+  if (date < 0) return std::nullopt;
+  const auto now_ms =
+      
std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch())
+          .count();
+  const auto date_seconds = static_cast<int64_t>(date);
+  if (date_seconds > (std::chrono::milliseconds::max)().count() / 1000) {
+    return (std::chrono::milliseconds::max)();
+  }
+  const auto date_ms = date_seconds * 1000;
+  if (date_ms <= now_ms) return std::nullopt;
+  int64_t delay;
+  if (!CheckedSubtract(date_ms, now_ms, delay)) return 
(std::chrono::milliseconds::max)();
+  return std::chrono::milliseconds(delay);
+}
+
+}  // namespace
+
+namespace detail {
+
+bool ShouldRetry(const cpr::Response& response, const HttpRequest& request,
+                 int64_t exec_count, const HttpClientOptions& options,
+                 std::optional<std::chrono::milliseconds> elapsed,
+                 std::chrono::system_clock::time_point now) {
+  if (exec_count > options.max_retries) return false;
+  const bool has_key = request.headers.contains("Idempotency-Key");
+  const bool safe = IsIdempotent(request.method) || has_key;
+  if (response.error) {
+    // Java reads the final response entity outside HttpRequestRetryExec. A 
body
+    // read failure is propagated, even for a successful status or keyed 
request.
+    if (response.status_code != 0 || !safe ||
+        !IsRetriableTransportError(response.error.code)) {
+      return false;

Review Comment:
   A nonzero status is available before the final header block is complete. A 
TCP reset in that window is still an execution-stage failure that Java retries 
for safe requests, but this condition suppresses it. Track final-header 
completion and add a partial-header reset test, while keeping body-read 
failures non-retryable.



-- 
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