Test camera writer completion, failed close, binding cleanup and cache transfer

This commit is contained in:
evgeny committed 2026-10-29 13:34:26 +01:00
1 parent 4fb8daf6c7
commit 2d22f845e9
2 files changed
+97 -4

No files matched your search

@@ -20,7 +20,9 @@ internal class CameraCaptureResources : AutoCloseable {
}
private data class Binding(val provider: ProcessCameraProvider, val cases: Array<out UseCase>)
private val files = mutableMapOf<File, Capture>()
private val completedWriters = mutableSetOf<File>()
private var binding: Binding? = null
private var bindingRetiring = false
private var closed = false
private val main = Handler(Looper.getMainLooper())
private var scheduled = false
@@ -34,6 +36,7 @@ internal class CameraCaptureResources : AutoCloseable {
}
fun recording(file: File, recording: AutoCloseable) {
if (file in completedWriters) return
val capture = checkNotNull(files[file]) { "Recording has no file owner" }
if (!capture.pending) return // Синхронный Finalize уже подтвердил закрытый Recording.
capture.recording = recording
@@ -43,6 +46,7 @@ internal class CameraCaptureResources : AutoCloseable {
/** Подтверждение writer; false означает discard/close и запрещает показывать либо отправлять результат. */
fun completed(file: File): Boolean {
val capture = files[file] ?: return false
completedWriters.add(file)
capture.pending = false; capture.recording = null
val usable = !closed && !capture.discarded
LogManager.addLog("INFO", "Capture", "Writer finished path=$file usable=$usable")
@@ -73,8 +77,9 @@ internal class CameraCaptureResources : AutoCloseable {
fun unbind(): Boolean {
val current = binding ?: return true
bindingRetiring = true
try {
current.provider.unbind(*current.cases); binding = null
current.provider.unbind(*current.cases); binding = null; bindingRetiring = false
LogManager.addLog("INFO", "Capture", "Own camera use cases unbound count=${current.cases.size}")
} catch (e: Exception) {
LogManager.addLog("ERROR", "Capture", "Camera unbind failed; owner retained: $e")
@@ -90,7 +95,7 @@ internal class CameraCaptureResources : AutoCloseable {
}
private fun cleanup() {
if (closed) unbind()
if (closed || bindingRetiring) unbind()
for (capture in files.values.toList()) {
if (!capture.discarded) continue
capture.recording?.let { record ->
@@ -107,14 +112,14 @@ internal class CameraCaptureResources : AutoCloseable {
}
private fun schedule() {
val pending = (closed && binding != null) || files.values.any { it.discarded }
val pending = (bindingRetiring && binding != null) || files.values.any { it.discarded }
if (!pending) {
main.removeCallbacks(retry); scheduled = false; delayMs = 250; retained.remove(this)
return
}
retained.add(this)
// Ожидание callback не опрашиваем: owner удерживается до подтверждения writer.
val retryable = binding != null || files.values.any { it.discarded && (!it.pending || it.recording != null) }
val retryable = bindingRetiring || files.values.any { it.discarded && (!it.pending || it.recording != null) }
if (!scheduled && retryable) {
scheduled = main.postDelayed(retry, delayMs)
if (scheduled) delayMs = (delayMs * 2).coerceAtMost(30_000)
@@ -0,0 +1,88 @@
package com.utun.chat.data
import android.os.Handler
import android.os.Looper
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import java.io.File
import java.nio.file.Files
class CameraCaptureResourcesTest {
private val root = Files.createTempDirectory("utun-camera-owner").toFile()
private val owner = CameraCaptureResources()
@Before fun prepare() { Handler.rejectDelayed = false }
@After fun release() { Handler.rejectDelayed = false; owner.close(); root.deleteRecursively(); Looper.getMainLooper().advanceBy(30_000) }
private fun file(name: String = "capture.mp4") = File(root, name).also { it.writeText("camera data") }
private class Recording : AutoCloseable {
var fail = false; var closes = 0
override fun close() { closes++; check(!fail) { "Recording close rejected" } }
}
@Test fun discardedVideoWaitsForFinalizeAfterSuccessfulClose() {
val file = file(); val record = Recording()
owner.own(file); owner.recording(file, record); owner.discard(file)
assertEquals(1, record.closes); assertTrue(file.exists())
owner.close(); assertTrue(file.exists()); assertFalse(owner.completed(file)); assertFalse(file.exists())
}
@Test fun discardedPhotoIsNotDeletedUnderTheImageWriter() {
val file = file("photo.jpg")
owner.own(file); owner.close(); assertTrue(file.exists())
file.appendText("late writer output")
assertFalse(owner.completed(file)); assertFalse(file.exists())
}
@Test fun closeFailureKeepsRecordingAndRetriesIndependentlyOfFileCompletion() {
val file = file(); val record = Recording().also { it.fail = true }
owner.own(file); owner.recording(file, record); owner.close()
assertTrue(file.exists()); assertEquals(1, record.closes)
record.fail = false; Looper.getMainLooper().advanceBy(250)
assertEquals(2, record.closes); assertTrue(file.exists())
owner.completed(file); assertFalse(file.exists())
}
@Test fun lateRecordingAdoptionAfterCloseStillClosesAndWaitsForFinalize() {
val file = file(); val record = Recording()
owner.own(file); owner.close(); owner.recording(file, record)
assertEquals(1, record.closes); assertTrue(file.exists())
owner.completed(file); assertFalse(file.exists())
}
@Test fun synchronousFinalizeBeforeHandleAdoptionDoesNotResurrectTheWriter() {
val file = file(); val record = Recording()
owner.own(file); owner.close(); owner.completed(file); owner.recording(file, record)
assertFalse(file.exists()); assertEquals(0, record.closes)
}
@Test fun cacheTransferredToSenderSurvivesUiCloseAndCannotBeDiscardedTwice() {
val file = file(); owner.own(file); assertTrue(owner.completed(file)); owner.transferred(file)
owner.close(); owner.discard(file); assertTrue(file.exists())
}
@Test fun unbindFailureRetainsOnlyOwnUseCasesUntilRetryAcknowledgesCleanup() {
val provider = ProcessCameraProvider(); val own = Preview.Builder().build(); val other = Preview.Builder().build()
provider.bound.addAll(listOf(own, other)); owner.binding(provider, own)
provider.failures = setOf("unbind"); owner.close()
assertTrue(own in provider.bound); assertTrue(other in provider.bound)
provider.failures = emptySet(); Looper.getMainLooper().advanceBy(250)
assertFalse(own in provider.bound); assertTrue(other in provider.bound)
}
@Test fun failedRebindCleanupAlsoRetriesBeforeTheUiOwnerIsClosed() {
val provider = ProcessCameraProvider(); val useCase = Preview.Builder().build()
provider.bound.add(useCase); owner.binding(provider, useCase); provider.failures = setOf("unbind")
assertFalse(owner.unbind()); provider.failures = emptySet(); Looper.getMainLooper().advanceBy(250)
assertFalse(useCase in provider.bound); assertTrue(owner.unbind())
}
@Test fun rejectedRetryDoesNotLoseTheRecordingOrPreventExplicitClose() {
val file = file(); val record = Recording().also { it.fail = true }
owner.own(file); owner.recording(file, record); Handler.rejectDelayed = true; owner.close()
record.fail = false; owner.close(); assertEquals(2, record.closes); assertTrue(file.exists())
owner.completed(file); assertFalse(file.exists())
}
@Test fun failedDeletionDoesNotPreventAnotherCacheFromBeingReleased() {
val directory = File(root, "cannot-delete-yet").also { it.mkdir() }
val child = File(directory, "busy").also { it.writeText("data") }
val second = file("second.jpg")
owner.own(directory); owner.completed(directory); owner.own(second); owner.completed(second); owner.close()
assertTrue(directory.exists()); assertFalse(second.exists())
child.delete(); Looper.getMainLooper().advanceBy(250); assertFalse(directory.exists())
}
}