The next-generation file converter. Open source, fully local* and free forever.
fix: memory optimizations, properly abort vertd downloads, pandoc caching
JovannMCc7b9f3921d6f
diff --git a/src/lib/converters/ffmpeg/ffmpeg.svelte.ts b/src/lib/converters/ffmpeg/ffmpeg.svelte.tsindex ab19604..8186278 100644--- a/src/lib/converters/ffmpeg/ffmpeg.svelte.ts+++ b/src/lib/converters/ffmpeg/ffmpeg.svelte.ts@@ -95,9 +95,14 @@ export class FFmpegConverter extends Converter {});this.status = "ready";+ this.ffmpeg.terminate();+ this.log(+ "preloaded ffmpeg assets and released the cache instance",+ );} catch (err) {this.error(`Error loading ffmpeg: ${err}`);this.status = "error";+ this.ffmpeg.terminate();ToastManager.add({type: "error",message: m["workers.errors.ffmpeg"](),@@ -556,7 +561,9 @@ const parseChannels = (value: ConversionSettings[string]): number | null => {if (!text || text === "auto") return null;const channels = Number(text);if (!Number.isSafeInteger(channels) || channels <= 0)- throw new Error(m["workers.errors.invalid_channels"]({ channels: text }));+ throw new Error(+ m["workers.errors.invalid_channels"]({ channels: text }),+ );return channels;};@@ -576,7 +583,11 @@ const handleSpecialOutput = async (const channels = parseChannels(conversionSettings.channels) ?? 2;if (channels > 255)- throw new Error(m["workers.errors.invalid_channels"]({ channels: String(channels) }));+ throw new Error(+ m["workers.errors.invalid_channels"]({+ channels: String(channels),+ }),+ );const pcmArgs = ["-i",diff --git a/src/lib/converters/vertd/vertd.svelte.ts b/src/lib/converters/vertd/vertd.svelte.tsindex 3394b2d..ade838d 100644--- a/src/lib/converters/vertd/vertd.svelte.ts+++ b/src/lib/converters/vertd/vertd.svelte.ts@@ -288,13 +288,18 @@ const createUploadTask = async (};};-const downloadFile = async (url: string, file: VertFile): Promise<Blob> => {+interface DownloadTask {+ promise: Promise<Blob>;+ abort: () => void;+}++const downloadTask = (url: string, file: VertFile): DownloadTask => {const xhr = new XMLHttpRequest();xhr.open("GET", url, true);xhr.responseType = "blob";const customHeaders = getVertdCustomHeaders();- return new Promise((resolve, reject) => {+ const promise = new Promise<Blob>((resolve, reject) => {xhr.addEventListener("progress", (e) => {if (e.lengthComputable) {file.progress = progressEstimate(@@ -316,11 +321,20 @@ const downloadFile = async (url: string, file: VertFile): Promise<Blob> => {reject(xhr.statusText);};+ xhr.onabort = () => {+ reject(new Error("Conversion cancelled"));+ };+for (const [key, value] of Object.entries(customHeaders))xhr.setRequestHeader(key, value);xhr.send();});++ return {+ promise,+ abort: () => xhr.abort(),+ };};// prettier-ignore@@ -344,6 +358,8 @@ export class VertdConverter extends Converter {private activeUploads = new Map<string, UploadTask>();+ private activeDownloads = new Map<string, DownloadTask>();+private cancelledConversions = new Set<string>();public supportedFormats = [@@ -687,6 +703,8 @@ export class VertdConverter extends Converter {clearTimeout(connectTimeout);this.cancelledConversions.delete(input.id);this.activeUploads.delete(input.id);+ this.activeDownloads.get(input.id)?.abort();+ this.activeDownloads.delete(input.id);this.activeConversions.delete(input.id);if (ws.readyState === WebSocket.CONNECTING ||@@ -703,6 +721,7 @@ export class VertdConverter extends Converter {clearTimeout(connectTimeout);this.cancelledConversions.delete(input.id);this.activeUploads.delete(input.id);+ this.activeDownloads.delete(input.id);this.activeConversions.delete(input.id);resolve(value);};@@ -799,9 +818,15 @@ export class VertdConverter extends Converter {case "jobFinished": {this.log(`job finished for file ${input.name}`);try {+ if (settled) break;const url = `${apiUrl}/api/download/${msg.data.jobId}/${uploadRes.auth}`;this.log(`downloading from ${url}`);- const res = await downloadFile(url, input);+ const download = downloadTask(url, input);+ this.activeDownloads.set(input.id, download);+ const res = await download.promise;+ this.activeDownloads.delete(input.id);++ if (settled) return; // cancelled during download// confirm download to clean up on servertry {@@ -824,7 +849,12 @@ export class VertdConverter extends Converter {new VertFile(new File([res], input.name), to),);} catch (e) {- if (hash) this.failure(hash);+ // don't count cancellations as failures+ if (+ hash &&+ !this.cancelledConversions.has(input.id)+ )+ this.failure(hash);rejectConversion(e);} finally {ws.close();@@ -876,9 +906,16 @@ export class VertdConverter extends Converter {this.activeUploads.delete(input.id);}+ const activeDownload = this.activeDownloads.get(input.id);+ if (activeDownload) {+ this.log(`cancelling download for file ${input.name}`);+ activeDownload.abort();+ this.activeDownloads.delete(input.id);+ }+const activeConversion = this.activeConversions.get(input.id);if (!activeConversion) {- if (!activeUpload)+ if (!activeUpload && !activeDownload)this.error(`no active conversion found for file ${input.name}`);return;}diff --git a/src/lib/store/index.svelte.ts b/src/lib/store/index.svelte.tsindex 8d0ef4e..d70783e 100644--- a/src/lib/store/index.svelte.ts+++ b/src/lib/store/index.svelte.ts@@ -15,7 +15,7 @@ import { getLocale, setLocale } from "$lib/paraglide/runtime";import { m } from "$lib/paraglide/messages";import sanitizeHtml from "sanitize-html";import { ToastManager } from "$lib/util/toast.svelte";-import { GB } from "$lib/util/consts";+import { conversionConcurrency, GB } from "$lib/util/consts";import { readSettings } from "$lib/util/settings";import { formatFilename } from "$lib/util/file";import { vertdFetch } from "$lib/converters/vertd/vertd.svelte";@@ -444,8 +444,7 @@ class Files {public async convertAll() {const filenames = this.files.map((file) => file.name);const promiseFns = this.files.map((f) => () => f.convert());- const coreCount = navigator.hardwareConcurrency || 4;- const queue = new PQueue({ concurrency: coreCount });+ const queue = new PQueue({ concurrency: conversionConcurrency() });const results = await Promise.allSettled(promiseFns.map((fn) => queue.add(fn)),);diff --git a/src/lib/types/file.svelte.ts b/src/lib/types/file.svelte.tsindex e8a5cb1..b045edc 100644--- a/src/lib/types/file.svelte.ts+++ b/src/lib/types/file.svelte.ts@@ -16,6 +16,7 @@ import type {import { error, log } from "$lib/util/logger";import { readSettings } from "$lib/util/settings";import { formatFilename } from "$lib/util/file";+import { conversionConcurrency } from "$lib/util/consts";import { fileTypeFromBuffer } from "file-type";const LARGE_FILE = 2 * 1024 * 1024 * 1024; // 2GB@@ -597,7 +598,7 @@ export class VertFile {}, 100);const queue = new PQueue({- concurrency: navigator.hardwareConcurrency || 4,+ concurrency: conversionConcurrency(),});const updateProgress = () => {diff --git a/src/lib/util/consts.ts b/src/lib/util/consts.tsindex 207d701..5ff7980 100644--- a/src/lib/util/consts.ts+++ b/src/lib/util/consts.ts@@ -17,3 +17,11 @@ export const DISABLE_ALL_EXTERNAL_REQUESTS =PUB_DISABLE_ALL_EXTERNAL_REQUESTS === "true";export const GB = 1024 * 1024 * 1024;++export function conversionConcurrency(): number {+ const cores =+ typeof navigator !== "undefined"+ ? navigator.hardwareConcurrency || 4+ : 4;+ return Math.max(1, cores - 1); // leave one core free just cause+}diff --git a/src/lib/util/file.ts b/src/lib/util/file.tsindex 803013a..81c9746 100644--- a/src/lib/util/file.ts+++ b/src/lib/util/file.ts@@ -25,7 +25,7 @@ export async function extractZip(file: File): Promise<ZipEntry[]> {.filter(([filename]) => !ignoreEntry(filename)).map(([filename, data]) => ({filename,- data: new Uint8Array(data),+ data,}));log(diff --git a/static/sw.js b/static/sw.jsindex 786f84a..6b5b9d3 100644--- a/static/sw.js+++ b/static/sw.js@@ -24,6 +24,45 @@ function shouldCacheUrl(url) {);}+const REVALIDATE_URLS = WASM_FILES.filter((file) => file.startsWith("/"));++function shouldRevalidate(url) {+ const urlObj = new URL(url);+ return REVALIDATE_URLS.includes(urlObj.pathname);+}++// compare the headers nginx/browsers send for static files so we only rewrite the cache when the file changed+function cacheSignature(response) {+ return (+ response.headers.get("etag") ||+ response.headers.get("last-modified") ||+ response.headers.get("content-length") ||+ ""+ );+}++async function revalidate(request) {+ try {+ const cache = await caches.open(CACHE_NAME);+ const cached = await cache.match(request);+ if (!cached) return;++ const response = await fetch(request, { cache: "no-cache" });+ // 304 or any non-2xx means the cached copy is still current+ if (!response.ok) return;++ const signature = cacheSignature(response);+ const cachedSignature = cacheSignature(cached);++ if (!signature || signature !== cachedSignature) {+ await cache.put(request, response);+ console.log("[SW] revalidated and updated:", request.url);+ }+ } catch (err) {+ console.warn("[SW] revalidation failed:", request.url, err);+ }+}+self.addEventListener("install", (e) => {console.log("[SW] installing service worker");@@ -75,6 +114,8 @@ self.addEventListener("fetch", (e) => {}// else intercept request+ const revalidateInBackground = shouldRevalidate(request.url);+e.respondWith(caches.match(request).then((cachedResponse) => {if (cachedResponse) {@@ -121,6 +162,9 @@ self.addEventListener("fetch", (e) => {});}),);++ // refresh same-origin wasm in the background so a redeploy is picked up, even while the cached copy is served+ if (revalidateInBackground) e.waitUntil(revalidate(request));});self.addEventListener("message", (e) => {