-
Notifications
You must be signed in to change notification settings - Fork 6
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
fix: backup and restore progress updates in a more meaningful way. #3124
base: develop
Are you sure you want to change the base?
Changes from all commits
36981da
b4f6899
caee694
21dfe74
7772ac4
38420f6
86583a0
82aedb4
8ec8b07
537a4a7
ddf4ade
52f094a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
/* | ||
* Wire | ||
* Copyright (C) 2024 Wire Swiss GmbH | ||
* | ||
* This program is free software: you can redistribute it and/or modify | ||
* it under the terms of the GNU General Public License as published by | ||
* the Free Software Foundation, either version 3 of the License, or | ||
* (at your option) any later version. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
* GNU General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU General Public License | ||
* along with this program. If not, see http://www.gnu.org/licenses/. | ||
*/ | ||
package com.wire.kalium.logic.util | ||
|
||
import co.touchlab.kermit.Logger | ||
import okio.ForwardingSink | ||
import okio.Sink | ||
|
||
/** | ||
* A sink that tracks the progress of writing data to a delegate sink. | ||
* | ||
* @param delegate The sink to which data is written. | ||
* @param totalBytes The total number of bytes that will be written. | ||
* @param onProgress A callback that is invoked with the number of bytes written and the total number of bytes. | ||
*/ | ||
class ProgressTrackingSink( | ||
delegate: Sink, | ||
private val totalBytes: Long, | ||
private val onProgress: (bytesWritten: Long, totalBytes: Long) -> Unit | ||
) : ForwardingSink(delegate) { | ||
private var bytesWritten: Long = 0 | ||
|
||
override fun write(source: okio.Buffer, byteCount: Long) { | ||
super.write(source, byteCount) | ||
bytesWritten += byteCount | ||
onProgress(bytesWritten, totalBytes) | ||
} | ||
|
||
override fun close() { | ||
delegate.close() | ||
} | ||
|
||
override fun flush() { | ||
delegate.flush() | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -26,11 +26,11 @@ import com.wire.kalium.logic.CoreFailure | |
import com.wire.kalium.logic.StorageFailure | ||
import com.wire.kalium.logic.clientPlatform | ||
import com.wire.kalium.logic.data.asset.KaliumFileSystem | ||
import com.wire.kalium.logic.data.id.CurrentClientIdProvider | ||
import com.wire.kalium.logic.data.id.IdMapper | ||
import com.wire.kalium.logic.data.user.UserId | ||
import com.wire.kalium.logic.data.user.UserRepository | ||
import com.wire.kalium.logic.di.MapperProvider | ||
import com.wire.kalium.logic.data.id.CurrentClientIdProvider | ||
import com.wire.kalium.logic.feature.backup.BackupConstants.BACKUP_ENCRYPTED_FILE_NAME | ||
import com.wire.kalium.logic.feature.backup.BackupConstants.BACKUP_METADATA_FILE_NAME | ||
import com.wire.kalium.logic.feature.backup.BackupConstants.BACKUP_USER_DB_NAME | ||
|
@@ -63,7 +63,7 @@ interface CreateBackupUseCase { | |
* with the provided password if it is not empty. Otherwise, the file will be unencrypted. | ||
* @param password The password to encrypt the backup file with. If empty, the file will be unencrypted. | ||
*/ | ||
suspend operator fun invoke(password: String): CreateBackupResult | ||
suspend operator fun invoke(password: String, onProgress: (Float) -> Unit): CreateBackupResult | ||
} | ||
|
||
@Suppress("LongParameterList") | ||
|
@@ -78,32 +78,33 @@ internal class CreateBackupUseCaseImpl( | |
private val idMapper: IdMapper = MapperProvider.idMapper(), | ||
) : CreateBackupUseCase { | ||
|
||
override suspend operator fun invoke(password: String): CreateBackupResult = withContext(dispatchers.default) { | ||
val userHandle = userRepository.getSelfUser()?.handle?.replace(".", "-") | ||
val timeStamp = DateTimeUtil.currentSimpleDateTimeString() | ||
val backupName = createBackupFileName(userHandle, timeStamp) | ||
val backupFilePath = kaliumFileSystem.tempFilePath(backupName) | ||
deletePreviousBackupFiles(backupFilePath) | ||
|
||
val plainDBPath = | ||
databaseExporter.exportToPlainDB(securityHelper.userDBOrSecretNull(userId))?.toPath() | ||
?: return@withContext CreateBackupResult.Failure(StorageFailure.DataNotFound) | ||
|
||
try { | ||
createBackupFile(userId, plainDBPath, backupFilePath).fold( | ||
{ error -> CreateBackupResult.Failure(error) }, | ||
{ (backupFilePath, backupSize) -> | ||
val isBackupEncrypted = password.isNotEmpty() | ||
if (isBackupEncrypted) { | ||
encryptAndCompressFile(backupFilePath, password) | ||
} else CreateBackupResult.Success(backupFilePath, backupSize, backupFilePath.name) | ||
}) | ||
} finally { | ||
databaseExporter.deleteBackupDBFile() | ||
override suspend operator fun invoke(password: String, onProgress: (Float) -> Unit): CreateBackupResult = | ||
withContext(dispatchers.default) { | ||
val userHandle = userRepository.getSelfUser()?.handle?.replace(".", "-") | ||
val timeStamp = DateTimeUtil.currentSimpleDateTimeString() | ||
val backupName = createBackupFileName(userHandle, timeStamp) | ||
val backupFilePath = kaliumFileSystem.tempFilePath(backupName) | ||
deletePreviousBackupFiles(backupFilePath) | ||
|
||
val plainDBPath = | ||
databaseExporter.exportToPlainDB(securityHelper.userDBOrSecretNull(userId))?.toPath() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. question: Doesn't this I really don't know 😅. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I can only test with our chats, as I don't have any big data to test tho. |
||
?: return@withContext CreateBackupResult.Failure(StorageFailure.DataNotFound) | ||
|
||
try { | ||
createBackupFile(userId, plainDBPath, backupFilePath, onProgress).fold( | ||
{ error -> CreateBackupResult.Failure(error) }, | ||
{ (backupFilePath, backupSize) -> | ||
val isBackupEncrypted = password.isNotEmpty() | ||
if (isBackupEncrypted) { | ||
encryptAndCompressFile(backupFilePath, password, onProgress) | ||
} else CreateBackupResult.Success(backupFilePath, backupSize, backupFilePath.name) | ||
}) | ||
} finally { | ||
databaseExporter.deleteBackupDBFile() | ||
} | ||
} | ||
} | ||
|
||
private suspend fun encryptAndCompressFile(backupFilePath: Path, password: String): CreateBackupResult { | ||
private suspend fun encryptAndCompressFile(backupFilePath: Path, password: String, onProgress: (Float) -> Unit): CreateBackupResult { | ||
val encryptedBackupFilePath = kaliumFileSystem.tempFilePath(BACKUP_ENCRYPTED_FILE_NAME) | ||
val backupEncryptedDataSize = encryptBackup( | ||
kaliumFileSystem.source(backupFilePath), | ||
|
@@ -117,7 +118,9 @@ internal class CreateBackupUseCaseImpl( | |
|
||
return createCompressedFile( | ||
listOf(kaliumFileSystem.source(encryptedBackupFilePath) to encryptedBackupFilePath.name), | ||
kaliumFileSystem.sink(finalBackupFilePath) | ||
kaliumFileSystem.sink(finalBackupFilePath), | ||
kaliumFileSystem.fileSize(encryptedBackupFilePath), | ||
onProgress | ||
).fold({ | ||
CreateBackupResult.Failure(StorageFailure.Generic(RuntimeException("Failed to compress encrypted backup file"))) | ||
}, { backupEncryptedCompressedDataSize -> | ||
|
@@ -167,7 +170,8 @@ internal class CreateBackupUseCaseImpl( | |
private suspend fun createBackupFile( | ||
userId: UserId, | ||
plainDBPath: Path, | ||
backupZipFilePath: Path | ||
backupZipFilePath: Path, | ||
onProgress: (Float) -> Unit | ||
): Either<CoreFailure, Pair<Path, Long>> { | ||
return try { | ||
val backupSink = kaliumFileSystem.sink(backupZipFilePath) | ||
|
@@ -176,8 +180,9 @@ internal class CreateBackupUseCaseImpl( | |
kaliumFileSystem.source(backupMetadataPath) to BACKUP_METADATA_FILE_NAME, | ||
kaliumFileSystem.source(plainDBPath) to BACKUP_USER_DB_NAME | ||
) | ||
val totalBytes = listOf(backupZipFilePath, plainDBPath).sumOf { kaliumFileSystem.fileSize(it) } | ||
|
||
createCompressedFile(filesList, backupSink).flatMap { compressedFileSize -> | ||
createCompressedFile(filesList, backupSink, totalBytes, onProgress).flatMap { compressedFileSize -> | ||
Either.Right(backupZipFilePath to compressedFileSize) | ||
} | ||
} catch (e: FileNotFoundException) { | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I guess a callback works, but it could be a bit safer to instead return a
Flow
that emits progress.A Flow can be configured to handle back pressure more gracefully. For example, what if the backup creation calls
onProgress
faster than it can be executed?I think it would be nicer to just return a
Flow<BackupProgress>
instead.And
BackupProgress
could be something like:Another argument for Flow:
if we change the implementation of
CreateBackupUseCase
and it runs on a different scope, this different scope would keep a reference toonProgress
, which could lead to a leak.It's easier to just return a flow and if it is cancelled, it is cancelled :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
My initial implementation, was done using a flow. I need to ask about the iOS implementation though. The return of the actual function is Either, so changing that would require to do the same functionality in iOS.
I know that is the best approach and for sure will try to implement it.
Thanks for the input man
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
iOS and Web do not use the code in
:kalium:logic
and they're a long way from this at the moment. They have their own code, their own databases, etc.We are creating a Kotlin Multiplatform library for Backup that will live inside Kalium and it should be the first one.
It is gonna be a new module called
backup
, which we will publish as a stand-alone library fro Web and iOS.It will not be responsible for exporting the data, but only to create the file, zip, encrypt, and reverse these operations.
Web, iOS and
:kalium:logic
will call this library with the data they want to backup. And call it with the file to get the restored data.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Amazing, then i will do the refactoring of this using flow 👍🏻