Speed up downloads by combining multiple network connections in parallel
TypeScript bandwidth-aggregationcross-platformdesktop-appdownloaderdownloadmanagerlinuxmacosmulticonnectionparallel-downloadswindows
fix: address multi-angle review of settings persistence
Anmol Kapilfd411f25cd9c
diff --git a/src/main/index.ts b/src/main/index.tsindex 52e1b2a..d84a16a 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -95,12 +95,13 @@ function createWindow(): void {app.whenReady().then(async () => {electronApp.setAppUserModelId('com.plexo.app')- // Applied before the window is created so the initial background/icon already match —- // the saved preference otherwise only takes effect on the next 'updated' event.// A failed move keeps the old file, to retry next launch — it must never stop the window opening.await migrateLegacyNetworkPreferences().catch((error) =>console.error('[plexo] failed to migrate network-preferences.json', error))++ // Applied before the window is created so the initial background/icon already match —+ // the saved preference otherwise only takes effect on the next 'updated' event.nativeTheme.themeSource = await loadThemeSource()app.on('browser-window-created', (_, window) => {diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.tsindex 16fc6d7..72262e8 100644--- a/src/main/ipc/handlers.ts+++ b/src/main/ipc/handlers.ts@@ -96,11 +96,6 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down// Answered via sendSync from the preload, which blocks the page until returnValue is set — so a// throw here must still reply (with no saved values) rather than leave the window never showing.ipcMain.on(IpcChannels.getInitialState, async (event) => {- const paths = (): Pick<InitialState, 'homeDir' | 'downloadsDir' | 'isDev'> => ({- homeDir: getHomeDir(),- downloadsDir: getDefaultDownloadsDir(),- isDev: is.dev- })try {const settings = await loadSettings()const { destinationDir } = settings@@ -116,7 +111,9 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Downnew Promise<boolean>((resolve) => setTimeout(resolve, DESTINATION_CHECK_MS, false))]))event.returnValue = {- ...paths(),+ homeDir: getHomeDir(),+ downloadsDir: getDefaultDownloadsDir(),+ isDev: is.dev,themeSource: currentThemeSource(),networkPreferences: settings.networkPreferences ?? {},streamsPerNetwork: settings.streamsPerNetwork,@@ -124,14 +121,11 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Down} satisfies InitialState} catch (error) {console.error('[plexo] failed to read initial state', error)- let fallbackPaths: ReturnType<typeof paths>- try {- fallbackPaths = paths()- } catch {- fallbackPaths = { homeDir: '', downloadsDir: '', isDev: is.dev }- }+ // No getPath() here — it may be what threw. An empty destination just keeps Start disabled.event.returnValue = {- ...fallbackPaths,+ homeDir: '',+ downloadsDir: '',+ isDev: is.dev,themeSource: currentThemeSource(),networkPreferences: {}} satisfies InitialStatediff --git a/src/main/jsonFile.ts b/src/main/jsonFile.tsindex 7ab6e34..5462629 100644--- a/src/main/jsonFile.ts+++ b/src/main/jsonFile.ts@@ -1,8 +1,17 @@import { readFile, rename, writeFile } from 'node:fs/promises'+import { setTimeout as sleep } from 'node:timers/promises'++const writeChains = new Map<string, Promise<unknown>>()/** Parsed contents, or undefined when the file is missing (first run) or corrupt. Any other- * failure (a lock, too many open files) throws, so a save never overwrites what it couldn't read. */+ * failure (a lock, too many open files) throws, so a save never overwrites what it couldn't read.+ * Waits for queued writes first, so a read right after a save (e.g. a reload) sees it. */export async function readJson(path: string): Promise<unknown> {+ await writeChains.get(path)?.catch(() => {})+ return readJsonNow(path)+}++async function readJsonNow(path: string): Promise<unknown> {try {return JSON.parse(await readFile(path, 'utf-8'))} catch (error) {@@ -13,20 +22,32 @@ export async function readJson(path: string): Promise<unknown> {}}-const writeChains = new Map<string, Promise<unknown>>()+/** On Windows, antivirus/indexers/sync clients briefly hold files open, which fails a rename+ * over them — worth a few short retries before giving up on the save. */+async function renameWithRetry(from: string, to: string): Promise<void> {+ for (let attempt = 0; ; attempt++) {+ try {+ return await rename(from, to)+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code+ if (attempt >= 4 || !['EPERM', 'EACCES', 'EBUSY'].includes(code ?? '')) throw error+ await sleep(50 * (attempt + 1))+ }+ }+}/** Read-modify-write, queued per file so two quick saves can't drop each other's change, and* written via a temp file + rename so a crash mid-write can't leave a half-written file (which- * would read back as corrupt and wipe every saved value). */-export function updateJson<T>(path: string, update: (current: unknown) => T): Promise<T> {+ * would read back as corrupt and wipe every saved value). The temp name is per process, so a+ * second running instance can't truncate it mid-rename. */+export function updateJson(path: string, update: (current: unknown) => unknown): Promise<void> {const next = (writeChains.get(path) ?? Promise.resolve()).catch(() => {}).then(async () => {- const value = update(await readJson(path))- const temporaryPath = `${path}.tmp`+ const value = update(await readJsonNow(path))+ const temporaryPath = `${path}.${process.pid}.tmp`await writeFile(temporaryPath, JSON.stringify(value, null, 2), 'utf-8')- await rename(temporaryPath, path)- return value+ await renameWithRetry(temporaryPath, path)})writeChains.set(path, next)return nextdiff --git a/src/main/settings.ts b/src/main/settings.tsindex ec4f3ef..0d48600 100644--- a/src/main/settings.ts+++ b/src/main/settings.ts@@ -63,11 +63,15 @@ function sanitizeSettings(parsed: unknown): AppSettings {export async function loadSettings(): Promise<AppSettings> {// Reading can fall back to defaults; only a save must not act on a failed read.- return sanitizeSettings(await readJson(settingsPath()).catch(() => undefined))+ try {+ return sanitizeSettings(await readJson(settingsPath()))+ } catch {+ return {}+ }}-/** Merges `patch` over what's saved and returns the result as written. */-export function saveSettings(patch: unknown): Promise<AppSettings> {+/** Merges `patch` over what's saved. */+export function saveSettings(patch: unknown): Promise<void> {return updateJson(settingsPath(), (current) =>sanitizeSettings({ ...sanitizeSettings(current), ...(isRecord(patch) ? patch : {}) }))