jerryshao commented on code in PR #14942: URL: https://github.com/apache/gravitino/pull/14942#discussion_r4548442751
########## iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/idempotency/InMemoryIdempotencyStore.java: ########## @@ -0,0 +1,229 @@ +/* + * 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.common.idempotency; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.github.benmanes.caffeine.cache.Expiry; +import com.github.benmanes.caffeine.cache.RemovalCause; +import com.google.common.annotations.VisibleForTesting; +import java.util.Iterator; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.LongSupplier; +import javax.annotation.Nullable; +import org.apache.gravitino.iceberg.common.IcebergConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Node-local {@link IdempotencyStore} backed by a Caffeine cache. + * + * <p>This store is best-effort and intended for single-node deployments, development, and tests. It + * is not durable, and it is not shared between replicas: a retry routed to another node, or to a + * node that restarted, finds no record and re-executes the mutation. Its size bound can also evict + * a record before its reuse window elapses, including an in-flight reservation. A retry can then + * reserve the same key and run the mutation concurrently with the original request. At-most-once + * execution therefore depends on the reservation remaining cached; claim fencing prevents stale + * writes to a replacement record but cannot prevent duplicate mutations after eviction. Size the + * cache for all keys within the reuse window, including in-flight requests. Production deployments + * that need durable deduplication or run more than one replica should use a shared, durable store + * instead. + * + * <p>Each record's own {@code expiresAtMs} decides whether it still counts, so a record past its + * deadline reads as absent whether or not the cache has reclaimed it yet. Caffeine's expiry only + * reclaims memory, which keeps behavior independent of when maintenance runs and matches how a + * database-backed store compares {@code expires_at} in its queries. + */ +public class InMemoryIdempotencyStore implements IdempotencyStore { + + private static final Logger LOG = LoggerFactory.getLogger(InMemoryIdempotencyStore.class); + + /** Evictions between two warnings, so an undersized cache is visible without flooding the log. */ + private static final long EVICTION_LOG_INTERVAL = 1000; + + private final AtomicLong sizeEvictions = new AtomicLong(); + private final LongSupplier clock; + + private Cache<String, IdempotencyRecord> cache; + + /** Creates a store reading wall-clock time. */ + public InMemoryIdempotencyStore() { + this(System::currentTimeMillis); + } + + @VisibleForTesting + InMemoryIdempotencyStore(LongSupplier clock) { + this.clock = clock; + } + + @Override + public void initialize(Map<String, String> properties) { + IcebergConfig icebergConfig = new IcebergConfig(properties); + int maxEntries = icebergConfig.get(IcebergConfig.ICEBERG_IDEMPOTENCY_MAX_ENTRIES); + this.cache = + Caffeine.newBuilder() + // Expiry off each record's own deadline rather than expireAfterWrite, which restarts on + // every write: finalizing a record is a write, and would otherwise push a record + // finalized late in its window well past the lifetime advertised to clients. + .expireAfter( + new Expiry<String, IdempotencyRecord>() { + @Override + public long expireAfterCreate( + String key, IdempotencyRecord record, long currentTimeNanos) { + return remainingNanos(record); + } + + @Override + public long expireAfterUpdate( + String key, + IdempotencyRecord record, + long currentTimeNanos, + long currentDurationNanos) { + return remainingNanos(record); + } + + @Override + public long expireAfterRead( + String key, + IdempotencyRecord record, + long currentTimeNanos, + long currentDurationNanos) { + return remainingNanos(record); + } + }) + .maximumSize(maxEntries) + .removalListener( + (String key, IdempotencyRecord record, RemovalCause cause) -> { + if (cause == RemovalCause.SIZE) { + onSizeEviction(maxEntries); + } + }) + .build(); + LOG.info("Initialized in-memory Iceberg idempotency store, max entries: {}.", maxEntries); + } + + @Override + public ReserveResult reserve( + String idempotencyKey, String operationBinding, long claim, long expiresAtMs) { + String key = IdempotencyKeys.canonicalize(idempotencyKey); Review Comment: If the caller passes an expiresAtMs that is already in the past, reserve returns RESERVED but the record is instantly expired, so a concurrent retry can reserve too. Consider rejecting a non-future expiresAtMs with a precondition check. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
