Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(sync): decode pulled blobs into a reusable buffer to stop mobile OOM crashes
Elian Doran8c8b67ae910c
diff --git a/apps/standalone/src/lightweight/crypto_provider.spec.ts b/apps/standalone/src/lightweight/crypto_provider.spec.tsindex 80466d015d..d0b81064b6 100644--- a/apps/standalone/src/lightweight/crypto_provider.spec.ts+++ b/apps/standalone/src/lightweight/crypto_provider.spec.ts@@ -242,4 +242,68 @@ describe("BrowserCryptoProvider base64", () => {expect(Array.from(provider.base64Decode(wrapped))).toEqual(Array.from(bytes));});});++ describe("base64DecodeInto (pooled decode for the sync blob path)", () => {+ // Force the pure-JS in-place decoder — same rationale as the fallback decoder suite.+ /* eslint-disable @typescript-eslint/no-explicit-any */+ const proto = Uint8Array.prototype as any;+ const savedSetFromBase64 = proto.setFromBase64;+ beforeEach(() => delete proto.setFromBase64);+ afterEach(() => {+ if (savedSetFromBase64 === undefined) delete proto.setFromBase64;+ else proto.setFromBase64 = savedSetFromBase64;+ });+ /* eslint-enable @typescript-eslint/no-explicit-any */++ it("decodes into the given buffer and returns the number of bytes written", () => {+ const target = new Uint8Array(16);+ const written = provider.base64DecodeInto("Zm9vYmFy", target);++ expect(written).toBe(6);+ expect(decoder.decode(target.subarray(0, written))).toBe("foobar");+ });++ it("reusing the same buffer across decodes yields correct, uncontaminated results", () => {+ const pool = new Uint8Array(32);++ const first = provider.base64DecodeInto(provider.base64Encode(new TextEncoder().encode("first-blob-content")), pool);+ expect(decoder.decode(pool.subarray(0, first))).toBe("first-blob-content");++ const second = provider.base64DecodeInto(provider.base64Encode(new TextEncoder().encode("2nd")), pool);+ expect(second).toBe(3);+ expect(decoder.decode(pool.subarray(0, second))).toBe("2nd");+ });++ it("skips whitespace and padding, writing fewer bytes than the upper bound", () => {+ const target = new Uint8Array(16);+ const written = provider.base64DecodeInto("Zm9v\nYmFy\n", target);++ expect(written).toBe(6);+ expect(decoder.decode(target.subarray(0, written))).toBe("foobar");+ });++ it("matches base64Decode output for every byte value", () => {+ const bytes = new Uint8Array(256);+ for (let i = 0; i < 256; i++) bytes[i] = i;+ const base64 = provider.base64Encode(bytes);++ const target = new Uint8Array((base64.length * 3) >> 2);+ const written = provider.base64DecodeInto(base64, target);++ expect(Array.from(target.subarray(0, written ?? 0))).toEqual(Array.from(bytes));+ });++ it("prefers the native setFromBase64 when the runtime provides it", () => {+ /* eslint-disable @typescript-eslint/no-explicit-any */+ (Uint8Array.prototype as any).setFromBase64 = function (base64: string) {+ this[0] = base64.length;+ return { read: base64.length, written: 1 };+ };+ /* eslint-enable @typescript-eslint/no-explicit-any */++ const target = new Uint8Array(4);+ expect(provider.base64DecodeInto("abcd", target)).toBe(1);+ expect(target[0]).toBe(4);+ });+ });});diff --git a/apps/standalone/src/lightweight/crypto_provider.ts b/apps/standalone/src/lightweight/crypto_provider.tsindex fcc499aaa0..f9ee391b4b 100644--- a/apps/standalone/src/lightweight/crypto_provider.ts+++ b/apps/standalone/src/lightweight/crypto_provider.ts@@ -129,6 +129,16 @@ export default class BrowserCryptoProvider implements CryptoProvider {return base64FallbackDecode(base64);}++ base64DecodeInto(base64: string, target: Uint8Array): number {+ // Native in-place decode (TC39 arraybuffer-base64, Chrome 140+) skips even the JS loop.+ const nativeTarget = target as NativeBase64Array;+ if (!FORCE_B64_FALLBACK && typeof nativeTarget.setFromBase64 === "function") {+ return nativeTarget.setFromBase64(base64).written;+ }++ return base64DecodeIntoBuffer(base64, target);+ }}// Sentinel for a char code that is not part of the base64 alphabet. Distinct from 0 so the decoder@@ -156,12 +166,18 @@ const B64_DECODE_TABLE = /* @__PURE__ */ (() => {* stays allocation-free (no sanitized copy of the whole string) and preserves the memory win.*/function base64FallbackDecode(base64: string): Uint8Array {- const len = base64.length;- const table = B64_DECODE_TABLE;-// Upper bound: every 4 alphabet symbols yield 3 bytes. Padding/whitespace only ever reduce the// real output, so this never under-allocates; the exact length is returned as a view at the end.- const bytes = new Uint8Array((len * 3) >> 2);+ const bytes = new Uint8Array((base64.length * 3) >> 2);+ const o = base64DecodeIntoBuffer(base64, bytes);++ return o === bytes.length ? bytes : bytes.subarray(0, o);+}++/** The streaming decode pass shared by the allocating and the in-place (pooled) decode paths. */+function base64DecodeIntoBuffer(base64: string, bytes: Uint8Array): number {+ const len = base64.length;+ const table = B64_DECODE_TABLE;let o = 0;let acc = 0; // bit accumulator holding up to three pending 6-bit symbols@@ -180,7 +196,7 @@ function base64FallbackDecode(base64: string): Uint8Array {}}- return o === bytes.length ? bytes : bytes.subarray(0, o);+ return o;}/**@@ -189,6 +205,7 @@ function base64FallbackDecode(base64: string): Uint8Array {*/interface NativeBase64Array extends Uint8Array {toBase64?(): string;+ setFromBase64?(base64: string): { read: number; written: number };}interface NativeBase64Constructor {fromBase64?(base64: string): Uint8Array;diff --git a/packages/trilium-core/src/services/encryption/crypto.ts b/packages/trilium-core/src/services/encryption/crypto.tsindex 3b6d561266..7becde7b98 100644--- a/packages/trilium-core/src/services/encryption/crypto.ts+++ b/packages/trilium-core/src/services/encryption/crypto.ts@@ -48,6 +48,15 @@ export interface CryptoProvider {/** Decodes a standard (RFC 4648) base64 string back into raw bytes. */base64Decode(base64: string): Uint8Array;++ /**+ * Decodes a standard (RFC 4648) base64 string into a caller-provided buffer, returning the+ * number of bytes written. Optional — implemented where avoiding a fresh allocation per+ * decode matters (the browser/WASM build, whose renderer accumulates uncollected+ * ArrayBuffer backing stores during initial sync). The target must be at least+ * `(base64.length * 3) >> 2` bytes.+ */+ base64DecodeInto?(base64: string, target: Uint8Array): number;}let crypto: CryptoProvider | null = null;diff --git a/packages/trilium-core/src/services/sync_update.spec.ts b/packages/trilium-core/src/services/sync_update.spec.tsindex 821dcd1c8d..007c84d516 100644--- a/packages/trilium-core/src/services/sync_update.spec.ts+++ b/packages/trilium-core/src/services/sync_update.spec.ts@@ -158,6 +158,25 @@ describe("sync_update service (real DB)", () => {expect(empty === "" || (empty && Buffer.from(empty as Uint8Array).length === 0)).toBeTruthy();});+ it("stores distinct content for sequential blobs of different sizes (decode pool reuse must not cross-contaminate)", () => {+ // The decode pool reuses one scratch buffer across blobs on platforms with an in-place+ // decoder. A longer blob followed by a shorter one exercises the case where stale bytes+ // from the previous decode sit beyond the new content's end in the same buffer.+ const longContent = "long-blob-content-".repeat(50);+ const shortContent = "tiny";++ apply([+ { entityChange: buildEC({ entityName: "blobs", entityId: "su_blob_pool_a" }), entity: blobRow("su_blob_pool_a", encodeBase64(longContent)) },+ { entityChange: buildEC({ entityName: "blobs", entityId: "su_blob_pool_b" }), entity: blobRow("su_blob_pool_b", encodeBase64(shortContent)) }+ ]);++ const a = getSql().getValue<Buffer | Uint8Array>("SELECT content FROM blobs WHERE blobId = ?", ["su_blob_pool_a"]);+ const b = getSql().getValue<Buffer | Uint8Array>("SELECT content FROM blobs WHERE blobId = ?", ["su_blob_pool_b"]);++ expect(Buffer.from(a ?? []).toString()).toBe(longContent);+ expect(Buffer.from(b ?? []).toString()).toBe(shortContent);+ });+it("ignores option changes that have no entity row", () => {// entityName 'options' + no row -> early return, no throw.expect(() => apply([{ entityChange: buildEC({ entityName: "options", entityId: "su_missing_option" }), entity: undefined }])).not.toThrow();diff --git a/packages/trilium-core/src/services/sync_update.ts b/packages/trilium-core/src/services/sync_update.tsindex 233ceba514..3baae2d7b2 100644--- a/packages/trilium-core/src/services/sync_update.ts+++ b/packages/trilium-core/src/services/sync_update.ts@@ -6,7 +6,7 @@ import { getSql } from "./sql/index.js";import ws from "./ws.js";import { default as eventService } from "./events.js";import entity_constructor from "../becca/entity_constructor.js";-import { decodeBase64 } from "./utils/binary.js";+import { decodeBase64, decodeBase64Into } from "./utils/binary.js";interface UpdateContext {alreadyErased: number;@@ -120,7 +120,7 @@ function preProcessContent(remoteEC: EntityChange, remoteEntityRow: EntityRow) {// "string notes". The problem is that in general, it's not possible to detect whether a blob content// is string note or note (syncs can arrive out of order)if (typeof remoteEntityRow.content === "string") {- remoteEntityRow.content = decodeBase64(remoteEntityRow.content);+ remoteEntityRow.content = decodeBlobContent(remoteEntityRow.content);if (remoteEntityRow.content.byteLength === 0) {// there seems to be a bug which causes empty buffer to be stored as NULL which is then picked up as inconsistency@@ -131,6 +131,49 @@ function preProcessContent(remoteEC: EntityChange, remoteEntityRow: EntityRow) {}}+/**+ * Ceiling of the blob decode pool size. Covers the mobile blob cap (20 MB) with headroom;+ * blobs beyond this (only possible on uncapped platforms) fall back to a one-off allocation+ * rather than pinning an oversized pool forever.+ */+const BLOB_DECODE_POOL_MAX_BYTES = 32 * 1024 * 1024;++let blobDecodePool: Uint8Array | null = null;++/**+ * Decodes a pulled blob's base64 content, reusing one grow-only scratch buffer where the+ * platform supports in-place decode (the browser/WASM build).+ *+ * The decoded bytes only need to live until the row is INSERTed a moment later — SQLite copies+ * them synchronously — but a fresh ArrayBuffer per blob proved fatal on mobile: ArrayBuffer+ * backing stores live outside the V8 heap, so during an initial sync V8 saw no heap pressure,+ * ran major GCs too rarely, and ~200 MB of dead decoded blobs routinely sat in the WebView+ * renderer (hard-capped around ~650 MB) until it was OOM-killed. Reusing the pool removes the+ * allocation churn at the source. The returned view is only valid until the next call.+ */+function decodeBlobContent(base64: string): Uint8Array {+ // Upper bound of the decoded size: every 4 base64 chars yield at most 3 bytes.+ const maxBytes = (base64.length * 3) >> 2;++ if (maxBytes > BLOB_DECODE_POOL_MAX_BYTES) {+ return decodeBase64(base64);+ }++ if (!blobDecodePool || blobDecodePool.length < maxBytes) {+ blobDecodePool = new Uint8Array(maxBytes);+ }++ const written = decodeBase64Into(base64, blobDecodePool);+ if (written === null) {+ // No in-place decoder on this platform (native builds) — plain decode. Also keeps+ // better-sqlite3 receiving the Buffer instances it expects.+ blobDecodePool = null;+ return decodeBase64(base64);+ }++ return blobDecodePool.subarray(0, written);+}+function updateNoteReordering(remoteEC: EntityChange, remoteEntityRow: EntityRow | undefined, instanceId: string) {if (!remoteEntityRow) {throw new Error(`Empty note_reordering body for: ${JSON.stringify(remoteEC)}`);diff --git a/packages/trilium-core/src/services/utils/binary.ts b/packages/trilium-core/src/services/utils/binary.tsindex 7b934c4d80..453e41bc40 100644--- a/packages/trilium-core/src/services/utils/binary.ts+++ b/packages/trilium-core/src/services/utils/binary.ts@@ -24,6 +24,19 @@ export function decodeBase64(base64: string): Uint8Array {return getCrypto().base64Decode(base64);}+/**+ * Decodes a standard base64 string into a caller-provided buffer (at least+ * `(base64.length * 3) >> 2` bytes), returning the number of bytes written — or `null` when the+ * active crypto provider has no in-place decoder, in which case the caller should fall back to+ * {@link decodeBase64}. Used to reuse one scratch buffer across many decodes instead of+ * allocating a fresh ArrayBuffer per call (see the blob decode pool in sync_update).+ */+export function decodeBase64Into(base64: string, target: Uint8Array): number | null {+ const provider = getCrypto();++ return provider.base64DecodeInto ? provider.base64DecodeInto(base64, target) : null;+}+export function decodeUtf8(stringOrBuffer: string | Uint8Array) {if (typeof stringOrBuffer === "string") {return stringOrBuffer;