Startup Performance tuning

This commit is contained in:
2026-10-18 20:17:28 +03:00
parent e63b1c5c8e
commit 640fca8a70
12 changed files with 83 additions and 25 deletions
+2 -2
View File
@@ -171,7 +171,7 @@ IPC modules should validate and translate renderer requests, then call services.
- Electron Builder and the desktop Actions artifact name derive from `package.json`. - Electron Builder and the desktop Actions artifact name derive from `package.json`.
- Android `versionName` derives from the same package version. Its current `versionCode` mapping is `major * 10000 + minor * 100 + patch`; keep minor and patch below 100, and revise the mapping before reaching that boundary to avoid collisions. - Android `versionName` derives from the same package version. Its current `versionCode` mapping is `major * 10000 + minor * 100 + patch`; keep minor and patch below 100, and revise the mapping before reaching that boundary to avoid collisions.
- `scripts/build-all.ps1` uses the package version for APK naming. Before a release, bump once with `npm run bump:build`, verify the lockfile and computed Android version code, and build every target without another bump. - `scripts/build-all.ps1` uses the package version for APK naming. Before a release, bump once with `npm run bump:build`, verify the lockfile and computed Android version code, and build every target without another bump.
- Latest version check: `package.json` and both lockfile version fields are `0.4.39`; Android derives `versionName 0.4.39` and `versionCode 439`. OAuth2 desktop support is in this source version; the artifact still needs to be built and verified. - Latest version check: `package.json` and both lockfile version fields are `0.5.0`; Android derives `versionName 0.5.0` and `versionCode 500`. OAuth2 desktop support is in this source version; the artifact still needs to be built and verified.
## Progress log ## Progress log
@@ -212,7 +212,7 @@ IPC modules should validate and translate renderer requests, then call services.
- Step 6 at version `0.4.36` consolidates the HTML sanitization and remote-image policy API under `window.epMailFeatures.contentSecurity`. - Step 6 at version `0.4.36` consolidates the HTML sanitization and remote-image policy API under `window.epMailFeatures.contentSecurity`.
- Step 7 at version `0.4.37` adds focused sanitizer coverage for dangerous DOM nodes/attributes and verifies that remote images remain data-only pending explicit loading. - Step 7 at version `0.4.37` adds focused sanitizer coverage for dangerous DOM nodes/attributes and verifies that remote images remain data-only pending explicit loading.
- Step 7 at version `0.4.38` tests main-process native confirmation for OpenPGP key replacement and trust elevation; cancellation must not mutate stored key state. - Step 7 at version `0.4.38` tests main-process native confirmation for OpenPGP key replacement and trust elevation; cancellation must not mutate stored key state.
- Desktop OAuth2 support for Google and Microsoft was added after the `0.4.38` artifact; `0.4.39` uses configurable OAuth client IDs, PKCE, encrypted token persistence, and provider-fixed mail endpoints. - Desktop OAuth2 support for Google and Microsoft was added after the `0.4.38` artifact; `0.5.0` uses configurable OAuth client IDs, PKCE, encrypted token persistence, and provider-fixed mail endpoints.
- Step 7 coverage status: sanitizer/remote-image, DAV reference/ETag, and OpenPGP trust/replacement paths have regression coverage. A direct plaintext-send IPC confirmation test and the documented human/security review remain open. - Step 7 coverage status: sanitizer/remote-image, DAV reference/ETag, and OpenPGP trust/replacement paths have regression coverage. A direct plaintext-send IPC confirmation test and the documented human/security review remain open.
- Renderer modularization step 6 is complete: feature modules are scoped, legacy renderer-state aliases are removed, public cross-feature interfaces are namespaced, and root/`www/` parity plus classic-script ordering are tested. Native ES module conversion remains a deferred follow-up. - Renderer modularization step 6 is complete: feature modules are scoped, legacy renderer-state aliases are removed, public cross-feature interfaces are namespaced, and root/`www/` parity plus classic-script ordering are tested. Native ES module conversion remains a deferred follow-up.
- The current IPC/DAV validation changes pass the full suite: 108 tests. - The current IPC/DAV validation changes pass the full suite: 108 tests.
+45 -11
View File
@@ -1,3 +1,12 @@
const startupTraceEnabled = process.env.EP_MAIL_STARTUP_TRACE === '1';
const startupTraceStartedAt = process.hrtime.bigint();
function traceStartup(message) {
if (!startupTraceEnabled) return;
const elapsed = Number(process.hrtime.bigint() - startupTraceStartedAt) / 1e6;
console.info(`[ep-mail startup +${elapsed.toFixed(1)}ms] ${message}`);
}
traceStartup('main process entered');
const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog, Notification, powerMonitor, Menu, Tray, nativeImage } = require('electron'); const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog, Notification, powerMonitor, Menu, Tray, nativeImage } = require('electron');
const fsSync = require('node:fs'); const fsSync = require('node:fs');
const path = require('node:path'); const path = require('node:path');
@@ -82,10 +91,18 @@ let windowsAppIcon = null;
let tray = null; let tray = null;
function registerIpcHandler(channel, handler) { function registerIpcHandler(channel, handler) {
return ipcMainHandle(channel, (event, ...args) => { return ipcMainHandle(channel, async (event, ...args) => {
assertTrustedIpcSender(event, applicationHtmlPath); const startedAt = startupTraceEnabled ? process.hrtime.bigint() : null;
validateIpcArguments(channel, args); try {
return handler(event, ...args); assertTrustedIpcSender(event, applicationHtmlPath);
validateIpcArguments(channel, args);
return await handler(event, ...args);
} finally {
if (startedAt) {
const elapsed = Number(process.hrtime.bigint() - startedAt) / 1e6;
traceStartup(`${channel} IPC completed in ${elapsed.toFixed(1)}ms`);
}
}
}); });
} }
@@ -502,8 +519,10 @@ registerDavIpcHandlers({
randomUUID, randomUUID,
assertDavObjectReference assertDavObjectReference
}); });
traceStartup('main services and IPC handlers initialized');
function createWindow() { function createWindow() {
traceStartup('creating BrowserWindow');
const window = new BrowserWindow({ const window = new BrowserWindow({
width: 1440, width: 1440,
height: 920, height: 920,
@@ -522,9 +541,17 @@ function createWindow() {
} }
}); });
window.once('ready-to-show', () => window.show()); window.webContents.on('dom-ready', () => traceStartup('renderer DOM ready'));
window.webContents.on('did-finish-load', () => traceStartup('renderer load complete'));
window.once('ready-to-show', () => {
traceStartup('BrowserWindow ready-to-show');
window.show();
});
window.loadFile(path.join(__dirname, '..', 'index.html')); window.loadFile(path.join(__dirname, '..', 'index.html')).catch(error => {
traceStartup(`loadFile failed: ${error.message}`);
console.error('Could not load the application window:', error);
});
window.webContents.setWindowOpenHandler(() => { window.webContents.setWindowOpenHandler(() => {
return { action: 'deny' }; return { action: 'deny' };
}); });
@@ -596,22 +623,29 @@ function repairWindowsStartMenuShortcut() {
} }
app.whenReady().then(() => { app.whenReady().then(() => {
traceStartup('Electron app.whenReady');
app.setAppUserModelId(windowsAppUserModelId); app.setAppUserModelId(windowsAppUserModelId);
if (process.platform === 'win32') { if (process.platform === 'win32') {
windowsAppIcon = nativeImage.createFromPath(path.join(__dirname, '..', 'icon.ico')); windowsAppIcon = nativeImage.createFromPath(path.join(__dirname, '..', 'icon.ico'));
if (windowsAppIcon.isEmpty()) throw new Error('Could not load the Windows application icon.'); if (windowsAppIcon.isEmpty()) throw new Error('Could not load the Windows application icon.');
repairWindowsStartMenuShortcut();
createWindowsTray();
} }
createWindow(); const mainWindow = createWindow();
mainWindow.once('ready-to-show', () => {
if (process.platform === 'win32') {
repairWindowsStartMenuShortcut();
createWindowsTray();
}
void checkSnoozeReminders();
const startupSyncTimer = setTimeout(() => requestBackgroundSync(), 3000);
startupSyncTimer.unref();
traceStartup('post-first-frame work started; background sync scheduled');
});
const syncTimer = setInterval(() => { const syncTimer = setInterval(() => {
void runBackgroundSync(true).catch(error => console.error('Periodic mail sync failed:', error)); void runBackgroundSync(true).catch(error => console.error('Periodic mail sync failed:', error));
}, backgroundSyncIntervalMs); }, backgroundSyncIntervalMs);
syncTimer.unref(); syncTimer.unref();
const snoozeTimer = setInterval(() => void checkSnoozeReminders(), snoozeCheckIntervalMs); const snoozeTimer = setInterval(() => void checkSnoozeReminders(), snoozeCheckIntervalMs);
snoozeTimer.unref(); snoozeTimer.unref();
void checkSnoozeReminders();
requestBackgroundSync();
powerMonitor.on('suspend', () => { powerMonitor.on('suspend', () => {
idleWatcherManager.stopAll(); idleWatcherManager.stopAll();
}); });
+1 -1
View File
@@ -67,7 +67,7 @@
<script src="renderer-state.js"></script> <script src="renderer-state.js"></script>
<script src="mail-content-security.js"></script> <script src="mail-content-security.js"></script>
<script src="app.js"></script> <script src="app.js"></script>
<script src="platform-bridge.js"></script> <script src="platform-bridge-loader.js"></script>
<script src="renderer-mail-api.js"></script> <script src="renderer-mail-api.js"></script>
<script src="mail-ui.js"></script> <script src="mail-ui.js"></script>
<script src="productivity.js"></script> <script src="productivity.js"></script>
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.4.39", "version": "0.5.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ep-mail", "name": "ep-mail",
"version": "0.4.39", "version": "0.5.0",
"dependencies": { "dependencies": {
"@capacitor/android": "^8.5.2", "@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2", "@capacitor/core": "^8.5.2",
+2 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.4.39", "version": "0.5.0",
"private": true, "private": true,
"description": "Eternity Project mail client", "description": "Eternity Project mail client",
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client", "homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
@@ -40,6 +40,7 @@
"files": [ "files": [
"index.html", "index.html",
"platform-bridge.js", "platform-bridge.js",
"platform-bridge-loader.js",
"styles.css", "styles.css",
"branding.css", "branding.css",
"renderer-state.js", "renderer-state.js",
+5
View File
@@ -0,0 +1,5 @@
(() => {
// Electron's preload already provides the desktop bridge; avoid parsing the Capacitor bundle there.
if (window.daybreakMail) return;
document.write('<script src="platform-bridge.js"><\/script>');
})();
+1
View File
@@ -8,6 +8,7 @@ const assets = [
'index.html', 'index.html',
'styles.css', 'styles.css',
'branding.css', 'branding.css',
'platform-bridge-loader.js',
'renderer-state.js', 'renderer-state.js',
'mail-content-security.js', 'mail-content-security.js',
'renderer-mail-api.js', 'renderer-mail-api.js',
+2 -2
View File
@@ -1,5 +1,5 @@
const CACHE='ep-mail-v11'; const CACHE='ep-mail-v12';
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)))); self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))}); self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
+15 -3
View File
@@ -13,15 +13,26 @@ test('renderer bootstrap loads shared state and mail security before the applica
const contentSecurity = html.indexOf('<script src="mail-content-security.js"></script>'); const contentSecurity = html.indexOf('<script src="mail-content-security.js"></script>');
const mailApi = html.indexOf('<script src="renderer-mail-api.js"></script>'); const mailApi = html.indexOf('<script src="renderer-mail-api.js"></script>');
const app = html.indexOf('<script src="app.js"></script>'); const app = html.indexOf('<script src="app.js"></script>');
const platformBridge = html.indexOf('<script src="platform-bridge.js"></script>'); const platformBridgeLoader = html.indexOf('<script src="platform-bridge-loader.js"></script>');
const mailUi = html.indexOf('<script src="mail-ui.js"></script>'); const mailUi = html.indexOf('<script src="mail-ui.js"></script>');
const productivity = html.indexOf('<script src="productivity.js"></script>'); const productivity = html.indexOf('<script src="productivity.js"></script>');
const davUi = html.indexOf('<script src="dav-ui.js"></script>'); const davUi = html.indexOf('<script src="dav-ui.js"></script>');
const accountUi = html.indexOf('<script src="account-ui.js"></script>'); const accountUi = html.indexOf('<script src="account-ui.js"></script>');
assert.ok(state >= 0 && contentSecurity > state && app > contentSecurity && mailApi > platformBridge && mailUi > mailApi); assert.ok(state >= 0 && contentSecurity > state && app > contentSecurity && platformBridgeLoader > app && mailApi > platformBridgeLoader && mailUi > mailApi);
assert.ok(productivity > mailUi && davUi > productivity && accountUi > davUi); assert.ok(productivity > mailUi && davUi > productivity && accountUi > davUi);
}); });
test('desktop skips the generated Capacitor bridge while web/Android bootstrap loads it synchronously', () => {
const source = read('platform-bridge-loader.js');
let desktopWrite = false;
vm.runInNewContext(source, { window: { daybreakMail: {} }, document: { write() { desktopWrite = true; } } });
assert.equal(desktopWrite, false);
let written = '';
vm.runInNewContext(source, { window: {}, document: { write(value) { written = value; } } });
assert.equal(written, '<script src="platform-bridge.js"></script>');
});
test('core app shell uses the namespaced renderer state', () => { test('core app shell uses the namespaced renderer state', () => {
const app = read('app.js'); const app = read('app.js');
assert.match(app, /^\(\(\) => \{/); assert.match(app, /^\(\(\) => \{/);
@@ -44,7 +55,7 @@ test('desktop, Android web generation, and offline cache include renderer suppor
const buildFiles = require(path.join(root, 'package.json')).build.files; const buildFiles = require(path.join(root, 'package.json')).build.files;
const androidAssets = read('scripts/prepare-android-web.cjs'); const androidAssets = read('scripts/prepare-android-web.cjs');
const worker = read('service-worker.js'); const worker = read('service-worker.js');
for (const file of ['renderer-state.js', 'mail-content-security.js', 'renderer-mail-api.js']) { for (const file of ['renderer-state.js', 'mail-content-security.js', 'renderer-mail-api.js', 'platform-bridge-loader.js']) {
assert.ok(buildFiles.includes(file), `Electron package is missing ${file}`); assert.ok(buildFiles.includes(file), `Electron package is missing ${file}`);
assert.ok(androidAssets.includes(`'${file}'`), `Android web generator is missing ${file}`); assert.ok(androidAssets.includes(`'${file}'`), `Android web generator is missing ${file}`);
assert.ok(worker.includes(`'./${file}'`), `service worker is missing ${file}`); assert.ok(worker.includes(`'./${file}'`), `service worker is missing ${file}`);
@@ -54,6 +65,7 @@ test('desktop, Android web generation, and offline cache include renderer suppor
test('classic renderer scripts have no duplicate global lexical declarations', () => { test('classic renderer scripts have no duplicate global lexical declarations', () => {
const html = read('index.html'); const html = read('index.html');
const scripts = [...html.matchAll(/<script src="([^"]+)"/g)].map(match => match[1]); const scripts = [...html.matchAll(/<script src="([^"]+)"/g)].map(match => match[1]);
scripts.push('platform-bridge.js'); // Loaded synchronously by the platform loader outside Electron.
const source = scripts.map(script => read(script)).join('\n'); const source = scripts.map(script => read(script)).join('\n');
assert.doesNotThrow(() => new vm.Script(source, { filename: 'renderer-classic-scripts.js' })); assert.doesNotThrow(() => new vm.Script(source, { filename: 'renderer-classic-scripts.js' }));
}); });
+1 -1
View File
@@ -67,7 +67,7 @@
<script src="renderer-state.js"></script> <script src="renderer-state.js"></script>
<script src="mail-content-security.js"></script> <script src="mail-content-security.js"></script>
<script src="app.js"></script> <script src="app.js"></script>
<script src="platform-bridge.js"></script> <script src="platform-bridge-loader.js"></script>
<script src="renderer-mail-api.js"></script> <script src="renderer-mail-api.js"></script>
<script src="mail-ui.js"></script> <script src="mail-ui.js"></script>
<script src="productivity.js"></script> <script src="productivity.js"></script>
+5
View File
@@ -0,0 +1,5 @@
(() => {
// Electron's preload already provides the desktop bridge; avoid parsing the Capacitor bundle there.
if (window.daybreakMail) return;
document.write('<script src="platform-bridge.js"><\/script>');
})();
+2 -2
View File
@@ -1,5 +1,5 @@
const CACHE='ep-mail-v11'; const CACHE='ep-mail-v12';
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)))); self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))}); self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});