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

feat: Relay connection lifecycle #1491

Closed
wants to merge 9 commits into from
Closed
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.walletconnect.android.internal.common

import com.tinder.scarlet.retry.BackoffStrategy
import kotlin.math.pow

class ConditionalExponentialBackoffStrategy(
private val initialDurationMillis: Long,
private val maxDurationMillis: Long
) : BackoffStrategy {
init {
require(initialDurationMillis > 0) { "initialDurationMillis, $initialDurationMillis, must be positive" }
require(maxDurationMillis > 0) { "maxDurationMillis, $maxDurationMillis, must be positive" }
}

override var shouldBackoff: Boolean = false

fun shouldBackoff(shouldBackoff: Boolean) {
this.shouldBackoff = shouldBackoff
}

override fun backoffDurationMillisAt(retryCount: Int): Long =
maxDurationMillis.toDouble().coerceAtMost(initialDurationMillis.toDouble() * 2.0.pow(retryCount.toDouble())).toLong()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
@file:JvmSynthetic

package com.walletconnect.android.internal.common.connection

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.tinder.scarlet.Lifecycle
import com.tinder.scarlet.ShutdownReason
import com.tinder.scarlet.lifecycle.LifecycleRegistry
import com.walletconnect.foundation.network.ConnectionLifecycle
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit

internal class DefaultConnectionLifecycle(
application: Application,
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry()
) : Lifecycle by lifecycleRegistry, ConnectionLifecycle {
private val job = SupervisorJob()
private var scope = CoroutineScope(job + Dispatchers.Default)

private val _onResume = MutableStateFlow<Boolean?>(null)
override val onResume: StateFlow<Boolean?> = _onResume.asStateFlow()

init {
application.registerActivityLifecycleCallbacks(ActivityLifecycleCallbacks())
}

override fun reconnect() {
lifecycleRegistry.onNext(Lifecycle.State.Stopped.WithReason())
lifecycleRegistry.onNext(Lifecycle.State.Started)
}

private inner class ActivityLifecycleCallbacks : Application.ActivityLifecycleCallbacks {
var isResumed: Boolean = false
var job: Job? = null

override fun onActivityPaused(activity: Activity) {
isResumed = false

job = scope.launch {
delay(TimeUnit.SECONDS.toMillis(30))
if (!isResumed) {
lifecycleRegistry.onNext(Lifecycle.State.Stopped.WithReason(ShutdownReason(1000, "App is paused")))
job = null
_onResume.value = false
}
}
}

override fun onActivityResumed(activity: Activity) {
isResumed = true

if (job?.isActive == true) {
job?.cancel()
job = null
}


scope.launch {
_onResume.value = true
}
}

override fun onActivityStarted(activity: Activity) {}

override fun onActivityDestroyed(activity: Activity) {}

override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

override fun onActivityStopped(activity: Activity) {}

override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ package com.walletconnect.android.internal.common.connection

import com.tinder.scarlet.Lifecycle
import com.tinder.scarlet.lifecycle.LifecycleRegistry
import com.walletconnect.foundation.network.ConnectionLifecycle
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

internal class ManualConnectionLifecycle(
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(),
) : Lifecycle by lifecycleRegistry {
) : Lifecycle by lifecycleRegistry, ConnectionLifecycle {
fun connect() {
lifecycleRegistry.onNext(Lifecycle.State.Started)
}
Expand All @@ -16,7 +19,10 @@ internal class ManualConnectionLifecycle(
lifecycleRegistry.onNext(Lifecycle.State.Stopped.WithReason())
}

fun restart() {
override val onResume: StateFlow<Boolean?>
get() = MutableStateFlow(null)

override fun reconnect() {
lifecycleRegistry.onNext(Lifecycle.State.Stopped.WithReason())
lifecycleRegistry.onNext(Lifecycle.State.Started)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ enum class AndroidCommonDITags {
SCARLET,
MSG_ADAPTER,
MANUAL_CONNECTION_LIFECYCLE,
AUTOMATIC_CONNECTION_LIFECYCLE,
DEFAULT_CONNECTION_LIFECYCLE,
LOGGER,
CONNECTIVITY_STATE,
PUSH_RETROFIT,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import org.koin.core.qualifier.named
import org.koin.dsl.module
import kotlin.reflect.KClass


@JvmSynthetic
fun coreJsonRpcModule() = module {

Expand All @@ -27,6 +28,7 @@ fun coreJsonRpcModule() = module {
jsonRpcHistory = get(),
pushMessageStorage = get(),
logger = get(named(AndroidCommonDITags.LOGGER)),
backoffStrategy = get()
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ import com.pandulapeter.beagle.logOkHttp.BeagleOkHttpLogger
import com.squareup.moshi.Moshi
import com.tinder.scarlet.Lifecycle
import com.tinder.scarlet.Scarlet
import com.tinder.scarlet.lifecycle.android.AndroidLifecycle
import com.tinder.scarlet.messageadapter.moshi.MoshiMessageAdapter
import com.tinder.scarlet.retry.ExponentialBackoffStrategy
import com.tinder.scarlet.websocket.okhttp.newWebSocketFactory
import com.walletconnect.android.BuildConfig
import com.walletconnect.android.internal.common.ConditionalExponentialBackoffStrategy
import com.walletconnect.android.internal.common.connection.ConnectivityState
import com.walletconnect.android.internal.common.connection.DefaultConnectionLifecycle
import com.walletconnect.android.internal.common.connection.ManualConnectionLifecycle
import com.walletconnect.android.internal.common.jwt.clientid.GenerateJwtStoreClientIdUseCase
import com.walletconnect.android.relay.ConnectionType
Expand Down Expand Up @@ -109,17 +109,17 @@ fun coreAndroidNetworkModule(serverUrl: String, connectionType: ConnectionType,
ManualConnectionLifecycle()
}

single<Lifecycle>(named(AndroidCommonDITags.AUTOMATIC_CONNECTION_LIFECYCLE)) {
AndroidLifecycle.ofApplicationForeground(androidApplication())
single<DefaultConnectionLifecycle>(named(AndroidCommonDITags.DEFAULT_CONNECTION_LIFECYCLE)) {
DefaultConnectionLifecycle(androidApplication())
}

single { ExponentialBackoffStrategy(INIT_BACKOFF_MILLIS, TimeUnit.SECONDS.toMillis(MAX_BACKOFF_SEC)) }
single { ConditionalExponentialBackoffStrategy(INIT_BACKOFF_MILLIS, TimeUnit.SECONDS.toMillis(MAX_BACKOFF_SEC)) }

single { FlowStreamAdapter.Factory() }

single(named(AndroidCommonDITags.SCARLET)) {
Scarlet.Builder()
.backoffStrategy(get<ExponentialBackoffStrategy>())
.backoffStrategy((get<ConditionalExponentialBackoffStrategy>()))
.webSocketFactory(get<OkHttpClient>(named(AndroidCommonDITags.OK_HTTP)).newWebSocketFactory(get<String>(named(AndroidCommonDITags.RELAY_URL))))
.lifecycle(getLifecycle(connectionType))
.addMessageAdapterFactory(get<MoshiMessageAdapter.Factory>(named(AndroidCommonDITags.MSG_ADAPTER)))
Expand All @@ -136,9 +136,9 @@ fun coreAndroidNetworkModule(serverUrl: String, connectionType: ConnectionType,
}
}

private fun Scope.getLifecycle(connectionType: ConnectionType) =
private fun Scope.getLifecycle(connectionType: ConnectionType): Lifecycle =
if (connectionType == ConnectionType.MANUAL) {
get<ManualConnectionLifecycle>(named(AndroidCommonDITags.MANUAL_CONNECTION_LIFECYCLE))
} else {
get<Lifecycle>(named(AndroidCommonDITags.AUTOMATIC_CONNECTION_LIFECYCLE))
get<DefaultConnectionLifecycle>(named(AndroidCommonDITags.DEFAULT_CONNECTION_LIFECYCLE))
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@ fun corePairingModule(pairing: PairingInterface, pairingController: PairingContr
pairingRepository = get(),
jsonRpcInteractor = get(),
logger = get(named(AndroidCommonDITags.LOGGER)),
insertTelemetryEventUseCase = get(),
insertEventUseCase = get(),
sendBatchEventUseCase = get(),
clientId = get(named(AndroidCommonDITags.CLIENT_ID)),
userAgent = get(named(AndroidCommonDITags.USER_AGENT))
)
}
single { pairing }
Expand Down
Loading
Loading