Улучшена фоновая синхронизация, обработана ошибка

This commit is contained in:
2026-05-23 23:36:35 +03:00
parent 6e719e7f52
commit adc3730b8d
13 changed files with 284 additions and 97 deletions

View File

@@ -1,5 +1,6 @@
package com.github.nullptroma.wallenc.usecases
import com.github.nullptroma.wallenc.domain.errors.WallencException
import com.github.nullptroma.wallenc.domain.errors.toWallencException
import com.github.nullptroma.wallenc.domain.interfaces.IStorageSyncEngine
import com.github.nullptroma.wallenc.domain.tasks.ITaskOrchestrator
@@ -11,11 +12,13 @@ import com.github.nullptroma.wallenc.domain.tasks.TaskLogLevel
import com.github.nullptroma.wallenc.domain.tasks.TaskProgressLabel
import com.github.nullptroma.wallenc.domain.tasks.TaskRunState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withTimeout
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject
import javax.inject.Singleton
@@ -87,12 +90,24 @@ class RunStorageSyncUseCase @Inject constructor(
}
val taskId = _activeSyncTaskId.value
?: return StorageSyncRunOutcome.Completed
syncRunning.filter { !it }.first()
val state = orchestrator.pipelineState.value.tasks.find { it.id == taskId }?.state
return when (state) {
is TaskRunState.Failed -> StorageSyncRunOutcome.Failed(state.error)
TaskRunState.Cancelled -> StorageSyncRunOutcome.Cancelled
else -> StorageSyncRunOutcome.Completed
return try {
withTimeout(SYNC_AWAIT_TIMEOUT_MS) {
syncRunning.filter { !it }.first()
}
val state = orchestrator.pipelineState.value.tasks.find { it.id == taskId }?.state
when (state) {
is TaskRunState.Failed -> StorageSyncRunOutcome.Failed(state.error)
TaskRunState.Cancelled -> StorageSyncRunOutcome.Cancelled
else -> StorageSyncRunOutcome.Completed
}
} catch (_: TimeoutCancellationException) {
orchestrator.cancel(taskId)
clearRunningState()
StorageSyncRunOutcome.Failed(
WallencException.Unknown(
cause = IllegalStateException("Storage sync await timed out after ${SYNC_AWAIT_TIMEOUT_MS}ms"),
),
)
}
}
@@ -134,5 +149,8 @@ class RunStorageSyncUseCase @Inject constructor(
companion object {
/** Пауза после последнего изменения перед debounce-sync; же окно подавления после sync. */
const val DEBOUNCE_AFTER_CHANGE_MS = 60_000L
/** Максимальное ожидание фонового worker (WorkManager) — не блокировать periodic work навсегда. */
private const val SYNC_AWAIT_TIMEOUT_MS = 25L * 60 * 1000
}
}