Skip to content

Commit

Permalink
Prevent concurrent insert of sessions
Browse files Browse the repository at this point in the history
  • Loading branch information
Brutus5000 committed Nov 3, 2023
1 parent 3740f35 commit fcce220
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,17 @@ class IceSessionRepository : PanacheRepository<IceSessionEntity> {

fun findByCreatedAtLesserThan(instant: Instant) =
find("createdAt <= ?1", instant).list()

fun acquireGameLock(gameId: Long, timeout: Int = 10) {
getEntityManager().createNativeQuery("SELECT GET_LOCK(:lockName,:timeout)", Boolean::class.java).apply {
setParameter("lockName", "game_id_$gameId")
setParameter("timeout", timeout)
}.singleResult
}

fun releaseGameLock(gameId: Long) {
getEntityManager().createNativeQuery("SELECT RELEASE_LOCK(:lockName)", Boolean::class.java).apply {
setParameter("lockName", "game_id_$gameId")
}.singleResult
}
}
30 changes: 18 additions & 12 deletions src/main/kotlin/com/faforever/icebreaker/service/SessionService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,27 @@ class SessionService(

@Transactional
fun getSession(gameId: Long): Session {
val session = iceSessionRepository.findByGameId(gameId)
?: IceSessionEntity(gameId = gameId, createdAt = Instant.now()).also {
LOG.debug("Creating session for gameId $gameId")
iceSessionRepository.persist(it)
try {
iceSessionRepository.acquireGameLock(gameId)

val session = iceSessionRepository.findByGameId(gameId)
?: IceSessionEntity(gameId = gameId, createdAt = Instant.now()).also {
LOG.debug("Creating session for gameId $gameId")
iceSessionRepository.persist(it)
}

val servers = activeSessionHandlers.flatMap {
it.createSession(session.id)
it.getIceServersSession(session.id)
}

val servers = activeSessionHandlers.flatMap {
it.createSession(session.id)
it.getIceServersSession(session.id)
return Session(
id = session.id,
servers = servers,
)
} finally {
iceSessionRepository.releaseGameLock(gameId)
}

return Session(
id = session.id,
servers = servers,
)
}

@Transactional
Expand Down

0 comments on commit fcce220

Please sign in to comment.