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
Open
balamaninayard
wants to merge
14
commits into
braintree:view-edit-fi-beta-feature
Choose a base branch
from
balamaninayard:feature/saved-payment-method-image-loader
base: view-edit-fi-beta-feature
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.
+1,305
−1
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
ec026f5
feat(SharedUtils): add size-limited binary body support to HttpClient
4381b29
feat(PayPalSavedPaymentMethod): add ImageLoader and Compose LoaderImage
d2ac1b4
fix(PayPalSavedPaymentMethod): address PR review feedback on ImageLoader
154b7b0
fix(PayPalSavedPaymentMethod): address PR review feedback on ImageLoader
fc93da3
test(PayPalSavedPaymentMethod): add Compose tests for LoaderImage
2d1228c
fix(PayPalSavedPaymentMethod): address Copilot review on ImageLoader
balamaninayard c06a61b
fix(PayPalSavedPaymentMethod): show a loading state instead of the fa…
balamaninayard fdb9ea0
Merge branch 'view-edit-fi-beta-feature' into feature/saved-payment-m…
balamaninayard 58f5bd4
fix(PayPalSavedPaymentMethod): validate image URLs with asHttpsUrlOrNull
68ef661
fix(SharedUtils): bound binary downloads by default and address revie…
balamaninayard 1abdc8c
test(SharedUtils): add instrumentation tests for binary downloads
balamaninayard eb73840
fix(ImageLoader): bound concurrent icon fetches, add clearCache for m…
balamaninayard 8771cd1
docs(CHANGELOG): simplify sendRequestForBytes entry per review sugges…
balamaninayard 8e26d86
fix(PayPalSavedPaymentMethod): move calculateInSampleSize out of Imag…
balamaninayard 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 hidden or 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 hidden or 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
260 changes: 260 additions & 0 deletions
260
...c/main/java/com/braintreepayments/api/paypalsavedpaymentmethod/imageloader/ImageLoader.kt
This file contains hidden or 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,260 @@ | ||
| 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 fetched and 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). | ||
| * | ||
| * Call [clearCache] from the host app's memory-pressure callback to release cached bitmaps; see [clearCache] for why | ||
| * this loader can't do that on its own. | ||
| */ | ||
| internal class ImageLoader internal constructor( | ||
| 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), | ||
| private val fetchSemaphore: Semaphore = Semaphore(DEFAULT_MAX_PARALLEL_FETCHES), | ||
| ) { | ||
| // 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) | ||
|
|
||
| /** | ||
| * Evicts every cached bitmap. The loader holds no [android.content.Context] and so cannot register for memory | ||
| * callbacks itself; call this from the host app's [android.content.ComponentCallbacks2.onTrimMemory] (e.g. | ||
| * `Application.onTrimMemory`) to release the cache under memory pressure. Safe to call at any time -- in-flight | ||
| * downloads are unaffected and simply re-populate the cache on completion. | ||
| */ | ||
| fun clearCache() { | ||
| memoryCache.evictAll() | ||
| } | ||
|
|
||
| /** | ||
| * 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 { | ||
| // Bounds how many icon downloads run over the network at once; distinct URLs are not deduplicated like | ||
| // repeat requests for the same URL are (see inFlightRequest), so without this a burst of distinct icons | ||
| // (e.g. a list screen) could open one connection per icon at the same time. | ||
| val bytes = fetchSemaphore.withPermit { | ||
| httpClient.sendRequestForBytes(OkHttpRequest(url, Method.Get), MAX_IMAGE_BYTES) | ||
| } | ||
| 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.
|
||
|
|
||
| // 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 | ||
|
|
||
| // Bounds concurrent icon downloads so a burst of distinct URLs can't open unbounded connections at once. | ||
| private const val DEFAULT_MAX_PARALLEL_FETCHES = 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 } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Top level rather than a member: it uses nothing from the loader. | ||
| 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 | ||
| } | ||
85 changes: 85 additions & 0 deletions
85
...c/main/java/com/braintreepayments/api/paypalsavedpaymentmethod/imageloader/LoaderImage.kt
This file contains hidden or 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,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" |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.