shangxinli commented on code in PR #985:
URL: https://github.com/apache/iceberg-cpp/pull/985#discussion_r4304042501
##########
src/iceberg/catalog/rest/auth/auth_manager.cc:
##########
@@ -217,21 +243,31 @@ class OAuth2Manager : public AuthManager {
Result<std::shared_ptr<AuthSession>> ContextualSession(
const SessionContext& context, std::shared_ptr<AuthSession> parent)
override {
- // TODO(lishuxu): Add child-session caching and refresh, matching Java
- // AuthSessionCache.
+ // Use session_id as cache key for contextual sessions
+ std::string cache_key = context.session_id.empty() ? "" : "ctx:" +
context.session_id;
return MaybeCreateChildSession(context.credentials,
/*allow_credential=*/true,
- std::move(parent));
+ std::move(parent), cache_key);
}
Result<std::shared_ptr<AuthSession>> TableSession(
[[maybe_unused]] const TableIdentifier& table,
const std::unordered_map<std::string, std::string>& properties,
std::shared_ptr<AuthSession> parent) override {
+ // Use token value as cache key for table sessions
+ auto token_it = properties.find(AuthProperties::kToken.key());
+ std::string cache_key;
+ if (token_it != properties.end() && !token_it->second.empty()) {
+ cache_key = "tbl:" + token_it->second;
Review Comment:
The cache key is built only from the plain token property, so a table
session carrying a typed token (jwt, saml2, id_token and the rest) gets an
empty key and does a fresh ExchangeToken on every call. Java keys those off the
token value as well, via cacheKeyFunc applied to each type in
TOKEN_PREFERENCE_ORDER at OAuth2Manager.java:244.
##########
src/iceberg/catalog/rest/auth/auth_manager.cc:
##########
@@ -283,42 +320,78 @@ class OAuth2Manager : public AuthManager {
ICEBERG_PRECHECK(parent_info.has_value(),
"OAuth2 child session requires OAuth2 parent metadata");
+ // Use cache if we have a valid cache_key
+ if (!cache_key.empty() && session_cache_) {
+ return session_cache_->Get(cache_key,
+ [&]() -> Result<std::shared_ptr<AuthSession>>
{
+ return CreateChildSessionUncached(
+ credentials, allow_credential,
*parent_info);
+ });
+ }
+
+ // No cache, create session directly
+ return CreateChildSessionUncached(credentials, allow_credential,
*parent_info);
+ }
+
+ Result<std::shared_ptr<AuthSession>> CreateChildSessionUncached(
+ const std::unordered_map<std::string, std::string>& credentials,
+ bool allow_credential, const OAuth2SessionInfo& parent_info) {
+ auto token_it = credentials.find(AuthProperties::kToken.key());
+ auto credential_it = credentials.find(AuthProperties::kCredential.key());
+ auto typed_token = FindPreferredTypedToken(credentials);
+
if (token_it != credentials.end()) {
- ICEBERG_ASSIGN_OR_RAISE(auto config,
- ChildConfig(*parent_info,
parent_info->credential));
+ // Token child session: don't include parent credential in config.
+ // Token-based sessions are not refreshed; when token exchange is
enabled,
+ // refresh will use the token itself rather than the parent credential.
+ auto properties = parent_info.optional_oauth_params;
+ properties[AuthProperties::kScope.key()] = parent_info.scope;
+ properties[AuthProperties::kOAuth2ServerUri.key()] =
parent_info.oauth2_server_uri;
+ ICEBERG_ASSIGN_OR_RAISE(auto config,
AuthProperties::FromProperties(properties));
return MakeSession(AccessTokenResponse(token_it->second), config,
/*keep_refreshed=*/false);
}
if (allow_credential && credential_it != credentials.end()) {
ICEBERG_ASSIGN_OR_RAISE(auto config,
- ChildConfig(*parent_info,
credential_it->second));
- ICEBERG_ASSIGN_OR_RAISE(auto response,
- OAuth2Util::FetchToken(*refresh_client_,
*parent, config));
- return MakeSession(response, config, /*keep_refreshed=*/false);
+ ChildConfig(parent_info, credential_it->second));
+ // Use parent session headers for FetchToken authentication
+ auto temp_parent = AuthSession::MakeDefault(parent_info.headers);
+ ICEBERG_ASSIGN_OR_RAISE(
+ auto response, OAuth2Util::FetchToken(*refresh_client_,
*temp_parent, config));
+ // Credential child sessions use keep_refreshed from catalog level
+ return MakeSession(response, config, keep_refreshed_);
}
std::optional<std::string> actor_token;
std::optional<std::string> actor_token_type;
- if (!parent_info->token.empty()) {
- actor_token = parent_info->token;
- actor_token_type = parent_info->issued_token_type;
+ if (!parent_info.token.empty()) {
+ actor_token = parent_info.token;
+ actor_token_type = parent_info.issued_token_type;
}
+ // Use parent session headers for ExchangeToken authentication
+ auto temp_parent = AuthSession::MakeDefault(parent_info.headers);
ICEBERG_ASSIGN_OR_RAISE(
auto response,
- OAuth2Util::ExchangeToken(*refresh_client_, *parent, {},
typed_token->second,
+ OAuth2Util::ExchangeToken(*refresh_client_, *temp_parent, {},
typed_token->second,
typed_token->first, actor_token,
actor_token_type,
- parent_info->scope,
parent_info->oauth2_server_uri,
- parent_info->optional_oauth_params));
+ parent_info.scope,
parent_info.oauth2_server_uri,
+ parent_info.optional_oauth_params));
ICEBERG_ASSIGN_OR_RAISE(auto config,
- ChildConfig(*parent_info,
parent_info->credential));
+ ChildConfig(parent_info, parent_info.credential));
return MakeSession(response, config, /*keep_refreshed=*/false);
Review Comment:
Token-exchange children are pinned to keep_refreshed false, so an exchanged
token just expires. Java builds this one through fromTokenExchange with
refreshExecutor at OAuth2Manager.java:271, the same as the credential path, so
it should probably follow keep_refreshed_ too.
##########
src/iceberg/catalog/rest/auth/auth_session_cache.cc:
##########
@@ -0,0 +1,240 @@
+/*
+ * 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.
+ */
+
+#include <utility>
+
+#include "iceberg/catalog/rest/auth/auth_session_cache_internal.h"
+#include "iceberg/catalog/rest/auth/auth_session_internal.h"
+#include "iceberg/catalog/rest/auth/token_refresh_scheduler.h"
+#include "iceberg/util/macros.h"
+
+namespace iceberg::rest::auth::internal {
+
+Result<std::shared_ptr<AuthSessionCache>> AuthSessionCache::Make(
+ std::chrono::milliseconds session_timeout, RemovalListener on_removal,
Clock clock) {
+ ICEBERG_PRECHECK(session_timeout >= std::chrono::milliseconds::zero(),
+ "Auth session timeout must not be negative: {} ms",
+ session_timeout.count());
+ ICEBERG_PRECHECK(clock != nullptr, "Auth session cache clock must not be
null");
+ return std::shared_ptr<AuthSessionCache>(
+ new AuthSessionCache(session_timeout, std::move(on_removal),
std::move(clock)));
+}
+
+AuthSessionCache::AuthSessionCache(std::chrono::milliseconds session_timeout,
+ RemovalListener on_removal, Clock clock)
+ : session_timeout_(session_timeout),
+ on_removal_(std::move(on_removal)),
+ clock_(std::move(clock)) {}
+
+AuthSessionCache::~AuthSessionCache() { Close(); }
+
+Result<std::shared_ptr<AuthSession>> AuthSessionCache::Get(const std::string&
key,
+ const Loader&
loader) {
+ // Phase 1: Look up cache (under lock)
+ std::shared_ptr<Slot> slot;
+ std::vector<std::shared_ptr<AuthSession>> removed;
+ {
+ std::unique_lock lock(mutex_);
+ while (true) {
+ if (closed_) {
+ return Invalid("Auth session cache is closed");
+ }
+ auto it = slots_.find(key);
+ if (it == slots_.end()) {
+ break;
+ }
+ auto existing = it->second;
+ if (existing->loading) {
+ // Wait for another thread to finish loading. Loop again after waking
+ // because a failed load removes the slot.
+ load_finished_.wait(lock, [&] { return closed_ || !existing->loading;
});
+ continue;
+ }
+ auto now = clock_();
+ if (!IsExpired(*existing, now)) {
+ existing->last_access = now;
+ return existing->session;
+ }
+ removed.push_back(std::move(existing->session));
+ slots_.erase(it);
+ break;
+ }
+ // Create loading slot. Other threads calling Get(key) will wait.
+ slot = std::make_shared<Slot>();
+ slots_.emplace(key, slot);
+ }
+
+ // Phase 2: Call loader (lock released)
+ NotifyRemoved(removed);
+ auto result = loader();
+ if (result.has_value() && result.value() == nullptr) {
+ result = Invalid("Auth session loader returned a null session");
+ }
+
+ // Phase 3: Update cache (re-acquire lock)
+ std::shared_ptr<AuthSession> orphan;
+ {
+ std::lock_guard lock(mutex_);
+ slot->loading = false;
+ auto it = slots_.find(key);
+ bool current = it != slots_.end() && it->second == slot;
+
+ if (!result.has_value()) {
+ // Failed loads are not cached. Remove the slot so next Get() can retry.
+ if (current) {
+ slots_.erase(it);
+ }
+ } else if (closed_ || !current) {
+ // Cache closed during load, or slot replaced. Mark as orphan.
+ orphan = result.value();
+ } else {
+ slot->session = result.value();
+ slot->last_access = clock_();
+ }
+ }
+ load_finished_.notify_all();
+
+ if (orphan != nullptr) {
+ if (on_removal_) {
+ on_removal_(orphan);
+ }
+ return Invalid("Auth session cache is closed");
+ }
+ return result;
+}
+
+void AuthSessionCache::Sweep() {
+ std::vector<std::shared_ptr<AuthSession>> removed;
+ {
+ std::lock_guard lock(mutex_);
+ auto now = clock_();
+ for (auto it = slots_.begin(); it != slots_.end();) {
+ if (!it->second->loading && IsExpired(*it->second, now)) {
+ removed.push_back(std::move(it->second->session));
+ it = slots_.erase(it);
+ } else {
+ ++it;
+ }
+ }
+ }
+ NotifyRemoved(removed);
+}
+
+Status AuthSessionCache::StartPeriodicSweep(TokenRefreshScheduler& scheduler,
+ std::chrono::milliseconds
interval) {
+ ICEBERG_PRECHECK(interval > std::chrono::milliseconds::zero(),
+ "Auth session sweep interval must be positive: {} ms",
+ interval.count());
+ std::lock_guard lock(mutex_);
+ if (closed_ || sweep_scheduler_ != nullptr) {
+ return {};
+ }
+ sweep_scheduler_ = &scheduler;
+ sweep_interval_ = interval;
+ ScheduleSweepLocked();
+ return {};
+}
+
+void AuthSessionCache::Close() {
+ std::vector<std::shared_ptr<AuthSession>> removed;
+ TokenRefreshScheduler* scheduler = nullptr;
+ uint64_t sweep_task_id = 0;
+ {
+ std::lock_guard lock(mutex_);
+ if (closed_) {
+ return;
+ }
+ closed_ = true;
+ for (auto& [key, slot] : slots_) {
+ // Sessions still loading are handed to the listener when their load
ends.
+ if (!slot->loading) {
+ removed.push_back(std::move(slot->session));
+ }
+ }
+ slots_.clear();
+ scheduler = sweep_scheduler_;
+ sweep_task_id = std::exchange(sweep_task_id_, 0);
+ }
+ load_finished_.notify_all();
+ if (scheduler != nullptr) {
+ scheduler->Cancel(sweep_task_id);
+ }
+ NotifyRemoved(removed);
+}
+
+size_t AuthSessionCache::size() const {
+ std::lock_guard lock(mutex_);
+ return slots_.size();
+}
+
+bool AuthSessionCache::IsExpired(const Slot& slot,
+ std::chrono::steady_clock::time_point now)
const {
+ // Check 1: Idle timeout (expireAfterAccess semantics)
+ if (now - slot.last_access >= session_timeout_) {
+ return true;
+ }
+
+ // Check 2: Token expiration
Review Comment:
This token-expiry check has no Java counterpart, the Caffeine cache there is
expireAfterAccess only at AuthSessionCache.java:129. For a credential child
with keep_refreshed true, a sweep landing between expiry and the refresh
completing will evict a live session and call StopRefreshing on it while
callers still hold it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]