Modern Apps git

← Modern-Apps.git

apps: stop swallowing write failures; fix two crash derefs

Commit
32dfa0645c19755d844407c0ed9cb47e51ef2d51
Author
Vayun Mathur <[email protected]>
When
2026-11-20 19:21 UTC (15 days ago)
Parents
3906f46
Silent writes found by census now log: web addBookmark/
createFolder (the history path already logged - these did not),
openassistant pending tool-call persist/delete, games-hub
achievement inserts (best-effort semantics unchanged), and the
backup transport's TRANSPORT_ERROR exits (restore failures were
invisible in the field).

Two crashes: youpipe shared-text URLs without a v parameter hit
getQueryParameter("v")!! (NPE) - now falls back to the
youtu.be/shorts/live/embed parser, then a clear
IllegalArgumentException; a null upload date hit !! - now an
early null like the sibling path. findfamily startup read
userid with !! on a set-then-get race - now regenerates via
onlyIfAbsent and re-reads, preserving the 0L sentinel its
callers already guard.

Verified: compile for all six modules; findfamily and web unit
suites pass.

Diff

backup/src/main/java/com/vayunmathur/backup/service/ConfigurableBackupTransport.kt
diff --git a/backup/src/main/java/com/vayunmathur/backup/service/ConfigurableBackupTransport.kt b/backup/src/main/java/com/vayunmathur/backup/service/ConfigurableBackupTransport.ktindex 690d69152c..f3f22d695d 100644--- a/backup/src/main/java/com/vayunmathur/backup/service/ConfigurableBackupTransport.kt+++ b/backup/src/main/java/com/vayunmathur/backup/service/ConfigurableBackupTransport.kt@@ -18,6 +18,7 @@ import com.vayunmathur.backup.data.backend.BackupRepository import com.vayunmathur.backup.domain.crypto.Crypto import com.vayunmathur.backup.platform.crypto.KeyManager import com.vayunmathur.backup.data.BackupConfig+import com.vayunmathur.library.log.Log import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import java.io.File@@ -275,7 +276,10 @@ class ConfigurableBackupTransport(private val context: Context) : BackupTranspor         return try {             val pkg = currentRestorePackage ?: return NO_MORE_DATA             if (fullRestoreInput == null) {-                val repo = repoOrNull() ?: return TRANSPORT_ERROR+                val repo = repoOrNull() ?: run {+                    Log.status(TAG, "getNextFullRestoreDataChunk: no repo for $pkg")+                    return TRANSPORT_ERROR+                }                 if (!runBlocking { repo.exists(BackupRepository.fullPath(pkg)) }) return NO_MORE_DATA                 val temp = File.createTempFile("full-restore", ".tmp", context.cacheDir)                 runBlocking {@@ -285,8 +289,14 @@ class ConfigurableBackupTransport(private val context: Context) : BackupTranspor                 fullRestoreInput = FileInputStream(temp)                 fullRestoreOutput = ParcelFileDescriptor.AutoCloseOutputStream(socket)             }-            val input = fullRestoreInput ?: return TRANSPORT_ERROR-            val out = fullRestoreOutput ?: return TRANSPORT_ERROR+            val input = fullRestoreInput ?: run {+                Log.status(TAG, "getNextFullRestoreDataChunk: restore stream not open for $pkg")+                return TRANSPORT_ERROR+            }+            val out = fullRestoreOutput ?: run {+                Log.status(TAG, "getNextFullRestoreDataChunk: restore socket not open for $pkg")+                return TRANSPORT_ERROR+            }             val buffer = ByteArray(CHUNK)             val read = input.read(buffer)             if (read < 0) {@@ -297,7 +307,8 @@ class ConfigurableBackupTransport(private val context: Context) : BackupTranspor                 out.flush()                 read             }-        } catch (_: Exception) {+        } catch (e: Exception) {+            Log.error(TAG, "getNextFullRestoreDataChunk failed for ${currentRestorePackage ?: "?"}", e)             resetFullRestore()             TRANSPORT_ERROR         }@@ -321,14 +332,18 @@ class ConfigurableBackupTransport(private val context: Context) : BackupTranspor             val backend = BackendFactory.create(context, settings) ?: return null             if (!keyManager.hasMasterKey()) return null             BackupRepository(backend, Crypto(keyManager.getMasterKey()))-        } catch (_: Exception) {+        } catch (e: Exception) {+            // Null also means "not configured yet" (no backend / no master key+            // above); an exception here is a real setup failure worth a trail.+            Log.error(TAG, "repo unavailable: backend/key setup failed", e)             null         }     }      private inline fun tryOp(block: () -> Int): Int = try {         block()-    } catch (_: Exception) {+    } catch (e: Exception) {+        Log.error(TAG, "backup transport operation failed", e)         TRANSPORT_ERROR     } @@ -366,6 +381,7 @@ class ConfigurableBackupTransport(private val context: Context) : BackupTranspor      /** Transport component name and streaming constants for [ConfigurableBackupTransport]. */     companion object {+        private const val TAG = "BackupTransport"         private const val COMPONENT = "com.vayunmathur.backup/.service.ConfigurableBackupTransportService"         private const val CHUNK = 32 * 1024         // A single current backup set; token is stable so restore can find it.
findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.ktindex 0f60f33ffd..f9a88ff38f 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt@@ -119,10 +119,17 @@ object Networking {             }             // Avoid negative IDs: server keys on ULong; generating only positive IDs keeps both             // sides consistent and makes Base26 encoding stable.-            if (dataStoreUtils.getLongAwait("userid") == null) {-                dataStoreUtils.setLong("userid", Random.nextLong(from = 1, until = Long.MAX_VALUE), true)+            userid = dataStoreUtils.getLongAwait("userid") ?: run {+                val generated = Random.nextLong(from = 1, until = Long.MAX_VALUE)+                dataStoreUtils.setLong("userid", generated, true)+                // Re-read for the onlyIfAbsent race (another writer may have won);+                // if the fresh write is not visible yet, the generated value is+                // what was just persisted โ€” never crash on a set-then-get race.+                // (0L is the not-ready sentinel callers already guard against.)+                dataStoreUtils.getLongAwait("userid") ?: generated.also {+                    Log.error(TAG, "userid re-read null after write; using generated id")+                }             }-            userid = dataStoreUtils.getLongAwait("userid")!!              if (repository.getUser(userid) == null) {                 repository.upsertUser(
openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.ktindex ab605a61ee..c253bef414 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -485,6 +485,7 @@ class InferenceService : Service() {      private suspend fun persistPending(conversationId: Long, pending: PendingToolCall) {         runCatching { pendingDao?.upsert(store.pendingToEntity(pending, conversationId)) }+            .onFailure { Log.error("InferenceService", "persistPending failed for ${pending.id}", it) }     }      /**@@ -534,6 +535,7 @@ class InferenceService : Service() {             val pending = loadPendingDomain(cancelId)             tools.removePending(cancelId)             runCatching { pendingDao?.deleteById(cancelId) }+                .onFailure { Log.error("InferenceService", "delete pending $cancelId failed", it) }             return "[Cancelled \"${pending?.name ?: "tool"}\"]"         }         if (confirmId == null) return null@@ -556,7 +558,7 @@ class InferenceService : Service() {         }         runCatching {             pendingDao?.upsert(store.pendingToEntity(pending.copy(consumed = true), conversationId))-        }+        }.onFailure { Log.error("InferenceService", "mark pending ${pending.id} consumed failed", it) }         store.upsert(             DbMessage(                 conversationId = conversationId,
sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubClient.kt
diff --git a/sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubClient.kt b/sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubClient.ktindex ffa208933f..8d4028283c 100644--- a/sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubClient.kt+++ b/sdk/games/src/main/java/com/vayunmathur/sdk/games/GameHubClient.kt@@ -5,9 +5,12 @@ package com.vayunmathur.sdk.games import kotlin.uuid.Uuid import android.content.ContentValues import android.content.Context+import com.vayunmathur.library.log.Log import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext +private const val TAG = "GameHubClient"+ /**  * Client SDK for games to report into the GameHub hub app.  * No leaderboards โ€” only game registration, achievements, and sessions.@@ -71,7 +74,9 @@ class GameHubClient(                 put(GameHubContract.AchievementDefs.TIER, def.tier.name)                 put(GameHubContract.AchievementDefs.ICON_RES_NAME, def.iconResName)             }-            try { resolver.insert(uri, values) } catch (_: Exception) { }+            try { resolver.insert(uri, values) } catch (e: Exception) {+                Log.error(TAG, "registerAchievements insert ${def.id} failed", e)+            }         }     } @@ -90,7 +95,9 @@ class GameHubClient(                 put(GameHubContract.AchievementProgressCols.UNLOCKED_AT, s.unlockedAt)                 put(GameHubContract.AchievementProgressCols.LAST_UPDATED, now)             }-            try { resolver.insert(uri, values) } catch (_: Exception) { }+            try { resolver.insert(uri, values) } catch (e: Exception) {+                Log.error(TAG, "syncAchievementProgress insert ${s.achievementId} failed", e)+            }         }     } @@ -147,7 +154,9 @@ class GameHubClient(                     if (idx >= 0) currentProgress = cursor.getInt(idx)                 }             }-        } catch (_: Exception) { }+        } catch (e: Exception) {+            Log.error(TAG, "incrementProgress query $achievementId failed", e)+        }         reportProgress(achievementId, currentProgress + delta)     } 
web/src/main/java/com/vayunmathur/web/platform/WebViewModelLibrary.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/WebViewModelLibrary.kt b/web/src/main/java/com/vayunmathur/web/platform/WebViewModelLibrary.ktindex 03c0ee3723..2c1db61b0e 100644--- a/web/src/main/java/com/vayunmathur/web/platform/WebViewModelLibrary.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/WebViewModelLibrary.kt@@ -25,6 +25,7 @@ fun WebViewModel.addBookmark(url: String, title: String, folderId: Long? = null)     scope.launch {         val entry = Bookmark(url = url, title = title, folderId = folderId)         runCatching { repository.bookmarks.upsert(entry) }+            .onFailure { Log.error(TAG, "addBookmark", it) }     } } @@ -33,7 +34,10 @@ fun WebViewModel.removeBookmark(bookmark: Bookmark) { }  fun WebViewModel.createFolder(name: String) {-    scope.launch { runCatching { repository.bookmarks.upsertFolder(BookmarkFolder(name = name)) } }+    scope.launch {+        runCatching { repository.bookmarks.upsertFolder(BookmarkFolder(name = name)) }+            .onFailure { Log.error(TAG, "createFolder", it) }+    } }  fun WebViewModel.deleteFolder(folder: BookmarkFolder) {
youpipe/src/main/java/com/vayunmathur/youpipe/network/Extractor.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/network/Extractor.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/network/Extractor.ktindex 2678eb5aba..2d1be0e63e 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/network/Extractor.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/network/Extractor.kt@@ -53,8 +53,17 @@ fun StreamInfoItem.toVideoInfo(): VideoInfo? { }  fun videoURLtoID(url: String): Long {-    val encoded = url.toUri().getQueryParameter("v")!!-    return ByteBuffer.wrap(Base64.UrlSafe.withPadding(Base64.PaddingOption.ABSENT).decode(encoded)).long+    // Watch URLs carry the id in `v`; shared URLs often don't (youtu.be/<id>,+    // /shorts/<id>, /live/<id>, /embed/<id>) โ€” fall back to those forms instead+    // of crashing on a missing query parameter. A URL with no id anywhere is a+    // caller bug / malformed input, so fail with a clear exception: every caller+    // either pre-checks for a watch link or wraps this in runCatching/per-entry+    // try-catch (see toVideoInfo, importTakeout*History, YouPipeViewModel).+    url.toUri().getQueryParameter("v")?.takeIf { it.isNotBlank() }?.let { encoded ->+        return ByteBuffer.wrap(Base64.UrlSafe.withPadding(Base64.PaddingOption.ABSENT).decode(encoded)).long+    }+    parseSharedVideoId(url)?.let { return it }+    throw IllegalArgumentException("no video id in url: $url") }  fun channelURLtoID(url: String): String {@@ -92,16 +101,18 @@ fun channelIDtoURL(id: String): String {     } } -suspend fun getVideoInfo(videoId: Long): VideoInfo = coroutineScope {+/** Full [VideoInfo] for one video, or null if it has no upload date (same rule as [toVideoInfo]). */+suspend fun getVideoInfo(videoId: Long): VideoInfo? = coroutineScope {     val idString = decodeVideoID(videoId)     val ex = ServiceList.YouTube.getStreamExtractor("https://www.youtube.com/watch?v=$idString")     ex.fetchPage()+    val uploadDate = ex.getUploadDate() ?: return@coroutineScope null     VideoInfo(         ex.getName().decodeHtml(),         videoId,         ex.getLength(),         ex.getViewCount(),-        ex.getUploadDate()!!.instant.toKotlinInstant(),+        uploadDate.instant.toKotlinInstant(),         ex.getThumbnails().first().url,         ex.getUploaderName().decodeHtml()     )