Skip to content

Build your personal knowledge base with Trilium Notes

refactor(sync): drop the TriliumHttp plugin now that pulls stream through the proxy

Elian Doran6f1619e4a9bb
diff --git a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/MainActivity.java b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/MainActivity.java
index 930d7c568a..3d1635c9d1 100644
--- a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/MainActivity.java
+++ b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/MainActivity.java
@@ -19,8 +19,6 @@ public class MainActivity extends BridgeActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
- // Custom plugins must be registered before super.onCreate() initializes the bridge.
- registerPlugin(TriliumHttp.class);
super.onCreate(savedInstanceState);
// Streaming HTTP proxy for the sync worker (see TriliumWebViewClient).
getBridge().setWebViewClient(new TriliumWebViewClient(getBridge()));
diff --git a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumHttp.java b/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumHttp.java
deleted file mode 100644
index 1fa7141db4..0000000000
--- a/apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/TriliumHttp.java
+++ /dev/null
@@ -1,151 +0,0 @@
-package org.triliumnotes.trilium;
-
-import android.text.TextUtils;
-import android.util.Base64;
-
-import com.getcapacitor.JSObject;
-import com.getcapacitor.Plugin;
-import com.getcapacitor.PluginCall;
-import com.getcapacitor.PluginMethod;
-import com.getcapacitor.annotation.CapacitorPlugin;
-import com.getcapacitor.plugin.util.CapacitorHttpUrlConnection;
-
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.nio.charset.StandardCharsets;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-/**
- * Minimal HTTP plugin used by the sync worker instead of CapacitorHttp.
- *
- * CapacitorHttp force-parses any response whose Content-Type is application/json into an
- * org.json object tree and then re-serializes it into the bridge message ("backward
- * compatibility" branch in HttpRequestHandler.readData), ignoring the requested
- * responseType. For multi-megabyte sync pull responses that costs two full JSON passes and
- * hundreds of thousands of short-lived Java objects per request — measured at ~60% of a CPU
- * core for the duration of an initial sync. This plugin performs the same request via
- * CapacitorHttpUrlConnection but always returns the body as a single string (or base64 for
- * binary), leaving JSON parsing to the web worker that actually consumes it.
- */
-@CapacitorPlugin(name = "TriliumHttp")
-public class TriliumHttp extends Plugin {
-
- private static final int CONNECT_TIMEOUT_MS = 30_000;
- // The JS side enforces its own (configurable) sync timeout; this is only a backstop so a
- // dead connection cannot pin a native thread forever.
- private static final int READ_TIMEOUT_MS = 600_000;
-
- private ExecutorService executor;
-
- @Override
- public void load() {
- executor = Executors.newCachedThreadPool();
- super.load();
- }
-
- @Override
- protected void handleOnDestroy() {
- super.handleOnDestroy();
- if (executor != null) {
- executor.shutdownNow();
- }
- }
-
- @PluginMethod
- public void request(final PluginCall call) {
- if (executor == null || executor.isShutdown()) {
- call.reject("Failed to execute request - TriliumHttp plugin was shut down");
- return;
- }
-
- executor.submit(() -> {
- try {
- call.resolve(doRequest(call));
- } catch (Exception e) {
- call.reject(e.getLocalizedMessage(), e.getClass().getSimpleName(), e);
- }
- });
- }
-
- private JSObject doRequest(PluginCall call) throws Exception {
- String urlString = call.getString("url");
- if (urlString == null) {
- throw new IllegalArgumentException("url is required");
- }
- String method = call.getString("method", "GET").toUpperCase();
- JSObject headers = call.getObject("headers", new JSObject());
- String body = call.getString("data");
- String responseType = call.getString("responseType", "text");
-
- URL url = new URL(urlString);
- CapacitorHttpUrlConnection connection = new CapacitorHttpUrlConnection((HttpURLConnection) url.openConnection());
-
- try {
- connection.setAllowUserInteraction(false);
- connection.setRequestMethod(method);
- connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
- connection.setReadTimeout(READ_TIMEOUT_MS);
- connection.setRequestHeaders(headers);
- connection.setSSLSocketFactory(getBridge());
-
- if (body != null && !"GET".equals(method) && !"HEAD".equals(method)) {
- connection.setDoOutput(true);
- try (OutputStream os = connection.getHttpConnection().getOutputStream()) {
- os.write(body.getBytes(StandardCharsets.UTF_8));
- }
- }
-
- connection.connect();
-
- int status = connection.getResponseCode();
-
- JSObject responseHeaders = new JSObject();
- for (Map.Entry<String, List<String>> entry : connection.getHttpConnection().getHeaderFields().entrySet()) {
- // The status line arrives as a header with a null key — skip it.
- if (entry.getKey() != null) {
- responseHeaders.put(entry.getKey(), TextUtils.join(", ", entry.getValue()));
- }
- }
-
- InputStream stream = connection.getErrorStream();
- if (stream == null) {
- stream = connection.getInputStream();
- }
-
- String data;
- if (stream == null) {
- data = "";
- } else if ("arraybuffer".equals(responseType) || "blob".equals(responseType)) {
- data = Base64.encodeToString(readFully(stream), Base64.NO_WRAP);
- } else {
- data = new String(readFully(stream), StandardCharsets.UTF_8);
- }
-
- JSObject result = new JSObject();
- result.put("status", status);
- result.put("headers", responseHeaders);
- result.put("data", data);
- return result;
- } finally {
- connection.disconnect();
- }
- }
-
- private static byte[] readFully(InputStream stream) throws Exception {
- try (InputStream in = stream) {
- ByteArrayOutputStream out = new ByteArrayOutputStream(64 * 1024);
- byte[] buffer = new byte[64 * 1024];
- int read;
- while ((read = in.read(buffer)) != -1) {
- out.write(buffer, 0, read);
- }
- return out.toByteArray();
- }
- }
-}
diff --git a/apps/standalone/src/services/capacitor_http_handler.spec.ts b/apps/standalone/src/services/capacitor_http_handler.spec.ts
index 5836432057..fe3e2020eb 100644
--- a/apps/standalone/src/services/capacitor_http_handler.spec.ts
+++ b/apps/standalone/src/services/capacitor_http_handler.spec.ts
@@ -9,33 +9,20 @@ interface CapacitorWindow {
type RequestMock = ReturnType<typeof vi.fn>;
/**
- * Models the real bridge: `Plugins` only contains JS-registered plugins (CapacitorHttp is
- * registered by @capacitor/core itself), while native-only plugins are announced via
- * `PluginHeaders` and must be materialized through `registerPlugin()`, which also stores
- * the proxy in `Plugins`.
+ * Models the bridge surface the handler touches: the plugin transport is stock CapacitorHttp
+ * (registered by @capacitor/core itself, so it lives in `Plugins`), and `getPlatform()`
+ * gates the streaming proxy to Android.
*/
-function installCapacitor({ triliumHttp, capacitorHttp, platform }: { triliumHttp?: RequestMock; capacitorHttp?: RequestMock; platform?: string }) {
+function installCapacitor({ capacitorHttp, platform }: { capacitorHttp?: RequestMock; platform?: string } = {}) {
const plugins: Record<string, { request: RequestMock }> = {};
if (capacitorHttp) {
plugins.CapacitorHttp = { request: capacitorHttp };
}
- const registerPlugin = vi.fn((name: string) => {
- if (name === "TriliumHttp" && triliumHttp) {
- plugins.TriliumHttp = { request: triliumHttp };
- return plugins.TriliumHttp;
- }
- return undefined;
- });
-
(window as unknown as CapacitorWindow).Capacitor = {
Plugins: plugins,
- PluginHeaders: triliumHttp ? [{ name: "TriliumHttp", methods: [{ name: "request" }] }] : [],
- registerPlugin,
...(platform ? { getPlatform: () => platform } : {})
};
-
- return { registerPlugin };
}
/** The minimal Response surface the handler touches, with fetch()'s lowercase header keys. */
@@ -61,47 +48,19 @@ describe("capacitorHttpHandler", () => {
});
it("throws when no native HTTP plugin is available", async () => {
+ installCapacitor();
await expect(
capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} })
).rejects.toThrow("No native HTTP plugin is available");
});
- it("materializes TriliumHttp via registerPlugin when the native bridge announces it", async () => {
- const triliumHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "via trilium" });
- const capacitorHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "via capacitor" });
- const { registerPlugin } = installCapacitor({ triliumHttp, capacitorHttp });
-
- const result = await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
-
- expect(result.body).toBe("via trilium");
- expect(registerPlugin).toHaveBeenCalledWith("TriliumHttp");
- expect(capacitorHttp).not.toHaveBeenCalled();
-
- // Second call reuses the proxy stored in Plugins instead of re-registering
- await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
- expect(registerPlugin).toHaveBeenCalledOnce();
- expect(triliumHttp).toHaveBeenCalledTimes(2);
- });
-
- it("falls back to CapacitorHttp when the native binary lacks TriliumHttp", async () => {
- const capacitorHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "via capacitor" });
- const { registerPlugin } = installCapacitor({ capacitorHttp });
-
- const result = await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
-
- expect(result.body).toBe("via capacitor");
- // Never registers a plugin the native side did not announce — the proxy would throw.
- expect(registerPlugin).not.toHaveBeenCalled();
- });
-
- it("requests the raw text response and passes a JSON string through unchanged (no re-parse/re-stringify)", async () => {
- const rawJson = '{"ok":true}';
- const triliumHttp = vi.fn().mockResolvedValue({
+ it("forwards the request to CapacitorHttp and returns a string body unchanged", async () => {
+ const capacitorHttp = vi.fn().mockResolvedValue({
status: 200,
headers: { "Content-Type": "application/json", "X-Custom": "v" },
- data: rawJson
+ data: '{"ok":true}'
});
- installCapacitor({ triliumHttp });
+ installCapacitor({ capacitorHttp });
const result = await capacitorHttpHandler({
method: "POST",
@@ -110,7 +69,7 @@ describe("capacitorHttpHandler", () => {
body: "{}"
});
- expect(triliumHttp).toHaveBeenCalledWith({
+ expect(capacitorHttp).toHaveBeenCalledWith({
method: "POST",
url: "https://api/test",
headers: { Authorization: "token" },
@@ -119,11 +78,10 @@ describe("capacitorHttpHandler", () => {
});
expect(result.status).toBe(200);
expect(result.headers).toEqual({ "content-type": "application/json", "x-custom": "v" });
- // Passed straight through — not JSON.stringify'd back.
- expect(result.body).toBe(rawJson);
+ expect(result.body).toBe('{"ok":true}');
});
- it("still serializes object response data (CapacitorHttp fallback pre-parses JSON)", async () => {
+ it("re-serializes object response data (CapacitorHttp pre-parses JSON)", async () => {
const capacitorHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: { ok: true } });
installCapacitor({ capacitorHttp });
@@ -131,17 +89,9 @@ describe("capacitorHttpHandler", () => {
expect(result.body).toBe(JSON.stringify({ ok: true }));
});
- it("passes string response data through unchanged", async () => {
- const triliumHttp = vi.fn().mockResolvedValue({ status: 201, headers: {}, data: "plain text" });
- installCapacitor({ triliumHttp });
-
- const result = await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
- expect(result.body).toBe("plain text");
- });
-
it("passes arraybuffer responses through as the raw base64 string", async () => {
- const triliumHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "QUJD" });
- installCapacitor({ triliumHttp });
+ const capacitorHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "QUJD" });
+ installCapacitor({ capacitorHttp });
const result = await capacitorHttpHandler({
method: "GET",
@@ -154,8 +104,8 @@ describe("capacitorHttpHandler", () => {
describe("native streaming proxy", () => {
it("streams GET text requests through the proxy with tunneled headers, probing only once", async () => {
- const triliumHttp = vi.fn();
- installCapacitor({ triliumHttp, platform: "android" });
+ const capacitorHttp = vi.fn();
+ installCapacitor({ capacitorHttp, platform: "android" });
const fetchMock = vi.fn()
.mockResolvedValueOnce(fakeResponse({ headers: { "x-trilium-native-http": "1" }, body: "pong" }))
.mockResolvedValueOnce(fakeResponse({
@@ -185,7 +135,7 @@ describe("capacitorHttpHandler", () => {
// Set-Cookie is unreadable through fetch(), so it arrives renamed and is mapped back.
expect(result.headers["set-cookie"]).toBe("sid=next");
expect(result.headers["x-trilium-set-cookie"]).toBeUndefined();
- expect(triliumHttp).not.toHaveBeenCalled();
+ expect(capacitorHttp).not.toHaveBeenCalled();
// The availability probe is cached — a second request goes straight to /fetch.
await capacitorHttpHandler({ method: "GET", url, headers: {} });
@@ -193,8 +143,8 @@ describe("capacitorHttpHandler", () => {
});
it("keeps POSTs and binary requests on the plugin transport", async () => {
- const triliumHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "ok" });
- installCapacitor({ triliumHttp, platform: "android" });
+ const capacitorHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "ok" });
+ installCapacitor({ capacitorHttp, platform: "android" });
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
@@ -202,24 +152,24 @@ describe("capacitorHttpHandler", () => {
await capacitorHttpHandler({ method: "GET", url: "https://x/image", headers: {}, responseType: "arraybuffer" });
expect(fetchMock).not.toHaveBeenCalled();
- expect(triliumHttp).toHaveBeenCalledTimes(2);
+ expect(capacitorHttp).toHaveBeenCalledTimes(2);
});
it("does not probe the proxy off Android", async () => {
- const triliumHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "ok" });
- installCapacitor({ triliumHttp, platform: "ios" });
+ const capacitorHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "ok" });
+ installCapacitor({ capacitorHttp, platform: "ios" });
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
expect(fetchMock).not.toHaveBeenCalled();
- expect(triliumHttp).toHaveBeenCalledOnce();
+ expect(capacitorHttp).toHaveBeenCalledOnce();
});
it("uses the plugin transport when the ping is not answered by the interceptor (stale APK)", async () => {
- const triliumHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "ok" });
- installCapacitor({ triliumHttp, platform: "android" });
+ const capacitorHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "ok" });
+ installCapacitor({ capacitorHttp, platform: "android" });
// An older APK serves the path from the asset server — no marker header.
const fetchMock = vi.fn().mockResolvedValue(fakeResponse({ status: 404, body: "not found" }));
vi.stubGlobal("fetch", fetchMock);
@@ -229,12 +179,12 @@ describe("capacitorHttpHandler", () => {
// The failed probe is cached too — pinged once, never fetched through the proxy.
expect(fetchMock).toHaveBeenCalledTimes(1);
- expect(triliumHttp).toHaveBeenCalledTimes(2);
+ expect(capacitorHttp).toHaveBeenCalledTimes(2);
});
it("falls back to the plugin transport when the proxy reports an internal error", async () => {
- const triliumHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "via plugin" });
- installCapacitor({ triliumHttp, platform: "android" });
+ const capacitorHttp = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "via plugin" });
+ installCapacitor({ capacitorHttp, platform: "android" });
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const fetchMock = vi.fn()
.mockResolvedValueOnce(fakeResponse({ headers: { "x-trilium-native-http": "1" }, body: "pong" }))
diff --git a/apps/standalone/src/services/capacitor_http_handler.ts b/apps/standalone/src/services/capacitor_http_handler.ts
index 5d196e7170..7ed28425ad 100644
--- a/apps/standalone/src/services/capacitor_http_handler.ts
+++ b/apps/standalone/src/services/capacitor_http_handler.ts
@@ -23,24 +23,10 @@ function getHttpPlugin(): HttpPlugin {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const cap = (window as any).Capacitor;
- // Prefer the app's own TriliumHttp plugin: it always returns the body as a plain string.
- // CapacitorHttp force-parses application/json responses into a Java object tree and
- // re-serializes them into the bridge message regardless of the requested responseType
- // (the "backward compatibility" branch in HttpRequestHandler.readData), which costs two
- // full JSON passes per multi-megabyte sync response.
- //
- // Capacitor.Plugins only contains plugins that were registered from the JS side, so a
- // native-only plugin like TriliumHttp does not appear there on its own — it has to be
- // looked up via registerPlugin(), and only when the native bridge actually announced it
- // in PluginHeaders (otherwise proxy method calls would throw "not implemented").
- // registerPlugin() also stores the proxy in Capacitor.Plugins, so the first branch acts
- // as the cache on subsequent calls. The CapacitorHttp fallback keeps things working if
- // the JS bundle is ever newer than the installed native binary.
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const hasTriliumHttp = cap?.PluginHeaders?.some((header: any) => header?.name === "TriliumHttp");
- const plugin = cap?.Plugins?.TriliumHttp
- ?? (hasTriliumHttp ? cap.registerPlugin("TriliumHttp") : null)
- ?? cap?.Plugins?.CapacitorHttp;
+ // The plugin transport only carries the requests the streaming proxy can't (login/push
+ // POSTs, binary responses, and everything on iOS) — small traffic where CapacitorHttp's
+ // response marshalling overhead is irrelevant, so stock CapacitorHttp is enough.
+ const plugin = cap?.Plugins?.CapacitorHttp;
if (!plugin) {
throw new Error("No native HTTP plugin is available");
@@ -182,12 +168,12 @@ export const capacitorHttpHandler: NativeHttpHandler = async (request) => {
let body: string;
if (request.responseType === "arraybuffer") {
- // Both plugins return binary data as a base64 string — pass it through directly
+ // CapacitorHttp returns binary data as a base64 string — pass it through directly.
body = String(response.data);
} else {
- // TriliumHttp always returns a string. On the CapacitorHttp fallback, JSON responses
- // arrive pre-parsed as an object (see above) and have to be re-serialized for the
- // worker, which parses the body itself.
+ // CapacitorHttp force-parses application/json responses into an object, so it has to
+ // be re-serialized for the worker (which parses the body itself); other content types
+ // arrive as a plain string and pass straight through.
body = typeof response.data === "string"
? response.data
: JSON.stringify(response.data);