Skip to content
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

chore: add handling NoNetworkConnection in image loader [WPB-3475] #2097

Merged
merged 5 commits into from
Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/src/main/kotlin/com/wire/android/di/CoreLogicModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ import com.wire.kalium.logic.feature.user.UpdateEmailUseCase
import com.wire.kalium.logic.feature.user.screenshotCensoring.ObserveScreenshotCensoringConfigUseCase
import com.wire.kalium.logic.feature.user.screenshotCensoring.PersistScreenshotCensoringConfigUseCase
import com.wire.kalium.logic.featureFlags.KaliumConfigs
import com.wire.kalium.logic.network.NetworkStateObserver
import com.wire.kalium.network.NetworkStateObserver
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import com.wire.android.util.ui.WireSessionImageLoader
import com.wire.kalium.logic.feature.asset.DeleteAssetUseCase
import com.wire.kalium.logic.feature.asset.GetAvatarAssetUseCase
import com.wire.kalium.logic.feature.asset.GetMessageAssetUseCase
import com.wire.kalium.logic.network.NetworkStateObserver
import com.wire.kalium.network.NetworkStateObserver
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ import com.wire.kalium.logic.data.message.Message
import com.wire.kalium.logic.data.user.ConnectionState
import com.wire.kalium.logic.data.user.UserAssetId
import com.wire.kalium.logic.data.user.UserAvailabilityStatus
import com.wire.kalium.logic.network.NetworkState
import com.wire.kalium.logic.network.NetworkStateObserver
import com.wire.kalium.network.NetworkState
import com.wire.kalium.network.NetworkStateObserver
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

Expand Down
26 changes: 21 additions & 5 deletions app/src/main/kotlin/com/wire/android/util/ui/AssetImageFetcher.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import coil.fetch.Fetcher
import coil.request.Options
import com.wire.android.model.ImageAsset
import com.wire.android.util.toDrawable
import com.wire.kalium.logic.CoreFailure
import com.wire.kalium.logic.NetworkFailure
import com.wire.kalium.logic.feature.asset.DeleteAssetUseCase
import com.wire.kalium.logic.feature.asset.GetAvatarAssetUseCase
import com.wire.kalium.logic.feature.asset.GetMessageAssetUseCase
Expand All @@ -55,13 +57,13 @@ internal class AssetImageFetcher(
return when (data) {
is ImageAsset.UserAvatarAsset -> {
val retryHash = options.parameters.value(OPTION_PARAMETER_RETRY_KEY) ?: DEFAULT_RETRY_ATTEMPT

if (retryHash >= RETRY_ATTEMPT_TO_DELETE_ASSET) {
deleteAsset(data.userAssetId)
}

when (val result = getPublicAsset(data.userAssetId)) {
is PublicAssetResult.Failure -> throw AssetImageException(result.isRetryNeeded)
is PublicAssetResult.Failure ->
throw AssetImageException(retryPolicy(result.isRetryNeeded, result.coreFailure))

is PublicAssetResult.Success -> {
drawableResultWrapper.toFetchResult(result.assetPath)
}
Expand All @@ -70,7 +72,9 @@ internal class AssetImageFetcher(

is ImageAsset.PrivateAsset -> {
when (val result = getPrivateAsset(data.conversationId, data.messageId).await()) {
is MessageAssetResult.Failure -> throw AssetImageException(result.isRetryNeeded)
is MessageAssetResult.Failure ->
throw AssetImageException(retryPolicy(result.isRetryNeeded, result.coreFailure))

is MessageAssetResult.Success -> {
drawableResultWrapper.toFetchResult(result.decodedAssetPath)
}
Expand All @@ -90,6 +94,12 @@ internal class AssetImageFetcher(
}
}

private fun retryPolicy(isRetryNeeded: Boolean, coreFailure: CoreFailure): AssetImageRetryPolicy = when {
!isRetryNeeded -> AssetImageRetryPolicy.DO_NOT_RETRY
coreFailure is NetworkFailure.NoNetworkConnection -> AssetImageRetryPolicy.RETRY_WHEN_CONNECTED
else -> AssetImageRetryPolicy.EXPONENTIAL_RETRY_WHEN_CONNECTED
}

class Factory(
private val getPublicAssetUseCase: GetAvatarAssetUseCase,
private val getPrivateAssetUseCase: GetMessageAssetUseCase,
Expand Down Expand Up @@ -117,4 +127,10 @@ data class AssetFetcherParameters(
val options: Options
)

data class AssetImageException(val isRetryNeeded: Boolean) : Exception("Load asset image exception")
data class AssetImageException(val retryPolicy: AssetImageRetryPolicy) : Exception("Load asset image exception")

enum class AssetImageRetryPolicy {
RETRY_WHEN_CONNECTED,
EXPONENTIAL_RETRY_WHEN_CONNECTED,
DO_NOT_RETRY
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,13 @@
import com.wire.kalium.logic.feature.asset.DeleteAssetUseCase
import com.wire.kalium.logic.feature.asset.GetAvatarAssetUseCase
import com.wire.kalium.logic.feature.asset.GetMessageAssetUseCase
import com.wire.kalium.logic.network.NetworkState
import com.wire.kalium.logic.network.NetworkStateObserver
import com.wire.kalium.logic.util.ExponentialDurationHelperImpl
import com.wire.kalium.network.NetworkState
import com.wire.kalium.network.NetworkStateObserver
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.firstOrNull
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds

/**
* An ImageLoader that is able to load AssetIds supplied by Kalium.
Expand All @@ -59,6 +63,8 @@
) {
private companion object {
const val RETRY_INCREMENT_ATTEMPT_PER_STEP = 1
val MIN_RETRY_DELAY = 1.seconds
val MAX_RETRY_DELAY = 10.minutes
}

/**
Expand All @@ -74,6 +80,7 @@
fallbackData: Any? = null
): Painter {
var retryHash by remember { mutableStateOf(0) }
val exponentialDurationHelper = remember { ExponentialDurationHelperImpl(MIN_RETRY_DELAY, MAX_RETRY_DELAY) }

Check warning on line 83 in app/src/main/kotlin/com/wire/android/util/ui/WireSessionImageLoader.kt

View check run for this annotation

Codecov / codecov/patch

app/src/main/kotlin/com/wire/android/util/ui/WireSessionImageLoader.kt#L83

Added line #L83 was not covered by tests
val painter = rememberAsyncImagePainter(
model = ImageRequest.Builder(LocalContext.current)
.memoryCacheKey(asset?.uniqueKey)
Expand All @@ -85,18 +92,26 @@
)
.build(),
error = (fallbackData as? Int)?.let { painterResource(id = it) },
placeholder = (fallbackData as? Int)?.let { painterResource(id = it) },
imageLoader = coilImageLoader
)

LaunchedEffect(painter.state) {
if (painter.state is AsyncImagePainter.State.Error) {
val isRetryNeeded =
((painter.state as AsyncImagePainter.State.Error).result.throwable as? AssetImageException)?.isRetryNeeded ?: false
if (isRetryNeeded) {
val retryPolicy = ((painter.state as AsyncImagePainter.State.Error).result.throwable as? AssetImageException)?.retryPolicy
?: AssetImageRetryPolicy.DO_NOT_RETRY

Check warning on line 102 in app/src/main/kotlin/com/wire/android/util/ui/WireSessionImageLoader.kt

View check run for this annotation

Codecov / codecov/patch

app/src/main/kotlin/com/wire/android/util/ui/WireSessionImageLoader.kt#L102

Added line #L102 was not covered by tests

if (retryPolicy == AssetImageRetryPolicy.EXPONENTIAL_RETRY_WHEN_CONNECTED) {
delay(exponentialDurationHelper.next())

Check warning on line 105 in app/src/main/kotlin/com/wire/android/util/ui/WireSessionImageLoader.kt

View check run for this annotation

Codecov / codecov/patch

app/src/main/kotlin/com/wire/android/util/ui/WireSessionImageLoader.kt#L105

Added line #L105 was not covered by tests
}

if (retryPolicy != AssetImageRetryPolicy.DO_NOT_RETRY) {
networkStateObserver.observeNetworkState().firstOrNull { it == NetworkState.ConnectedWithInternet }.let {
retryHash += RETRY_INCREMENT_ATTEMPT_PER_STEP
}
}
} else {
exponentialDurationHelper.reset()

Check warning on line 114 in app/src/main/kotlin/com/wire/android/util/ui/WireSessionImageLoader.kt

View check run for this annotation

Codecov / codecov/patch

app/src/main/kotlin/com/wire/android/util/ui/WireSessionImageLoader.kt#L114

Added line #L114 was not covered by tests
}
}
return painter
Expand Down
147 changes: 144 additions & 3 deletions app/src/test/kotlin/com/wire/android/util/ui/AssetImageFetcherTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import com.wire.android.framework.FakeKaliumFileSystem
import com.wire.android.model.ImageAsset
import com.wire.android.util.ui.AssetImageFetcher.Companion.OPTION_PARAMETER_RETRY_KEY
import com.wire.kalium.logic.CoreFailure
import com.wire.kalium.logic.NetworkFailure
import com.wire.kalium.logic.data.id.ConversationId
import com.wire.kalium.logic.data.user.AssetId
import com.wire.kalium.logic.feature.asset.DeleteAssetUseCase
Expand All @@ -43,6 +44,7 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import okio.Path
import okio.buffer
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows

Expand Down Expand Up @@ -144,6 +146,141 @@ internal class AssetImageFetcherTest {
coVerify(inverse = true) { arrangement.drawableResultWrapper.toFetchResult(any()) }
}

@Test
fun givenAUserAvatarAssetData_WhenCallingFetchReturnsFailureWithRetryNotNeeded_ThenThrowExceptionWithDoNotRetryPolicy() =
runTest {
// Given
val someUserAssetId = AssetId("value", "domain")
val data = ImageAsset.UserAvatarAsset(mockk(), someUserAssetId)
val (arrangement, assetImageFetcher) = Arrangement()
.withErrorResponse(
data = data,
isRetryNeeded = false,
coreFailure = CoreFailure.Unknown(null)
)
.arrange()

// When
val exception = assertThrows<AssetImageException> { assetImageFetcher.fetch() }

// Then
assertEquals(AssetImageRetryPolicy.DO_NOT_RETRY, exception.retryPolicy)
coVerify(inverse = true) { arrangement.drawableResultWrapper.toFetchResult(any()) }
}

@Test
fun givenAUserAvatarAssetData_WhenCallingFetchReturnsNoConnectionFailure_ThenThrowExceptionWithRetryPolicy() =
runTest {
// Given
val someUserAssetId = AssetId("value", "domain")
val data = ImageAsset.UserAvatarAsset(mockk(), someUserAssetId)
val (arrangement, assetImageFetcher) = Arrangement()
.withErrorResponse(
data = data,
isRetryNeeded = true,
coreFailure = NetworkFailure.NoNetworkConnection(null)
)
.arrange()

// When
val exception = assertThrows<AssetImageException> { assetImageFetcher.fetch() }

// Then
assertEquals(AssetImageRetryPolicy.RETRY_WHEN_CONNECTED, exception.retryPolicy)
coVerify(inverse = true) { arrangement.drawableResultWrapper.toFetchResult(any()) }
}

@Test
fun givenAUserAvatarAssetData_WhenCallingFetchReturnsFailureWithRetryNeeded_ThenThrowExceptionWithExponentialRetryPolicy() =
runTest {
// Given
val someUserAssetId = AssetId("value", "domain")
val data = ImageAsset.UserAvatarAsset(mockk(), someUserAssetId)
val (arrangement, assetImageFetcher) = Arrangement()
.withErrorResponse(
data = data,
isRetryNeeded = true,
coreFailure = CoreFailure.Unknown(null)
)
.arrange()

// When
val exception = assertThrows<AssetImageException> { assetImageFetcher.fetch() }

// Then
assertEquals(AssetImageRetryPolicy.EXPONENTIAL_RETRY_WHEN_CONNECTED, exception.retryPolicy)
coVerify(inverse = true) { arrangement.drawableResultWrapper.toFetchResult(any()) }
}

@Test
fun givenAPrivateAssetImageData_WhenCallingFetchReturnsFailureWithRetryNotNeeded_ThenThrowExceptionWithDoNotRetryPolicy() =
runTest {
// Given
val someConversationId = ConversationId("some-value", "some-domain")
val someMessageId = "some-message-id"
val data = ImageAsset.PrivateAsset(mockk(), someConversationId, someMessageId, true)
val (arrangement, assetImageFetcher) = Arrangement()
.withErrorResponse(
data = data,
isRetryNeeded = false,
coreFailure = CoreFailure.Unknown(null)
)
.arrange()

// When
val exception = assertThrows<AssetImageException> { assetImageFetcher.fetch() }

// Then
assertEquals(AssetImageRetryPolicy.DO_NOT_RETRY, exception.retryPolicy)
coVerify(inverse = true) { arrangement.drawableResultWrapper.toFetchResult(any()) }
}

@Test
fun givenAPrivateAssetImageData_WhenCallingFetchReturnsNoConnectionFailure_ThenThrowExceptionWithRetryPolicy() =
runTest {
// Given
val someConversationId = ConversationId("some-value", "some-domain")
val someMessageId = "some-message-id"
val data = ImageAsset.PrivateAsset(mockk(), someConversationId, someMessageId, true)
val (arrangement, assetImageFetcher) = Arrangement()
.withErrorResponse(
data = data,
isRetryNeeded = true,
coreFailure = NetworkFailure.NoNetworkConnection(null)
)
.arrange()

// When
val exception = assertThrows<AssetImageException> { assetImageFetcher.fetch() }

// Then
assertEquals(AssetImageRetryPolicy.RETRY_WHEN_CONNECTED, exception.retryPolicy)
coVerify(inverse = true) { arrangement.drawableResultWrapper.toFetchResult(any()) }
}

@Test
fun givenAPrivateAssetImageData_WhenCallingFetchReturnsFailureWithRetryNeeded_ThenThrowExceptionWithExponentialRetryPolicy() =
runTest {
// Given
val someConversationId = ConversationId("some-value", "some-domain")
val someMessageId = "some-message-id"
val data = ImageAsset.PrivateAsset(mockk(), someConversationId, someMessageId, true)
val (arrangement, assetImageFetcher) = Arrangement()
.withErrorResponse(
data = data,
isRetryNeeded = true,
coreFailure = CoreFailure.Unknown(null)
)
.arrange()

// When
val exception = assertThrows<AssetImageException> { assetImageFetcher.fetch() }

// Then
assertEquals(AssetImageRetryPolicy.EXPONENTIAL_RETRY_WHEN_CONNECTED, exception.retryPolicy)
coVerify(inverse = true) { arrangement.drawableResultWrapper.toFetchResult(any()) }
}

private class Arrangement {
val getPublicAsset = mockk<GetAvatarAssetUseCase>()
val getPrivateAsset = mockk<GetMessageAssetUseCase>()
Expand Down Expand Up @@ -198,11 +335,15 @@ internal class AssetImageFetcherTest {
return this
}

fun withErrorResponse(data: ImageAsset, isRetryNeeded: Boolean = false): Arrangement {
fun withErrorResponse(
data: ImageAsset,
isRetryNeeded: Boolean = false,
coreFailure: CoreFailure = CoreFailure.Unknown(null)
): Arrangement {
imageData = data
coEvery { getPublicAsset.invoke((any())) }.returns(
PublicAssetResult.Failure(
CoreFailure.Unknown(null),
coreFailure,
isRetryNeeded
)
)
Expand All @@ -214,7 +355,7 @@ internal class AssetImageFetcherTest {
}.returns(
CompletableDeferred(
MessageAssetResult.Failure(
CoreFailure.Unknown(null),
coreFailure,
isRetryNeeded
)
)
Expand Down
2 changes: 1 addition & 1 deletion kalium
Submodule kalium updated 52 files
+1 −0 build.gradle.kts
+1 −0 logic/build.gradle.kts
+1 −1 logic/src/androidMain/kotlin/com/wire/kalium/logic/CoreLogic.kt
+1 −1 logic/src/androidMain/kotlin/com/wire/kalium/logic/feature/UserSessionScope.kt
+1 −1 logic/src/androidMain/kotlin/com/wire/kalium/logic/feature/UserSessionScopeProviderImpl.kt
+2 −0 logic/src/androidMain/kotlin/com/wire/kalium/logic/network/NetworkStateObserverImpl.kt
+1 −1 logic/src/appleMain/kotlin/com/wire/kalium/logic/CoreLogic.kt
+1 −1 logic/src/appleMain/kotlin/com/wire/kalium/logic/feature/UserSessionScope.kt
+1 −1 logic/src/appleMain/kotlin/com/wire/kalium/logic/feature/UserSessionScopeProviderImpl.kt
+2 −0 logic/src/appleMain/kotlin/com/wire/kalium/logic/network/NetworkStateObserverImpl.kt
+9 −5 logic/src/commonMain/kotlin/com/wire/kalium/logic/CoreFailure.kt
+2 −2 logic/src/commonMain/kotlin/com/wire/kalium/logic/CoreLogger.kt
+4 −3 logic/src/commonMain/kotlin/com/wire/kalium/logic/CoreLogic.kt
+7 −3 logic/src/commonMain/kotlin/com/wire/kalium/logic/GlobalKaliumScope.kt
+4 −2 logic/src/commonMain/kotlin/com/wire/kalium/logic/feature/UserSessionScope.kt
+4 −2 logic/src/commonMain/kotlin/com/wire/kalium/logic/feature/appVersioning/ObserveIfAppUpdateRequiredUseCase.kt
+1 −0 logic/src/commonMain/kotlin/com/wire/kalium/logic/feature/asset/GetMessageAssetUseCase.kt
+8 −3 logic/src/commonMain/kotlin/com/wire/kalium/logic/feature/auth/AuthenticationScope.kt
+22 −0 logic/src/commonMain/kotlin/com/wire/kalium/logic/network/NetworkStateObserverImpl.kt
+1 −1 logic/src/commonMain/kotlin/com/wire/kalium/logic/sync/incremental/IncrementalSyncManager.kt
+1 −1 logic/src/commonMain/kotlin/com/wire/kalium/logic/sync/slow/SlowSyncManager.kt
+2 −2 logic/src/commonTest/kotlin/com/wire/kalium/logic/sync/incremental/IncrementalSyncManagerTest.kt
+2 −2 logic/src/commonTest/kotlin/com/wire/kalium/logic/sync/slow/SlowSyncManagerTest.kt
+1 −1 logic/src/jvmMain/kotlin/com/wire/kalium/logic/CoreLogic.kt
+1 −1 logic/src/jvmMain/kotlin/com/wire/kalium/logic/feature/UserSessionScope.kt
+1 −1 logic/src/jvmMain/kotlin/com/wire/kalium/logic/feature/UserSessionScopeProviderImpl.kt
+2 −0 logic/src/jvmMain/kotlin/com/wire/kalium/logic/network/NetworkStateObserverImpl.kt
+43 −0 network-util/build.gradle.kts
+13 −0 network-util/consumer-proguard-rules.pro
+2 −5 network-util/src/commonMain/kotlin/com/wire/kalium/network/NetworkStateObserver.kt
+39 −0 network-util/src/commonMain/kotlin/com/wire/kalium/network/NetworkUtilLogger.kt
+1 −0 network/build.gradle.kts
+1 −1 network/src/commonJvmAndroid/kotlin/com/wire/kalium/network/KaliumWebSocketFactory.kt
+16 −4 network/src/commonMain/kotlin/com/wire/kalium/network/NetworkClient.kt
+3 −0 ...ain/kotlin/com/wire/kalium/network/api/v0/authenticated/networkContainer/AuthenticatedNetworkContainerV0.kt
+3 −0 ...kotlin/com/wire/kalium/network/api/v0/unauthenticated/networkContainer/UnauthenticatedNetworkContainerV0.kt
+3 −0 ...ain/kotlin/com/wire/kalium/network/api/v2/authenticated/networkContainer/AuthenticatedNetworkContainerV2.kt
+3 −0 ...kotlin/com/wire/kalium/network/api/v2/unauthenticated/networkContainer/UnauthenticatedNetworkContainerV2.kt
+3 −0 ...ain/kotlin/com/wire/kalium/network/api/v3/authenticated/networkContainer/AuthenticatedNetworkContainerV3.kt
+3 −0 ...kotlin/com/wire/kalium/network/api/v3/unauthenticated/networkContainer/UnauthenticatedNetworkContainerV3.kt
+3 −0 ...ain/kotlin/com/wire/kalium/network/api/v4/authenticated/networkContainer/AuthenticatedNetworkContainerV4.kt
+3 −0 ...kotlin/com/wire/kalium/network/api/v4/unauthenticated/networkContainer/UnauthenticatedNetworkContainerV4.kt
+3 −0 network/src/commonMain/kotlin/com/wire/kalium/network/exceptions/KaliumException.kt
+13 −2 network/src/commonMain/kotlin/com/wire/kalium/network/networkContainer/AuthenticatedNetworkContainer.kt
+9 −1 network/src/commonMain/kotlin/com/wire/kalium/network/networkContainer/UnauthenticatedNetworkContainer.kt
+10 −2 network/src/commonMain/kotlin/com/wire/kalium/network/networkContainer/UnboundNetworkContainer.kt
+59 −0 network/src/commonMain/kotlin/com/wire/kalium/network/utils/KaliumKtorNoNetworkHandler.kt
+52 −23 network/src/commonTest/kotlin/com/wire/kalium/api/ApiTest.kt
+36 −0 network/src/commonTest/kotlin/com/wire/kalium/api/TestNetworkStateObserver.kt
+4 −1 network/src/commonTest/kotlin/com/wire/kalium/api/common/SessionManagerTest.kt
+2 −2 network/src/commonTest/kotlin/com/wire/kalium/api/v0/user/logout/LogoutApiV0Test.kt
+7 −7 network/src/commonTest/kotlin/com/wire/kalium/api/v0/user/self/SelfApiV0Test.kt
Loading