You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by "laserninja (via GitHub)" <gi...@apache.org> on 2026/08/16 23:46:51 UTC
[PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
laserninja opened a new pull request, #12474:
URL: https://github.com/apache/gravitino/pull/12474
> Second half of the split. Stacked on #12470 - the first commit here belongs to that PR, so review the second commit (`+1143/-32`) only. I'll rebase onto main and undraft once #12470 merges.
### What changes were proposed in this pull request?
Puts the storage seam from #12470 behind the REST endpoints.
- **`IcebergIdempotencyManager`** runs reserve, execute, finalize around a mutation. Retries replay the stored response; a key reused for another operation, or one whose first request is still in flight, gets `409 Conflict` (the latter with `Retry-After`); `5xx` releases the key so the client can retry with it.
- **Endpoint wiring** for create, update, drop, register, and rename across tables, namespaces, and views (13 endpoints). Each endpoint delegates to a private method holding its original body, so the idempotency seam is visible at the call site and the mutation itself reads unchanged.
- **`GET /v1/config`** advertises `idempotency-key-lifetime` as the top-level `CatalogConfig` field the spec defines, not a `defaults` entry as the design document's example showed, and only when enabled, since the spec reads its absence as no support. Iceberg 1.11's `ConfigResponse.Builder.withIdempotencyKeyLifetime()` already supports it.
One deliberate deviation from the spec: `401`, `403`, and `419` **release** the key rather than finalizing it. The spec finalizes deterministic terminal `4xx`, but auth outcomes depend on the caller's credentials rather than catalog state, so replaying them would keep failing a retry that has since obtained a valid token.
Known limitation, documented in the manager's Javadoc: a replayed response carries the original status and body but not headers, so a replayed create/update does not carry the `ETag` the first response did.
### Why are the changes needed?
Epic #12049. Completes phase 1 of the design. Phase 2, the durable multi-node JDBC store, follows separately.
Fix: #12049
### Does this PR introduce _any_ user-facing change?
Yes. Clients can send `Idempotency-Key: <UUIDv7>` on mutation requests for safe retries, and `GET /v1/config` includes `idempotency-key-lifetime` when enabled. Documents the four properties added in #12470. Off by default, so default behavior is unchanged.
### How was this patch tested?
- `TestIcebergIdempotencyManager` - replay, distinct keys, bodiless `204` replay, terminal `4xx` replay, `5xx`/`401`/thrown-exception release, invalid key rejected without executing, operation-binding mismatch, in-flight `409` with `Retry-After`, query-parameter-sorted bindings.
- `TestIcebergIdempotencyKey` - end-to-end through Jersey: a replayed create fires no second `IcebergCreateTableEvent`, a fresh key re-executes into `409 AlreadyExists`, a stored `409` replays, a key reused on `DELETE` is rejected and the table survives, a drop replays `204` where a retry would otherwise `404`, and `GET /v1/config` carries `PT30M`.
- `TestIcebergConfig` - the lifetime is absent when disabled.
`iceberg-rest-server` suite passes on JDK 17: 418 tests, 0 failures.
```bash
./gradlew :iceberg:iceberg-rest-server:test -PskipITs
```
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
Posted by "lasdf1234 (via GitHub) via commits" <co...@gravitino.apache.org>.
lasdf1234 commented on code in PR #12474:
URL: https://github.com/apache/gravitino/pull/12474#discussion_r4560305346
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation, and stores its response. While that record remains available, retries carrying the same
+ * key get the original answer back instead of a second mutation. Idempotency is off by default;
+ * when it is off, or when a request carries no key, the mutation runs directly and nothing is
+ * stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ *
+ * <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
+ * with different body/header values replays the first response; clients must use a new key for a
+ * different logical operation. The catalog mutation and response storage are not transactional:
+ * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ *
+ * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
+ * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
+ * scheduling durable cleanup belongs to the JDBC-store integration.
+ */
+public class IcebergIdempotencyManager {
Review Comment:
**Nit / structure — most private methods are not worth inlining; a couple of single-use wrappers are.**
Ignoring tests, the useful split is by **protocol stage**, not by line count:
| Keep | Why |
|------|-----|
| `replayOrExecute` / `operationBinding` / `advertisedKeyLifetime` / `close` | public surface used by `*Operations` / `RESTService` |
| `replay` | one clear DUPLICATE branch (load → in-flight 409 / binding 409 / rebuild body); inlining would bloat the hot path |
| `tryFinalize` | serialize + `finalizeRecord` + claim-fenced verify; nesting that `try/catch` inside `replayOrExecute`'s `try/finally` is worse |
| `conflict` | two call sites that share status/`ErrorResponse`/`Retry-After`; DRY is the reason, not testing |
Worth folding (single call site, no named stage):
1. **`serializeEntity`** → body of `tryFinalize`
2. **`isFinalizable`** → the one `if` in `replayOrExecute` (keep `NON_FINALIZABLE_STATUSES` + a short comment / the existing policy javadoc moved to that `if`)
So: not “很多方法该内联”, just those two thin helpers. Leave `replay` / `tryFinalize` / `conflict` as the REST adapter over the store SPI.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation, and stores its response. While that record remains available, retries carrying the same
+ * key get the original answer back instead of a second mutation. Idempotency is off by default;
+ * when it is off, or when a request carries no key, the mutation runs directly and nothing is
+ * stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ *
+ * <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
+ * with different body/header values replays the first response; clients must use a new key for a
+ * different logical operation. The catalog mutation and response storage are not transactional:
+ * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ *
+ * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
+ * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
+ * scheduling durable cleanup belongs to the JDBC-store integration.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding =
+ Hashing.sha256().hashString(operationBinding, StandardCharsets.UTF_8).toString();
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // Only release this attempt's claim when the response is retryable or was not retained.
+ // A replacement owner's reservation must remain untouched.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, encoded path, and sorted, encoded query parameters. Bodies
+ * and behavior-changing headers are not compared; clients must use a fresh key for a different
+ * logical operation. The manager stores a SHA-256 digest of the complete identity to fit the
+ * store's bounded binding column without truncating distinct requests.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST /v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding =
+ new StringBuilder(httpMethod).append(" /").append(uriInfo.getPath(false));
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) {
+ query.add(
+ URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8)
+ + "="
+ + URLEncoder.encode(value, StandardCharsets.UTF_8));
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ boolean finalized =
+ idempotencyStore
+ .load(idempotencyKey)
+ .filter(record -> record.isFinalized() && record.claim() == claim)
+ .isPresent();
+ if (!finalized) {
+ LOG.warn(
+ "Response for Idempotency-Key: {} was not retained under this claim", idempotencyKey);
+ }
+ // Keep the actual mutation response: returning a synthetic 5xx could encourage clients to
+ // retry an operation that already committed. Release is fenced to our claim in the caller.
+ return finalized;
+ }
+
+ @Nullable
+ private String serializeEntity(@Nullable Object entity) throws JsonProcessingException {
Review Comment:
**Nit — inline into `tryFinalize`.**
Only caller is `tryFinalize`, and the null / `String` / mapper branches are three lines. Pulling them into the serialize `try` there removes an indirection without hurting readability.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation, and stores its response. While that record remains available, retries carrying the same
+ * key get the original answer back instead of a second mutation. Idempotency is off by default;
+ * when it is off, or when a request carries no key, the mutation runs directly and nothing is
+ * stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ *
+ * <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
+ * with different body/header values replays the first response; clients must use a new key for a
+ * different logical operation. The catalog mutation and response storage are not transactional:
+ * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ *
+ * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
+ * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
+ * scheduling durable cleanup belongs to the JDBC-store integration.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding =
+ Hashing.sha256().hashString(operationBinding, StandardCharsets.UTF_8).toString();
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // Only release this attempt's claim when the response is retryable or was not retained.
+ // A replacement owner's reservation must remain untouched.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, encoded path, and sorted, encoded query parameters. Bodies
+ * and behavior-changing headers are not compared; clients must use a fresh key for a different
+ * logical operation. The manager stores a SHA-256 digest of the complete identity to fit the
+ * store's bounded binding column without truncating distinct requests.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST /v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding =
+ new StringBuilder(httpMethod).append(" /").append(uriInfo.getPath(false));
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) {
+ query.add(
+ URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8)
+ + "="
+ + URLEncoder.encode(value, StandardCharsets.UTF_8));
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ boolean finalized =
+ idempotencyStore
+ .load(idempotencyKey)
+ .filter(record -> record.isFinalized() && record.claim() == claim)
+ .isPresent();
+ if (!finalized) {
+ LOG.warn(
+ "Response for Idempotency-Key: {} was not retained under this claim", idempotencyKey);
+ }
+ // Keep the actual mutation response: returning a synthetic 5xx could encourage clients to
+ // retry an operation that already committed. Release is fenced to our claim in the caller.
+ return finalized;
+ }
+
+ @Nullable
+ private String serializeEntity(@Nullable Object entity) throws JsonProcessingException {
+ if (entity == null) {
+ return null;
+ }
+ if (entity instanceof String) {
+ return (String) entity;
+ }
+ return icebergObjectMapper.writeValueAsString(entity);
+ }
+
+ private static Response conflict(String message, boolean retryable) {
+ Response response =
+ Response.status(Response.Status.CONFLICT)
+ .entity(
+ IcebergRESTUtils.errorResponse(
+ Response.Status.CONFLICT.getStatusCode(),
+ "IdempotencyConflictException",
+ message))
+ .type(MediaType.APPLICATION_JSON)
+ .build();
+ if (!retryable) {
+ return response;
+ }
+ return Response.fromResponse(response)
+ .header(HttpHeaders.RETRY_AFTER, RETRY_AFTER_SECONDS)
+ .build();
+ }
+
+ /**
+ * Returns whether a response finalizes the key. Per the Iceberg REST spec, {@code 5xx} responses
+ * are retryable and must not be stored, while {@code 2xx} and deterministic terminal {@code 4xx}
+ * responses are replayed. Authentication/authorization outcomes (401, 403, 419) also release the
+ * claim so changed credentials can be evaluated on retry. Serialization or finalization failure
+ * releases only this attempt's claim as well.
+ */
+ private static boolean isFinalizable(int httpStatus) {
Review Comment:
**Nit — single use; inline at the call site in `replayOrExecute`.**
```java
if (status < 500 && !NON_FINALIZABLE_STATUSES.contains(status)) {
finalized = tryFinalize(...);
}
```
Keep `NON_FINALIZABLE_STATUSES` (and move this method's javadoc to a comment above that `if`). A one-line predicate method for a single caller adds more navigation than clarity.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation, and stores its response. While that record remains available, retries carrying the same
+ * key get the original answer back instead of a second mutation. Idempotency is off by default;
+ * when it is off, or when a request carries no key, the mutation runs directly and nothing is
+ * stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ *
+ * <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
+ * with different body/header values replays the first response; clients must use a new key for a
+ * different logical operation. The catalog mutation and response storage are not transactional:
+ * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ *
+ * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
+ * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
+ * scheduling durable cleanup belongs to the JDBC-store integration.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding =
+ Hashing.sha256().hashString(operationBinding, StandardCharsets.UTF_8).toString();
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // Only release this attempt's claim when the response is retryable or was not retained.
+ // A replacement owner's reservation must remain untouched.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, encoded path, and sorted, encoded query parameters. Bodies
+ * and behavior-changing headers are not compared; clients must use a fresh key for a different
+ * logical operation. The manager stores a SHA-256 digest of the complete identity to fit the
+ * store's bounded binding column without truncating distinct requests.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST /v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding =
+ new StringBuilder(httpMethod).append(" /").append(uriInfo.getPath(false));
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) {
+ query.add(
+ URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8)
+ + "="
+ + URLEncoder.encode(value, StandardCharsets.UTF_8));
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ boolean finalized =
+ idempotencyStore
+ .load(idempotencyKey)
+ .filter(record -> record.isFinalized() && record.claim() == claim)
+ .isPresent();
+ if (!finalized) {
+ LOG.warn(
+ "Response for Idempotency-Key: {} was not retained under this claim", idempotencyKey);
+ }
+ // Keep the actual mutation response: returning a synthetic 5xx could encourage clients to
+ // retry an operation that already committed. Release is fenced to our claim in the caller.
+ return finalized;
+ }
+
+ @Nullable
+ private String serializeEntity(@Nullable Object entity) throws JsonProcessingException {
+ if (entity == null) {
+ return null;
+ }
+ if (entity instanceof String) {
+ return (String) entity;
+ }
+ return icebergObjectMapper.writeValueAsString(entity);
+ }
+
+ private static Response conflict(String message, boolean retryable) {
Review Comment:
**Note — keep; do not inline.**
Used twice from `replay` (in-flight vs binding mismatch). The shared `409` + `ErrorResponse` + optional `Retry-After` construction is real duplication if inlined, not test scaffolding.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation, and stores its response. While that record remains available, retries carrying the same
+ * key get the original answer back instead of a second mutation. Idempotency is off by default;
+ * when it is off, or when a request carries no key, the mutation runs directly and nothing is
+ * stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ *
+ * <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
+ * with different body/header values replays the first response; clients must use a new key for a
+ * different logical operation. The catalog mutation and response storage are not transactional:
+ * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ *
+ * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
+ * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
+ * scheduling durable cleanup belongs to the JDBC-store integration.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding =
+ Hashing.sha256().hashString(operationBinding, StandardCharsets.UTF_8).toString();
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // Only release this attempt's claim when the response is retryable or was not retained.
+ // A replacement owner's reservation must remain untouched.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, encoded path, and sorted, encoded query parameters. Bodies
+ * and behavior-changing headers are not compared; clients must use a fresh key for a different
+ * logical operation. The manager stores a SHA-256 digest of the complete identity to fit the
+ * store's bounded binding column without truncating distinct requests.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST /v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding =
+ new StringBuilder(httpMethod).append(" /").append(uriInfo.getPath(false));
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) {
+ query.add(
+ URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8)
+ + "="
+ + URLEncoder.encode(value, StandardCharsets.UTF_8));
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
Review Comment:
**Note — keep as its own method.**
This is the whole `DUPLICATE` half of the store contract (`load` empty / binding mismatch / rebuild `Response`). Inlining into `replayOrExecute` would bury that branch under reserve/claim/finally noise; the name matches what the SPI javadoc says the REST handler owns.
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
Posted by "roryqi (via GitHub) via commits" <co...@gravitino.apache.org>.
roryqi merged PR #12474:
URL: https://github.com/apache/gravitino/pull/12474
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
Posted by "lasdf1234 (via GitHub) via commits" <co...@gravitino.apache.org>.
lasdf1234 commented on code in PR #12474:
URL: https://github.com/apache/gravitino/pull/12474#discussion_r4559373718
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
Review Comment:
test ping from review (will delete)
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
Review Comment:
**High — binding excludes the request body.**
`operationBinding` is only `method + path + query`. Two `POST .../tables` creates with different `CreateTableRequest` bodies (or an update with different requirements) share one binding, so a reused key replays the *first* response even when the second body is different.
The Javadoc says this matches “fresh key per operation”, but clients commonly retry the same URL after editing the body, or accidentally reuse a key across creates. Consider hashing a canonical body (or rejecting when a finalized record exists and a body digest differs), or at least document this as a hard limitation next to the ETag note and add a regression test that two different create bodies with one key do not both execute.
Same class of issue for headers that change behavior but are outside the binding (e.g. `X-Iceberg-Access-Delegation` on create/register).
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding = new StringBuilder(httpMethod).append(' ').append(uriInfo.getPath());
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue()) {
+ query.add(parameter.getKey() + "=" + value);
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ return true;
Review Comment:
**High — `tryFinalize` treats a no-op finalize as success.**
`IdempotencyStore.finalizeRecord` is documented to silently ignore stale/expired claims, but this method always `return true` after calling it. That sets `finalized = true` in `replayOrExecute`, so the `finally` block **skips `release`**.
If this caller lost the reservation (eviction / expiry / another node reserved the key) and still produced a successful `Response`, the client gets a 2xx whose body was never stored under a usable claim. A retry then either races the new owner or re-executes. The store SPI cannot signal “finalize applied”; either change the SPI to return a boolean, or treat “load after finalize still empty / claim mismatch” as finalize failure and `release` when safe (or surface 5xx so the client retries with a new reservation path).
Please add a unit test where `finalizeRecord` is a no-op (mock) and assert the key is released or the caller does not report success as finalized.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding = new StringBuilder(httpMethod).append(' ').append(uriInfo.getPath());
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue()) {
+ query.add(parameter.getKey() + "=" + value);
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ return true;
+ }
+
+ @Nullable
+ private String serializeEntity(@Nullable Object entity) throws JsonProcessingException {
+ if (entity == null) {
+ return null;
+ }
+ if (entity instanceof String) {
+ return (String) entity;
+ }
+ return icebergObjectMapper.writeValueAsString(entity);
+ }
+
+ private static Response conflict(String message, boolean retryable) {
+ Response response =
+ IcebergRESTUtils.errorResponse(
+ new IdempotencyConflictException(message), Response.Status.CONFLICT.getStatusCode());
+ if (!retryable) {
+ return response;
+ }
+ return Response.fromResponse(response)
+ .header(HttpHeaders.RETRY_AFTER, RETRY_AFTER_SECONDS)
+ .build();
+ }
+
+ /**
+ * Returns whether a response finalizes the key. Per the Iceberg REST spec, {@code 5xx} responses
+ * are retryable and must not be stored, while {@code 2xx} and deterministic terminal {@code 4xx}
+ * responses are replayed.
+ */
+ private static boolean isFinalizable(int httpStatus) {
+ return httpStatus < Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()
+ && !NON_FINALIZABLE_STATUSES.contains(httpStatus);
+ }
+
+ private static String truncate(String operationBinding) {
+ return operationBinding.length() <= MAX_OPERATION_BINDING_LENGTH
+ ? operationBinding
+ : operationBinding.substring(0, MAX_OPERATION_BINDING_LENGTH);
Review Comment:
**Medium — truncation can alias distinct operations.**
Cutting to 512 characters means two long paths/queries that share a prefix become the same binding. After one finalizes, the other gets a binding mismatch `409` or, worse before finalize, can confuse in-flight handling. Prefer a fixed-width digest (e.g. hash of the full binding) for storage while keeping a human-readable form in logs, or reject bindings that exceed the DB width instead of silently truncating.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding = new StringBuilder(httpMethod).append(' ').append(uriInfo.getPath());
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue()) {
+ query.add(parameter.getKey() + "=" + value);
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
Review Comment:
**Medium — replay rebuilds the entity as a JSON `String`.**
`serializeEntity` stores mapper output (or a raw String), and replay does `builder.entity(found.responseSummary()).type(APPLICATION_JSON)`. The first response typically carried a typed Iceberg model (`LoadTableResponse`, etc.) written by the MessageBodyWriter. Please verify Jersey serves the string body identically (no double-encoding / different null handling). Also worth repeating in the class Javadoc that **headers such as `ETag` are dropped on replay** (already mentioned above) so clients must reload after a replayed create/update.
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
Posted by "lasdf1234 (via GitHub) via commits" <co...@gravitino.apache.org>.
lasdf1234 commented on code in PR #12474:
URL: https://github.com/apache/gravitino/pull/12474#discussion_r4559377672
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding = new StringBuilder(httpMethod).append(' ').append(uriInfo.getPath());
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
Review Comment:
**Low — query values are not encoded when building the binding.**
`key=value` is concatenated without URL-encoding. A value containing `&` or `=` can make two different MultivaluedMaps serialize to the same (or ambiguous) binding string. Prefer encoding values (and sorting multi-values) so retries stay stable.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java:
##########
@@ -180,8 +186,21 @@ public Response createTable(
@AuthorizationMetadata(type = Entity.EntityType.SCHEMA) @Encoded() @PathParam("namespace")
String namespace,
CreateTableRequest createTableRequest,
- @HeaderParam(X_ICEBERG_ACCESS_DELEGATION) String accessDelegation) {
+ @HeaderParam(X_ICEBERG_ACCESS_DELEGATION) String accessDelegation,
+ @HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,
+ @Context UriInfo uriInfo) {
IcebergRESTUtils.validateRequest(createTableRequest, "CreateTableRequest");
+ return idempotencyManager.replayOrExecute(
+ idempotencyKey,
+ IcebergIdempotencyManager.operationBinding(HttpMethod.POST, uriInfo),
+ () -> doCreateTable(prefix, namespace, createTableRequest, accessDelegation));
Review Comment:
**Medium (wiring) — good that `doCreateTable` maps exceptions to `Response` inside the supplier.**
That keeps 4xx/5xx inside `replayOrExecute` so finalize/release can run. Please confirm *every* wrapped mutation (`doUpdate*`, drop, rename, namespace/view paths) uses the same try/catch → `IcebergExceptionMapper.toRESTResponse` pattern. If any path still throws out of the supplier, the key is released (good for retry) but a **successful catalog mutation followed by a post-commit throw** would re-execute on retry — call that out as a phase-1 limitation if unavoidable.
Also: `validateRequest` runs *before* `replayOrExecute`, so invalid bodies never reserve the key (good). Auth filters that fail before entering the method also never reserve — consistent with releasing 401/403 when they occur inside the action.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergConfigOperations.java:
##########
@@ -124,6 +129,9 @@ public Response getConfig(
if (StringUtils.isNotBlank(warehouse)) {
builder.withDefault("prefix", warehouse);
}
+ // Advertised only when idempotency is enabled: the Iceberg REST spec reads the absence of this
+ // field as "the server does not support Idempotency-Key semantics".
+ idempotencyManager.advertisedKeyLifetime().ifPresent(builder::withIdempotencyKeyLifetime);
Review Comment:
**Low — config advertisement looks correct** (top-level lifetime only when enabled). Consider a test that enabled + custom `ICEBERG_IDEMPOTENCY_KEY_LIFETIME` (e.g. `PT2H`) appears as that value in `GET /v1/config`, not only the default `PT30M` path in `TestIcebergIdempotencyKey`.
##########
docs/iceberg-rest-service.md:
##########
@@ -178,6 +178,25 @@ The settings below tune the background workers and are optional.
| `gravitino.iceberg-rest.async-cleanup.max-attempts` | Number of failed attempts before a cleanup job is marked `FAILED`. | `5` | No |
| `gravitino.iceberg-rest.async-cleanup.retention-hours` | Retention time for terminal `SUCCEEDED` or `FAILED` cleanup rows before pruning. | `720` | No |
+#### Idempotency Key
+
+The Iceberg REST spec defines an optional `Idempotency-Key` header on mutation endpoints so that a client can safely retry a request whose response it never saw. When the header is present, the server executes the mutation once, stores the response, and replays that stored response to every retry carrying the same key.
+
+Support is disabled by default. Once enabled, the reuse window is advertised as `idempotency-key-lifetime` in `GET /v1/config`; per the spec, clients must assume idempotency is unsupported when that field is absent.
Review Comment:
**Docs** — please explicitly document phase-1 limitations clients must know: (1) binding is URL-based, body not included; (2) replayed responses omit headers such as `ETag`; (3) in-memory store is node-local / best-effort under eviction. That matches the code comments but operators will look here first.
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
Posted by "lasdf1234 (via GitHub) via commits" <co...@gravitino.apache.org>.
lasdf1234 commented on code in PR #12474:
URL: https://github.com/apache/gravitino/pull/12474#discussion_r4559431625
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding = new StringBuilder(httpMethod).append(' ').append(uriInfo.getPath());
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue()) {
+ query.add(parameter.getKey() + "=" + value);
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
Review Comment:
**Medium (vs `IdempotencyStore`) — `purgeExpired` is never driven from this manager / `RESTService`.**
The common-module SPI exposes `purgeExpired(beforeMs)` as part of the store lifecycle. `InMemoryIdempotencyStore` can live without it (Caffeine expiry + `expiresAtMs` checks), but a durable implementation that only marks rows expired in queries still needs a caller. Either:
- schedule purge here (or next to async-cleanup), or
- document that purge is the durable store’s own responsibility / out of scope for phase-1.
Otherwise the SPI surface and this driver are only half-wired relative to `iceberg-common`.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
Review Comment:
**Low (vs `IdempotencyStore` / `IdempotencyRecord` docs) — binding shape differs from the SPI examples.**
`IdempotencyStore#reserve` / `IdempotencyRecord` javadoc examples use `POST /v1/cat1/namespaces/ns1/tables` (leading `/`). This builds `POST v1/...` from `uriInfo.getPath()` with no leading slash.
Not a functional bug if every caller goes through `operationBinding`, but please either match the common-module examples or update those javadocs so a future store/UI/debug tooling does not assume the slash form.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding = new StringBuilder(httpMethod).append(' ').append(uriInfo.getPath());
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue()) {
+ query.add(parameter.getKey() + "=" + value);
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ return true;
+ }
+
+ @Nullable
+ private String serializeEntity(@Nullable Object entity) throws JsonProcessingException {
+ if (entity == null) {
+ return null;
+ }
+ if (entity instanceof String) {
+ return (String) entity;
+ }
+ return icebergObjectMapper.writeValueAsString(entity);
+ }
+
+ private static Response conflict(String message, boolean retryable) {
+ Response response =
+ IcebergRESTUtils.errorResponse(
+ new IdempotencyConflictException(message), Response.Status.CONFLICT.getStatusCode());
+ if (!retryable) {
+ return response;
+ }
+ return Response.fromResponse(response)
+ .header(HttpHeaders.RETRY_AFTER, RETRY_AFTER_SECONDS)
+ .build();
+ }
+
+ /**
+ * Returns whether a response finalizes the key. Per the Iceberg REST spec, {@code 5xx} responses
+ * are retryable and must not be stored, while {@code 2xx} and deterministic terminal {@code 4xx}
+ * responses are replayed.
+ */
+ private static boolean isFinalizable(int httpStatus) {
Review Comment:
**Low/docs (vs `IdempotencyStore#release`) — release policy is wider than the SPI javadoc.**
`IdempotencyStore#release` is documented as for responses the Iceberg REST spec treats as retryable (**any 5xx**). Here `isFinalizable` also keeps **401 / 403 / 419** from finalizing, so they hit `release` in the `finally` block — which is a good product choice (auth outcomes must not sticky-replay), but it is an extension of the store’s written contract.
Please update the common-module `release` javadoc (or this method’s javadoc) so store implementors know non-5xx “do not finalize” statuses are also expected to `release`, matching this driver.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
Review Comment:
**Note (architecture) — yes, this class belongs here relative to `iceberg-common`.**
`IdempotencyStore` / `InMemoryIdempotencyStore` / `IdempotencyKeys` only provide storage + key folding. This manager is the REST protocol adapter the SPI was written for (`reserve` → mutation → `finalizeRecord`/`release`, binding check on `load`). Do not fold it into the common module; keep HTTP/`Response`/Retry-After/`ErrorResponse` concerns in `iceberg-rest-server`.
The substantive follow-ups are correctness of that cycle (especially `finalizeRecord` no-op → still returning `true`, and URL-only binding), not whether the class should exist.
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #12474:
URL: https://github.com/apache/gravitino/pull/12474#issuecomment-5310637979
<!-- coverage-report -->
### Code Coverage Report
|Overall Project|68.73% **`+0.15%`**|:green_circle:|
|:-|:-|:-:|
|Files changed|79.75%|:green_circle:|
<br>
|Module|Coverage||
|:-|:-|:-:|
|aliyun|1.72%|:red_circle:|
|api|49.31%|:green_circle:|
|authorization-common|85.96%|:green_circle:|
|aws|42.04%|:green_circle:|
|azure|2.47%|:red_circle:|
|catalog-common|9.92% **`-0.02%`**|:red_circle:|
|catalog-fileset|79.77%|:green_circle:|
|catalog-glue|68.95%|:green_circle:|
|catalog-hive|79.4%|:green_circle:|
|catalog-jdbc-common|45.7%|:green_circle:|
|catalog-jdbc-doris|81.8%|:green_circle:|
|catalog-jdbc-mysql|79.33%|:green_circle:|
|catalog-jdbc-postgresql|83.39%|:green_circle:|
|catalog-jdbc-starrocks|79.16%|:green_circle:|
|catalog-kafka|77.01%|:green_circle:|
|catalog-lakehouse-generic|59.18%|:green_circle:|
|catalog-lakehouse-hudi|79.1%|:green_circle:|
|catalog-lakehouse-iceberg|85.93%|:green_circle:|
|catalog-lakehouse-paimon|84.23%|:green_circle:|
|catalog-model|77.72%|:green_circle:|
|cli|44.48%|:green_circle:|
|client-java|78.56%|:green_circle:|
|common|52.75%|:green_circle:|
|core|83.63%|:green_circle:|
|filesystem-hadoop3|77.28%|:green_circle:|
|flink|0.0%|:red_circle:|
|flink-common|48.68%|:green_circle:|
|flink-runtime|0.0%|:red_circle:|
|gcp|14.12%|:red_circle:|
|hadoop-auth|68.0%|:green_circle:|
|hadoop-common|12.7%|:red_circle:|
|hive-metastore-common|53.4%|:green_circle:|
|iceberg-aliyun-bundle|0.0%|:red_circle:|
|iceberg-common|67.17% **`+12.01%`**|:green_circle:|
|iceberg-rest-server|75.5% **`-0.77%`**|:green_circle:|
|idp-basic|86.02%|:green_circle:|
|integration-test-common|0.0%|:red_circle:|
|jobs|62.92%|:green_circle:|
|lance-common|31.75%|:red_circle:|
|lance-rest-server|63.47%|:green_circle:|
|lineage|53.02%|:green_circle:|
|optimizer|83.24%|:green_circle:|
|optimizer-api|21.95%|:red_circle:|
|server|87.25%|:green_circle:|
|server-common|79.41%|:green_circle:|
|spark|28.57%|:red_circle:|
|spark-common|45.89%|:green_circle:|
|tencent|69.84%|:green_circle:|
|trino-connector|40.29%|:green_circle:|
<details>
<summary>Files</summary>
|Module|File|Coverage||
|:-|:-|:-|:-:|
|catalog-common|[IcebergConstants.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/catalogs/catalog-common/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergConstants.java)|0.0%|:red_circle:|
|iceberg-common|[IdempotencyKeys.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyKeys.java)|100.0%|:green_circle:|
||[IdempotencyStore.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStore.java)|100.0%|:green_circle:|
||[IdempotencyStoreFactory.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyStoreFactory.java)|100.0%|:green_circle:|
||[InMemoryIdempotencyStore.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/InMemoryIdempotencyStore.java)|100.0%|:green_circle:|
||[IcebergConfig.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/IcebergConfig.java)|98.57%|:green_circle:|
||[IdempotencyRecord.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/IdempotencyRecord.java)|57.58%|:red_circle:|
|iceberg-rest-server|[IdempotencyConflictException.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyConflictException.java)|100.0%|:green_circle:|
||[IcebergConfigOperations.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergConfigOperations.java)|96.55%|:green_circle:|
||[IcebergTableRenameOperations.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableRenameOperations.java)|95.0%|:green_circle:|
||[IcebergViewRenameOperations.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergViewRenameOperations.java)|95.0%|:green_circle:|
||[IcebergIdempotencyManager.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java)|87.91%|:green_circle:|
||[IcebergNamespaceOperations.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergNamespaceOperations.java)|83.11%|:green_circle:|
||[IcebergTableOperations.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java)|82.1%|:green_circle:|
||[IcebergViewOperations.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergViewOperations.java)|75.37%|:green_circle:|
||[RESTService.java](https://github.com/laserninja/gravitino/blob/178230fdfb21fc466699f54ed5733ce493372e20/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/RESTService.java)|0.0%|:red_circle:|
</details>
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
Posted by "lasdf1234 (via GitHub) via commits" <co...@gravitino.apache.org>.
lasdf1234 commented on code in PR #12474:
URL: https://github.com/apache/gravitino/pull/12474#discussion_r4559408747
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyConflictException.java:
##########
@@ -0,0 +1,36 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+/**
+ * Thrown when an {@code Idempotency-Key} cannot be honored: the first request using it is still
+ * running, or the key was already used for a different operation. Both cases are reported to the
+ * client as {@code 409 Conflict}.
+ */
+public class IdempotencyConflictException extends RuntimeException {
Review Comment:
**Medium — this custom exception is unnecessary.**
In `iceberg-rest-server`, the only other hand-rolled exception is `AuthenticationTimeoutException` (extends `RESTException`), and that exists solely because the Iceberg SDK has no 419 type for `IcebergExceptionMapper`. Here `conflict()` already builds the JAX-RS `Response` via `IcebergRESTUtils.errorResponse(...)` and never throws into the mapper, so a dedicated class adds no status mapping.
Iceberg `ErrorModel.type` is just a free-form string (examples use names like `NoSuchNamespaceException`); the OpenAPI `Idempotency-Key` text requires 409 Conflict behavior, not a Java type named `IdempotencyConflictException`. Prefer the existing overload `errorResponse(409, "<type>", message)` (or a small string constant for the type), same pattern as the auth filter / Jetty error path.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding = new StringBuilder(httpMethod).append(' ').append(uriInfo.getPath());
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue()) {
+ query.add(parameter.getKey() + "=" + value);
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ return true;
+ }
+
+ @Nullable
+ private String serializeEntity(@Nullable Object entity) throws JsonProcessingException {
+ if (entity == null) {
+ return null;
+ }
+ if (entity instanceof String) {
+ return (String) entity;
+ }
+ return icebergObjectMapper.writeValueAsString(entity);
+ }
+
+ private static Response conflict(String message, boolean retryable) {
+ Response response =
+ IcebergRESTUtils.errorResponse(
+ new IdempotencyConflictException(message), Response.Status.CONFLICT.getStatusCode());
+ if (!retryable) {
Review Comment:
**Medium (same as on `IdempotencyConflictException`) — drop the wrapper and pass type/message directly.**
`errorResponse(Throwable, status)` only uses the exception for `getSimpleName()` + message. Since this path already returns a `Response` (not thrown to `IcebergExceptionMapper`), `IcebergRESTUtils.errorResponse(Status.CONFLICT.getStatusCode(), "IdempotencyConflictException", message)` (or a shorter type string) is enough and matches project convention + the Iceberg ErrorModel / Idempotency-Key OpenAPI (no required exception class).
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
Posted by "laserninja (via GitHub) via commits" <co...@gravitino.apache.org>.
laserninja commented on code in PR #12474:
URL: https://github.com/apache/gravitino/pull/12474#discussion_r4559966136
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergConfigOperations.java:
##########
@@ -124,6 +129,9 @@ public Response getConfig(
if (StringUtils.isNotBlank(warehouse)) {
builder.withDefault("prefix", warehouse);
}
+ // Advertised only when idempotency is enabled: the Iceberg REST spec reads the absence of this
+ // field as "the server does not support Idempotency-Key semantics".
+ idempotencyManager.advertisedKeyLifetime().ifPresent(builder::withIdempotencyKeyLifetime);
Review Comment:
Added TestIcebergIdempotencyConfig, which exercises GET /v1/config with idempotency enabled and PT2H configured. It verifies PT2H appears at the top level and is absent from defaults and overrides. Existing tests retain default-lifetime and disabled coverage.
Changes pushed in e4a9470e6. Validation: 769 REST server tests passed; formatting and Javadoc tasks succeeded.
##########
docs/iceberg-rest-service.md:
##########
@@ -178,6 +178,25 @@ The settings below tune the background workers and are optional.
| `gravitino.iceberg-rest.async-cleanup.max-attempts` | Number of failed attempts before a cleanup job is marked `FAILED`. | `5` | No |
| `gravitino.iceberg-rest.async-cleanup.retention-hours` | Retention time for terminal `SUCCEEDED` or `FAILED` cleanup rows before pruning. | `720` | No |
+#### Idempotency Key
+
+The Iceberg REST spec defines an optional `Idempotency-Key` header on mutation endpoints so that a client can safely retry a request whose response it never saw. When the header is present, the server executes the mutation once, stores the response, and replays that stored response to every retry carrying the same key.
+
+Support is disabled by default. Once enabled, the reuse window is advertised as `idempotency-key-lifetime` in `GET /v1/config`; per the spec, clients must assume idempotency is unsupported when that field is absent.
Review Comment:
Added a phase-1 limitations section covering URL-based identity without body/header comparison, replay without ETag, non-transactional mutation/response storage, and cleanup ownership. Expanded the in-memory warning to include eviction of in-flight reservations and concurrent re-execution.
Changes pushed in e4a9470e6. Validation: 769 REST server tests passed; formatting and Javadoc tasks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IdempotencyConflictException.java:
##########
@@ -0,0 +1,36 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+/**
+ * Thrown when an {@code Idempotency-Key} cannot be honored: the first request using it is still
+ * running, or the key was already used for a different operation. Both cases are reported to the
+ * client as {@code 409 Conflict}.
+ */
+public class IdempotencyConflictException extends RuntimeException {
Review Comment:
Removed the exception class. The conflict response now uses the existing errorResponse(status, type, message) helper and wraps the ErrorResponse model in a JSON JAX-RS response. The existing wire type and Retry-After behavior are preserved.
Changes pushed in e4a9470e6. Validation: 769 REST server tests passed; formatting and Javadoc tasks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding = new StringBuilder(httpMethod).append(' ').append(uriInfo.getPath());
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue()) {
+ query.add(parameter.getKey() + "=" + value);
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ return true;
+ }
+
+ @Nullable
+ private String serializeEntity(@Nullable Object entity) throws JsonProcessingException {
+ if (entity == null) {
+ return null;
+ }
+ if (entity instanceof String) {
+ return (String) entity;
+ }
+ return icebergObjectMapper.writeValueAsString(entity);
+ }
+
+ private static Response conflict(String message, boolean retryable) {
+ Response response =
+ IcebergRESTUtils.errorResponse(
+ new IdempotencyConflictException(message), Response.Status.CONFLICT.getStatusCode());
+ if (!retryable) {
Review Comment:
Done. conflict() now builds its JSON response from errorResponse(409, "IdempotencyConflictException", message), without constructing an exception. Added an HTTP assertion for the error type; the in-flight Retry-After test remains covered.
Changes pushed in e4a9470e6. Validation: 769 REST server tests passed; formatting and Javadoc tasks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding = new StringBuilder(httpMethod).append(' ').append(uriInfo.getPath());
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue()) {
+ query.add(parameter.getKey() + "=" + value);
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
Review Comment:
Documented cleanup ownership in both the manager Javadoc and operator guide. Phase 1 has no purge scheduler: Caffeine reclaims in-memory entries, while custom stores must enforce expiration and arrange their own reclamation. Durable purge scheduling remains part of the JDBC-store follow-up.
Changes pushed in e4a9470e6. Validation: 769 REST server tests passed; formatting and Javadoc tasks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
Review Comment:
Aligned operationBinding with the common-module examples: the readable identity now starts with POST /v1/..., retaining the encoded path. Its full SHA-256 digest is what the manager stores. Updated the binding tests and documented the distinction.
Changes pushed in e4a9470e6. Validation: 769 REST server tests passed; formatting and Javadoc tasks succeeded.
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
Posted by "laserninja (via GitHub) via commits" <co...@gravitino.apache.org>.
laserninja commented on code in PR #12474:
URL: https://github.com/apache/gravitino/pull/12474#discussion_r4566900700
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation, and stores its response. While that record remains available, retries carrying the same
+ * key get the original answer back instead of a second mutation. Idempotency is off by default;
+ * when it is off, or when a request carries no key, the mutation runs directly and nothing is
+ * stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ *
+ * <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
+ * with different body/header values replays the first response; clients must use a new key for a
+ * different logical operation. The catalog mutation and response storage are not transactional:
+ * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ *
+ * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
+ * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
+ * scheduling durable cleanup belongs to the JDBC-store integration.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding =
+ Hashing.sha256().hashString(operationBinding, StandardCharsets.UTF_8).toString();
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // Only release this attempt's claim when the response is retryable or was not retained.
+ // A replacement owner's reservation must remain untouched.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, encoded path, and sorted, encoded query parameters. Bodies
+ * and behavior-changing headers are not compared; clients must use a fresh key for a different
+ * logical operation. The manager stores a SHA-256 digest of the complete identity to fit the
+ * store's bounded binding column without truncating distinct requests.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST /v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding =
+ new StringBuilder(httpMethod).append(" /").append(uriInfo.getPath(false));
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) {
+ query.add(
+ URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8)
+ + "="
+ + URLEncoder.encode(value, StandardCharsets.UTF_8));
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ boolean finalized =
+ idempotencyStore
+ .load(idempotencyKey)
+ .filter(record -> record.isFinalized() && record.claim() == claim)
+ .isPresent();
+ if (!finalized) {
+ LOG.warn(
+ "Response for Idempotency-Key: {} was not retained under this claim", idempotencyKey);
+ }
+ // Keep the actual mutation response: returning a synthetic 5xx could encourage clients to
+ // retry an operation that already committed. Release is fenced to our claim in the caller.
+ return finalized;
+ }
+
+ @Nullable
+ private String serializeEntity(@Nullable Object entity) throws JsonProcessingException {
Review Comment:
Inlined the null/String/mapper handling directly into tryFinalize's existing serialization try/catch and removed serializeEntity. Null responses, string responses, and typed model replay remain covered.
Pushed in 64f10ea09. All 770 REST server tests passed; formatting and Javadoc checks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation, and stores its response. While that record remains available, retries carrying the same
+ * key get the original answer back instead of a second mutation. Idempotency is off by default;
+ * when it is off, or when a request carries no key, the mutation runs directly and nothing is
+ * stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ *
+ * <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
+ * with different body/header values replays the first response; clients must use a new key for a
+ * different logical operation. The catalog mutation and response storage are not transactional:
+ * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ *
+ * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
+ * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
+ * scheduling durable cleanup belongs to the JDBC-store integration.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding =
+ Hashing.sha256().hashString(operationBinding, StandardCharsets.UTF_8).toString();
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // Only release this attempt's claim when the response is retryable or was not retained.
+ // A replacement owner's reservation must remain untouched.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, encoded path, and sorted, encoded query parameters. Bodies
+ * and behavior-changing headers are not compared; clients must use a fresh key for a different
+ * logical operation. The manager stores a SHA-256 digest of the complete identity to fit the
+ * store's bounded binding column without truncating distinct requests.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST /v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding =
+ new StringBuilder(httpMethod).append(" /").append(uriInfo.getPath(false));
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) {
+ query.add(
+ URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8)
+ + "="
+ + URLEncoder.encode(value, StandardCharsets.UTF_8));
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ boolean finalized =
+ idempotencyStore
+ .load(idempotencyKey)
+ .filter(record -> record.isFinalized() && record.claim() == claim)
+ .isPresent();
+ if (!finalized) {
+ LOG.warn(
+ "Response for Idempotency-Key: {} was not retained under this claim", idempotencyKey);
+ }
+ // Keep the actual mutation response: returning a synthetic 5xx could encourage clients to
+ // retry an operation that already committed. Release is fenced to our claim in the caller.
+ return finalized;
+ }
+
+ @Nullable
+ private String serializeEntity(@Nullable Object entity) throws JsonProcessingException {
+ if (entity == null) {
+ return null;
+ }
+ if (entity instanceof String) {
+ return (String) entity;
+ }
+ return icebergObjectMapper.writeValueAsString(entity);
+ }
+
+ private static Response conflict(String message, boolean retryable) {
+ Response response =
+ Response.status(Response.Status.CONFLICT)
+ .entity(
+ IcebergRESTUtils.errorResponse(
+ Response.Status.CONFLICT.getStatusCode(),
+ "IdempotencyConflictException",
+ message))
+ .type(MediaType.APPLICATION_JSON)
+ .build();
+ if (!retryable) {
+ return response;
+ }
+ return Response.fromResponse(response)
+ .header(HttpHeaders.RETRY_AFTER, RETRY_AFTER_SECONDS)
+ .build();
+ }
+
+ /**
+ * Returns whether a response finalizes the key. Per the Iceberg REST spec, {@code 5xx} responses
+ * are retryable and must not be stored, while {@code 2xx} and deterministic terminal {@code 4xx}
+ * responses are replayed. Authentication/authorization outcomes (401, 403, 419) also release the
+ * claim so changed credentials can be evaluated on retry. Serialization or finalization failure
+ * releases only this attempt's claim as well.
+ */
+ private static boolean isFinalizable(int httpStatus) {
Review Comment:
Inlined the status predicate in replayOrExecute and moved the finalization/release policy comment beside it. Kept NON_FINALIZABLE_STATUSES and the existing behavior.
Pushed in 64f10ea09. All 770 REST server tests passed; formatting and Javadoc checks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation, and stores its response. While that record remains available, retries carrying the same
+ * key get the original answer back instead of a second mutation. Idempotency is off by default;
+ * when it is off, or when a request carries no key, the mutation runs directly and nothing is
+ * stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ *
+ * <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
+ * with different body/header values replays the first response; clients must use a new key for a
+ * different logical operation. The catalog mutation and response storage are not transactional:
+ * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ *
+ * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
+ * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
+ * scheduling durable cleanup belongs to the JDBC-store integration.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding =
+ Hashing.sha256().hashString(operationBinding, StandardCharsets.UTF_8).toString();
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // Only release this attempt's claim when the response is retryable or was not retained.
+ // A replacement owner's reservation must remain untouched.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, encoded path, and sorted, encoded query parameters. Bodies
+ * and behavior-changing headers are not compared; clients must use a fresh key for a different
+ * logical operation. The manager stores a SHA-256 digest of the complete identity to fit the
+ * store's bounded binding column without truncating distinct requests.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST /v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding =
+ new StringBuilder(httpMethod).append(" /").append(uriInfo.getPath(false));
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) {
+ query.add(
+ URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8)
+ + "="
+ + URLEncoder.encode(value, StandardCharsets.UTF_8));
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ boolean finalized =
+ idempotencyStore
+ .load(idempotencyKey)
+ .filter(record -> record.isFinalized() && record.claim() == claim)
+ .isPresent();
+ if (!finalized) {
+ LOG.warn(
+ "Response for Idempotency-Key: {} was not retained under this claim", idempotencyKey);
+ }
+ // Keep the actual mutation response: returning a synthetic 5xx could encourage clients to
+ // retry an operation that already committed. Release is fenced to our claim in the caller.
+ return finalized;
+ }
+
+ @Nullable
+ private String serializeEntity(@Nullable Object entity) throws JsonProcessingException {
+ if (entity == null) {
+ return null;
+ }
+ if (entity instanceof String) {
+ return (String) entity;
+ }
+ return icebergObjectMapper.writeValueAsString(entity);
+ }
+
+ private static Response conflict(String message, boolean retryable) {
Review Comment:
Kept conflict as the shared helper for both in-flight and different-operation conflicts, preserving ErrorResponse and Retry-After handling.
Pushed in 64f10ea09. All 770 REST server tests passed; formatting and Javadoc checks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation, and stores its response. While that record remains available, retries carrying the same
+ * key get the original answer back instead of a second mutation. Idempotency is off by default;
+ * when it is off, or when a request carries no key, the mutation runs directly and nothing is
+ * stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ *
+ * <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
+ * with different body/header values replays the first response; clients must use a new key for a
+ * different logical operation. The catalog mutation and response storage are not transactional:
+ * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ *
+ * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
+ * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
+ * scheduling durable cleanup belongs to the JDBC-store integration.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding =
+ Hashing.sha256().hashString(operationBinding, StandardCharsets.UTF_8).toString();
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // Only release this attempt's claim when the response is retryable or was not retained.
+ // A replacement owner's reservation must remain untouched.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, encoded path, and sorted, encoded query parameters. Bodies
+ * and behavior-changing headers are not compared; clients must use a fresh key for a different
+ * logical operation. The manager stores a SHA-256 digest of the complete identity to fit the
+ * store's bounded binding column without truncating distinct requests.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST /v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding =
+ new StringBuilder(httpMethod).append(" /").append(uriInfo.getPath(false));
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) {
+ query.add(
+ URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8)
+ + "="
+ + URLEncoder.encode(value, StandardCharsets.UTF_8));
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
Review Comment:
Kept replay separate, including all three outcomes: in-flight conflict, binding conflict, and stored-response replay.
Pushed in 64f10ea09. All 770 REST server tests passed; formatting and Javadoc checks succeeded.
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
Posted by "laserninja (via GitHub) via commits" <co...@gravitino.apache.org>.
laserninja commented on code in PR #12474:
URL: https://github.com/apache/gravitino/pull/12474#discussion_r4559964954
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
Review Comment:
Addressed using the documented phase-1 limitation option you suggested. The manager Javadoc and operator guide now explicitly say that bodies and behavior-changing headers (including X-Iceberg-Access-Delegation) are not compared. Added an HTTP regression that reuses a key with a different create body, verifies the original response is replayed, and verifies the second table does not exist. Clients must generate a new key for a changed logical operation.
Changes pushed in e4a9470e6. Validation: 769 REST server tests passed; formatting and Javadoc tasks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding = new StringBuilder(httpMethod).append(' ').append(uriInfo.getPath());
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue()) {
+ query.add(parameter.getKey() + "=" + value);
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ return true;
Review Comment:
Fixed: after finalizeRecord, the manager loads the record and verifies it is finalized under this attempt's claim. An empty result or a replacement claim now makes tryFinalize return false and invokes claim-fenced release. Added tests for both a no-op finalize and a finalized replacement claim. The original mutation response is preserved: replacing an already-successful mutation with a synthetic 5xx would encourage another execution. This does not make catalog mutation and response persistence atomic; that limitation is now explicit in the guide and Javadoc.
Changes pushed in e4a9470e6. Validation: 769 REST server tests passed; formatting and Javadoc tasks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding = new StringBuilder(httpMethod).append(' ').append(uriInfo.getPath());
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue()) {
+ query.add(parameter.getKey() + "=" + value);
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ return true;
+ }
+
+ @Nullable
+ private String serializeEntity(@Nullable Object entity) throws JsonProcessingException {
+ if (entity == null) {
+ return null;
+ }
+ if (entity instanceof String) {
+ return (String) entity;
+ }
+ return icebergObjectMapper.writeValueAsString(entity);
+ }
+
+ private static Response conflict(String message, boolean retryable) {
+ Response response =
+ IcebergRESTUtils.errorResponse(
+ new IdempotencyConflictException(message), Response.Status.CONFLICT.getStatusCode());
+ if (!retryable) {
+ return response;
+ }
+ return Response.fromResponse(response)
+ .header(HttpHeaders.RETRY_AFTER, RETRY_AFTER_SECONDS)
+ .build();
+ }
+
+ /**
+ * Returns whether a response finalizes the key. Per the Iceberg REST spec, {@code 5xx} responses
+ * are retryable and must not be stored, while {@code 2xx} and deterministic terminal {@code 4xx}
+ * responses are replayed.
+ */
+ private static boolean isFinalizable(int httpStatus) {
+ return httpStatus < Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()
+ && !NON_FINALIZABLE_STATUSES.contains(httpStatus);
+ }
+
+ private static String truncate(String operationBinding) {
+ return operationBinding.length() <= MAX_OPERATION_BINDING_LENGTH
+ ? operationBinding
+ : operationBinding.substring(0, MAX_OPERATION_BINDING_LENGTH);
Review Comment:
Replaced truncation with a SHA-256 digest of the entire operation binding. Added an HTTP regression with query values sharing a 600-character prefix but different suffixes. It reproduced the incorrect 200 replay before the change and now returns 409.
Changes pushed in e4a9470e6. Validation: 769 REST server tests passed; formatting and Javadoc tasks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding = new StringBuilder(httpMethod).append(' ').append(uriInfo.getPath());
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue()) {
+ query.add(parameter.getKey() + "=" + value);
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
Review Comment:
Verified through Jersey with a new wire-level regression: the original typed create response and replay have identical response strings and JSON media type, with no double encoding. The test also asserts that the original has an ETag and the replay omits it. Both the class Javadoc and operator guide explain that clients needing an ETag should reload the table.
Changes pushed in e4a9470e6. Validation: 769 REST server tests passed; formatting and Javadoc tasks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding = new StringBuilder(httpMethod).append(' ').append(uriInfo.getPath());
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
Review Comment:
Fixed: query names and values are URL-encoded, names and repeated values are sorted, and duplicate values are preserved. Added an HTTP regression for a=b%26c%3Dd versus a=b&c=d, plus a unit test covering delimiters in names/values and repeated-value ordering. The encoded path is preserved as well.
Changes pushed in e4a9470e6. Validation: 769 REST server tests passed; formatting and Javadoc tasks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java:
##########
@@ -180,8 +186,21 @@ public Response createTable(
@AuthorizationMetadata(type = Entity.EntityType.SCHEMA) @Encoded() @PathParam("namespace")
String namespace,
CreateTableRequest createTableRequest,
- @HeaderParam(X_ICEBERG_ACCESS_DELEGATION) String accessDelegation) {
+ @HeaderParam(X_ICEBERG_ACCESS_DELEGATION) String accessDelegation,
+ @HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,
+ @Context UriInfo uriInfo) {
IcebergRESTUtils.validateRequest(createTableRequest, "CreateTableRequest");
+ return idempotencyManager.replayOrExecute(
+ idempotencyKey,
+ IcebergIdempotencyManager.operationBinding(HttpMethod.POST, uriInfo),
+ () -> doCreateTable(prefix, namespace, createTableRequest, accessDelegation));
Review Comment:
Checked all 13 wrapped mutation helpers: table create/update/drop; namespace create/update/drop and table/view registration; view create/replace/drop; table/view rename. Each maps dispatcher exceptions through IcebergExceptionMapper inside the supplier. Pre-dispatch decoding or validation can still throw, in which case the manager releases its claim. A post-commit error can still leave a mutation without a replayable response; the operator guide and manager Javadoc now explicitly document that catalog mutation and response storage are not transactional.
Changes pushed in e4a9470e6. Validation: 769 REST server tests passed; formatting and Javadoc tasks succeeded.
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
Posted by "laserninja (via GitHub) via commits" <co...@gravitino.apache.org>.
laserninja commented on code in PR #12474:
URL: https://github.com/apache/gravitino/pull/12474#discussion_r4566898657
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation, and stores its response. While that record remains available, retries carrying the same
+ * key get the original answer back instead of a second mutation. Idempotency is off by default;
+ * when it is off, or when a request carries no key, the mutation runs directly and nothing is
+ * stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ *
+ * <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
+ * with different body/header values replays the first response; clients must use a new key for a
+ * different logical operation. The catalog mutation and response storage are not transactional:
+ * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ *
+ * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
+ * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
+ * scheduling durable cleanup belongs to the JDBC-store integration.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding =
+ Hashing.sha256().hashString(operationBinding, StandardCharsets.UTF_8).toString();
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // Only release this attempt's claim when the response is retryable or was not retained.
+ // A replacement owner's reservation must remain untouched.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, encoded path, and sorted, encoded query parameters. Bodies
+ * and behavior-changing headers are not compared; clients must use a fresh key for a different
+ * logical operation. The manager stores a SHA-256 digest of the complete identity to fit the
+ * store's bounded binding column without truncating distinct requests.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST /v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding =
+ new StringBuilder(httpMethod).append(" /").append(uriInfo.getPath(false));
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) {
+ query.add(
+ URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8)
+ + "="
+ + URLEncoder.encode(value, StandardCharsets.UTF_8));
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ boolean finalized =
+ idempotencyStore
+ .load(idempotencyKey)
+ .filter(record -> record.isFinalized() && record.claim() == claim)
+ .isPresent();
+ if (!finalized) {
+ LOG.warn(
+ "Response for Idempotency-Key: {} was not retained under this claim", idempotencyKey);
+ }
+ // Keep the actual mutation response: returning a synthetic 5xx could encourage clients to
+ // retry an operation that already committed. Release is fenced to our claim in the caller.
+ return finalized;
Review Comment:
Added an HTTP fault-injection test with a store that accepts reservations but never finalizes responses. The initial namespace create returns 200 and a GET verifies the catalog mutation committed. Retrying the same create with the same key returns the catalog's AlreadyExistsException (409, without Retry-After), proving release allowed execution again rather than replaying 200 or reporting an in-flight conflict. This pins the documented phase-1 tradeoff for future durable-store work.
Pushed in 64f10ea09. All 770 REST server tests passed; formatting and Javadoc checks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java:
##########
@@ -180,8 +186,21 @@ public Response createTable(
@AuthorizationMetadata(type = Entity.EntityType.SCHEMA) @Encoded() @PathParam("namespace")
String namespace,
CreateTableRequest createTableRequest,
- @HeaderParam(X_ICEBERG_ACCESS_DELEGATION) String accessDelegation) {
+ @HeaderParam(X_ICEBERG_ACCESS_DELEGATION) String accessDelegation,
+ @HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,
+ @Context UriInfo uriInfo) {
IcebergRESTUtils.validateRequest(createTableRequest, "CreateTableRequest");
Review Comment:
Added the phase-1 note: validation precedes replay, so an invalid retry body can return 400 even when the key has a stored success. Kept the current validation ordering.
Pushed in 64f10ea09. All 770 REST server tests passed; formatting and Javadoc checks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation, and stores its response. While that record remains available, retries carrying the same
+ * key get the original answer back instead of a second mutation. Idempotency is off by default;
+ * when it is off, or when a request carries no key, the mutation runs directly and nothing is
+ * stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ *
+ * <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
+ * with different body/header values replays the first response; clients must use a new key for a
+ * different logical operation. The catalog mutation and response storage are not transactional:
+ * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ *
+ * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
+ * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
+ * scheduling durable cleanup belongs to the JDBC-store integration.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding =
+ Hashing.sha256().hashString(operationBinding, StandardCharsets.UTF_8).toString();
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // Only release this attempt's claim when the response is retryable or was not retained.
+ // A replacement owner's reservation must remain untouched.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, encoded path, and sorted, encoded query parameters. Bodies
+ * and behavior-changing headers are not compared; clients must use a fresh key for a different
+ * logical operation. The manager stores a SHA-256 digest of the complete identity to fit the
+ * store's bounded binding column without truncating distinct requests.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST /v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding =
+ new StringBuilder(httpMethod).append(" /").append(uriInfo.getPath(false));
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) {
+ query.add(
+ URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8)
+ + "="
+ + URLEncoder.encode(value, StandardCharsets.UTF_8));
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
Review Comment:
Removed the stored digest from the client-facing conflict message. It now says the key was already used for a different operation and asks for a new key. Added an HTTP assertion for the complete readable message; it failed against the previous hash-bearing response and now passes.
Pushed in 64f10ea09. All 770 REST server tests passed; formatting and Javadoc checks succeeded.
##########
docs/iceberg-rest-service.md:
##########
@@ -178,6 +178,32 @@ The settings below tune the background workers and are optional.
| `gravitino.iceberg-rest.async-cleanup.max-attempts` | Number of failed attempts before a cleanup job is marked `FAILED`. | `5` | No |
| `gravitino.iceberg-rest.async-cleanup.retention-hours` | Retention time for terminal `SUCCEEDED` or `FAILED` cleanup rows before pruning. | `720` | No |
+#### Idempotency Key
+
+The Iceberg REST spec defines an optional `Idempotency-Key` header on mutation endpoints so that a client can safely retry a request whose response it never saw. When enabled and the header is present, the server reserves the key, executes the mutation, and stores the response for replay while the record remains available.
+
+Support is disabled by default. Once enabled, the reuse window is advertised as `idempotency-key-lifetime` in `GET /v1/config`; per the spec, clients must assume idempotency is unsupported when that field is absent.
+
+The header applies to the create, update, drop, register, and rename endpoints for tables, namespaces, and views. Its value must be a UUIDv7 in string form ([RFC 9562](https://www.rfc-editor.org/rfc/rfc9562)); anything else returns `400 Bad Request`. Keys must be globally unique: reusing one with a different HTTP method, path, or query returns `409 Conflict`, and so does a retry that arrives while the first request is still running (with a `Retry-After` header). Successful and deterministic terminal `4xx` responses are stored and replayed, while `5xx`, `401`, `403`, and `419` responses release the key so the client can retry with it.
+
+| Configuration item | Description | Default value | Required |
+|---------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------|
+| `gravitino.iceberg-rest.idempotency-enabled` | Whether to honor the `Idempotency-Key` header. When `false`, the header is ignored and no lifetime is advertised. | `false` | No |
+| `gravitino.iceberg-rest.idempotency-key-lifetime` | The client reuse window for a key, an ISO-8601 duration such as `PT30M`. Advertised to clients as `idempotency-key-lifetime`. | `PT30M` | No |
+| `gravitino.iceberg-rest.idempotency-store-type` | The store holding idempotency records, either the `in-memory` short name or the fully-qualified class name of an `IdempotencyStore` implementation. | `in-memory` | No |
+| `gravitino.iceberg-rest.idempotency-max-entries` | The maximum number of records retained by the in-memory store. Records beyond it are evicted before their reuse window elapses. | `10000` | No |
+
+Phase-1 limitations:
+
+- Request identity covers the HTTP method, path, and query parameters. It does **not** compare request bodies or behavior-changing headers such as `X-Iceberg-Access-Delegation`. Reusing a key on the same URL with a changed body or header replays the first response; it does not apply the changed request. Always generate a new key for a different logical operation.
+- Replay preserves the status and JSON body but omits response headers such as `ETag`. Load the table again if the client needs its current ETag.
+- The catalog mutation and response persistence are not one transaction. A crash, serialization failure, lost reservation, or post-commit failure can leave a successful mutation without a replayable response. A retry can then execute again. Claim fencing protects replacement records, but cannot undo or fence catalog side effects.
+- This phase does not schedule `IdempotencyStore.purgeExpired`. The in-memory store reclaims expired entries through Caffeine. Custom stores must enforce expiry on reads/reservations and arrange their own cleanup; durable-store purge scheduling belongs to the JDBC follow-up.
+
+:::caution
+The `in-memory` store is node-local and not durable. A retry routed to another replica, or to a replica that restarted, finds no record and re-executes the mutation, and its size bound can evict a record before its reuse window elapses, including an in-flight reservation. A retry can then run concurrently with the original mutation. Use it for single-node deployments, development, and testing.
Review Comment:
Sharpened the operator caution to explicitly state that idempotency-enabled=true with the default in-memory store on multiple replicas does not provide cluster-wide deduplication and retries can execute a mutation twice.
Pushed in 64f10ea09. All 770 REST server tests passed; formatting and Javadoc checks succeeded.
##########
docs/iceberg-rest-service.md:
##########
@@ -178,6 +178,32 @@ The settings below tune the background workers and are optional.
| `gravitino.iceberg-rest.async-cleanup.max-attempts` | Number of failed attempts before a cleanup job is marked `FAILED`. | `5` | No |
| `gravitino.iceberg-rest.async-cleanup.retention-hours` | Retention time for terminal `SUCCEEDED` or `FAILED` cleanup rows before pruning. | `720` | No |
+#### Idempotency Key
+
+The Iceberg REST spec defines an optional `Idempotency-Key` header on mutation endpoints so that a client can safely retry a request whose response it never saw. When enabled and the header is present, the server reserves the key, executes the mutation, and stores the response for replay while the record remains available.
+
+Support is disabled by default. Once enabled, the reuse window is advertised as `idempotency-key-lifetime` in `GET /v1/config`; per the spec, clients must assume idempotency is unsupported when that field is absent.
+
+The header applies to the create, update, drop, register, and rename endpoints for tables, namespaces, and views. Its value must be a UUIDv7 in string form ([RFC 9562](https://www.rfc-editor.org/rfc/rfc9562)); anything else returns `400 Bad Request`. Keys must be globally unique: reusing one with a different HTTP method, path, or query returns `409 Conflict`, and so does a retry that arrives while the first request is still running (with a `Retry-After` header). Successful and deterministic terminal `4xx` responses are stored and replayed, while `5xx`, `401`, `403`, and `419` responses release the key so the client can retry with it.
+
+| Configuration item | Description | Default value | Required |
+|---------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------|
+| `gravitino.iceberg-rest.idempotency-enabled` | Whether to honor the `Idempotency-Key` header. When `false`, the header is ignored and no lifetime is advertised. | `false` | No |
+| `gravitino.iceberg-rest.idempotency-key-lifetime` | The client reuse window for a key, an ISO-8601 duration such as `PT30M`. Advertised to clients as `idempotency-key-lifetime`. | `PT30M` | No |
+| `gravitino.iceberg-rest.idempotency-store-type` | The store holding idempotency records, either the `in-memory` short name or the fully-qualified class name of an `IdempotencyStore` implementation. | `in-memory` | No |
+| `gravitino.iceberg-rest.idempotency-max-entries` | The maximum number of records retained by the in-memory store. Records beyond it are evicted before their reuse window elapses. | `10000` | No |
+
+Phase-1 limitations:
+
+- Request identity covers the HTTP method, path, and query parameters. It does **not** compare request bodies or behavior-changing headers such as `X-Iceberg-Access-Delegation`. Reusing a key on the same URL with a changed body or header replays the first response; it does not apply the changed request. Always generate a new key for a different logical operation.
+- Replay preserves the status and JSON body but omits response headers such as `ETag`. Load the table again if the client needs its current ETag.
Review Comment:
Kept the intentional ETag behavior and the existing HTTP wire-body/ETag regression unchanged.
Pushed in 64f10ea09. All 770 REST server tests passed; formatting and Javadoc checks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation, and stores its response. While that record remains available, retries carrying the same
+ * key get the original answer back instead of a second mutation. Idempotency is off by default;
+ * when it is off, or when a request carries no key, the mutation runs directly and nothing is
+ * stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ *
+ * <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
+ * with different body/header values replays the first response; clients must use a new key for a
+ * different logical operation. The catalog mutation and response storage are not transactional:
+ * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ *
+ * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
+ * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
+ * scheduling durable cleanup belongs to the JDBC-store integration.
+ */
+public class IcebergIdempotencyManager {
Review Comment:
Inlined only serializeEntity and isFinalizable into their single call sites, retaining the status policy comment and NON_FINALIZABLE_STATUSES. replay, tryFinalize, and conflict remain separate protocol-stage helpers.
Pushed in 64f10ea09. All 770 REST server tests passed; formatting and Javadoc checks succeeded.
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
Posted by "laserninja (via GitHub) via commits" <co...@gravitino.apache.org>.
laserninja commented on code in PR #12474:
URL: https://github.com/apache/gravitino/pull/12474#discussion_r4559967357
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding = new StringBuilder(httpMethod).append(' ').append(uriInfo.getPath());
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue()) {
+ query.add(parameter.getKey() + "=" + value);
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ return true;
+ }
+
+ @Nullable
+ private String serializeEntity(@Nullable Object entity) throws JsonProcessingException {
+ if (entity == null) {
+ return null;
+ }
+ if (entity instanceof String) {
+ return (String) entity;
+ }
+ return icebergObjectMapper.writeValueAsString(entity);
+ }
+
+ private static Response conflict(String message, boolean retryable) {
+ Response response =
+ IcebergRESTUtils.errorResponse(
+ new IdempotencyConflictException(message), Response.Status.CONFLICT.getStatusCode());
+ if (!retryable) {
+ return response;
+ }
+ return Response.fromResponse(response)
+ .header(HttpHeaders.RETRY_AFTER, RETRY_AFTER_SECONDS)
+ .build();
+ }
+
+ /**
+ * Returns whether a response finalizes the key. Per the Iceberg REST spec, {@code 5xx} responses
+ * are retryable and must not be stored, while {@code 2xx} and deterministic terminal {@code 4xx}
+ * responses are replayed.
+ */
+ private static boolean isFinalizable(int httpStatus) {
Review Comment:
Expanded the manager's finalization-policy Javadoc and operator guide to explicitly cover release for 401/403/419 as well as 5xx and serialization/finalization failure. Releases remain fenced to this attempt's claim.
Changes pushed in e4a9470e6. Validation: 769 REST server tests passed; formatting and Javadoc tasks succeeded.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
Review Comment:
Kept the manager in iceberg-rest-server. The fixes stay in this REST adapter: full-binding hashing, encoded query identity, verification of finalized claims, direct ErrorResponse construction, HTTP tests, and explicit phase-1 limitations. The merged common-module SPI is unchanged.
Changes pushed in e4a9470e6. Validation: 769 REST server tests passed; formatting and Javadoc tasks succeeded.
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
Posted by "lasdf1234 (via GitHub) via commits" <co...@gravitino.apache.org>.
lasdf1234 commented on code in PR #12474:
URL: https://github.com/apache/gravitino/pull/12474#discussion_r4559373718
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,312 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation exactly once, and stores its response so that retries carrying the same key get the
+ * original answer back instead of a second mutation. Idempotency is off by default; when it is off,
+ * or when a request carries no key, the mutation runs directly and nothing is stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Cap on the stored operation binding, matching the width a database backed store can hold. */
+ @VisibleForTesting static final int MAX_OPERATION_BINDING_LENGTH = 512;
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding = truncate(operationBinding);
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // The mutation failed in a way the spec treats as retryable, or its response could not be
+ // stored. Either way the key must go back so the client can retry with it.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, path, and query parameters, not the request body. A client
+ * that reuses one key for two different bodies on the same endpoint gets the first response
+ * replayed, which is exactly what the header promises; the spec already requires a fresh key per
+ * operation.
+ *
Review Comment:
test ping from review (will delete)
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12049] feat(iceberg-rest-server): honor Idempotency-Key on mutation endpoints [gravitino]
Posted by "lasdf1234 (via GitHub) via commits" <co...@gravitino.apache.org>.
lasdf1234 commented on code in PR #12474:
URL: https://github.com/apache/gravitino/pull/12474#discussion_r4560295001
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation, and stores its response. While that record remains available, retries carrying the same
+ * key get the original answer back instead of a second mutation. Idempotency is off by default;
+ * when it is off, or when a request carries no key, the mutation runs directly and nothing is
+ * stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ *
+ * <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
+ * with different body/header values replays the first response; clients must use a new key for a
+ * different logical operation. The catalog mutation and response storage are not transactional:
+ * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ *
+ * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
+ * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
+ * scheduling durable cleanup belongs to the JDBC-store integration.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding =
+ Hashing.sha256().hashString(operationBinding, StandardCharsets.UTF_8).toString();
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // Only release this attempt's claim when the response is retryable or was not retained.
+ // A replacement owner's reservation must remain untouched.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, encoded path, and sorted, encoded query parameters. Bodies
+ * and behavior-changing headers are not compared; clients must use a fresh key for a different
+ * logical operation. The manager stores a SHA-256 digest of the complete identity to fit the
+ * store's bounded binding column without truncating distinct requests.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST /v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding =
+ new StringBuilder(httpMethod).append(" /").append(uriInfo.getPath(false));
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) {
+ query.add(
+ URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8)
+ + "="
+ + URLEncoder.encode(value, StandardCharsets.UTF_8));
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
+ + "`, the Iceberg REST spec requires a new key for a different operation",
+ false);
+ }
+
+ LOG.info(
+ "Replaying the stored response for Idempotency-Key: {}, operation: {}, http status: {}.",
+ idempotencyKey,
+ binding,
+ found.httpStatus());
+ Response.ResponseBuilder builder = Response.status(found.httpStatus());
+ if (found.responseSummary() != null) {
+ builder.entity(found.responseSummary()).type(MediaType.APPLICATION_JSON);
+ }
+ return builder.build();
+ }
+
+ private boolean tryFinalize(
+ IdempotencyStore idempotencyStore, String idempotencyKey, long claim, Response response) {
+ String responseSummary;
+ try {
+ responseSummary = serializeEntity(response.getEntity());
+ } catch (JsonProcessingException e) {
+ LOG.warn(
+ "Failed to serialize the response for Idempotency-Key: {}, it will not be replayed.",
+ idempotencyKey,
+ e);
+ return false;
+ }
+ idempotencyStore.finalizeRecord(idempotencyKey, claim, response.getStatus(), responseSummary);
+ boolean finalized =
+ idempotencyStore
+ .load(idempotencyKey)
+ .filter(record -> record.isFinalized() && record.claim() == claim)
+ .isPresent();
+ if (!finalized) {
+ LOG.warn(
+ "Response for Idempotency-Key: {} was not retained under this claim", idempotencyKey);
+ }
+ // Keep the actual mutation response: returning a synthetic 5xx could encourage clients to
+ // retry an operation that already committed. Release is fenced to our claim in the caller.
+ return finalized;
Review Comment:
**Medium (Bugbot) — successful mutation + failed finalize still releases the key.**
`tryFinalize` correctly verifies retention after `finalizeRecord`, and returning the real 2xx (instead of a synthetic 5xx) is the right call. But when serialize fails or the post-check sees no record under this claim, `return false` → caller `release` → a client retry can run the mutation again.
Javadoc/docs already describe this phase-1 tradeoff. Remaining gap: no IT covering “action returns 2xx, finalize fails, same key retries and executes again”. Worth adding so the release-after-commit path does not regress when a durable store lands.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/rest/IcebergTableOperations.java:
##########
@@ -180,8 +186,21 @@ public Response createTable(
@AuthorizationMetadata(type = Entity.EntityType.SCHEMA) @Encoded() @PathParam("namespace")
String namespace,
CreateTableRequest createTableRequest,
- @HeaderParam(X_ICEBERG_ACCESS_DELEGATION) String accessDelegation) {
+ @HeaderParam(X_ICEBERG_ACCESS_DELEGATION) String accessDelegation,
+ @HeaderParam(IcebergIdempotencyManager.IDEMPOTENCY_KEY) String idempotencyKey,
+ @Context UriInfo uriInfo) {
IcebergRESTUtils.validateRequest(createTableRequest, "CreateTableRequest");
Review Comment:
**Low (Bugbot) — `validateRequest` runs before `replayOrExecute`.**
A retry that reuses the same `Idempotency-Key` but sends a body that fails validation gets **400** here and never reaches replay of a previously stored success. Spec-compliant clients retry the same payload, so this is an edge case; consider a one-line note in the phase-1 limitations docs, or moving validation inside the supplier if you want “same key always hits the manager first”.
##########
iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/idempotency/IcebergIdempotencyManager.java:
##########
@@ -0,0 +1,341 @@
+/*
+ * 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 org.apache.gravitino.iceberg.service.idempotency;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.hash.Hashing;
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.iceberg.common.IcebergConfig;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyKeys;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyRecord;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStore.ReserveResult;
+import org.apache.gravitino.iceberg.common.idempotency.IdempotencyStoreFactory;
+import org.apache.gravitino.iceberg.service.IcebergExceptionMapper;
+import org.apache.gravitino.iceberg.service.IcebergObjectMapper;
+import org.apache.gravitino.iceberg.service.IcebergRESTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies {@code Idempotency-Key} semantics to Iceberg REST mutation endpoints.
+ *
+ * <p>Each mutation runs through {@link #replayOrExecute}, which claims the key, executes the
+ * mutation, and stores its response. While that record remains available, retries carrying the same
+ * key get the original answer back instead of a second mutation. Idempotency is off by default;
+ * when it is off, or when a request carries no key, the mutation runs directly and nothing is
+ * stored.
+ *
+ * <p>A replayed response carries the original status and body. Response headers are not stored, so
+ * a replayed create or update does not carry the {@code ETag} the first response did; clients that
+ * rely on it simply load the table again.
+ *
+ * <p>Request bodies and behavior-changing headers are not compared. Reusing a key on the same URL
+ * with different body/header values replays the first response; clients must use a new key for a
+ * different logical operation. The catalog mutation and response storage are not transactional:
+ * eviction, a crash, serialization failure, or a post-commit exception can permit re-execution.
+ *
+ * <p>This phase does not schedule {@link IdempotencyStore#purgeExpired}. The in-memory store uses
+ * Caffeine for reclamation. Custom stores must enforce deadlines and arrange their own cleanup;
+ * scheduling durable cleanup belongs to the JDBC-store integration.
+ */
+public class IcebergIdempotencyManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergIdempotencyManager.class);
+
+ /** The idempotency key header defined by the Iceberg REST spec. */
+ public static final String IDEMPOTENCY_KEY = "Idempotency-Key";
+
+ /** Seconds a client should wait before retrying a request whose key is still in flight. */
+ private static final int RETRY_AFTER_SECONDS = 1;
+
+ /**
+ * Statuses that are terminal for the request but not for the key. Authentication and
+ * authorization outcomes depend on the caller's credentials rather than on catalog state, so
+ * replaying them would keep failing a retry that has since obtained valid credentials.
+ */
+ private static final Set<Integer> NON_FINALIZABLE_STATUSES = ImmutableSet.of(401, 403, 419);
+
+ private final boolean enabled;
+ private final Duration keyLifetime;
+ private final ObjectMapper icebergObjectMapper;
+ private final Optional<IdempotencyStore> store;
+
+ /**
+ * Creates a manager, loading the configured store when idempotency is enabled.
+ *
+ * @param icebergConfig the Iceberg REST server configuration
+ */
+ public IcebergIdempotencyManager(IcebergConfig icebergConfig) {
+ this(
+ icebergConfig,
+ icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED)
+ ? Optional.of(IdempotencyStoreFactory.create(icebergConfig))
+ : Optional.empty());
+ }
+
+ @VisibleForTesting
+ IcebergIdempotencyManager(IcebergConfig icebergConfig, Optional<IdempotencyStore> store) {
+ this.enabled = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_ENABLED);
+ this.keyLifetime =
+ Duration.parse(icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_KEY_LIFETIME));
+ this.icebergObjectMapper = IcebergObjectMapper.getInstance();
+ this.store = store;
+ }
+
+ /**
+ * Returns the key reuse window to advertise to clients.
+ *
+ * @return the lifetime as an ISO-8601 duration, or {@link Optional#empty()} when idempotency is
+ * disabled. The Iceberg REST spec reads the absence of {@code idempotency-key-lifetime} in
+ * the config response as "this server does not support idempotency".
+ */
+ public Optional<String> advertisedKeyLifetime() {
+ return enabled ? Optional.of(keyLifetime.toString()) : Optional.empty();
+ }
+
+ /**
+ * Runs a mutation under the given idempotency key.
+ *
+ * <p>Without a key, or with idempotency disabled, this just runs {@code action}. With a key, the
+ * first request claims it and stores the response; retries carrying the same key replay that
+ * response. A retry that arrives while the first request is still running, or that reuses a key
+ * already spent on a different operation, gets {@code 409 Conflict}.
+ *
+ * @param idempotencyKey the raw {@code Idempotency-Key} header value, may be {@code null}
+ * @param operationBinding request identity, see {@link #operationBinding(String, UriInfo)}
+ * @param action the mutation, which is expected to return its own error responses rather than
+ * throw
+ * @return the response to send to the client
+ */
+ public Response replayOrExecute(
+ @Nullable String idempotencyKey, String operationBinding, Supplier<Response> action) {
+ if (!enabled || StringUtils.isBlank(idempotencyKey) || !store.isPresent()) {
+ return action.get();
+ }
+
+ String key;
+ try {
+ key = IdempotencyKeys.canonicalize(idempotencyKey);
+ } catch (IllegalArgumentException e) {
+ return IcebergExceptionMapper.toRESTResponse(e);
+ }
+
+ IdempotencyStore idempotencyStore = store.get();
+ String binding =
+ Hashing.sha256().hashString(operationBinding, StandardCharsets.UTF_8).toString();
+ long expiresAtMs = System.currentTimeMillis() + keyLifetime.toMillis();
+ // A fresh claim per attempt, so that if this reservation is dropped underneath us and another
+ // request takes the key, our finalize or release lands on nothing instead of on its record.
+ long claim = ThreadLocalRandom.current().nextLong();
+ if (idempotencyStore.reserve(key, binding, claim, expiresAtMs) == ReserveResult.DUPLICATE) {
+ return replay(idempotencyStore, key, binding);
+ }
+
+ boolean finalized = false;
+ try {
+ Response response = action.get();
+ if (isFinalizable(response.getStatus())) {
+ finalized = tryFinalize(idempotencyStore, key, claim, response);
+ }
+ return response;
+ } finally {
+ if (!finalized) {
+ // Only release this attempt's claim when the response is retryable or was not retained.
+ // A replacement owner's reservation must remain untouched.
+ idempotencyStore.release(key, claim);
+ }
+ }
+ }
+
+ /**
+ * Builds the request identity stored alongside a key. Retries of the same logical operation
+ * produce the same binding, while a key reused for a different request does not.
+ *
+ * <p>The identity covers the method, encoded path, and sorted, encoded query parameters. Bodies
+ * and behavior-changing headers are not compared; clients must use a fresh key for a different
+ * logical operation. The manager stores a SHA-256 digest of the complete identity to fit the
+ * store's bounded binding column without truncating distinct requests.
+ *
+ * @param httpMethod the HTTP method of the endpoint
+ * @param uriInfo the request URI, may be {@code null} outside a request context
+ * @return the operation binding, for example {@code POST /v1/cat1/namespaces/ns1/tables}
+ */
+ public static String operationBinding(String httpMethod, @Nullable UriInfo uriInfo) {
+ if (uriInfo == null) {
+ return httpMethod;
+ }
+ StringBuilder binding =
+ new StringBuilder(httpMethod).append(" /").append(uriInfo.getPath(false));
+ MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
+ if (queryParameters != null && !queryParameters.isEmpty()) {
+ // Sorted, so that clients that order query parameters differently between a request and its
+ // retry still land on the same binding.
+ StringJoiner query = new StringJoiner("&", "?", "");
+ for (Map.Entry<String, List<String>> parameter : new TreeMap<>(queryParameters).entrySet()) {
+ for (String value : parameter.getValue().stream().sorted().collect(Collectors.toList())) {
+ query.add(
+ URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8)
+ + "="
+ + URLEncoder.encode(value, StandardCharsets.UTF_8));
+ }
+ }
+ binding.append(query);
+ }
+ return binding.toString();
+ }
+
+ /** Closes the underlying store. */
+ public void close() {
+ store.ifPresent(
+ idempotencyStore -> {
+ try {
+ idempotencyStore.close();
+ } catch (IOException e) {
+ LOG.warn("Close Iceberg idempotency store failed.", e);
+ }
+ });
+ }
+
+ private Response replay(
+ IdempotencyStore idempotencyStore, String idempotencyKey, String binding) {
+ Optional<IdempotencyRecord> record = idempotencyStore.load(idempotencyKey);
+ if (!record.isPresent()) {
+ // Reserved but not finalized: the first request is still running, here or on another node.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " is being processed by another request, retry later",
+ true);
+ }
+
+ IdempotencyRecord found = record.get();
+ if (!found.operationBinding().equals(binding)) {
+ // Replaying here would hand the client the response of an unrelated operation.
+ return conflict(
+ "Idempotency-Key: "
+ + idempotencyKey
+ + " was already used for `"
+ + found.operationBinding()
Review Comment:
**Low (Bugbot) — conflict message embeds the stored SHA-256 binding, not a human-readable operation.**
`found.operationBinding()` is the digest passed to `reserve`, so the client sees something like `` was already used for `a1b2…` ``. Prefer omitting the binding from the client-facing message (keep the hash for equality only), or store the pre-hash binding for diagnostics while still comparing hashes.
##########
docs/iceberg-rest-service.md:
##########
@@ -178,6 +178,32 @@ The settings below tune the background workers and are optional.
| `gravitino.iceberg-rest.async-cleanup.max-attempts` | Number of failed attempts before a cleanup job is marked `FAILED`. | `5` | No |
| `gravitino.iceberg-rest.async-cleanup.retention-hours` | Retention time for terminal `SUCCEEDED` or `FAILED` cleanup rows before pruning. | `720` | No |
+#### Idempotency Key
+
+The Iceberg REST spec defines an optional `Idempotency-Key` header on mutation endpoints so that a client can safely retry a request whose response it never saw. When enabled and the header is present, the server reserves the key, executes the mutation, and stores the response for replay while the record remains available.
+
+Support is disabled by default. Once enabled, the reuse window is advertised as `idempotency-key-lifetime` in `GET /v1/config`; per the spec, clients must assume idempotency is unsupported when that field is absent.
+
+The header applies to the create, update, drop, register, and rename endpoints for tables, namespaces, and views. Its value must be a UUIDv7 in string form ([RFC 9562](https://www.rfc-editor.org/rfc/rfc9562)); anything else returns `400 Bad Request`. Keys must be globally unique: reusing one with a different HTTP method, path, or query returns `409 Conflict`, and so does a retry that arrives while the first request is still running (with a `Retry-After` header). Successful and deterministic terminal `4xx` responses are stored and replayed, while `5xx`, `401`, `403`, and `419` responses release the key so the client can retry with it.
+
+| Configuration item | Description | Default value | Required |
+|---------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------|
+| `gravitino.iceberg-rest.idempotency-enabled` | Whether to honor the `Idempotency-Key` header. When `false`, the header is ignored and no lifetime is advertised. | `false` | No |
+| `gravitino.iceberg-rest.idempotency-key-lifetime` | The client reuse window for a key, an ISO-8601 duration such as `PT30M`. Advertised to clients as `idempotency-key-lifetime`. | `PT30M` | No |
+| `gravitino.iceberg-rest.idempotency-store-type` | The store holding idempotency records, either the `in-memory` short name or the fully-qualified class name of an `IdempotencyStore` implementation. | `in-memory` | No |
+| `gravitino.iceberg-rest.idempotency-max-entries` | The maximum number of records retained by the in-memory store. Records beyond it are evicted before their reuse window elapses. | `10000` | No |
+
+Phase-1 limitations:
+
+- Request identity covers the HTTP method, path, and query parameters. It does **not** compare request bodies or behavior-changing headers such as `X-Iceberg-Access-Delegation`. Reusing a key on the same URL with a changed body or header replays the first response; it does not apply the changed request. Always generate a new key for a different logical operation.
+- Replay preserves the status and JSON body but omits response headers such as `ETag`. Load the table again if the client needs its current ETag.
+- The catalog mutation and response persistence are not one transaction. A crash, serialization failure, lost reservation, or post-commit failure can leave a successful mutation without a replayable response. A retry can then execute again. Claim fencing protects replacement records, but cannot undo or fence catalog side effects.
+- This phase does not schedule `IdempotencyStore.purgeExpired`. The in-memory store reclaims expired entries through Caffeine. Custom stores must enforce expiry on reads/reservations and arrange their own cleanup; durable-store purge scheduling belongs to the JDBC follow-up.
+
+:::caution
+The `in-memory` store is node-local and not durable. A retry routed to another replica, or to a replica that restarted, finds no record and re-executes the mutation, and its size bound can evict a record before its reuse window elapses, including an in-flight reservation. A retry can then run concurrently with the original mutation. Use it for single-node deployments, development, and testing.
Review Comment:
**Low (Bugbot) — consider a sharper operator warning when enabling idempotency with the default store.**
The caution already states node-local / non-durable behavior. Operators who flip `idempotency-enabled=true` and leave `idempotency-store-type=in-memory` on a multi-replica deploy may still assume cluster-wide dedup. A one-liner tying “enabled + in-memory + >1 replica ⇒ retries can double-execute” would make the footgun harder to miss (optional: log a WARN at manager startup in that config).
##########
docs/iceberg-rest-service.md:
##########
@@ -178,6 +178,32 @@ The settings below tune the background workers and are optional.
| `gravitino.iceberg-rest.async-cleanup.max-attempts` | Number of failed attempts before a cleanup job is marked `FAILED`. | `5` | No |
| `gravitino.iceberg-rest.async-cleanup.retention-hours` | Retention time for terminal `SUCCEEDED` or `FAILED` cleanup rows before pruning. | `720` | No |
+#### Idempotency Key
+
+The Iceberg REST spec defines an optional `Idempotency-Key` header on mutation endpoints so that a client can safely retry a request whose response it never saw. When enabled and the header is present, the server reserves the key, executes the mutation, and stores the response for replay while the record remains available.
+
+Support is disabled by default. Once enabled, the reuse window is advertised as `idempotency-key-lifetime` in `GET /v1/config`; per the spec, clients must assume idempotency is unsupported when that field is absent.
+
+The header applies to the create, update, drop, register, and rename endpoints for tables, namespaces, and views. Its value must be a UUIDv7 in string form ([RFC 9562](https://www.rfc-editor.org/rfc/rfc9562)); anything else returns `400 Bad Request`. Keys must be globally unique: reusing one with a different HTTP method, path, or query returns `409 Conflict`, and so does a retry that arrives while the first request is still running (with a `Retry-After` header). Successful and deterministic terminal `4xx` responses are stored and replayed, while `5xx`, `401`, `403`, and `419` responses release the key so the client can retry with it.
+
+| Configuration item | Description | Default value | Required |
+|---------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|----------|
+| `gravitino.iceberg-rest.idempotency-enabled` | Whether to honor the `Idempotency-Key` header. When `false`, the header is ignored and no lifetime is advertised. | `false` | No |
+| `gravitino.iceberg-rest.idempotency-key-lifetime` | The client reuse window for a key, an ISO-8601 duration such as `PT30M`. Advertised to clients as `idempotency-key-lifetime`. | `PT30M` | No |
+| `gravitino.iceberg-rest.idempotency-store-type` | The store holding idempotency records, either the `in-memory` short name or the fully-qualified class name of an `IdempotencyStore` implementation. | `in-memory` | No |
+| `gravitino.iceberg-rest.idempotency-max-entries` | The maximum number of records retained by the in-memory store. Records beyond it are evicted before their reuse window elapses. | `10000` | No |
+
+Phase-1 limitations:
+
+- Request identity covers the HTTP method, path, and query parameters. It does **not** compare request bodies or behavior-changing headers such as `X-Iceberg-Access-Delegation`. Reusing a key on the same URL with a changed body or header replays the first response; it does not apply the changed request. Always generate a new key for a different logical operation.
+- Replay preserves the status and JSON body but omits response headers such as `ETag`. Load the table again if the client needs its current ETag.
Review Comment:
**Info (Bugbot) — ETag omission on replay looks intentional and tested.**
Class javadoc + this bullet + `testReplayPreservesWireJsonAndOmitsEtag` cover it. No change needed unless you want the HTTP test matrix to also assert create/update replay paths explicitly.
--
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: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org