maps: run reviews WebView scraper in a separate :reviews process
- Commit
f00a518dfdefd59e9f84641871d9b7802bb357d4- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 21:02 UTC (1 month ago)
- Parents
56b5796
Diff
maps/src/main/AndroidManifest.xml
diff --git a/maps/src/main/AndroidManifest.xml b/maps/src/main/AndroidManifest.xmlindex dabb679e5a..f472c6caf9 100644--- a/maps/src/main/AndroidManifest.xml+++ b/maps/src/main/AndroidManifest.xml@@ -101,6 +101,10 @@ android:name=".util.NavigationService" android:foregroundServiceType="location" android:exported="false" />+ <service+ android:name=".service.ReviewsScraperService"+ android:process=":reviews"+ android:exported="false" /> <service android:name=".car.MapsCarAppService"
maps/src/main/java/com/vayunmathur/maps/data/google/WebReviewsFetcher.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/google/WebReviewsFetcher.kt b/maps/src/main/java/com/vayunmathur/maps/data/google/WebReviewsFetcher.ktindex 5620cf4230..61ffaa683f 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/google/WebReviewsFetcher.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/google/WebReviewsFetcher.kt@@ -30,39 +30,21 @@ import java.util.concurrent.atomic.AtomicInteger * [ReviewsWebParser] turns it into [GoogleReview]s. * * Strictly best-effort + lazy: any failure/timeout returns empty and the place sheet just shows no- * reviews. Serialized by a [Mutex] since the single WebView navigates per place. Takes an Android- * [Context] (application context preferred) — no DI framework, standalone.+ * reviews. Serialized by a [Mutex] since the single WebView navigates per place.+ *+ * Only ever constructed inside [com.vayunmathur.maps.service.ReviewsScraperService]'s `:reviews`+ * process: loading Chromium pins ~100 MB that `WebView.destroy()` never unmaps, so it must live in+ * a process that can exit. */ class WebReviewsFetcher(private val context: Context) { private val pending = ConcurrentHashMap<String, CompletableDeferred<String>>() private val progress = ConcurrentHashMap<String, (Int) -> Unit>()- private val partial = ConcurrentHashMap<String, (List<GoogleReview>) -> Unit>()+ private val partial = ConcurrentHashMap<String, (String) -> Unit>() private val seq = AtomicInteger() private val mutex = Mutex() private val main = Handler(Looper.getMainLooper()) @Volatile private var webView: WebView? = null- private var reap: Runnable? = null-- /** Free the WebView after a quiet period: a warm fetcher pins a full maps.google.com page for- * the rest of the session, which is real memory. The next fetch after a reap re-creates it. */- private fun scheduleReap() {- reap?.let(main::removeCallbacks)- val r = Runnable { reapNow() }- reap = r- main.postDelayed(r, REAP_IDLE_MS)- }-- /** Destroy the WebView immediately. Must run on the main thread (WebView requirement). */- private fun reapNow() {- webView?.let { runCatching { it.loadUrl("about:blank"); it.destroy() } }- webView = null- }-- private fun cancelReap() {- reap?.let(main::removeCallbacks)- reap = null- } private inner class Bridge { @JavascriptInterface@@ -79,39 +61,33 @@ class WebReviewsFetcher(private val context: Context) { // The accumulated reviews SO FAR, sent whenever the count grows — the sheet streams them // into the list under the progress bar instead of making the user stare at a bar for 30 s.- // Same JavaBridge thread; parse failures are dropped (the final onResult is authoritative).+ // Same JavaBridge thread; the raw JSON is parsed by the client (the final onResult is+ // authoritative). @JavascriptInterface fun onPartial(id: String, payload: String) {- val cb = partial[id] ?: return- runCatching { ReviewsWebParser.parse(payload) }.getOrNull()?.let { if (it.isNotEmpty()) cb(it) }+ partial[id]?.invoke(payload) } } - /** Reviews for [featureId] (`0x..:0x..`) — newest/most-relevant first as Google renders them,- * each with its uploaded photos — or empty on any failure. [onProgress] streams the running- * count while the scrape is in flight; [onPartial] streams the accumulated reviews themselves- * (a growing prefix of the final result). Both are called off the main thread. */+ /** Raw reviews JSON (see [ReviewsWebParser]) for [featureId] (`0x..:0x..`) — newest/most-relevant+ * first as Google renders them, each with its uploaded photos — or null on any failure.+ * [onProgress] streams the running count while the scrape is in flight; [onPartial] streams the+ * accumulated reviews JSON (a growing prefix of the final result). Both are called off the main+ * thread. */ suspend fun fetch( featureId: String, onProgress: (Int) -> Unit = {},- onPartial: (List<GoogleReview>) -> Unit = {},- ): List<GoogleReview> {- val cid = cidOf(featureId) ?: return emptyList()- return mutex.withLock {- cancelReap()- try {- fetchLocked(cid, onProgress, onPartial)- } finally {- scheduleReap()- }- }+ onPartial: (String) -> Unit = {},+ ): String? {+ val cid = cidOf(featureId) ?: return null+ return mutex.withLock { fetchLocked(cid, onProgress, onPartial) } } private suspend fun fetchLocked( cid: String, onProgress: (Int) -> Unit,- onPartial: (List<GoogleReview>) -> Unit,- ): List<GoogleReview> {+ onPartial: (String) -> Unit,+ ): String? { return run { val id = BRIDGE_ID_PREFIX + seq.incrementAndGet() val deferred = CompletableDeferred<String>()@@ -160,11 +136,7 @@ class WebReviewsFetcher(private val context: Context) { progress.remove(id) partial.remove(id) }- if (raw.isNullOrEmpty()) {- emptyList()- } else {- runCatching { ReviewsWebParser.parse(raw) }.getOrDefault(emptyList())- }+ raw?.ifEmpty { null } } } @@ -414,7 +386,6 @@ class WebReviewsFetcher(private val context: Context) { // Must outlast the script's own hard stop (130 ticks × 250 ms ≈ 33 s + page load) — if Kotlin // times out first we return EMPTY, which is worse than few. Lazy + best-effort as ever. const val TOTAL_TIMEOUT_MS = 45_000L- const val REAP_IDLE_MS = 120_000L // destroy the idle WebView after this quiet period const val SETTLE_MS = 150L const val MAX_LOAD_MS = 7_000L // Offscreen viewport for the headless WebView — tall so the virtualized review list renders a
maps/src/main/java/com/vayunmathur/maps/service/ReviewsScraperClient.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/service/ReviewsScraperClient.kt b/maps/src/main/java/com/vayunmathur/maps/service/ReviewsScraperClient.ktnew file mode 100644index 0000000000..722df4f231--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/service/ReviewsScraperClient.kt@@ -0,0 +1,133 @@+package com.vayunmathur.maps.service++import android.content.ComponentName+import android.content.Context+import android.content.Intent+import android.content.ServiceConnection+import android.os.Bundle+import android.os.Handler+import android.os.IBinder+import android.os.Looper+import android.os.Message+import android.os.Messenger+import android.os.RemoteException+import com.vayunmathur.maps.data.google.GoogleReview+import com.vayunmathur.maps.data.google.ReviewsWebParser+import com.vayunmathur.maps.service.ReviewsScraperService.Companion.KEY_FEATURE_ID+import com.vayunmathur.maps.service.ReviewsScraperService.Companion.KEY_JSON+import com.vayunmathur.maps.service.ReviewsScraperService.Companion.MSG_CANCEL+import com.vayunmathur.maps.service.ReviewsScraperService.Companion.MSG_FETCH+import com.vayunmathur.maps.service.ReviewsScraperService.Companion.MSG_PARTIAL+import com.vayunmathur.maps.service.ReviewsScraperService.Companion.MSG_RESULT+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.NonCancellable+import kotlinx.coroutines.channels.Channel+import kotlinx.coroutines.withContext+import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.atomic.AtomicInteger++/**+ * Map-process side of [ReviewsScraperService]: binds on demand, streams parsed reviews back, and+ * unbinds after [IDLE_UNBIND_MS] without requests so the `:reviews` process (and Chromium) exits.+ * Best-effort like the scraper itself: any IPC failure yields an empty list.+ */+class ReviewsScraperClient(context: Context) {+ private sealed interface Event {+ data class Partial(val json: String) : Event+ data class Result(val json: String?) : Event+ }++ private val app = context.applicationContext+ private val main = Handler(Looper.getMainLooper())+ private val requests = ConcurrentHashMap<Int, Channel<Event>>()+ private val seq = AtomicInteger()+ private val incoming = Messenger(Handler(Looper.getMainLooper()) { onReply(it); true })+ private val idleUnbind = Runnable { disconnect() }++ // Main thread only.+ private var remote: CompletableDeferred<Messenger?>? = null+ private var connection: ServiceConnection? = null++ suspend fun fetch(featureId: String, onPartial: (List<GoogleReview>) -> Unit): List<GoogleReview> {+ val id = seq.incrementAndGet()+ val events = Channel<Event>(Channel.UNLIMITED)+ requests[id] = events+ var service: Messenger? = null+ try {+ val svc = withContext(Dispatchers.Main) {+ main.removeCallbacks(idleUnbind)+ connect()+ }.await() ?: return emptyList()+ service = svc+ val msg = Message.obtain(null, MSG_FETCH, id, 0)+ msg.data = Bundle().apply { putString(KEY_FEATURE_ID, featureId) }+ msg.replyTo = incoming+ svc.send(msg)+ for (event in events) {+ when (event) {+ is Event.Partial -> ReviewsWebParser.parse(event.json).takeIf { it.isNotEmpty() }?.let(onPartial)+ is Event.Result -> return event.json?.let(ReviewsWebParser::parse).orEmpty()+ }+ }+ return emptyList()+ } catch (_: RemoteException) {+ return emptyList()+ } finally {+ requests.remove(id)+ withContext(NonCancellable + Dispatchers.Main) {+ // No-op once the request already finished; frees the scrape slot if it was abandoned.+ runCatching { service?.send(Message.obtain(null, MSG_CANCEL, id, 0)) }+ if (requests.isEmpty() && connection != null) main.postDelayed(idleUnbind, IDLE_UNBIND_MS)+ }+ }+ }++ private fun connect(): CompletableDeferred<Messenger?> {+ remote?.let { return it }+ val deferred = CompletableDeferred<Messenger?>()+ val conn = object : ServiceConnection {+ override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {+ deferred.complete(binder?.let(::Messenger))+ }+ override fun onServiceDisconnected(name: ComponentName?) = onLost()+ override fun onBindingDied(name: ComponentName?) = onLost()+ override fun onNullBinding(name: ComponentName?) = onLost()+ }+ remote = deferred+ connection = conn+ val bound = runCatching {+ app.bindService(Intent(app, ReviewsScraperService::class.java), conn, Context.BIND_AUTO_CREATE)+ }.getOrDefault(false)+ if (!bound) disconnect()+ return deferred+ }++ /** The `:reviews` process died mid-session: fail in-flight requests, rebind on the next fetch. */+ private fun onLost() {+ requests.values.forEach { it.trySend(Event.Result(null)) }+ disconnect()+ }++ private fun disconnect() {+ main.removeCallbacks(idleUnbind)+ connection?.let { runCatching { app.unbindService(it) } }+ connection = null+ remote?.complete(null)+ remote = null+ }++ private fun onReply(msg: Message) {+ val events = requests[msg.arg1] ?: return+ val json = msg.data.getString(KEY_JSON)+ when (msg.what) {+ MSG_PARTIAL -> json?.let { events.trySend(Event.Partial(it)) }+ MSG_RESULT -> events.trySend(Event.Result(json))+ }+ }++ private companion object {+ // Keep the scraper warm across back-to-back place taps, then let the process exit.+ const val IDLE_UNBIND_MS = 120_000L+ }+}
maps/src/main/java/com/vayunmathur/maps/service/ReviewsScraperService.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/service/ReviewsScraperService.kt b/maps/src/main/java/com/vayunmathur/maps/service/ReviewsScraperService.ktnew file mode 100644index 0000000000..7c2fa86574--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/service/ReviewsScraperService.kt@@ -0,0 +1,77 @@+package com.vayunmathur.maps.service++import android.app.Service+import android.content.Intent+import android.os.Bundle+import android.os.Handler+import android.os.IBinder+import android.os.Looper+import android.os.Message+import android.os.Messenger+import android.os.Process+import android.os.RemoteException+import com.vayunmathur.maps.data.google.WebReviewsFetcher+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import java.util.concurrent.ConcurrentHashMap++/**+ * Hosts [WebReviewsFetcher] in the `:reviews` process. Chromium's ~100 MB of mappings stay pinned+ * for the life of whichever process first creates a WebView, so the scraper lives here and the+ * process exits once [ReviewsScraperClient] unbinds instead of bloating the map process forever.+ */+class ReviewsScraperService : Service() {+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)+ private val fetcher by lazy { WebReviewsFetcher(applicationContext) }+ private val jobs = ConcurrentHashMap<Int, Job>()+ private val messenger = Messenger(Handler(Looper.getMainLooper()) { handle(it); true })++ override fun onBind(intent: Intent?): IBinder = messenger.binder++ override fun onDestroy() {+ scope.cancel()+ super.onDestroy()+ // Nothing else runs in this process; a cached-but-idle process would keep Chromium resident.+ Process.killProcess(Process.myPid())+ }++ private fun handle(msg: Message) {+ val id = msg.arg1+ when (msg.what) {+ MSG_FETCH -> {+ val reply = msg.replyTo ?: return+ val featureId = msg.data.getString(KEY_FEATURE_ID) ?: return+ val job = scope.launch {+ val json = fetcher.fetch(featureId, onPartial = { reply.post(MSG_PARTIAL, id, it) })+ reply.post(MSG_RESULT, id, json)+ }+ jobs[id] = job+ job.invokeOnCompletion { jobs.remove(id, job) }+ }+ MSG_CANCEL -> jobs.remove(id)?.cancel()+ }+ }++ private fun Messenger.post(what: Int, id: Int, json: String?) {+ val msg = Message.obtain(null, what, id, 0)+ msg.data = Bundle().apply { putString(KEY_JSON, json) }+ try {+ send(msg)+ } catch (_: RemoteException) {+ // Client process died; its unbind tears this service down.+ }+ }++ internal companion object {+ const val MSG_FETCH = 1+ const val MSG_CANCEL = 2+ const val MSG_PARTIAL = 3+ const val MSG_RESULT = 4+ const val KEY_FEATURE_ID = "featureId"+ const val KEY_JSON = "json"+ }+}
maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.ktindex 9dac0569b3..f99e5bd504 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt@@ -8,7 +8,7 @@ import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.data.osmPlace import com.vayunmathur.maps.data.google.GooglePoiDataSource import com.vayunmathur.maps.data.google.GooglePoiInfo-import com.vayunmathur.maps.data.google.WebReviewsFetcher+import com.vayunmathur.maps.service.ReviewsScraperClient import com.vayunmathur.maps.data.parse import com.vayunmathur.maps.data.google.PoiSection import kotlinx.coroutines.Dispatchers@@ -127,9 +127,9 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli */ private var lastPersisted: GeoPoint? = null - // Hidden-WebView reviews scraper (keyless; Google 404'd the old reviews RPC). Holds a single- // WebView built from the application Context, serialized + idle-reaped internally.- private val webReviews = WebReviewsFetcher(application)+ // Hidden-WebView reviews scraper (keyless; Google 404'd the old reviews RPC), run in the+ // `:reviews` process so Chromium never maps into this one.+ private val webReviews = ReviewsScraperClient(application) init { locationManager.startUpdates(