-
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
Open
kl3jvi
wants to merge
11
commits into
wireapp:develop
Choose a base branch
from
kl3jvi:detached
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
36981da
fix: backup and restore progress updates in a more meaningful way.
kl3jvi b4f6899
Merge branch 'develop' into detached
kl3jvi caee694
Merge branch 'develop' into detached
kl3jvi 21dfe74
Merge branch 'develop' into detached
kl3jvi 7772ac4
small fix
kl3jvi 38420f6
KaliumFileSystemImpl.kt small fix
kl3jvi 86583a0
Merge branch 'develop' into detached
kl3jvi 82aedb4
Merge branch 'develop' into detached
kl3jvi 8ec8b07
Merge branch 'develop' into detached
kl3jvi 537a4a7
Merge branch 'develop' into detached
kl3jvi ddf4ade
Merge branch 'develop' into detached
kl3jvi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
51 changes: 51 additions & 0 deletions
51
logic/src/commonJvmAndroid/kotlin/com/wire/kalium/logic/util/ProgressTrackingSink.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 😅. |
||
?: 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) { | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 👍🏻