-
Notifications
You must be signed in to change notification settings - Fork 73
Fix for occasional duplicate key errors on session create or update #711
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
aurambaj
merged 1 commit into
box:master
from
maallen:spring_session_duplicate_sql_key_error
Aug 26, 2021
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
72 changes: 72 additions & 0 deletions
72
...o/service/security/user/session/CustomCreateSessionAttributeInsertQueryConfiguration.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
package com.box.l10n.mojito.service.security.user.session; | ||
|
||
import com.box.l10n.mojito.service.DBUtils; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Conditional; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.session.jdbc.JdbcIndexedSessionRepository; | ||
import org.springframework.session.jdbc.config.annotation.web.http.JdbcHttpSessionConfiguration; | ||
import org.springframework.util.StringUtils; | ||
|
||
|
||
/** | ||
* Workaround for issue <a href="https://github.com/spring-projects/spring-session/issues/1213">Concurrent requests adding the same session attribute result in duplicate key constraint violation</a> | ||
* to change the Create Session Attribute query to use an MySQL UPDATE command to update the ATTRIBUTE_BYTES | ||
* of the existing row if a duplicate key is encountered. | ||
* | ||
* <b>NOTE:</b>This custom insert query should only be used with a MySQL database. | ||
*/ | ||
@Configuration | ||
@ConditionalOnProperty(value = "l10n.spring.session.use-custom-mysql-create-session-attribute-query", havingValue = "true") | ||
public class CustomCreateSessionAttributeInsertQueryConfiguration extends JdbcHttpSessionConfiguration { | ||
|
||
static Logger logger = LoggerFactory.getLogger(CustomCreateSessionAttributeInsertQueryConfiguration.class); | ||
|
||
private static final String CREATE_SESSION_ATTRIBUTE_QUERY_ON_DUPLICATE_KEY_UPDATE = | ||
"INSERT INTO %TABLE_NAME%_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) " | ||
+ "SELECT PRIMARY_ID, ?, ? " | ||
+ "FROM %TABLE_NAME% " | ||
+ "WHERE SESSION_ID = ? ON DUPLICATE KEY UPDATE ATTRIBUTE_BYTES=VALUES(ATTRIBUTE_BYTES)"; | ||
|
||
@Autowired | ||
DBUtils dbUtils; | ||
|
||
@Value("${spring.session.jdbc.table-name}") | ||
private String customTableName; | ||
|
||
@Bean | ||
@Override | ||
public JdbcIndexedSessionRepository sessionRepository() { | ||
logger.debug("Setting Spring Session custom session attribute query."); | ||
JdbcIndexedSessionRepository sessionRepository = super.sessionRepository(); | ||
sessionRepository.setTableName(getTableName()); | ||
updateCreateSessionAttributeQuery(sessionRepository); | ||
return sessionRepository; | ||
} | ||
|
||
private void updateCreateSessionAttributeQuery(JdbcIndexedSessionRepository sessionRepository) { | ||
logger.debug("Updating the Create Session Attribute query"); | ||
if (dbUtils.isMysql()) { | ||
sessionRepository.setCreateSessionAttributeQuery(getCustomCreateSessionAttributeQuery()); | ||
} else { | ||
logger.warn("The database is not MySQL, skipping query update."); | ||
} | ||
} | ||
|
||
private String getCustomCreateSessionAttributeQuery() { | ||
return StringUtils.replace( | ||
CREATE_SESSION_ATTRIBUTE_QUERY_ON_DUPLICATE_KEY_UPDATE, | ||
"%TABLE_NAME%", | ||
getTableName()); | ||
} | ||
|
||
private String getTableName() { | ||
return customTableName != null ? customTableName : JdbcIndexedSessionRepository.DEFAULT_TABLE_NAME; | ||
} | ||
|
||
} |
60 changes: 60 additions & 0 deletions
60
...rvice/security/user/session/CustomCreateSessionAttributeInsertQueryConfigurationTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
package com.box.l10n.mojito.service.security.user.session; | ||
|
||
import com.box.l10n.mojito.service.DBUtils; | ||
import org.junit.Before; | ||
import org.junit.Test; | ||
import org.junit.runner.RunWith; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.boot.test.context.SpringBootTest; | ||
import org.springframework.boot.test.mock.mockito.MockBean; | ||
import org.springframework.boot.test.mock.mockito.SpyBean; | ||
import org.springframework.session.jdbc.JdbcIndexedSessionRepository; | ||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; | ||
import org.springframework.transaction.PlatformTransactionManager; | ||
import org.springframework.util.ReflectionUtils; | ||
|
||
import javax.sql.DataSource; | ||
import java.lang.reflect.Field; | ||
|
||
import static org.junit.Assert.assertEquals; | ||
import static org.junit.Assert.assertNotNull; | ||
import static org.mockito.Mockito.times; | ||
import static org.mockito.Mockito.verify; | ||
|
||
@RunWith(SpringJUnit4ClassRunner.class) | ||
@SpringBootTest(classes = { | ||
CustomCreateSessionAttributeInsertQueryConfiguration.class | ||
}, properties = { | ||
"l10n.spring.session.use-custom-mysql-create-session-attribute-query=true", | ||
"spring.session.jdbc.table-name=test_table", | ||
"spring.datasource.url=jdbc:mysql:testDB" | ||
}) | ||
public class CustomCreateSessionAttributeInsertQueryConfigurationTest { | ||
|
||
@MockBean | ||
DataSource dataSourceMock; | ||
|
||
@MockBean | ||
PlatformTransactionManager platformTransactionManagerMock; | ||
|
||
@SpyBean | ||
DBUtils dbUtils; | ||
|
||
@Autowired | ||
JdbcIndexedSessionRepository jdbcIndexedSessionRepository; | ||
|
||
String requiredString = "INSERT INTO test_table_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) " | ||
+ "SELECT PRIMARY_ID, ?, ? " | ||
+ "FROM test_table " | ||
+ "WHERE SESSION_ID = ? ON DUPLICATE KEY UPDATE ATTRIBUTE_BYTES=VALUES(ATTRIBUTE_BYTES)"; | ||
|
||
@Test | ||
public void testCustomSessionAttributeQueryIsSetOnSessionRepository() throws IllegalAccessException { | ||
assertNotNull(jdbcIndexedSessionRepository); | ||
Field createSessionAttributeQueryField = ReflectionUtils.findField(jdbcIndexedSessionRepository.getClass(), "createSessionAttributeQuery", String.class); | ||
createSessionAttributeQueryField.setAccessible(true); | ||
String actualQueryString = (String) createSessionAttributeQueryField.get(jdbcIndexedSessionRepository); | ||
verify(dbUtils, times(1)).isMysql(); | ||
assertEquals(requiredString, actualQueryString); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
only be used with a MySQL database
, can this be made explicit with a@Conditional
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've pushed an update containing a custom condition (MySQLDatabaseCondition) that checks the prefix of the
spring.datasource.url
property, if the prefix matches "jdbc:mysql:" the condition passes