nastra commented on code in PR #11844: URL: https://github.com/apache/iceberg/pull/11844#discussion_r1909181281
########## core/src/main/java/org/apache/iceberg/rest/auth/RefreshingAuthManager.java: ########## @@ -0,0 +1,88 @@ +/* + * 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.iceberg.rest.auth; + +import java.util.List; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; +import org.apache.iceberg.util.ThreadPools; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * An {@link AuthManager} that provides machinery for refreshing authentication data asynchronously, + * using a background thread pool. + */ +public abstract class RefreshingAuthManager implements AuthManager { + + private static final Logger LOG = LoggerFactory.getLogger(RefreshingAuthManager.class); + + private final String executorNamePrefix; + private boolean keepRefreshed = true; + private volatile ScheduledExecutorService refreshExecutor; + + protected RefreshingAuthManager(String executorNamePrefix) { + this.executorNamePrefix = executorNamePrefix; + } + + public void keepRefreshed(boolean keep) { + this.keepRefreshed = keep; + } + + @Override + public void close() { + ScheduledExecutorService service = refreshExecutor; + this.refreshExecutor = null; + if (service != null) { + List<Runnable> tasks = service.shutdownNow(); + tasks.forEach( + task -> { + if (task instanceof Future) { + ((Future<?>) task).cancel(true); + } + }); + + try { + if (!service.awaitTermination(1, TimeUnit.MINUTES)) { + LOG.warn("Timed out waiting for refresh executor to terminate"); + } + } catch (InterruptedException e) { + LOG.warn("Interrupted while waiting for refresh executor to terminate", e); + Thread.currentThread().interrupt(); + } + } + } + + @Nullable + protected ScheduledExecutorService refreshExecutor() { + if (!keepRefreshed) { + return null; + } + if (refreshExecutor == null) { + synchronized (this) { + if (refreshExecutor == null) { + this.refreshExecutor = ThreadPools.newScheduledPool(executorNamePrefix, 1); + } + } + } Review Comment: newline here and a few lines above ########## core/src/main/java/org/apache/iceberg/rest/auth/AuthConfig.java: ########## @@ -69,4 +70,42 @@ default String oauth2ServerUri() { static ImmutableAuthConfig.Builder builder() { return ImmutableAuthConfig.builder(); } + + static AuthConfig fromProperties(Map<String, String> properties) { + return builder() + .credential(properties.get(OAuth2Properties.CREDENTIAL)) + .token(properties.get(OAuth2Properties.TOKEN)) + .scope(properties.getOrDefault(OAuth2Properties.SCOPE, OAuth2Properties.CATALOG_SCOPE)) + .oauth2ServerUri( + properties.getOrDefault(OAuth2Properties.OAUTH2_SERVER_URI, ResourcePaths.tokens())) + .optionalOAuthParams(OAuth2Util.buildOptionalParam(properties)) + .keepRefreshed( + PropertyUtil.propertyAsBoolean( + properties, + OAuth2Properties.TOKEN_REFRESH_ENABLED, + OAuth2Properties.TOKEN_REFRESH_ENABLED_DEFAULT)) + .expiresAtMillis(expiresAtMillis(properties)) + .build(); + } + + private static Long expiresAtMillis(Map<String, String> props) { + Long expiresAtMillis = null; + + if (props.containsKey(OAuth2Properties.TOKEN)) { + expiresAtMillis = OAuth2Util.expiresAtMillis(props.get(OAuth2Properties.TOKEN)); + } + + if (expiresAtMillis == null) { Review Comment: both ifs can be combined ########## core/src/test/java/org/apache/iceberg/rest/auth/TestAuthSessionCache.java: ########## @@ -0,0 +1,91 @@ +/* + * 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.iceberg.rest.auth; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; + +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Function; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class TestAuthSessionCache { + + @Test + void cachedHitsAndMisses() { + AuthSessionCache cache = + new AuthSessionCache(Duration.ofHours(1), Runnable::run, System::nanoTime); + AuthSession session1 = Mockito.mock(AuthSession.class); + AuthSession session2 = Mockito.mock(AuthSession.class); + + @SuppressWarnings("unchecked") + Function<String, AuthSession> loader = Mockito.mock(Function.class); + Mockito.when(loader.apply("key1")).thenReturn(session1); + Mockito.when(loader.apply("key2")).thenReturn(session2); + + AuthSession session = cache.cachedSession("key1", loader); + assertThat(session).isNotNull().isSameAs(session1); + + session = cache.cachedSession("key1", loader); + assertThat(session).isNotNull().isSameAs(session1); + + session = cache.cachedSession("key2", loader); + assertThat(session).isNotNull().isSameAs(session2); + + session = cache.cachedSession("key2", loader); + assertThat(session).isNotNull().isSameAs(session2); + + Mockito.verify(loader, times(1)).apply("key1"); + Mockito.verify(loader, times(1)).apply("key2"); + + assertThat(cache.sessionCache().asMap()).hasSize(2); + cache.close(); + assertThat(cache.sessionCache().asMap()).isEmpty(); + + Mockito.verify(session1).close(); + Mockito.verify(session2).close(); + } + + @Test + void cacheEviction() { + AtomicLong ticker = new AtomicLong(0); + AuthSessionCache cache = new AuthSessionCache(Duration.ofHours(1), Runnable::run, ticker::get); + AuthSession session1 = Mockito.mock(AuthSession.class); + + @SuppressWarnings("unchecked") Review Comment: we typically add this to the enclosing method ########## core/src/main/java/org/apache/iceberg/rest/auth/AuthSessionCache.java: ########## @@ -0,0 +1,127 @@ +/* + * 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.iceberg.rest.auth; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import java.time.Duration; +import java.util.concurrent.Executor; +import java.util.concurrent.ForkJoinPool; +import java.util.function.Function; +import java.util.function.LongSupplier; +import javax.annotation.Nullable; +import org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting; + +/** A cache for {@link AuthSession} instances. */ +public class AuthSessionCache implements AutoCloseable { + + private final Duration sessionTimeout; + private final Executor executor; + private final LongSupplier nanoTimeSupplier; + + private volatile Cache<String, AuthSession> sessionCache; + + /** + * Creates a new cache with the given session timeout, and with default executor and nano time + * supplier for eviction tasks. + * + * @param sessionTimeout the session timeout. Sessions will become eligible for eviction after + * this duration of inactivity. + */ + public AuthSessionCache(Duration sessionTimeout) { + this(sessionTimeout, null, null); + } + + /** + * Creates a new cache with the given session timeout, executor, and nano time supplier. This + * method is useful for testing mostly. + * + * @param sessionTimeout the session timeout. Sessions will become eligible for eviction after + * this duration of inactivity. + * @param executor the executor to use for eviction tasks; if null, the cache will use the + * {@linkplain ForkJoinPool#commonPool() common pool}. The executor will not be closed when + * this cache is closed. + * @param nanoTimeSupplier the supplier for nano time; if null, the cache will use {@link + * System#nanoTime()}. + */ + public AuthSessionCache( + Duration sessionTimeout, + @Nullable Executor executor, + @Nullable LongSupplier nanoTimeSupplier) { + this.sessionTimeout = sessionTimeout; + this.executor = executor; + this.nanoTimeSupplier = nanoTimeSupplier; + } + + /** + * Returns a cached session for the given key, loading it with the given loader if it is not + * already cached. + * + * @param key the key to use for the session. + * @param loader the loader to use to load the session if it is not already cached. + * @param <T> the type of the session. + * @return the cached session. + */ + @SuppressWarnings("unchecked") + public <T extends AuthSession> T cachedSession(String key, Function<String, T> loader) { + return (T) sessionCache().get(key, loader); + } + + @Override + public void close() { + Cache<String, AuthSession> cache = sessionCache; + this.sessionCache = null; + if (cache != null) { + cache.invalidateAll(); + cache.cleanUp(); + } + } + + @VisibleForTesting + Cache<String, AuthSession> sessionCache() { + if (sessionCache == null) { + synchronized (this) { + if (sessionCache == null) { + this.sessionCache = newSessionCache(sessionTimeout, executor, nanoTimeSupplier); + } + } + } + return sessionCache; Review Comment: nit: newline after } here and in the method further below -- 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: issues-unsubscr...@iceberg.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org For additional commands, e-mail: issues-h...@iceberg.apache.org