From 21a8bc83ef400d13c5f0efc6eb7fab3d533f97d7 Mon Sep 17 00:00:00 2001 From: Andrey Prokopyuk Date: Mon, 23 Nov 2026 18:44:53 +0300 Subject: [PATCH 1/2] Keep Android capture and controls responsive during recovery and provider I/O --- .../message487/StorageDeliveryDeviceTest.kt | 28 +++++ .../andre/message487/ConnectionViewModel.kt | 100 ++++++++++++++---- .../life/andre/message487/DeliveryWorker.kt | 5 + .../life/andre/message487/EventPreview.kt | 4 +- .../life/andre/message487/MessageGraph.kt | 2 +- .../message487/NotificationCaptureService.kt | 9 +- .../andre/message487/NotificationImages.kt | 20 ++-- .../main/java/life/andre/message487/Outbox.kt | 53 +++++++--- .../andre/message487/ProviderOperations.kt | 35 ++++++ .../andre/message487/SettingsTransferPanel.kt | 21 ++-- app/src/main/res/values-ru/strings.xml | 3 + app/src/main/res/values/strings.xml | 3 + .../message487/AndroidFailureRecoveryTest.kt | 28 +++++ .../java/life/andre/message487/OutboxTest.kt | 15 ++- .../andre/message487/ScreenInteractionTest.kt | 19 ++++ 15 files changed, 286 insertions(+), 59 deletions(-) create mode 100644 app/src/main/java/life/andre/message487/ProviderOperations.kt diff --git a/app/src/androidTest/java/life/andre/message487/StorageDeliveryDeviceTest.kt b/app/src/androidTest/java/life/andre/message487/StorageDeliveryDeviceTest.kt index fafbad8..cdfba5d 100644 --- a/app/src/androidTest/java/life/andre/message487/StorageDeliveryDeviceTest.kt +++ b/app/src/androidTest/java/life/andre/message487/StorageDeliveryDeviceTest.kt @@ -190,6 +190,34 @@ class StorageDeliveryDeviceTest { finally { discardImages(images); input.delete() } } + @Test fun waitingForImageProviderLeavesBitmapBudgetAvailable() { + val uri = android.net.Uri.parse("content://life.andre.message487.test.images/slow") + context.contentResolver.call(uri, "release", null, null) + val style = android.app.Notification.MessagingStyle("self").addMessage( + android.app.Notification.MessagingStyle.Message("", 1L, "sender").setData("image/png", uri)) + val notification = android.app.Notification.Builder(context, "test") + .setSmallIcon(android.R.drawable.ic_dialog_info).setStyle(style).build() + val executor = java.util.concurrent.Executors.newFixedThreadPool(2) + val signal = android.os.CancellationSignal() + val capture = executor.submit { + try { discardImages(notificationImages(context, notification, ForwardingSettings(), cancellation = signal) {}) } + catch (_: android.os.OperationCanceledException) { } + } + try { + val until = android.os.SystemClock.elapsedRealtime() + 3000 + while (context.contentResolver.call(uri, "opened", null, null)!!.getInt("count") == 0) { + check(android.os.SystemClock.elapsedRealtime() < until) { "Provider did not open the pipe" } + Thread.sleep(20) + } + executor.submit { withImageMemory { Unit } }.get(2, TimeUnit.SECONDS) + assertFalse(capture.isDone) + } finally { + signal.cancel() + context.contentResolver.call(uri, "release", null, null) + try { capture.get(5, TimeUnit.SECONDS) } finally { executor.shutdownNow() } + } + } + @Test fun blockedContentPipeExpiresAndStillCompletesTextCallback() { val uri = android.net.Uri.parse("content://life.andre.message487.test.images/slow") context.contentResolver.call(uri, "release", null, null) diff --git a/app/src/main/java/life/andre/message487/ConnectionViewModel.kt b/app/src/main/java/life/andre/message487/ConnectionViewModel.kt index 99ed353..317bd36 100644 --- a/app/src/main/java/life/andre/message487/ConnectionViewModel.kt +++ b/app/src/main/java/life/andre/message487/ConnectionViewModel.kt @@ -11,6 +11,8 @@ import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow @@ -64,21 +66,55 @@ class ConnectionViewModel @JvmOverloads constructor(application: Application, internal val previewCandidates = mutableCandidates.asStateFlow() private var previewClosed = false - fun exportDocument(uri: android.net.Uri, includeToken: Boolean) = action(R.string.settings_exported) { - val json = exportSettings(graph.settings.load(), includeToken) - require(json.toByteArray(Charsets.UTF_8).size <= MAX_SETTINGS_FILE_BYTES) - requireNotNull(getApplication().contentResolver.openOutputStream(uri, "wt")).use { - it.write(json.toByteArray(Charsets.UTF_8)) + private var transferJob: Job? = null + private val mutableTransferring = MutableStateFlow(false) + val transferring = mutableTransferring.asStateFlow() + + fun cancelTransfer() { transferJob?.cancel() } + + private fun transfer(errorNotice: Int, operation: suspend () -> Unit) { + if (mutableTransferring.value || !settingsLoaded.value) return + mutableTransferring.value = true + transferJob = viewModelScope.launch { + try { + if (withTimeoutOrNull(30_000) { operation(); true } == null) { + mutableState.value = state.value.copy(notice = R.string.document_timeout) + } + } catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled } + catch (_: Exception) { mutableState.value = state.value.copy(notice = errorNotice) } + finally { mutableTransferring.value = false } + } + } + + fun exportDocument(uri: android.net.Uri, includeToken: Boolean) = transfer(R.string.local_error) { + documentIo.providerOperation { signal -> + val bytes = exportSettings(graph.settings.load(), includeToken).toByteArray(Charsets.UTF_8) + require(bytes.size <= MAX_SETTINGS_FILE_BYTES) + withDocument(uri, "wt", signal) { asset -> + asset.createOutputStream().use { it.write(bytes) } + } } + mutableState.value = state.value.copy(notice = R.string.settings_exported) } - fun importDocument(uri: android.net.Uri) = action(failureNotice = R.string.invalid_settings_file) { - try { - val text = requireNotNull(getApplication().contentResolver.openInputStream(uri)).use(::readSettingsFile) - mutableImport.value = importSettings(text, graph.settings.load()) - } catch (error: Exception) { - // Parser/provider errors can include file contents or credentials. Do not log them. - throw java.io.IOException("Settings file could not be imported") + fun importDocument(uri: android.net.Uri) = transfer(R.string.invalid_settings_file) { + mutableImport.value = documentIo.providerOperation { signal -> + val text = withDocument(uri, "r", signal) { asset -> + asset.createInputStream().use(::readSettingsFile) + } + signal.throwIfCanceled() + importSettings(text, graph.settings.load()) + } + } + + private fun withDocument(uri: android.net.Uri, mode: String, signal: android.os.CancellationSignal, + action: (android.content.res.AssetFileDescriptor) -> T): T { + val resolver = getApplication().contentResolver + signal.throwIfCanceled() + return requireNotNull(resolver.openAssetFileDescriptor(uri, mode, signal)).use { asset -> + signal.setOnCancelListener { runCatching { asset.close() } } + try { signal.throwIfCanceled(); action(asset) } + finally { signal.setOnCancelListener(null) } } } @@ -112,15 +148,37 @@ class ConnectionViewModel @JvmOverloads constructor(application: Application, mutableCandidates.value = NotificationCaptureService.previewCandidates(settings.value.packages) } - internal fun previewNotification(key: String) = action { - val config = graph.settings.load() - val notification = NotificationCaptureService.preview(key, config) - try { replacePreview(EventPreview(graph.notificationEvent(notification, config), config, notification.imageWarning)) } - catch (error: Exception) { discardImages(notification.images); throw error } - mutableCandidates.value = null + private var previewJob: Job? = null + private val mutableLoadingPreview = MutableStateFlow(false) + internal val loadingPreview = mutableLoadingPreview.asStateFlow() + + internal fun previewNotification(key: String) { + if (previewJob?.isActive == true || state.value.busy) return + mutableLoadingPreview.value = true + previewJob = viewModelScope.launch { + try { + val completed = withTimeoutOrNull(10_000) { + val result = previewIo.providerOperation(discard = { discardImages(it.event.images) }) { signal -> + val config = graph.settings.load() + val notification = NotificationCaptureService.preview(key, config, signal) + try { EventPreview(graph.notificationEvent(notification, config), config, notification.imageWarning) } + catch (error: Exception) { discardImages(notification.images); throw error } + } + replacePreview(result) + mutableCandidates.value = null + true + } + if (completed == null) mutableState.value = state.value.copy(notice = R.string.preview_timeout) + } catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled } + catch (_: Exception) { mutableState.value = state.value.copy(notice = R.string.local_error) } + finally { mutableLoadingPreview.value = false } + } } - internal fun dismissCandidates() { mutableCandidates.value = null } + internal fun dismissCandidates() { + previewJob?.cancel() + mutableCandidates.value = null + } @Synchronized private fun replacePreview(value: EventPreview) { if (previewClosed) { discardImages(value.event.images); return } @@ -296,7 +354,7 @@ class ConnectionViewModel @JvmOverloads constructor(application: Application, } fun pause(paused: Boolean) = action { graph.settings.update { it.copy(paused = paused) } - if (!paused) graph.recover() + if (!paused) graph.scheduler.requestRecovery() } fun retry(id: String) = action { if (graph.outbox.retry(id)) { @@ -323,6 +381,8 @@ class ConnectionViewModel @JvmOverloads constructor(application: Application, } } } + fun showDocumentPickerError() { mutableState.value = state.value.copy(notice = R.string.document_picker_unavailable) } + fun showSettingsError() { mutableState.value = state.value.copy(notice = R.string.settings_unavailable) } private fun action(notice: Int? = null, failureNotice: Int = R.string.local_error, block: () -> Unit) { diff --git a/app/src/main/java/life/andre/message487/DeliveryWorker.kt b/app/src/main/java/life/andre/message487/DeliveryWorker.kt index f9e5823..844d13c 100644 --- a/app/src/main/java/life/andre/message487/DeliveryWorker.kt +++ b/app/src/main/java/life/andre/message487/DeliveryWorker.kt @@ -33,6 +33,9 @@ class DeliveryScheduler(context: Context) { return manager.enqueueUniqueWork("event-$id", if (replace) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP, work) } + fun requestRecovery() = manager.enqueueUniqueWork("outbox-recovery-now", ExistingWorkPolicy.KEEP, + OneTimeWorkRequestBuilder().build()) + fun startRecovery() { manager.enqueueUniquePeriodicWork("outbox-recovery", ExistingPeriodicWorkPolicy.KEEP, PeriodicWorkRequestBuilder(15, TimeUnit.MINUTES).build()) @@ -47,6 +50,8 @@ class DeliveryWorker(context: Context, parameters: WorkerParameters) : Coroutine if (pauseBlocksDelivery(graph.settings.load().paused, inputData.getBoolean("manual_test", false))) return@withContext Result.retry() val attempt = try { graph.outbox.beginAttempt(id) + } catch (_: PayloadMemoryException) { + return@withContext Result.retry() } catch (databaseError: android.database.SQLException) { throw databaseError } catch (error: Exception) { diff --git a/app/src/main/java/life/andre/message487/EventPreview.kt b/app/src/main/java/life/andre/message487/EventPreview.kt index 93cec28..d53ec7e 100644 --- a/app/src/main/java/life/andre/message487/EventPreview.kt +++ b/app/src/main/java/life/andre/message487/EventPreview.kt @@ -25,15 +25,17 @@ internal data class EventPreview(val event: MessageEvent, val settings: Forwardi @Composable internal fun EventPreviewDialogs(model: ConnectionViewModel, busy: Boolean, paused: Boolean) { val preview by model.preview.collectAsState() + val loading by model.loadingPreview.collectAsState() val candidates by model.previewCandidates.collectAsState() candidates?.let { notifications -> AlertDialog(onDismissRequest = { if (!busy) model.dismissCandidates() }, title = { Text(stringResource(R.string.preview_notifications)) }, text = { Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) { SupportingText(stringResource(R.string.preview_capture_hint)) + if (loading) LinearProgressIndicator(Modifier.fillMaxWidth()) if (notifications.isEmpty()) Text(stringResource(R.string.preview_no_notifications)) notifications.forEach { notification -> - OutlinedButton(onClick = { model.previewNotification(notification.key) }, enabled = !busy, + OutlinedButton(onClick = { model.previewNotification(notification.key) }, enabled = !busy && !loading, modifier = Modifier.fillMaxWidth()) { Text(notification.packageName + "\n" + notification.title, maxLines = 3) } diff --git a/app/src/main/java/life/andre/message487/MessageGraph.kt b/app/src/main/java/life/andre/message487/MessageGraph.kt index 5ffbc07..5a16611 100644 --- a/app/src/main/java/life/andre/message487/MessageGraph.kt +++ b/app/src/main/java/life/andre/message487/MessageGraph.kt @@ -48,7 +48,7 @@ class MessageGraph internal constructor(private val context: Application) { submitCapture { settings.update { it } scheduler.startRecovery() - recover() + scheduler.requestRecovery() } } diff --git a/app/src/main/java/life/andre/message487/NotificationCaptureService.kt b/app/src/main/java/life/andre/message487/NotificationCaptureService.kt index a8866e1..78adff8 100644 --- a/app/src/main/java/life/andre/message487/NotificationCaptureService.kt +++ b/app/src/main/java/life/andre/message487/NotificationCaptureService.kt @@ -30,7 +30,7 @@ class NotificationCaptureService : NotificationListenerService() { ListenerState.mutableConnected.value = true val graph = MessageGraph.get(this) graph.submitCapture { - try { graph.recover() } catch (error: Exception) { graph.captureFailed(error) } + try { graph.scheduler.requestRecovery() } catch (error: Exception) { graph.captureFailed(error) } } } @@ -106,14 +106,15 @@ class NotificationCaptureService : NotificationListenerService() { it.notification.flags and Notification.FLAG_GROUP_SUMMARY == 0 } .sortedByDescending { it.postTime }.take(20).map(::notificationContent) - internal fun preview(key: String, config: ForwardingSettings): CapturedNotification { + internal fun preview(key: String, config: ForwardingSettings, cancellation: android.os.CancellationSignal): CapturedNotification { val listener = requireNotNull(activeListener.get()) { "Notification listener disconnected" } val current = listener.getActiveNotifications(arrayOf(key)).firstOrNull() ?: error("Notification is no longer available") require(current.packageName in config.packages && current.packageName != listener.packageName) var imageWarning = false - val images = notificationImages(listener, current.notification, config, current.packageName) { imageWarning = true } - return notificationContent(current).copy(images = images, imageWarning = imageWarning) + val content = notificationContent(current) + val images = notificationImages(listener, current.notification, config, current.packageName, cancellation) { imageWarning = true } + return content.copy(images = images, imageWarning = imageWarning) } } diff --git a/app/src/main/java/life/andre/message487/NotificationImages.kt b/app/src/main/java/life/andre/message487/NotificationImages.kt index b569663..2da6e51 100644 --- a/app/src/main/java/life/andre/message487/NotificationImages.kt +++ b/app/src/main/java/life/andre/message487/NotificationImages.kt @@ -153,9 +153,9 @@ private fun decodeImageFile(file: File, maxEdge: Int, limited: Boolean): Bitmap internal fun notificationImages(context: Context, notification: Notification, settings: ForwardingSettings, sourcePackage: String = context.packageName, cancellation: CancellationSignal = CancellationSignal(), - onFailure: (Exception) -> Unit): List = withImageMemory({ cancellation.throwIfCanceled() }) { + onFailure: (Exception) -> Unit): List = try { captureNotificationImages(context, notification, settings, sourcePackage, cancellation, onFailure) - } + } catch (_: OutOfMemoryError) { throw ImageMemoryException() } @Suppress("DEPRECATION") private fun captureNotificationImages(context: Context, notification: Notification, settings: ForwardingSettings, @@ -204,10 +204,12 @@ private fun captureNotificationImages(context: Context, notification: Notificati } } } finally { cancellation.setOnCancelListener(null) } } ?: error("Image is unavailable") - val orientation = runCatching { ExifInterface(source.path).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) } - .getOrDefault(ExifInterface.ORIENTATION_NORMAL) - val bitmap = decodeImageFile(source, edge, limited) - try { add(bitmap, kind, time, orientation, presentation) } finally { bitmap.recycle() } + withImageMemory(::checkActive) { + val orientation = runCatching { ExifInterface(source.path).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) } + .getOrDefault(ExifInterface.ORIENTATION_NORMAL) + val bitmap = decodeImageFile(source, edge, limited) + try { add(bitmap, kind, time, orientation, presentation) } finally { bitmap.recycle() } + } } finally { source.delete() } } fun addDrawable(drawable: Drawable, kind: String, presentation: String = "file") { @@ -226,7 +228,7 @@ private fun captureNotificationImages(context: Context, notification: Notificati if (icon.type in setOf(IconCompat.TYPE_URI, IconCompat.TYPE_URI_ADAPTIVE_BITMAP)) addUri(icon.uri, kind, presentation = presentation) else { require(icon.type in setOf(IconCompat.TYPE_BITMAP, IconCompat.TYPE_ADAPTIVE_BITMAP, IconCompat.TYPE_RESOURCE)) { "Unsupported picture icon" } - addDrawable(icon.loadDrawable(context) ?: error("Icon unavailable"), kind, presentation) + withImageMemory(::checkActive) { addDrawable(icon.loadDrawable(context) ?: error("Icon unavailable"), kind, presentation) } } } fun attempt(block: () -> Unit) { try { checkActive(); block() } catch (error: Exception) { onFailure(error) } } @@ -254,7 +256,7 @@ private fun captureNotificationImages(context: Context, notification: Notificati else notification.getLargeIcon()?.let { addIcon(requireNotNull(IconCompat.createFromIcon(context, it)), "avatar") } ?: (extras.getParcelable(Notification.EXTRA_LARGE_ICON) as? Bitmap)?.let { add(it, "avatar") } } - if (settings.forwardAppIcons) attempt { addDrawable(context.packageManager.getApplicationIcon(sourcePackage), "app_icon") } + if (settings.forwardAppIcons) attempt { withImageMemory(::checkActive) { addDrawable(context.packageManager.getApplicationIcon(sourcePackage), "app_icon") } } var remaining = if (limited) settings.imageTotalKiB.toLong() * 1024 else Long.MAX_VALUE // Canonical order precedes count/size limits so input permutations cannot change encoding or selection. for ((candidate, _) in candidates.sortedWith(compareBy> { @@ -263,7 +265,7 @@ private fun captureNotificationImages(context: Context, notification: Notificati if (limited && candidate.kind == "attachment" && selected.count { it.kind == "attachment" } >= settings.imageMaxCount) continue if (remaining <= 0) break attempt { - val image = if (candidate.file.length() <= remaining) candidate else { + val image = if (candidate.file.length() <= remaining) candidate else withImageMemory(::checkActive) { val bitmap = decodeImageFile(candidate.file, edge, limited) try { encodeNotificationImage(bitmap, settings.imageFormat, settings.imageQuality, directory, remaining, edge, checkActive = ::checkActive).copy(kind = candidate.kind, presentation = candidate.presentation) } finally { bitmap.recycle() } diff --git a/app/src/main/java/life/andre/message487/Outbox.kt b/app/src/main/java/life/andre/message487/Outbox.kt index 0c26346..6f0b29b 100644 --- a/app/src/main/java/life/andre/message487/Outbox.kt +++ b/app/src/main/java/life/andre/message487/Outbox.kt @@ -17,6 +17,13 @@ import java.util.Base64 internal const val MAX_STORED_PAYLOAD_BYTES = 8 * 1024 * 1024 +internal class PayloadMemoryException : java.io.IOException("Insufficient memory to read queued payload") + +internal fun checkPayloadSize(size: Long, minimum: Int, available: Long) { + if (size !in minimum.toLong()..MAX_STORED_PAYLOAD_BYTES.toLong()) throw java.io.IOException("Invalid queued payload size") + if (size > available / 8) throw PayloadMemoryException() +} + private const val ENTRY_COLUMNS = "id,type,source_name,created_at,state,attempts,outcome,http_code" enum class QueueState { PENDING, SENDING, RETRY, BLOCKED, ACCEPTED, HTTP_SUCCESS } @@ -50,7 +57,7 @@ fun deliveryQueueState(result: DeliveryResult): QueueState = when (result.status } else QueueState.BLOCKED } -class Outbox(context: Context, private val cipher: PayloadCipher) : SQLiteOpenHelper(context, "outbox.db", null, 4) { +class Outbox(context: Context, private val cipher: PayloadCipher) : SQLiteOpenHelper(context, "outbox.db", null, 5) { internal val files by lazy { File(context.noBackupFilesDir, "outbox").apply { mkdirs() } } internal val previewDirectories: MutableSet = java.util.concurrent.ConcurrentHashMap.newKeySet() private val mutableRevision = MutableStateFlow(0L) @@ -65,6 +72,7 @@ class Outbox(context: Context, private val cipher: PayloadCipher) : SQLiteOpenHe db.execSQL("CREATE INDEX events_state ON events(state)") createDeduplicationTable(db) createWindowTable(db) + createPayloadIndex(db) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { @@ -81,8 +89,13 @@ class Outbox(context: Context, private val cipher: PayloadCipher) : SQLiteOpenHe } if (!hasFileColumn) db.execSQL("ALTER TABLE events ADD COLUMN payload_file TEXT") } + if (oldVersion < 5) createPayloadIndex(db) } + private fun createPayloadIndex(db: SQLiteDatabase) = db.execSQL( + "CREATE INDEX events_payload_file ON events(payload_file) WHERE payload_file IS NOT NULL" + ) + private fun createWindowTable(db: SQLiteDatabase) { db.execSQL("""CREATE TABLE message_windows ( fingerprint TEXT NOT NULL, occurred_at INTEGER NOT NULL, @@ -176,7 +189,11 @@ class Outbox(context: Context, private val cipher: PayloadCipher) : SQLiteOpenHe ).use { it.moveToFirst(); it.getInt(0) } @Synchronized - fun beginAttempt(id: String): Attempt? { + fun beginAttempt(id: String): Attempt? = try { + loadAttempt(id) + } catch (_: OutOfMemoryError) { throw PayloadMemoryException() } + + private fun loadAttempt(id: String): Attempt? { val db = writableDatabase val (entry, stored) = db.rawQuery("SELECT $ENTRY_COLUMNS,payload_file FROM events WHERE id = ?", arrayOf(id)).use { if (!it.moveToFirst()) return null @@ -185,10 +202,10 @@ class Outbox(context: Context, private val cipher: PayloadCipher) : SQLiteOpenHe entry to it.getString(it.getColumnIndexOrThrow("payload_file")) } var directory = stored?.let(::snapshotDirectory) - val envelope = try { + val envelope = run { val bytes = if (directory != null) AtomicFile(File(directory, "request.enc")).openRead().use { input -> val size = input.channel.size() - if (size !in 28..payloadReadLimit().toLong()) throw java.io.IOException("Queued metadata exceeds memory budget") + checkPayloadSize(size, 28, availableMemory()) val bytes = ByteArray(size.toInt()) var offset = 0 while (offset < bytes.size) { @@ -200,7 +217,7 @@ class Outbox(context: Context, private val cipher: PayloadCipher) : SQLiteOpenHe bytes } else readLegacyPayload(id) JSONObject(cipher.decrypt(bytes)) - } catch (_: OutOfMemoryError) { throw java.io.IOException("Queued metadata exceeds available memory") } + } val authToken = envelope.getString("auth_token") require(validAuthToken(authToken)) { "Missing queued authentication token" } if (directory == null) { @@ -320,10 +337,9 @@ class Outbox(context: Context, private val cipher: PayloadCipher) : SQLiteOpenHe } catch (error: Exception) { directory.deleteRecursively(); throw error } } - private fun payloadReadLimit(): Int { + private fun availableMemory(): Long { val runtime = Runtime.getRuntime() - val available = runtime.maxMemory() - (runtime.totalMemory() - runtime.freeMemory()) - return minOf(MAX_STORED_PAYLOAD_BYTES.toLong(), (available / 8).coerceAtLeast(0)).toInt() + return runtime.maxMemory() - (runtime.totalMemory() - runtime.freeMemory()) } private fun readLegacyPayload(id: String): ByteArray { @@ -332,7 +348,7 @@ class Outbox(context: Context, private val cipher: PayloadCipher) : SQLiteOpenHe check(it.moveToFirst() && !it.isNull(0)) { "Missing queued payload" } it.getLong(0) } - if (size !in 1..payloadReadLimit().toLong()) throw java.io.IOException("Legacy payload exceeds memory budget") + checkPayloadSize(size, 1, availableMemory()) val output = ByteArrayOutputStream(size.toInt()) var offset = 1 while (true) { @@ -347,14 +363,21 @@ class Outbox(context: Context, private val cipher: PayloadCipher) : SQLiteOpenHe } } - @Synchronized fun cleanupFiles() { - val referenced = readableDatabase.rawQuery("SELECT payload_file FROM events WHERE payload_file IS NOT NULL", null).use { - buildSet { while (it.moveToNext()) add(it.getString(0)) } - } val cutoff = System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5) - files.listFiles()?.filter { it.isDirectory && it.name !in referenced && it !in previewDirectories && it.lastModified() < cutoff } - ?.forEach { it.deleteRecursively() } + java.nio.file.Files.newDirectoryStream(files.toPath()).use { paths -> + for (path in paths) { + val dir = path.toFile() + if (dir.lastModified() >= cutoff) continue + synchronized(this) { + if (!dir.isDirectory || dir.lastModified() >= cutoff || dir in previewDirectories) return@synchronized + val referenced = readableDatabase.rawQuery( + "SELECT 1 FROM events WHERE payload_file = ? LIMIT 1", arrayOf(dir.name) + ).use { it.moveToFirst() } + if (!referenced) dir.deleteRecursively() + } + } + } } private fun changed() { mutableRevision.value += 1 } diff --git a/app/src/main/java/life/andre/message487/ProviderOperations.kt b/app/src/main/java/life/andre/message487/ProviderOperations.kt new file mode 100644 index 0000000..2063a98 --- /dev/null +++ b/app/src/main/java/life/andre/message487/ProviderOperations.kt @@ -0,0 +1,35 @@ +package life.andre.message487 + +import android.os.CancellationSignal +import java.util.concurrent.ThreadPoolExecutor +import kotlin.coroutines.EmptyCoroutineContext +import kotlin.coroutines.resumeWithException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.suspendCancellableCoroutine + +// A provider may ignore cancellation. Bound its threads and let the caller stop waiting independently. +internal val documentIo = boundedExecutor("message487-documents", 1) +internal val previewIo = boundedExecutor("message487-preview", 1) + +@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) +internal suspend fun ThreadPoolExecutor.providerOperation( + discard: (T) -> Unit = {}, + read: (CancellationSignal) -> T, +): T = suspendCancellableCoroutine { continuation -> + val signal = CancellationSignal() + val task = Runnable { + if (!continuation.isActive) return@Runnable + try { + val value = read(signal) + continuation.resume(value) { _, lost, _ -> + Dispatchers.IO.dispatch(EmptyCoroutineContext, Runnable { discard(lost) }) + } + } catch (error: Exception) { continuation.resumeWithException(error) } + } + continuation.invokeOnCancellation { + remove(task) + Dispatchers.IO.dispatch(EmptyCoroutineContext, Runnable { signal.cancel() }) + } + try { execute(task) } + catch (error: java.util.concurrent.RejectedExecutionException) { continuation.resumeWithException(error) } +} diff --git a/app/src/main/java/life/andre/message487/SettingsTransferPanel.kt b/app/src/main/java/life/andre/message487/SettingsTransferPanel.kt index 75b3495..c2b35eb 100644 --- a/app/src/main/java/life/andre/message487/SettingsTransferPanel.kt +++ b/app/src/main/java/life/andre/message487/SettingsTransferPanel.kt @@ -24,6 +24,12 @@ internal fun SettingsTransferPanel(model: ConnectionViewModel, busy: Boolean) { val import = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> if (uri != null) model.importDocument(uri) } + val transferring by model.transferring.collectAsState() + fun openDocumentPicker(launch: () -> Unit) { + try { launch() } + catch (_: android.content.ActivityNotFoundException) { model.showDocumentPickerError() } + catch (_: SecurityException) { model.showDocumentPickerError() } + } val pending by model.pendingImport.collectAsState() Panel { SectionTitle(stringResource(R.string.settings_transfer)) @@ -31,20 +37,21 @@ internal fun SettingsTransferPanel(model: ConnectionViewModel, busy: Boolean) { Surface(color = MaterialTheme.colorScheme.tertiaryContainer, shape = MaterialTheme.shapes.small) { Column(Modifier.padding(12.dp)) { Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).toggleable( - value = includeToken, enabled = !busy, role = Role.Switch, onValueChange = { includeToken = it }), + value = includeToken, enabled = !busy && !transferring, role = Role.Switch, onValueChange = { includeToken = it }), verticalAlignment = Alignment.CenterVertically) { Text(stringResource(R.string.export_include_token), Modifier.weight(1f)) - Switch(checked = includeToken, onCheckedChange = null, enabled = !busy) + Switch(checked = includeToken, onCheckedChange = null, enabled = !busy && !transferring) } Text(stringResource(if (includeToken) R.string.export_token_warning else R.string.export_without_token), style = MaterialTheme.typography.bodySmall) } } - Button(onClick = { export.launch("message487-settings.json") }, enabled = !busy, modifier = Modifier.fillMaxWidth()) { + Button(onClick = { openDocumentPicker { export.launch("message487-settings.json") } }, enabled = !busy && !transferring, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.export_settings)) } - OutlinedButton(onClick = { import.launch(arrayOf("application/json", "text/plain", "application/octet-stream")) }, - enabled = !busy, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.import_settings)) } + OutlinedButton(onClick = { openDocumentPicker { import.launch(arrayOf("application/json", "text/plain", "application/octet-stream")) } }, + enabled = !busy && !transferring, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.import_settings)) } + if (transferring) TextButton(onClick = model::cancelTransfer) { Text(stringResource(R.string.cancel)) } } pending?.let { settings -> AlertDialog(onDismissRequest = { if (!busy) model.cancelImport() }, @@ -58,7 +65,7 @@ internal fun SettingsTransferPanel(model: ConnectionViewModel, busy: Boolean) { Text(stringResource(if (settings.sms) R.string.import_sms_on else R.string.import_sms_off)) Text(stringResource(if (settings.authToken.isEmpty()) R.string.import_token_missing else R.string.import_token_present)) } }, - confirmButton = { TextButton(onClick = model::confirmImport, enabled = !busy) { Text(stringResource(R.string.apply_settings)) } }, - dismissButton = { TextButton(onClick = model::cancelImport, enabled = !busy) { Text(stringResource(R.string.cancel)) } }) + confirmButton = { TextButton(onClick = model::confirmImport, enabled = !busy && !transferring) { Text(stringResource(R.string.apply_settings)) } }, + dismissButton = { TextButton(onClick = model::cancelImport, enabled = !busy && !transferring) { Text(stringResource(R.string.cancel)) } }) } } diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 29f4d17..0a02ccf 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -249,4 +249,7 @@ Событие сохранено в очередь. Результат появится в журнале. Событие совпало с прежним и пропущено фильтром дублей. Новый запрос не добавлен в очередь. Автоматическая пересылка на паузе. Можно отправить этот тест, не возобновляя сбор и доставку сообщений из очереди. + Истекло время передачи файла. + Истекло время предпросмотра уведомления. + Не удалось открыть системный выбор файла. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 45412ac..ca60bd4 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -249,4 +249,7 @@ Event saved to the queue. Check Journal for its result. This event matches a previous capture and was skipped by the duplicate filter. No new request was queued. Automatic forwarding is paused. You can send this test without resuming automatic capture or queued message delivery. + Document transfer timed out. + Notification preview timed out. + Could not open the Android document picker. diff --git a/app/src/test/java/life/andre/message487/AndroidFailureRecoveryTest.kt b/app/src/test/java/life/andre/message487/AndroidFailureRecoveryTest.kt index 0afea5e..d04acfb 100644 --- a/app/src/test/java/life/andre/message487/AndroidFailureRecoveryTest.kt +++ b/app/src/test/java/life/andre/message487/AndroidFailureRecoveryTest.kt @@ -7,6 +7,9 @@ import java.io.IOException import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.Assert.* import org.junit.Test @@ -18,6 +21,31 @@ import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(application = Application::class, sdk = [26, 35], manifest = Config.NONE) class AndroidFailureRecoveryTest { + @Test fun `cancelled provider operation releases caller and discards a late result`() = runBlocking { + val worker = boundedExecutor("provider-test", 1) + val started = CountDownLatch(1) + val cancelled = CountDownLatch(1) + val release = CountDownLatch(1) + val discarded = CountDownLatch(1) + try { + val job = launch(start = CoroutineStart.UNDISPATCHED) { + worker.providerOperation(discard = { _: String -> discarded.countDown() }) { signal -> + signal.setOnCancelListener { cancelled.countDown() } + started.countDown() + release.await(5, TimeUnit.SECONDS) + "late result" + } + fail("Cancelled provider returned a result") + } + assertTrue(started.await(2, TimeUnit.SECONDS)) + job.cancelAndJoin() + assertTrue(cancelled.await(2, TimeUnit.SECONDS)) + release.countDown() + assertTrue(discarded.await(2, TimeUnit.SECONDS)) + } finally { release.countDown(); worker.shutdownNow() } + Unit + } + @Test fun `bounded notification backlog rejects overflow and leaves SMS independent`() { val notifications = boundedExecutor("test-notifications", 1) val sms = boundedExecutor("test-sms", 1) diff --git a/app/src/test/java/life/andre/message487/OutboxTest.kt b/app/src/test/java/life/andre/message487/OutboxTest.kt index 9a17207..f338540 100644 --- a/app/src/test/java/life/andre/message487/OutboxTest.kt +++ b/app/src/test/java/life/andre/message487/OutboxTest.kt @@ -42,6 +42,15 @@ class OutboxTest { assertTrue(outbox.pendingIds("page-6", 3).isEmpty()) } + @Test fun `temporary memory pressure can recover while invalid sizes remain unreadable`() { + assertThrows(PayloadMemoryException::class.java) { checkPayloadSize(1024, 28, 2048) } + checkPayloadSize(1024, 28, 8192) + for (invalid in listOf(27L, MAX_STORED_PAYLOAD_BYTES + 1L)) { + val failure = assertThrows(java.io.IOException::class.java) { checkPayloadSize(invalid, 28, 0) } + assertFalse(failure is PayloadMemoryException) + } + } + @Test fun `oversized legacy payload is refused before decryption and retained`() { outbox.enqueue(event("huge"), settings) outbox.writableDatabase.execSQL("UPDATE events SET payload=zeroblob(?),payload_file=NULL WHERE id='huge'", @@ -294,13 +303,14 @@ class OutboxTest { execSQL("DROP TABLE message_fingerprints") execSQL("DROP TABLE message_windows") execSQL("CREATE TABLE notifications (notification_key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL)") + execSQL("DROP INDEX events_payload_file") version = 1 } outbox.close() outbox = Outbox(context, codec) assertEquals(original.text, JSONObject(outbox.beginAttempt(original.eventId)!!.request.json).getString("text")) assertTrue(outbox.enqueue(event(), settings)) - assertEquals(4, outbox.readableDatabase.version) + assertEquals(5, outbox.readableDatabase.version) } @Test fun `version two migration preserves queued payloads and old exact history`() { @@ -311,6 +321,7 @@ class OutboxTest { outbox.writableDatabase.apply { execSQL("DROP TABLE message_windows") execSQL("INSERT INTO message_fingerprints (fingerprint) VALUES (?)", arrayOf(legacy)) + execSQL("DROP INDEX events_payload_file") version = 2 } outbox.close() @@ -320,7 +331,7 @@ class OutboxTest { val fresh = original.copy(eventId = "fresh", occurredAt = "2026-09-09T10:01:00Z") assertTrue(outbox.enqueue(fresh, settings)) assertFalse(outbox.enqueue(fresh.copy(eventId = "fresh-duplicate", occurredAt = "2026-09-09T10:01:00.500Z"), settings)) - assertEquals(4, outbox.readableDatabase.version) + assertEquals(5, outbox.readableDatabase.version) } @Test fun `invalid acknowledgement blocks automatic delivery until manual retry`() { diff --git a/app/src/test/java/life/andre/message487/ScreenInteractionTest.kt b/app/src/test/java/life/andre/message487/ScreenInteractionTest.kt index b54b650..b6e1747 100644 --- a/app/src/test/java/life/andre/message487/ScreenInteractionTest.kt +++ b/app/src/test/java/life/andre/message487/ScreenInteractionTest.kt @@ -331,6 +331,25 @@ class ScreenInteractionTest { assertNull(model.preview.value) } + @Test fun `waiting document import can be cancelled while forwarding controls stay available`() { + val release = java.util.concurrent.CountDownLatch(1) + documentIo.execute { release.await(10, java.util.concurrent.TimeUnit.SECONDS) } + try { + compose.runOnIdle { + model.importDocument(android.net.Uri.parse("content://example/settings")) + assertTrue(model.transferring.value) + assertFalse(model.state.value.busy) + model.pause(true) + model.cancelTransfer() + } + compose.waitUntil(10_000) { + compose.waitForIdle() + !model.transferring.value && !model.state.value.busy && model.settings.value.paused + } + assertNull(model.pendingImport.value) + } finally { release.countDown() } + } + @Test fun `settings import requires confirmation then pauses and preserves local identity`() { val settings = application.graph.settings val original = settings.update { it.copy(deviceId = "target-installation", authToken = "old-token") } From 613fa695a0f0004e63f78971056f65c264458e18 Mon Sep 17 00:00:00 2001 From: Andrey Prokopyuk Date: Mon, 23 Nov 2026 18:44:53 +0300 Subject: [PATCH 2/2] Delay the first Check Run update and retry transient reporting errors --- .github/workflows/test-reports.yml | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test-reports.yml b/.github/workflows/test-reports.yml index d931f96..3887f73 100644 --- a/.github/workflows/test-reports.yml +++ b/.github/workflows/test-reports.yml @@ -29,8 +29,28 @@ jobs: timeout-minutes: 5 steps: # Parse uploaded data only; never check out or run code from the tested PR. + - name: Check out the pinned JUnit reporter + uses: actions/checkout@v6 + with: + repository: dorny/test-reporter + ref: 79b4b4400dc2354b89e9dd811ef9caa9bdd4f665 # Includes retries for checks.update (upstream #867). + path: .test-reporter + persist-credentials: false + - name: Allow a new Check Run to become visible before updating it + run: | + python3 - <<'PYTHON' + from pathlib import Path + + # Upstream retries 404s but sends the first update immediately. + entry = Path(".test-reporter/dist/index.js") + source = entry.read_text() + update = "const resp = await retryOnNotFound(async () => this.octokit.rest.checks.update(" + if source.count(update) != 1: + raise SystemExit("Review the initial Check Run delay for this reporter version") + entry.write_text(source.replace(update, "await new Promise(resolve => setTimeout(resolve, 1000));\n" + update)) + PYTHON - name: Publish JUnit results in GitHub Checks - uses: dorny/test-reporter@d1b5dff021aa968b288b02285a8bf47471c5928a # v3 + uses: ./.test-reporter with: artifact: ${{ inputs.artifact || '/^junit-(.+)$/' }} name: 'Test results · $1' @@ -42,7 +62,7 @@ jobs: use-actions-summary: false - name: Add collapsible test groups to Actions Summary if: ${{ !cancelled() }} - uses: dorny/test-reporter@d1b5dff021aa968b288b02285a8bf47471c5928a # v3 + uses: ./.test-reporter with: artifact: ${{ inputs.artifact || '/^junit-(.+)$/' }} name: 'Test results · $1'