fjtirado commented on code in PR #4000: URL: https://github.com/apache/incubator-kie-kogito-runtimes/pull/4000#discussion_r2260680689
########## quarkus/extensions/kogito-quarkus-serverless-workflow-jdbc-token-persistence-extension/kogito-quarkus-serverless-workflow-jdbc-token-persistence/src/main/java/org/kie/kogito/serverless/workflow/token/persistence/jdbc/JdbcTokenCacheRepository.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.kie.kogito.serverless.workflow.token.persistence.jdbc; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import javax.sql.DataSource; + +import org.kie.kogito.addons.quarkus.token.exchange.persistence.TokenCacheRepository; +import org.kie.kogito.addons.quarkus.token.exchange.persistence.model.TokenCacheRecord; +import org.kie.kogito.addons.quarkus.token.exchange.utils.CacheUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import jakarta.annotation.Priority; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Alternative; + +/** + * JDBC-based repository for token cache operations. + * Follows the same pattern as other JDBC repositories in the codebase. + */ +@ApplicationScoped +@Alternative +@Priority(200) +public class JdbcTokenCacheRepository implements TokenCacheRepository { + + private static final Logger LOGGER = LoggerFactory.getLogger(JdbcTokenCacheRepository.class); + + // SQL queries following the same pattern as other JDBC repositories + static final String INSERT = + "INSERT INTO kogito_oauth2_token_cache (process_instance_id, auth_name, access_token, refresh_token, expiration_time, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)"; + static final String UPDATE = "UPDATE kogito_oauth2_token_cache SET access_token = ?, refresh_token = ?, expiration_time = ?, updated_at = ? WHERE process_instance_id = ? AND auth_name = ?"; + static final String FIND_BY_KEY = + "SELECT process_instance_id, auth_name, access_token, refresh_token, expiration_time, created_at, updated_at FROM kogito_oauth2_token_cache WHERE process_instance_id = ? AND auth_name = ?"; + static final String DELETE_BY_KEY = "DELETE FROM kogito_oauth2_token_cache WHERE process_instance_id = ? AND auth_name = ?"; + static final String DELETE_EXPIRED = "DELETE FROM kogito_oauth2_token_cache WHERE expiration_time < ?"; + static final String FIND_EXPIRING_SOON = + "SELECT process_instance_id, auth_name, access_token, refresh_token, expiration_time, created_at, updated_at FROM kogito_oauth2_token_cache WHERE expiration_time < ?"; + static final String FIND_ALL = "SELECT process_instance_id, auth_name, access_token, refresh_token, expiration_time, created_at, updated_at FROM kogito_oauth2_token_cache"; + + private final DataSource dataSource; + + public JdbcTokenCacheRepository(DataSource dataSource) { + this.dataSource = dataSource; + } + + @Override + public TokenCacheRecord save(TokenCacheRecord record) { + // Check if record exists first - use direct method since we have the components + Optional<TokenCacheRecord> existing = findByKey(record.getProcessInstanceId(), record.getAuthName()); + + if (existing.isPresent()) { + return update(record); + } else { + return insert(record); + } + } + + private TokenCacheRecord insert(TokenCacheRecord record) { + try (Connection connection = dataSource.getConnection(); + PreparedStatement statement = connection.prepareStatement(INSERT)) { + + statement.setString(1, record.getProcessInstanceId()); + statement.setString(2, record.getAuthName()); + statement.setString(3, record.getAccessToken()); + statement.setString(4, record.getRefreshToken()); + statement.setLong(5, record.getExpirationTime()); + statement.setTimestamp(6, Timestamp.from(record.getCreatedAt())); + statement.setTimestamp(7, Timestamp.from(record.getUpdatedAt())); + + int executed = statement.executeUpdate(); + if (executed > 0) { + LOGGER.debug("Inserted token cache record for processInstanceId: {}, authName: {}", + record.getProcessInstanceId(), record.getAuthName()); + return record; + } else { + throw new RuntimeException("Failed to insert token cache record for processInstanceId: " + + record.getProcessInstanceId() + ", authName: " + record.getAuthName()); + } + } catch (Exception e) { Review Comment: As a general comment, I think you should catch just SQLException and throw an UncheckedIOException ########## quarkus/addons/token-exchange/runtime/src/main/java/org/kie/kogito/addons/quarkus/token/exchange/cache/CachedTokens.java: ########## Review Comment: This call can be implemented as a record. In a record you can define the isExpiredNow and isExpiringSoon methods ########## quarkus/extensions/kogito-quarkus-serverless-workflow-jdbc-token-persistence-extension/kogito-quarkus-serverless-workflow-jdbc-token-persistence/src/main/java/org/kie/kogito/serverless/workflow/token/persistence/jdbc/JdbcTokenCacheRepository.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.kie.kogito.serverless.workflow.token.persistence.jdbc; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import javax.sql.DataSource; + +import org.kie.kogito.addons.quarkus.token.exchange.persistence.TokenCacheRepository; +import org.kie.kogito.addons.quarkus.token.exchange.persistence.model.TokenCacheRecord; +import org.kie.kogito.addons.quarkus.token.exchange.utils.CacheUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import jakarta.annotation.Priority; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Alternative; + +/** + * JDBC-based repository for token cache operations. + * Follows the same pattern as other JDBC repositories in the codebase. + */ +@ApplicationScoped +@Alternative +@Priority(200) +public class JdbcTokenCacheRepository implements TokenCacheRepository { + + private static final Logger LOGGER = LoggerFactory.getLogger(JdbcTokenCacheRepository.class); + + // SQL queries following the same pattern as other JDBC repositories + static final String INSERT = + "INSERT INTO kogito_oauth2_token_cache (process_instance_id, auth_name, access_token, refresh_token, expiration_time, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)"; + static final String UPDATE = "UPDATE kogito_oauth2_token_cache SET access_token = ?, refresh_token = ?, expiration_time = ?, updated_at = ? WHERE process_instance_id = ? AND auth_name = ?"; + static final String FIND_BY_KEY = + "SELECT process_instance_id, auth_name, access_token, refresh_token, expiration_time, created_at, updated_at FROM kogito_oauth2_token_cache WHERE process_instance_id = ? AND auth_name = ?"; + static final String DELETE_BY_KEY = "DELETE FROM kogito_oauth2_token_cache WHERE process_instance_id = ? AND auth_name = ?"; + static final String DELETE_EXPIRED = "DELETE FROM kogito_oauth2_token_cache WHERE expiration_time < ?"; + static final String FIND_EXPIRING_SOON = + "SELECT process_instance_id, auth_name, access_token, refresh_token, expiration_time, created_at, updated_at FROM kogito_oauth2_token_cache WHERE expiration_time < ?"; + static final String FIND_ALL = "SELECT process_instance_id, auth_name, access_token, refresh_token, expiration_time, created_at, updated_at FROM kogito_oauth2_token_cache"; + + private final DataSource dataSource; + + public JdbcTokenCacheRepository(DataSource dataSource) { + this.dataSource = dataSource; + } + + @Override + public TokenCacheRecord save(TokenCacheRecord record) { + // Check if record exists first - use direct method since we have the components + Optional<TokenCacheRecord> existing = findByKey(record.getProcessInstanceId(), record.getAuthName()); + + if (existing.isPresent()) { + return update(record); + } else { + return insert(record); + } + } + + private TokenCacheRecord insert(TokenCacheRecord record) { + try (Connection connection = dataSource.getConnection(); + PreparedStatement statement = connection.prepareStatement(INSERT)) { + + statement.setString(1, record.getProcessInstanceId()); + statement.setString(2, record.getAuthName()); + statement.setString(3, record.getAccessToken()); + statement.setString(4, record.getRefreshToken()); + statement.setLong(5, record.getExpirationTime()); + statement.setTimestamp(6, Timestamp.from(record.getCreatedAt())); + statement.setTimestamp(7, Timestamp.from(record.getUpdatedAt())); + + int executed = statement.executeUpdate(); + if (executed > 0) { + LOGGER.debug("Inserted token cache record for processInstanceId: {}, authName: {}", + record.getProcessInstanceId(), record.getAuthName()); + return record; + } else { + throw new RuntimeException("Failed to insert token cache record for processInstanceId: " + + record.getProcessInstanceId() + ", authName: " + record.getAuthName()); + } + } catch (Exception e) { + throw new RuntimeException("Error inserting token cache record for processInstanceId: " + + record.getProcessInstanceId() + ", authName: " + record.getAuthName(), e); + } + } + + private TokenCacheRecord update(TokenCacheRecord record) { + try (Connection connection = dataSource.getConnection(); + PreparedStatement statement = connection.prepareStatement(UPDATE)) { + + record.updateTimestamp(); // Update the timestamp + + statement.setString(1, record.getAccessToken()); + statement.setString(2, record.getRefreshToken()); + statement.setLong(3, record.getExpirationTime()); + statement.setTimestamp(4, Timestamp.from(record.getUpdatedAt())); + statement.setString(5, record.getProcessInstanceId()); + statement.setString(6, record.getAuthName()); + + int executed = statement.executeUpdate(); + if (executed > 0) { + LOGGER.debug("Updated token cache record for processInstanceId: {}, authName: {}", + record.getProcessInstanceId(), record.getAuthName()); + return record; + } else { + throw new RuntimeException("Failed to update token cache record for processInstanceId: " + + record.getProcessInstanceId() + ", authName: " + record.getAuthName()); + } + } catch (Exception e) { + throw new RuntimeException("Error updating token cache record for processInstanceId: " + + record.getProcessInstanceId() + ", authName: " + record.getAuthName(), e); + } + } + + @Override + public Optional<TokenCacheRecord> findByKey(String processInstanceId, String authName) { + try (Connection connection = dataSource.getConnection(); + PreparedStatement statement = connection.prepareStatement(FIND_BY_KEY)) { + + statement.setString(1, processInstanceId); + statement.setString(2, authName); + + try (ResultSet resultSet = statement.executeQuery()) { + if (resultSet.next()) { + return Optional.of(mapResultSetToRecord(resultSet)); + } + return Optional.empty(); + } + } catch (Exception e) { + throw new RuntimeException("Error finding token cache record by processInstanceId: " + + processInstanceId + ", authName: " + authName, e); + } + } + + @Override + public Optional<TokenCacheRecord> findByCacheKey(String cacheKey) { + // Extract components from cache key and delegate to the main method + String processInstanceId = CacheUtils.extractProcessInstanceIdFromCacheKey(cacheKey); + String authName = CacheUtils.extractAuthNameFromCacheKey(cacheKey); + return findByKey(processInstanceId, authName); + } + + @Override + public void deleteByKey(String processInstanceId, String authName) { + try (Connection connection = dataSource.getConnection(); + PreparedStatement statement = connection.prepareStatement(DELETE_BY_KEY)) { + + statement.setString(1, processInstanceId); + statement.setString(2, authName); + int executed = statement.executeUpdate(); + + if (executed > 0) { + LOGGER.debug("Deleted token cache record for processInstanceId: {}, authName: {}", + processInstanceId, authName); + } + } catch (Exception e) { + throw new RuntimeException("Error deleting token cache record for processInstanceId: " + + processInstanceId + ", authName: " + authName, e); + } + } + + @Override + public void deleteByCacheKey(String cacheKey) { + // Extract components from cache key and delegate to the main method + String processInstanceId = CacheUtils.extractProcessInstanceIdFromCacheKey(cacheKey); + String authName = CacheUtils.extractAuthNameFromCacheKey(cacheKey); + deleteByKey(processInstanceId, authName); + } + + @Override + public List<TokenCacheRecord> findAll() { Review Comment: In general is better to return Collection rather than LIst (because Collection is more generic and may you want to use a Set to guarantee uniqueness, or because you return a custom implementation, this is base on the assumption that you do not need random access to a particular position of the returned data) but.... ... If it exist the possibility of having a lot of TokenCacheRecord, may it is better to return a stream here. See [this](https://github.com/apache/incubator-kie-kogito-runtimes/blob/main/addons/common/persistence/jdbc/src/main/java/org/kie/kogito/persistence/jdbc/GenericRepository.java#L265-L303) as reference in case there is a lot of TokenCacheRecord (by a lot I mean more than 100k) ########## quarkus/addons/token-exchange/runtime/src/main/java/org/kie/kogito/addons/quarkus/token/exchange/cache/CachedTokens.java: ########## @@ -0,0 +1,66 @@ +/* + * 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.kie.kogito.addons.quarkus.token.exchange.cache; + +/** + * Data structure to hold both access and refresh tokens with expiration information. + */ +public class CachedTokens { + private final String accessToken; + private final String refreshToken; + private final long expirationTime; + + public CachedTokens(String accessToken, String refreshToken, long expirationTime) { + this.accessToken = accessToken; + this.refreshToken = refreshToken; + this.expirationTime = expirationTime; + } + + public String getAccessToken() { + return accessToken; + } + + public String getRefreshToken() { + return refreshToken; + } + + public long getExpirationTime() { + return expirationTime; + } + + /** + * Checks if the token is expired right now. + * + * @return true if the token is expired + */ + public boolean isExpiredNow() { + return System.currentTimeMillis() / 1000 >= expirationTime; + } + + /** + * Checks if the token is expiring soon based on the provided buffer. + * + * @param bufferSeconds Number of seconds before expiration to consider "expiring soon" + * @return true if the token is expiring within the buffer time + */ + public boolean isExpiringSoon(long bufferSeconds) { + return System.currentTimeMillis() / 1000 >= (expirationTime - bufferSeconds); Review Comment: ```suggestion return TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) >= (expirationTime - bufferSeconds); ``` ########## quarkus/addons/token-exchange/runtime/src/main/java/org/kie/kogito/addons/quarkus/token/exchange/cache/TokenPolicyManager.java: ########## @@ -0,0 +1,79 @@ +/* + * 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.kie.kogito.addons.quarkus.token.exchange.cache; + +import java.util.concurrent.TimeUnit; + +import org.kie.kogito.addons.quarkus.token.exchange.utils.CacheUtils; +import org.kie.kogito.addons.quarkus.token.exchange.utils.ConfigReaderUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.benmanes.caffeine.cache.Expiry; + +public class TokenPolicyManager { + + private static final Logger LOGGER = LoggerFactory.getLogger(TokenPolicyManager.class); + + /** + * Creates an expiry policy that uses each token's actual expiration time + */ + public static Expiry<String, CachedTokens> createTokenExpiryPolicy() { + return new Expiry<String, CachedTokens>() { + @Override + public long expireAfterCreate(String key, CachedTokens value, long currentTime) { + return calculateTimeToExpiration(key, value); + } + + @Override + public long expireAfterUpdate(String key, CachedTokens value, long currentTime, long currentDuration) { + return calculateTimeToExpiration(key, value); + } + + @Override + public long expireAfterRead(String key, CachedTokens value, long currentTime, long currentDuration) { + return currentDuration; // Don't change expiration on read + } + }; + } + + /** + * Calculate time to expiration based on token's actual expiration time minus proactive refresh buffer + */ + private static long calculateTimeToExpiration(String cacheKey, CachedTokens tokens) { + String authName = CacheUtils.extractAuthNameFromCacheKey(cacheKey); + long proactiveRefreshSeconds = ConfigReaderUtils.getProactiveRefreshSeconds(authName); + + long currentTimeSeconds = System.currentTimeMillis() / 1000; Review Comment: ``` suggestion long currentTimeSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); ``` ########## quarkus/addons/token-exchange/runtime/src/main/java/org/kie/kogito/addons/quarkus/token/exchange/cache/CachedTokens.java: ########## @@ -0,0 +1,66 @@ +/* + * 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.kie.kogito.addons.quarkus.token.exchange.cache; + +/** + * Data structure to hold both access and refresh tokens with expiration information. + */ +public class CachedTokens { + private final String accessToken; + private final String refreshToken; + private final long expirationTime; + + public CachedTokens(String accessToken, String refreshToken, long expirationTime) { + this.accessToken = accessToken; + this.refreshToken = refreshToken; + this.expirationTime = expirationTime; + } + + public String getAccessToken() { + return accessToken; + } + + public String getRefreshToken() { + return refreshToken; + } + + public long getExpirationTime() { + return expirationTime; + } + + /** + * Checks if the token is expired right now. + * + * @return true if the token is expired + */ + public boolean isExpiredNow() { + return System.currentTimeMillis() / 1000 >= expirationTime; Review Comment: ```suggestion return TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) >= expirationTime; ``` ########## quarkus/addons/token-exchange/runtime/src/main/java/org/kie/kogito/addons/quarkus/token/exchange/persistence/TokenDataStore.java: ########## @@ -0,0 +1,57 @@ +/* + * 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.kie.kogito.addons.quarkus.token.exchange.persistence; + +import java.util.List; +import java.util.Optional; + +import org.kie.kogito.addons.quarkus.token.exchange.cache.CachedTokens; + +/** + * Abstract interface for token storage operations. + * Provides a clean separation between caching logic and storage implementation. + */ +public interface TokenDataStore { + + /** + * Store or update tokens for a given cache key + */ + void store(String cacheKey, CachedTokens tokens); + + /** + * Retrieve tokens by cache key + */ + Optional<CachedTokens> retrieve(String cacheKey); + + /** + * Remove tokens by cache key + */ + void remove(String cacheKey); + + /** + * Load all non-expired tokens + */ + List<TokenEntry> loadAll(); Review Comment: It is loadAll used at all? ########## quarkus/addons/token-exchange/runtime/src/main/java/org/kie/kogito/addons/quarkus/token/exchange/persistence/model/TokenCacheRecord.java: ########## @@ -0,0 +1,131 @@ +/* + * 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.kie.kogito.addons.quarkus.token.exchange.persistence.model; + +import java.time.Instant; +import java.util.Objects; + +/** + * Simple POJO representing a token cache record for JDBC persistence. + * Uses composite primary key of processInstanceId and authName. + * Follows the same pattern as other JDBC entities in the codebase. + */ +public class TokenCacheRecord { Review Comment: I think you should use Record for this one. Then, rather than use setters when mapping from result set, you use the constructor. And when creating it to be saved, you use that just constructor passing instant.now for the dates. ########## quarkus/addons/token-exchange/runtime/src/main/java/org/kie/kogito/addons/quarkus/token/exchange/persistence/model/TokenCacheRecord.java: ########## @@ -0,0 +1,131 @@ +/* + * 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.kie.kogito.addons.quarkus.token.exchange.persistence.model; + +import java.time.Instant; +import java.util.Objects; + +/** + * Simple POJO representing a token cache record for JDBC persistence. + * Uses composite primary key of processInstanceId and authName. + * Follows the same pattern as other JDBC entities in the codebase. + */ +public class TokenCacheRecord { + + private String processInstanceId; + private String authName; + private String accessToken; + private String refreshToken; + private Long expirationTime; + private Instant createdAt; + private Instant updatedAt; + + public TokenCacheRecord() { + this.createdAt = Instant.now(); + this.updatedAt = Instant.now(); + } + + public TokenCacheRecord(String processInstanceId, String authName, + String accessToken, String refreshToken, Long expirationTime) { + this(); Review Comment: this can be removed ########## quarkus/extensions/kogito-quarkus-serverless-workflow-jdbc-token-persistence-extension/kogito-quarkus-serverless-workflow-jdbc-token-persistence/src/main/java/org/kie/kogito/serverless/workflow/token/persistence/jdbc/JdbcTokenCacheRepository.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.kie.kogito.serverless.workflow.token.persistence.jdbc; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import javax.sql.DataSource; + +import org.kie.kogito.addons.quarkus.token.exchange.persistence.TokenCacheRepository; +import org.kie.kogito.addons.quarkus.token.exchange.persistence.model.TokenCacheRecord; +import org.kie.kogito.addons.quarkus.token.exchange.utils.CacheUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import jakarta.annotation.Priority; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Alternative; + +/** + * JDBC-based repository for token cache operations. + * Follows the same pattern as other JDBC repositories in the codebase. + */ +@ApplicationScoped +@Alternative +@Priority(200) +public class JdbcTokenCacheRepository implements TokenCacheRepository { + + private static final Logger LOGGER = LoggerFactory.getLogger(JdbcTokenCacheRepository.class); + + // SQL queries following the same pattern as other JDBC repositories + static final String INSERT = + "INSERT INTO kogito_oauth2_token_cache (process_instance_id, auth_name, access_token, refresh_token, expiration_time, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)"; + static final String UPDATE = "UPDATE kogito_oauth2_token_cache SET access_token = ?, refresh_token = ?, expiration_time = ?, updated_at = ? WHERE process_instance_id = ? AND auth_name = ?"; + static final String FIND_BY_KEY = + "SELECT process_instance_id, auth_name, access_token, refresh_token, expiration_time, created_at, updated_at FROM kogito_oauth2_token_cache WHERE process_instance_id = ? AND auth_name = ?"; + static final String DELETE_BY_KEY = "DELETE FROM kogito_oauth2_token_cache WHERE process_instance_id = ? AND auth_name = ?"; + static final String DELETE_EXPIRED = "DELETE FROM kogito_oauth2_token_cache WHERE expiration_time < ?"; + static final String FIND_EXPIRING_SOON = + "SELECT process_instance_id, auth_name, access_token, refresh_token, expiration_time, created_at, updated_at FROM kogito_oauth2_token_cache WHERE expiration_time < ?"; + static final String FIND_ALL = "SELECT process_instance_id, auth_name, access_token, refresh_token, expiration_time, created_at, updated_at FROM kogito_oauth2_token_cache"; + + private final DataSource dataSource; + + public JdbcTokenCacheRepository(DataSource dataSource) { + this.dataSource = dataSource; + } + + @Override + public TokenCacheRecord save(TokenCacheRecord record) { + // Check if record exists first - use direct method since we have the components + Optional<TokenCacheRecord> existing = findByKey(record.getProcessInstanceId(), record.getAuthName()); + + if (existing.isPresent()) { + return update(record); + } else { + return insert(record); + } + } + + private TokenCacheRecord insert(TokenCacheRecord record) { + try (Connection connection = dataSource.getConnection(); + PreparedStatement statement = connection.prepareStatement(INSERT)) { + + statement.setString(1, record.getProcessInstanceId()); + statement.setString(2, record.getAuthName()); + statement.setString(3, record.getAccessToken()); + statement.setString(4, record.getRefreshToken()); + statement.setLong(5, record.getExpirationTime()); + statement.setTimestamp(6, Timestamp.from(record.getCreatedAt())); + statement.setTimestamp(7, Timestamp.from(record.getUpdatedAt())); + + int executed = statement.executeUpdate(); + if (executed > 0) { + LOGGER.debug("Inserted token cache record for processInstanceId: {}, authName: {}", + record.getProcessInstanceId(), record.getAuthName()); + return record; + } else { + throw new RuntimeException("Failed to insert token cache record for processInstanceId: " + + record.getProcessInstanceId() + ", authName: " + record.getAuthName()); + } + } catch (Exception e) { + throw new RuntimeException("Error inserting token cache record for processInstanceId: " + + record.getProcessInstanceId() + ", authName: " + record.getAuthName(), e); + } + } + + private TokenCacheRecord update(TokenCacheRecord record) { + try (Connection connection = dataSource.getConnection(); + PreparedStatement statement = connection.prepareStatement(UPDATE)) { + + record.updateTimestamp(); // Update the timestamp + + statement.setString(1, record.getAccessToken()); + statement.setString(2, record.getRefreshToken()); + statement.setLong(3, record.getExpirationTime()); + statement.setTimestamp(4, Timestamp.from(record.getUpdatedAt())); + statement.setString(5, record.getProcessInstanceId()); + statement.setString(6, record.getAuthName()); + + int executed = statement.executeUpdate(); + if (executed > 0) { + LOGGER.debug("Updated token cache record for processInstanceId: {}, authName: {}", + record.getProcessInstanceId(), record.getAuthName()); + return record; + } else { + throw new RuntimeException("Failed to update token cache record for processInstanceId: " + + record.getProcessInstanceId() + ", authName: " + record.getAuthName()); + } + } catch (Exception e) { + throw new RuntimeException("Error updating token cache record for processInstanceId: " + + record.getProcessInstanceId() + ", authName: " + record.getAuthName(), e); + } + } + + @Override + public Optional<TokenCacheRecord> findByKey(String processInstanceId, String authName) { + try (Connection connection = dataSource.getConnection(); + PreparedStatement statement = connection.prepareStatement(FIND_BY_KEY)) { + + statement.setString(1, processInstanceId); + statement.setString(2, authName); + + try (ResultSet resultSet = statement.executeQuery()) { + if (resultSet.next()) { + return Optional.of(mapResultSetToRecord(resultSet)); + } + return Optional.empty(); Review Comment: ```suggestion return resultSet.next() ? Optional.of(mapResultSetToRecord(resultSet)): Optional.empty(); ``` -- 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]
