Skip to content

Build your personal knowledge base with Trilium Notes

fix(mobile): drop response chunks that arrive after Android closes the stream

Elian Doran2cfe4af4940c
diff --git a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/LocalRequestBroker.java b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/LocalRequestBroker.java
index dc254633d4..5661068a39 100644
--- a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/LocalRequestBroker.java
+++ b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/LocalRequestBroker.java
@@ -348,6 +348,8 @@ final class LocalRequestBroker {
private byte[] current;
private int position;
private boolean finished;
+ /** Set when WebView stops reading, for instance on a canceled media load; later chunks are dropped. */
+ private volatile boolean closed;
/** Bytes before the first queued one, which {@link #skip} passes over without reading. */
private volatile long skippablePrefix;
@@ -372,7 +374,7 @@ final class LocalRequestBroker {
}
void append(byte[] chunk) {
- if (chunk.length > 0) {
+ if (chunk.length > 0 && !closed) {
chunks.add(chunk);
}
}
@@ -425,6 +427,7 @@ final class LocalRequestBroker {
@Override
public void close() {
+ closed = true;
chunks.clear();
finished = true;
}
diff --git a/apps/mobile/android/app/src/test/java/org/triliumnotes/trilium/LocalRequestBrokerTest.java b/apps/mobile/android/app/src/test/java/org/triliumnotes/trilium/LocalRequestBrokerTest.java
index 38b6e4c87c..11158f8277 100644
--- a/apps/mobile/android/app/src/test/java/org/triliumnotes/trilium/LocalRequestBrokerTest.java
+++ b/apps/mobile/android/app/src/test/java/org/triliumnotes/trilium/LocalRequestBrokerTest.java
@@ -12,10 +12,12 @@ import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
+import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -333,6 +335,13 @@ public class LocalRequestBrokerTest {
closed.append(new byte[] { 1 });
closed.close();
assertEquals(-1, closed.read());
+
+ // WebView closes the stream when a media load is canceled, while the page keeps sending.
+ closed.append(new byte[] { 2 });
+ Field chunks = LocalRequestBroker.ChunkStream.class.getDeclaredField("chunks");
+ chunks.setAccessible(true);
+ assertTrue("a closed stream must not buffer what the page sends after it",
+ ((Collection<?>) chunks.get(closed)).isEmpty());
}
@Test