Yokan / rebuild
Course 1 8624561

SyncService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncService.kt

implementation183 lines
1package eu.friedcutlet.yokan.services.sync23import eu.friedcutlet.yokan.database.DbSettings4import eu.friedcutlet.yokan.services.backup.BackupOptions5import eu.friedcutlet.yokan.services.backup.RestorePreview6import eu.friedcutlet.yokan.util.PlatformLock7import kotlinx.coroutines.flow.MutableStateFlow8import kotlinx.coroutines.flow.StateFlow9import kotlinx.coroutines.flow.asStateFlow10import kotlinx.coroutines.flow.update1112enum class SyncOperationStage {13    Syncing,14    Uploading,15    Downloading,16}1718enum class SyncOperationOutcome {19    Succeeded,20    Failed,21    Cancelled,22}2324data class SyncOperationState(25    val activeCount: Int = 0,26    val stage: SyncOperationStage? = null,27    val lastOutcome: SyncOperationOutcome? = null,28    /** 0..1 while a multi-page pull reports how far it got; null when unknown. */29    val progress: Float? = null,30) {31    val isActive: Boolean get() = activeCount > 032}3334/** Shared operation tracker used by manual, scheduled, outbox, and live sync paths. */35class SyncOperationMonitor {36    private val lock = PlatformLock()37    private val active = linkedMapOf<Long, SyncOperationStage>()38    private var nextId = 0L39    private val _state = MutableStateFlow(SyncOperationState())40    val state: StateFlow<SyncOperationState> = _state.asStateFlow()4142    fun begin(stage: SyncOperationStage): Long = lock.withLock {43        val id = ++nextId44        active[id] = stage45        _state.update { current ->46            current.copy(activeCount = active.size, stage = stage, progress = null)47        }48        id49    }5051    fun progress(id: Long, fraction: Float) = lock.withLock {52        if (id !in active) return@withLock53        _state.update { it.copy(progress = fraction.coerceIn(0f, 1f)) }54    }5556    fun finish(id: Long, outcome: SyncOperationOutcome) = lock.withLock {57        if (active.remove(id) == null) return@withLock58        _state.update { current ->59            current.copy(60                activeCount = active.size,61                stage = active.values.lastOrNull(),62                lastOutcome = outcome,63                progress = null,64            )65        }66    }67}6869private val IdleSyncOperationState = MutableStateFlow(SyncOperationState())7071interface SyncService {72    val operationState: StateFlow<SyncOperationState>73        get() = IdleSyncOperationState74    suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult75    fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? = null76    suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult? = null77    fun cancelBrowserLogin(attempt: BrowserLoginAttempt) = Unit78    suspend fun logout(syncId: Long)79    suspend fun sync(syncId: Long, settings: DbSettings): SyncResult80    suspend fun pushChanges(syncId: Long): SyncResult81    suspend fun pullChanges(syncId: Long): SyncResult82    fun status(syncId: Long): SyncConnectionStatus83    fun close() = Unit84    /** Wait for owned calls and their finalizers before releasing transport resources. */85    suspend fun closeAndJoin() { close() }86}8788/** Immutable, service-owned identity for one browser login, including its one-use CSRF state. */89@ConsistentCopyVisibility90data class BrowserLoginAttempt internal constructor(91    val syncId: Long,92    val server: String,93    val url: String,94    val device: String,95    val state: String,96    /** Redirect target the browser must intercept rather than load (OAuth loopback); null when the flow ends on a real page. */97    val callbackUrl: String? = null,98)99100interface CloudStorageProvider {101    val descriptor: CloudProviderDescriptor102103    suspend fun validate(connection: CloudConnection): CloudConnectionStatus104    suspend fun putObject(105        connection: CloudConnection,106        key: String,107        bytes: ByteArray,108        contentType: String,109    ): CloudObject110111    suspend fun listObjects(connection: CloudConnection, prefix: String): List<CloudObject>112    suspend fun getObject(connection: CloudConnection, objectRef: CloudObject): ByteArray113}114115class CloudStorageException(message: String) : RuntimeException(message)116117interface CloudBackupSyncService : SyncService {118    fun providers(): List<CloudProviderDescriptor>119    fun isCloudPreference(syncPreference: eu.friedcutlet.yokan.database.DbSyncPreference?): Boolean120    suspend fun connect(syncId: Long, providerId: String, accountLabel: String?, accessToken: String): SyncLoginResult121    suspend fun uploadBackup(syncId: Long, options: BackupOptions): CloudBackupResult122    suspend fun restoreLatestBackup(syncId: Long): CloudBackupRestoreResult123}124125data class SyncResult(126    val uploadedChanges: Int,127    val downloadedChanges: Int,128    val settingsSynced: Boolean,129    val errors: List<String> = emptyList(),130)131132data class SyncLoginResult(133    val success: Boolean,134    val message: String,135)136137data class SyncConnectionStatus(138    val loggedIn: Boolean,139    val email: String?,140    val server: String?,141    val lastSyncMillis: Long?,142)143144data class CloudProviderDescriptor(145    val id: String,146    val displayName: String,147    val description: String,148    val authInstructions: String,149)150151data class CloudConnection(152    val providerId: String,153    val accountLabel: String?,154    val accessToken: String,155)156157data class CloudConnectionStatus(158    val connected: Boolean,159    val accountLabel: String? = null,160    val message: String = "",161)162163data class CloudObject(164    val key: String,165    val displayName: String,166    val sizeBytes: Long,167    val modifiedAtMillis: Long,168    val providerFileId: String? = null,169)170171data class CloudBackupResult(172    val providerId: String,173    val fileName: String,174    val itemCount: Int,175    val bytesUploaded: Long,176    val remoteObject: CloudObject,177)178179data class CloudBackupRestoreResult(180    val providerId: String,181    val fileName: String,182    val preview: RestorePreview,183)184

Search chapters, reference and source filenames.