Skip to content

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
merged 1 commit into from
Aug 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
Copy link
Collaborator

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?

Copy link
Contributor Author

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

*/
@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;
}

}
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);
}
}