Don't allow multiple syncs at the same time

This commit is contained in:
Bartu Özen
2025-12-18 20:07:18 +03:00
parent 2b4dd34359
commit 57dcd4125b
2 changed files with 17 additions and 3 deletions

View File

@@ -7,6 +7,7 @@ import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import kotlinx.serialization.protobuf.ProtoBuf import kotlinx.serialization.protobuf.ProtoBuf
import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.selectAll
@@ -47,6 +48,7 @@ object SyncManager {
private val logger = KotlinLogging.logger {} private val logger = KotlinLogging.logger {}
private var currentTaskId: String? = null private var currentTaskId: String? = null
private val syncMutex = Mutex()
@OptIn(DelicateCoroutinesApi::class) @OptIn(DelicateCoroutinesApi::class)
fun scheduleSyncTask() { fun scheduleSyncTask() {
@@ -64,7 +66,7 @@ object SyncManager {
HAScheduler.schedule( HAScheduler.schedule(
{ {
GlobalScope.launch { GlobalScope.launch {
syncData() startSync()
} }
}, },
interval = intervalMs, interval = intervalMs,
@@ -79,11 +81,23 @@ object SyncManager {
) )
} }
suspend fun syncData() { suspend fun startSync() {
if (!serverConfig.syncYomiEnabled.value) { if (!serverConfig.syncYomiEnabled.value) {
return return
} }
if (!syncMutex.tryLock()) {
return
}
try {
syncData()
} finally {
syncMutex.unlock()
}
}
private suspend fun syncData() {
transaction { transaction {
MangaTable.update({ MangaTable.isSyncing eq true }) { MangaTable.update({ MangaTable.isSyncing eq true }) {
it[isSyncing] = false it[isSyncing] = false

View File

@@ -22,7 +22,7 @@ class SyncMutation {
val (clientMutationId) = input val (clientMutationId) = input
GlobalScope.launch { GlobalScope.launch {
SyncManager.syncData() SyncManager.startSync()
} }
return StartSyncPayload( return StartSyncPayload(