Repository navigation
Feature : saved payment method image loader #1721
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
base: view-edit-fi-beta-feature
Are you sure you want to change the base?
Changes from all commits
ec026f5
4381b29
d2ac1b4
154b7b0
fc93da3
2d1228c
c06a61b
fdb9ea0
58f5bd4
68ef661
1abdc8c
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,237 @@ | ||
| package com.braintreepayments.api.paypalsavedpaymentmethod.imageloader | ||
|
|
||
| import android.graphics.Bitmap | ||
| import android.graphics.BitmapFactory | ||
| import android.util.LruCache | ||
| import android.view.View | ||
| import android.widget.ImageView | ||
| import androidx.annotation.DrawableRes | ||
| import com.braintreepayments.api.paypalsavedpaymentmethod.asHttpsUrlOrNull | ||
| import com.braintreepayments.api.sharedutils.HttpClient | ||
| import com.braintreepayments.api.sharedutils.Method | ||
| import com.braintreepayments.api.sharedutils.OkHttpRequest | ||
| import kotlinx.coroutines.CoroutineDispatcher | ||
| import kotlinx.coroutines.CoroutineScope | ||
| import kotlinx.coroutines.CoroutineStart | ||
| import kotlinx.coroutines.Deferred | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.Job | ||
| import kotlinx.coroutines.SupervisorJob | ||
| import kotlinx.coroutines.async | ||
| import kotlinx.coroutines.job | ||
| import kotlinx.coroutines.launch | ||
| import kotlinx.coroutines.sync.Semaphore | ||
| import kotlinx.coroutines.sync.withPermit | ||
| import kotlinx.coroutines.withContext | ||
| import java.io.IOException | ||
| import java.lang.ref.WeakReference | ||
| import java.util.Collections | ||
| import java.util.WeakHashMap | ||
| import java.util.concurrent.ConcurrentHashMap | ||
| import kotlin.coroutines.cancellation.CancellationException | ||
|
|
||
| /** | ||
| * Loads funding-instrument icons into memory, de-duplicating concurrent requests for the same URL and bounding how | ||
| * many bitmaps are decoded at once. Bytes are fetched through the SDK's pinned [HttpClient]. Dependencies are | ||
| * injectable for tests; production code uses [getInstance]. | ||
| * | ||
| * Decodes raster formats only (PNG, JPEG, etc.) via [android.graphics.BitmapFactory]. There is currently no image | ||
| * loader in Braintree Native, and this custom implementation does not support SVG, matching standard Android image | ||
| * loading in general (BitmapFactory, and Coil/Glide without an SVG add-on). | ||
| */ | ||
| internal class ImageLoader internal constructor( | ||
|
Contributor
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. It seems like there is no way to explicitly clear the cache without process death. Is that intentional?
Author
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. Yes, intentional. It's a bounded 4 MB LRU that evicts itself and only holds small icons, so there's nothing to clear manually. If we want it to react to memory pressure (onTrimMemory) that can be a follow-up.
Contributor
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. What would the lift look like to add that now? If it's not added now, will you commit to adding it in a follow up? I just want to make sure this isn't lost in the shuffle between you doing this work and our team taking it over and my thinking here is just to make sure we gracefully exit if there's memory concerns |
||
| private val httpClient: HttpClient = HttpClient(), | ||
| private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default, | ||
| private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main.immediate, | ||
| private val memoryCache: LruCache<String, Bitmap> = createMemoryCache(), | ||
| private val decodeSemaphore: Semaphore = Semaphore(DEFAULT_MAX_PARALLEL_DECODES), | ||
| ) { | ||
| // Deliberately unscoped to any lifecycle: ImageLoader is a process-wide singleton (see getInstance()), so | ||
| // in-flight downloads outlive any single screen and are only ever torn down by process death. That is safe because | ||
| // each download is short and bounded (30 s call timeout, size cap) and failures aren't cached, so nothing | ||
| // accumulates. | ||
| private val loaderScope = CoroutineScope(SupervisorJob() + defaultDispatcher) | ||
| private val inFlightRequests = ConcurrentHashMap<String, Deferred<Bitmap>>() | ||
|
|
||
| // Weak keys: the loader is a process-wide singleton and must never keep a view alive. | ||
| private val viewRequests = Collections.synchronizedMap(WeakHashMap<ImageView, ViewRequest>()) | ||
|
|
||
| private val attachStateListener = object : View.OnAttachStateChangeListener { | ||
| override fun onViewAttachedToWindow(v: View) { | ||
| val imageView = v as? ImageView ?: return | ||
| // Resume a load whose wait was cancelled by a detach, e.g. a RecyclerView row re-attached without re-bind. | ||
| val request = viewRequests[imageView] | ||
| if (request != null && request.job.isCancelled) { | ||
| startViewRequest(imageView, request.url, request.errorPlaceholder) | ||
| } | ||
| } | ||
|
|
||
| override fun onViewDetachedFromWindow(v: View) { | ||
| val imageView = v as? ImageView ?: return | ||
| // Keep the record so a re-attach can resume; only the wait is cancelled, the download keeps running. | ||
| viewRequests[imageView]?.job?.cancel() | ||
| } | ||
| } | ||
|
|
||
| /** Returns the cached bitmap for [url] without touching the network, or `null` on a cache miss. */ | ||
| fun peek(url: String): Bitmap? = memoryCache.get(url) | ||
|
|
||
| /** | ||
| * Returns the bitmap for [url], from memory when cached. Throws [IllegalArgumentException] if [url] is not an https | ||
| * URL with a host, and [IOException] if the download or decode fails. | ||
| */ | ||
| suspend fun load(url: String): Bitmap { | ||
| val validUrl = requireNotNull(url.asHttpsUrlOrNull()) { "url must be an https URL with a host" } | ||
| memoryCache.get(validUrl)?.let { return it } | ||
| return inFlightRequest(validUrl).await() | ||
| } | ||
|
|
||
| /** | ||
| * Binds [url] into [imageView]. While the image loads, the view shows [loadingPlaceholder], or stays blank when it | ||
| * is `null`. If [url] is missing or not an https URL with a host, or the load fails, it shows [errorPlaceholder], | ||
| * or stays blank when it is `null`. | ||
| * | ||
| * Must be called on the main thread; it updates [imageView] directly. | ||
| */ | ||
| fun load( | ||
| url: String?, | ||
| imageView: ImageView, | ||
| @DrawableRes loadingPlaceholder: Int? = null, | ||
| @DrawableRes errorPlaceholder: Int? = null, | ||
| ) { | ||
|
balamaninayard marked this conversation as resolved.
|
||
| cancel(imageView) | ||
| val validUrl = url.asHttpsUrlOrNull() | ||
| val cached = validUrl?.let { memoryCache.get(it) } | ||
| if (cached != null) { | ||
| imageView.setImageBitmap(cached) | ||
| return | ||
| } | ||
| if (validUrl == null) { | ||
| imageView.setPlaceholder(errorPlaceholder) | ||
| return | ||
| } | ||
| imageView.setPlaceholder(loadingPlaceholder) | ||
|
|
||
| // Remove-then-add keeps exactly one listener per view, however many times the view is re-bound. | ||
| imageView.removeOnAttachStateChangeListener(attachStateListener) | ||
| imageView.addOnAttachStateChangeListener(attachStateListener) | ||
| startViewRequest(imageView, validUrl, errorPlaceholder) | ||
| } | ||
|
|
||
| /** Cancels any pending load for [imageView]. Must be called on the main thread. */ | ||
| fun cancel(imageView: ImageView) { | ||
| // Symmetric with the add in load(): once a request is fully cancelled there is nothing left to resume on | ||
| // a future re-attach, so the view shouldn't keep carrying the listener. | ||
| imageView.removeOnAttachStateChangeListener(attachStateListener) | ||
| viewRequests.remove(imageView)?.job?.cancel() | ||
| } | ||
|
|
||
| private fun inFlightRequest(url: String): Deferred<Bitmap> = | ||
| inFlightRequests[url] ?: synchronized(inFlightRequests) { | ||
| inFlightRequests[url] ?: loaderScope.async(start = CoroutineStart.LAZY) { | ||
| // Another download may have cached this URL after the caller's cache miss and before this started. | ||
| memoryCache.get(url) ?: fetchAndDecode(url) | ||
| }.also { deferred -> | ||
| inFlightRequests[url] = deferred | ||
| // Registered after the put and before start, so a download that finishes immediately cannot leave | ||
| // a stale (possibly failed) entry behind. Waiter cancellation never removes the entry. | ||
| deferred.invokeOnCompletion { inFlightRequests.remove(url, deferred) } | ||
| deferred.start() | ||
| } | ||
| } | ||
|
|
||
| private fun startViewRequest(imageView: ImageView, url: String, @DrawableRes errorPlaceholder: Int?) { | ||
| val target = WeakReference(imageView) | ||
| val job = loaderScope.launch(mainDispatcher, start = CoroutineStart.LAZY) { | ||
| val bitmap = try { | ||
| load(url) | ||
| } catch (ignored: IOException) { | ||
| null // keep the placeholder; no automatic retry | ||
| } catch (ignored: IllegalArgumentException) { | ||
| null // non-https or host-less URL rejected before any request | ||
| } catch (ignored: Exception) { | ||
| if (ignored is CancellationException) throw ignored | ||
| null // unexpected failure (e.g. a malformed response the decoder can't handle); keep the placeholder | ||
| } | ||
|
balamaninayard marked this conversation as resolved.
|
||
| val view = target.get() ?: return@launch | ||
| // Drop the result if the view has been re-bound to a different request since this one started. | ||
| if (viewRequests[view]?.job !== coroutineContext.job) return@launch | ||
| viewRequests.remove(view) | ||
| if (bitmap != null) view.setImageBitmap(bitmap) else view.setPlaceholder(errorPlaceholder) | ||
| } | ||
| // Recorded before start so the identity check above always sees this request. | ||
| viewRequests[imageView] = ViewRequest(url, errorPlaceholder, job) | ||
| job.start() | ||
| } | ||
|
|
||
| private suspend fun fetchAndDecode(url: String): Bitmap { | ||
| val bytes = httpClient.sendRequestForBytes(OkHttpRequest(url, Method.Get), MAX_IMAGE_BYTES) | ||
|
Contributor
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. Would there ever be a scenario where multiple concurrent fetches could be initiated? Would we also want a semaphore here to limit the number of fetches? |
||
| val bitmap = withContext(defaultDispatcher) { | ||
| decodeSemaphore.withPermit { decodeBitmap(bytes, url) } | ||
| } | ||
| memoryCache.put(url, bitmap) | ||
| return bitmap | ||
| } | ||
|
|
||
| // Two-pass decode: read bounds only, then decode a power-of-two subsample close to the display size. | ||
| // Reference: https://developer.android.com/topic/performance/graphics/load-bitmap | ||
| private fun decodeBitmap(bytes: ByteArray, url: String): Bitmap { | ||
| val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } | ||
| BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) | ||
|
|
||
| val options = BitmapFactory.Options().apply { | ||
| inSampleSize = calculateInSampleSize(bounds, MAX_DECODE_DIMENSION_PX, MAX_DECODE_DIMENSION_PX) | ||
| } | ||
| return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) | ||
| ?: throw IOException("Unable to decode image from $url") | ||
| } | ||
|
balamaninayard marked this conversation as resolved.
|
||
|
|
||
| private fun calculateInSampleSize( | ||
| options: BitmapFactory.Options, | ||
| reqWidth: Int, | ||
| reqHeight: Int, | ||
| ): Int { | ||
| val height = options.outHeight | ||
| val width = options.outWidth | ||
| var inSampleSize = 1 | ||
|
|
||
| while (height / inSampleSize > reqHeight || width / inSampleSize > reqWidth) { | ||
| inSampleSize *= 2 | ||
| } | ||
|
|
||
| return inSampleSize | ||
| } | ||
|
|
||
| // Also clears a stale image (e.g. from a recycled RecyclerView row) when there is no placeholder. | ||
| private fun ImageView.setPlaceholder(@DrawableRes placeholder: Int?) { | ||
| if (placeholder != null) setImageResource(placeholder) else setImageDrawable(null) | ||
| } | ||
|
|
||
| private class ViewRequest(val url: String, @DrawableRes val errorPlaceholder: Int?, val job: Job) | ||
|
|
||
| companion object { | ||
| // 4 MB keeps a reasonable number of small FI icons resident without pressuring low-memory devices. | ||
| private const val DEFAULT_CACHE_SIZE_BYTES = 4 * 1024 * 1024 | ||
|
balamaninayard marked this conversation as resolved.
|
||
|
|
||
| // Bounds concurrent BitmapFactory decodes so many icons loading at once can't spike memory/CPU. | ||
| private const val DEFAULT_MAX_PARALLEL_DECODES = 4 | ||
|
|
||
| // FI icons never render larger than this in any current layout; decoding beyond it wastes memory. | ||
| private const val MAX_DECODE_DIMENSION_PX = 128 | ||
|
|
||
| // Generous ceiling for a small icon; guards against an unexpectedly large or malicious response. | ||
| private const val MAX_IMAGE_BYTES = 1024 * 1024L | ||
|
|
||
| private fun createMemoryCache() = object : LruCache<String, Bitmap>(DEFAULT_CACHE_SIZE_BYTES) { | ||
| override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount | ||
| } | ||
|
|
||
| @Volatile | ||
| private var instance: ImageLoader? = null | ||
|
|
||
| fun getInstance(): ImageLoader = | ||
| instance ?: synchronized(this) { | ||
| instance ?: ImageLoader().also { instance = it } | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| package com.braintreepayments.api.paypalsavedpaymentmethod.imageloader | ||
|
|
||
| import android.graphics.Bitmap | ||
| import androidx.compose.foundation.Image | ||
| import androidx.compose.foundation.layout.Spacer | ||
| import androidx.compose.runtime.Composable | ||
| import androidx.compose.runtime.LaunchedEffect | ||
| import androidx.compose.runtime.getValue | ||
| import androidx.compose.runtime.mutableStateOf | ||
| import androidx.compose.runtime.remember | ||
| import androidx.compose.runtime.setValue | ||
| import androidx.compose.ui.Modifier | ||
| import androidx.compose.ui.graphics.asImageBitmap | ||
| import androidx.compose.ui.graphics.painter.Painter | ||
| import androidx.compose.ui.platform.testTag | ||
| import com.braintreepayments.api.paypalsavedpaymentmethod.asHttpsUrlOrNull | ||
| import java.io.IOException | ||
| import kotlin.coroutines.cancellation.CancellationException | ||
|
|
||
| /** | ||
| * Renders the funding-instrument icon at [url] via [ImageLoader]. While the image loads it shows [loading], which is | ||
| * blank by default. It shows [placeholder] only when there is no image to show: if the load fails, or if [url] is | ||
| * `null` or not an https URL with a host. | ||
| * | ||
| * The icon is decorative (the FI label is rendered next to it), so it has no content description. | ||
| * | ||
| * @param loading drawn while the image loads. It must apply the [Modifier] it receives so it takes the icon's size. | ||
| */ | ||
| @Composable | ||
| internal fun LoaderImage( | ||
| url: String?, | ||
| placeholder: Painter, | ||
| modifier: Modifier = Modifier, | ||
| loading: @Composable (Modifier) -> Unit = { Spacer(it) }, | ||
| imageLoader: ImageLoader = remember { ImageLoader.getInstance() }, | ||
| ) { | ||
| // Seeded from the memory cache so a cached icon renders on the first frame instead of flashing the loading state. | ||
| var state by remember(url) { mutableStateOf(initialState(url, imageLoader)) } | ||
|
|
||
| LaunchedEffect(url) { | ||
| if (state != LoadState.Loading || url == null) return@LaunchedEffect | ||
| state = try { | ||
| LoadState.Loaded(imageLoader.load(url)) | ||
| } catch (ignored: IOException) { | ||
| LoadState.Failed | ||
| } catch (ignored: IllegalArgumentException) { | ||
| LoadState.Failed | ||
| } catch (ignored: Exception) { | ||
| if (ignored is CancellationException) throw ignored | ||
| // Unexpected failure (e.g. a response the decoder can't handle): show the placeholder, don't crash. | ||
| LoadState.Failed | ||
| } | ||
| } | ||
|
|
||
| when (val current = state) { | ||
| LoadState.Loading -> loading(modifier.testTag(LOADING_TEST_TAG)) | ||
| is LoadState.Loaded -> Image( | ||
| bitmap = current.bitmap.asImageBitmap(), | ||
| contentDescription = null, | ||
| modifier = modifier.testTag(LOADED_IMAGE_TEST_TAG) | ||
| ) | ||
| LoadState.Failed -> Image( | ||
| painter = placeholder, | ||
| contentDescription = null, | ||
| modifier = modifier.testTag(PLACEHOLDER_IMAGE_TEST_TAG) | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| private sealed interface LoadState { | ||
| data object Loading : LoadState | ||
| data class Loaded(val bitmap: Bitmap) : LoadState | ||
| data object Failed : LoadState | ||
| } | ||
|
|
||
| // A missing or non-https URL has nothing to load, so it goes straight to the placeholder instead of showing loading. | ||
| private fun initialState(url: String?, imageLoader: ImageLoader): LoadState { | ||
| val validUrl = url.asHttpsUrlOrNull() ?: return LoadState.Failed | ||
| return imageLoader.peek(validUrl)?.let(LoadState::Loaded) ?: LoadState.Loading | ||
| } | ||
|
|
||
| // No semantic distinction exists otherwise, since the icon is decorative (contentDescription = null above). | ||
| internal const val LOADING_TEST_TAG = "loader_image_loading" | ||
| internal const val LOADED_IMAGE_TEST_TAG = "loader_image_loaded" | ||
| internal const val PLACEHOLDER_IMAGE_TEST_TAG = "loader_image_placeholder" |
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.