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

Tor initialization and disposal #1560

Merged
merged 2 commits into from
Aug 16, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,7 @@ class SdkSynchronizer private constructor(
coroutineScope.launch {
Twig.info { "Stopping synchronizer $synchronizerKey…" }
processor.stop()
fetchExchangeChangeUsd.dispose()
}

instances[synchronizerKey] = InstanceState.ShuttingDown(shutdownJob)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,24 @@ import cash.z.ecc.android.sdk.internal.model.TorClient
import cash.z.ecc.android.sdk.model.FetchFiatCurrencyResult
import cash.z.ecc.android.sdk.model.FiatCurrencyConversion
import kotlinx.coroutines.delay
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.datetime.Clock
import java.io.File

internal class UsdExchangeRateFetcher(private val torDir: File) {
internal class UsdExchangeRateFetcher(torDir: File) {
private val torHolder = TorClientHolder(torDir)

@Suppress("TooGenericExceptionCaught", "ReturnCount")
suspend operator fun invoke(): FetchFiatCurrencyResult {
val tor =
retry {
try {
Twig.info { "[USD] Tor client bootstrap" }
TorClient.new(torDir)
} catch (e: Exception) {
Twig.error(e) { "[USD] To client bootstrap failed" }
return FetchFiatCurrencyResult.Error(exception = e)
}
}

return retry {
val rate =
try {
Twig.info { "[USD] Fetch start" }
tor.getExchangeRateUsd()
torHolder().getExchangeRateUsd()
} catch (e: Exception) {
Twig.error(e) { "[USD] Fetch failed" }
return FetchFiatCurrencyResult.Error(e)
} finally {
tor.dispose()
}

Twig.debug { "[USD] Fetch success: $rate" }
Expand All @@ -46,6 +37,10 @@ internal class UsdExchangeRateFetcher(private val torDir: File) {
}
}

suspend fun dispose() {
torHolder.dispose()
}

/**
* Retry with geometric order.
*/
Expand All @@ -69,3 +64,21 @@ internal class UsdExchangeRateFetcher(private val torDir: File) {
return block() // last attempt
}
}

private class TorClientHolder(private val torDir: File) {
private val mutex = Mutex()
private var torClient: TorClient? = null

suspend operator fun invoke(): TorClient =
mutex.withLock {
if (torClient == null) {
torClient = TorClient.new(torDir)
}
return torClient!!
}

suspend fun dispose() =
mutex.withLock {
torClient?.dispose()
}
}
Loading