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
refactor(server): extract asBuffer into a shared byte helper
Elian Doran080e038c8f91
diff --git a/apps/server/src/services/binary.spec.ts b/apps/server/src/services/binary.spec.tsnew file mode 100644index 0000000000..39884e5d5f--- /dev/null+++ b/apps/server/src/services/binary.spec.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from "vitest";++import { asBuffer } from "./binary.js";++describe("asBuffer", () => {+ it("returns a Buffer holding the same bytes", () => {+ const bytes = Uint8Array.from([1, 2, 3, 254, 255]);++ const result = asBuffer(bytes);++ expect(Buffer.isBuffer(result)).toBe(true);+ expect([...result]).toEqual([1, 2, 3, 254, 255]);+ });++ it("shares memory with the source rather than copying it", () => {+ const bytes = Uint8Array.from([1, 2, 3]);++ const result = asBuffer(bytes);+ bytes[0] = 42;++ // A copy would still read 1 here. The whole point of this helper is that it does not copy.+ expect(result[0]).toBe(42);+ });++ it("scopes the view to a subarray, not its backing buffer", () => {+ const backing = Uint8Array.from([1, 2, 3, 4, 5, 6]);+ const slice = backing.subarray(2, 5);++ const result = asBuffer(slice);++ expect(result.byteLength).toBe(3);+ expect([...result]).toEqual([3, 4, 5]);+ });++ it("passes a Buffer through as it came", () => {+ const buffer = Buffer.from([7, 8, 9]);++ expect(asBuffer(buffer)).toBe(buffer);+ });++ it("handles an empty input", () => {+ const result = asBuffer(new Uint8Array(0));++ expect(Buffer.isBuffer(result)).toBe(true);+ expect(result.byteLength).toBe(0);+ });+});diff --git a/apps/server/src/services/binary.ts b/apps/server/src/services/binary.tsnew file mode 100644index 0000000000..3e942ce1ef--- /dev/null+++ b/apps/server/src/services/binary.ts@@ -0,0 +1,28 @@+/**+ * Byte helpers for server-side code, where `Buffer` is always available.+ *+ * Deliberately dependency-free. The image codec reaches for this, and the codec is loaded by a worker+ * that must not have to stand up half a server to host it — so nothing here may import Trilium.+ *+ * The browser-facing counterparts live in `@triliumnext/core`'s `services/utils/binary.ts`, which+ * cannot offer these: standalone runs core in a worker with no `Buffer` to convert to.+ */++/**+ * The same bytes as a `Buffer`, over the same memory.+ *+ * `Buffer.from(uint8Array)` duplicates what it is given, and the libraries this server hands bytes to+ * each want a `Buffer` — so an image was being copied whole several times on its way through, for+ * readers that only ever read. On a run over a tree that is a second copy of every photograph in it,+ * allocated and thrown away again, which costs more in collection than the copying does outright.+ *+ * `byteOffset`/`byteLength` keep the view scoped to the caller's slice, never the surrounding backing+ * buffer. A `Buffer` is already one and is returned as it came.+ */+export function asBuffer(bytes: Uint8Array): Buffer {+ if (Buffer.isBuffer(bytes)) {+ return bytes;+ }++ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);+}diff --git a/apps/server/src/services/image_codec.ts b/apps/server/src/services/image_codec.tsindex 63c7489506..7a33e03117 100644--- a/apps/server/src/services/image_codec.ts+++ b/apps/server/src/services/image_codec.ts@@ -20,6 +20,8 @@ import isSvg from "is-svg";import { Jimp } from "jimp";import * as UPNG from "upng-js";+import { asBuffer } from "./binary.js";+/*** Where a line the codec wants written goes. Dropped by default, since nothing here needs it.*@@ -210,18 +212,6 @@ export function decodeImage(buffer: Uint8Array, budgetMb: number = DECODE_MEMORYreturn Jimp.fromBuffer(asBuffer(buffer), { "image/jpeg": { maxMemoryUsageInMB: budgetMb } });}-/**- * The same bytes as a `Buffer`, over the same memory.- *- * `Buffer.from(uint8Array)` duplicates what it is given, and the libraries below each want one —- * so an image was being copied whole several times on its way through, for readers that only ever- * read. On a run over a tree that is a second copy of every photograph in it, allocated and thrown- * away again, which costs more in collection than the copying does outright.- */-export function asBuffer(bytes: Uint8Array): Buffer {- return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);-}-/** What {@link decodeImage} hands back, for the helpers that work on a decoded image. */type DecodedImage = Awaited<ReturnType<typeof decodeImage>>;diff --git a/apps/server/src/services/ocr/ocr_service.ts b/apps/server/src/services/ocr/ocr_service.tsindex 6a21985f65..ce9581a006 100644--- a/apps/server/src/services/ocr/ocr_service.ts+++ b/apps/server/src/services/ocr/ocr_service.ts@@ -1,7 +1,7 @@import { getTesseractCode } from '@triliumnext/commons';import { becca, blob as blobService, entity_changes as entityChangesService, getLog, options } from '@triliumnext/core';-import { asBuffer } from '../image_codec.js';+import { asBuffer } from '../binary.js';import sql from '../sql.js';import { FileProcessor } from './processors/file_processor.js';import { ImageProcessor } from './processors/image_processor.js';diff --git a/apps/server/src/zip_provider.ts b/apps/server/src/zip_provider.tsindex 2e6c943d31..f7c9d269b7 100644--- a/apps/server/src/zip_provider.ts+++ b/apps/server/src/zip_provider.ts@@ -4,6 +4,8 @@ import fs from "fs";import type { Stream } from "stream";import * as yauzl from "yauzl";+import { asBuffer } from "./services/binary.js";+class NodejsZipArchive implements ZipArchive {readonly #archive: ArchiverZip;// Byte sizes of appended entries not yet written out, in FIFO order.@@ -55,11 +57,8 @@ class NodejsZipArchive implements ZipArchive {if (this.#error) {throw this.#error;}- // Wrap the Uint8Array in a Buffer view sharing the same memory rather- // than copying it (Buffer.from(uint8array) would allocate a full copy).- // byteOffset/byteLength keep the view scoped to this slice, never the- // surrounding backing buffer. archiver only reads, so sharing is safe.- const payload = typeof content === "string" ? content : Buffer.from(content.buffer, content.byteOffset, content.byteLength);+ // A Buffer view over the same memory rather than a copy; archiver only reads, so sharing is safe.+ const payload = typeof content === "string" ? content : asBuffer(content);const size = typeof content === "string" ? Buffer.byteLength(content) : content.byteLength;this.#pendingSizes.push(size);this.#queuedBytes += size;@@ -103,8 +102,7 @@ async function openZip(source: ZipSource) {// Wrap the bytes in a Buffer *view* (no copy); fall through to fromBuffer. A `path` source is// opened straight from disk so a multi-GB zip is never held in memory (and dodges fs.readFile's// ~2 GiB ceiling) — yauzl reads the central directory and each entry on demand from the fd.- const buf = Buffer.isBuffer(source) ? source : Buffer.from(source.buffer, source.byteOffset, source.byteLength);- return yauzl.fromBufferPromise(buf, options);+ return yauzl.fromBufferPromise(asBuffer(source), options);}return yauzl.openPromise(source.path, options);}