@bobfrankston/mailx-store 0.1.26 → 0.1.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/db.d.ts +20 -3
- package/db.js +204 -107
- package/package.json +3 -3
- package/parse-serial.js +7 -1
- package/parse-worker.js +45 -10
- package/store.d.ts +10 -0
- package/store.js +54 -36
package/db.d.ts
CHANGED
|
@@ -347,6 +347,14 @@ export declare class MailxDB {
|
|
|
347
347
|
beginTransaction(): void;
|
|
348
348
|
commitTransaction(): void;
|
|
349
349
|
rollbackTransaction(): void;
|
|
350
|
+
/** Run `fn` inside a transaction — nesting-safe. `node:sqlite` throws on
|
|
351
|
+
* a nested BEGIN, and the async chunked walkers (seedContactsFromMessages,
|
|
352
|
+
* applyContactsConfig) can interleave with the sync backfill's own
|
|
353
|
+
* transactions across their `setImmediate` yields. If a transaction is
|
|
354
|
+
* already open this just runs `fn` (its writes join the open txn);
|
|
355
|
+
* otherwise it owns a fresh BEGIN/COMMIT. `fn` MUST be synchronous so it
|
|
356
|
+
* can't span an await and leave a transaction open across a yield. */
|
|
357
|
+
runInTxn<T>(fn: () => T): T;
|
|
350
358
|
/** Record an address used in sent mail */
|
|
351
359
|
recordSentAddress(name: string, email: string): void;
|
|
352
360
|
/** True if `email` (lowercased) appears in the active denylist. Cached
|
|
@@ -399,7 +407,16 @@ export declare class MailxDB {
|
|
|
399
407
|
* Discovered is a single tier; sub-distinctions like sent-vs-received
|
|
400
408
|
* collapse here because the user-facing UI shows them as one "discovered"
|
|
401
409
|
* source. Recency-weighted use_count differentiates within the tier. */
|
|
402
|
-
|
|
410
|
+
/** ASYNC + chunked. This walks every cached message's address fields —
|
|
411
|
+
* on a large account that is hundreds of thousands of rows. The old
|
|
412
|
+
* synchronous version did `.all()` on the whole messages table in one
|
|
413
|
+
* call, materialising every row and blocking the event loop for tens
|
|
414
|
+
* of seconds to minutes (profiled 2026-05-15: 99% of daemon ticks were
|
|
415
|
+
* in native SQLite while this ran — every getMessage IPC, every preview
|
|
416
|
+
* click, queued behind it; that IS the "loading body takes forever"
|
|
417
|
+
* bug). Now keyset-paginated by `m.id` with a `setImmediate` yield
|
|
418
|
+
* between pages, so user IPC lands in the gaps. */
|
|
419
|
+
seedContactsFromMessages(): Promise<number>;
|
|
403
420
|
/** Apply the contents of contacts.jsonc — replaces all preferred-tier rows
|
|
404
421
|
* with the entries in `preferred[]`, merges `discovered[]` into the local
|
|
405
422
|
* cache, sets the in-memory denylist, and purges any discovered rows
|
|
@@ -428,12 +445,12 @@ export declare class MailxDB {
|
|
|
428
445
|
useCount?: number;
|
|
429
446
|
lastUsed?: number;
|
|
430
447
|
}[];
|
|
431
|
-
}): {
|
|
448
|
+
}): Promise<{
|
|
432
449
|
preferred: number;
|
|
433
450
|
discovered: number;
|
|
434
451
|
purged: number;
|
|
435
452
|
conflicts: string[];
|
|
436
|
-
}
|
|
453
|
+
}>;
|
|
437
454
|
/** Build the contacts.jsonc shape from current DB state — for round-trip
|
|
438
455
|
* to GDrive. Preferred-tier rows come from anything not in the reserved
|
|
439
456
|
* system sources; discovered comes from `source='discovered'` rows;
|
package/db.js
CHANGED
|
@@ -1901,6 +1901,30 @@ export class MailxDB {
|
|
|
1901
1901
|
beginTransaction() { this.db.exec("BEGIN"); }
|
|
1902
1902
|
commitTransaction() { this.db.exec("COMMIT"); }
|
|
1903
1903
|
rollbackTransaction() { this.db.exec("ROLLBACK"); }
|
|
1904
|
+
/** Run `fn` inside a transaction — nesting-safe. `node:sqlite` throws on
|
|
1905
|
+
* a nested BEGIN, and the async chunked walkers (seedContactsFromMessages,
|
|
1906
|
+
* applyContactsConfig) can interleave with the sync backfill's own
|
|
1907
|
+
* transactions across their `setImmediate` yields. If a transaction is
|
|
1908
|
+
* already open this just runs `fn` (its writes join the open txn);
|
|
1909
|
+
* otherwise it owns a fresh BEGIN/COMMIT. `fn` MUST be synchronous so it
|
|
1910
|
+
* can't span an await and leave a transaction open across a yield. */
|
|
1911
|
+
runInTxn(fn) {
|
|
1912
|
+
if (this.db.isTransaction)
|
|
1913
|
+
return fn();
|
|
1914
|
+
this.db.exec("BEGIN");
|
|
1915
|
+
try {
|
|
1916
|
+
const r = fn();
|
|
1917
|
+
this.db.exec("COMMIT");
|
|
1918
|
+
return r;
|
|
1919
|
+
}
|
|
1920
|
+
catch (e) {
|
|
1921
|
+
try {
|
|
1922
|
+
this.db.exec("ROLLBACK");
|
|
1923
|
+
}
|
|
1924
|
+
catch { /* already rolled back */ }
|
|
1925
|
+
throw e;
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1904
1928
|
// ── Contacts ──
|
|
1905
1929
|
/** Record an address used in sent mail */
|
|
1906
1930
|
recordSentAddress(name, email) {
|
|
@@ -1992,7 +2016,16 @@ export class MailxDB {
|
|
|
1992
2016
|
* Discovered is a single tier; sub-distinctions like sent-vs-received
|
|
1993
2017
|
* collapse here because the user-facing UI shows them as one "discovered"
|
|
1994
2018
|
* source. Recency-weighted use_count differentiates within the tier. */
|
|
1995
|
-
|
|
2019
|
+
/** ASYNC + chunked. This walks every cached message's address fields —
|
|
2020
|
+
* on a large account that is hundreds of thousands of rows. The old
|
|
2021
|
+
* synchronous version did `.all()` on the whole messages table in one
|
|
2022
|
+
* call, materialising every row and blocking the event loop for tens
|
|
2023
|
+
* of seconds to minutes (profiled 2026-05-15: 99% of daemon ticks were
|
|
2024
|
+
* in native SQLite while this ran — every getMessage IPC, every preview
|
|
2025
|
+
* click, queued behind it; that IS the "loading body takes forever"
|
|
2026
|
+
* bug). Now keyset-paginated by `m.id` with a `setImmediate` yield
|
|
2027
|
+
* between pages, so user IPC lands in the gaps. */
|
|
2028
|
+
async seedContactsFromMessages() {
|
|
1996
2029
|
const VALID = /^[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+$/;
|
|
1997
2030
|
const now = Date.now();
|
|
1998
2031
|
const agg = new Map();
|
|
@@ -2016,57 +2049,75 @@ export class MailxDB {
|
|
|
2016
2049
|
agg.set(email, { name: name || "", cnt: 1, last: date || 0 });
|
|
2017
2050
|
}
|
|
2018
2051
|
};
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
catch {
|
|
2034
|
-
continue;
|
|
2035
|
-
}
|
|
2036
|
-
if (!Array.isArray(parsed))
|
|
2052
|
+
const eatRecipients = (field, date) => {
|
|
2053
|
+
if (!field)
|
|
2054
|
+
return;
|
|
2055
|
+
let parsed;
|
|
2056
|
+
try {
|
|
2057
|
+
parsed = JSON.parse(field);
|
|
2058
|
+
}
|
|
2059
|
+
catch {
|
|
2060
|
+
return;
|
|
2061
|
+
}
|
|
2062
|
+
if (!Array.isArray(parsed))
|
|
2063
|
+
return;
|
|
2064
|
+
for (const a of parsed) {
|
|
2065
|
+
if (!a)
|
|
2037
2066
|
continue;
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2067
|
+
bump(a.name || "", a.address || a.email || "", date);
|
|
2068
|
+
}
|
|
2069
|
+
};
|
|
2070
|
+
const yieldLoop = () => new Promise(r => setImmediate(r));
|
|
2071
|
+
const PAGE = 2000;
|
|
2072
|
+
// Sent folder: recipients only (skip the user's own From address).
|
|
2073
|
+
// Keyset pagination by m.id — each page is a bounded `.all()`, and
|
|
2074
|
+
// the event loop is handed back between pages.
|
|
2075
|
+
{
|
|
2076
|
+
const stmt = this.db.prepare(`SELECT m.id AS id, m.to_json, m.cc_json, m.bcc_json, m.date
|
|
2077
|
+
FROM messages m
|
|
2078
|
+
JOIN folders f ON m.folder_id = f.id
|
|
2079
|
+
WHERE f.special_use = 'sent' AND m.id > ?
|
|
2080
|
+
ORDER BY m.id LIMIT ?`);
|
|
2081
|
+
let lastId = 0;
|
|
2082
|
+
for (;;) {
|
|
2083
|
+
const rows = stmt.all(lastId, PAGE);
|
|
2084
|
+
if (rows.length === 0)
|
|
2085
|
+
break;
|
|
2086
|
+
for (const r of rows) {
|
|
2087
|
+
const date = r.date || 0;
|
|
2088
|
+
eatRecipients(r.to_json, date);
|
|
2089
|
+
eatRecipients(r.cc_json, date);
|
|
2090
|
+
eatRecipients(r.bcc_json, date);
|
|
2042
2091
|
}
|
|
2092
|
+
lastId = rows[rows.length - 1].id;
|
|
2093
|
+
if (rows.length < PAGE)
|
|
2094
|
+
break;
|
|
2095
|
+
await yieldLoop();
|
|
2043
2096
|
}
|
|
2044
2097
|
}
|
|
2045
2098
|
// Other folders: From + recipients.
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
for (
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
if (!Array.isArray(parsed))
|
|
2064
|
-
continue;
|
|
2065
|
-
for (const a of parsed) {
|
|
2066
|
-
if (!a)
|
|
2067
|
-
continue;
|
|
2068
|
-
bump(a.name || "", a.address || a.email || "", date);
|
|
2099
|
+
{
|
|
2100
|
+
const stmt = this.db.prepare(`SELECT m.id AS id, m.from_name, m.from_address, m.to_json, m.cc_json, m.bcc_json, m.date
|
|
2101
|
+
FROM messages m
|
|
2102
|
+
LEFT JOIN folders f ON m.folder_id = f.id
|
|
2103
|
+
WHERE (f.special_use IS NULL OR f.special_use != 'sent') AND m.id > ?
|
|
2104
|
+
ORDER BY m.id LIMIT ?`);
|
|
2105
|
+
let lastId = 0;
|
|
2106
|
+
for (;;) {
|
|
2107
|
+
const rows = stmt.all(lastId, PAGE);
|
|
2108
|
+
if (rows.length === 0)
|
|
2109
|
+
break;
|
|
2110
|
+
for (const r of rows) {
|
|
2111
|
+
const date = r.date || 0;
|
|
2112
|
+
bump(r.from_name, r.from_address, date);
|
|
2113
|
+
eatRecipients(r.to_json, date);
|
|
2114
|
+
eatRecipients(r.cc_json, date);
|
|
2115
|
+
eatRecipients(r.bcc_json, date);
|
|
2069
2116
|
}
|
|
2117
|
+
lastId = rows[rows.length - 1].id;
|
|
2118
|
+
if (rows.length < PAGE)
|
|
2119
|
+
break;
|
|
2120
|
+
await yieldLoop();
|
|
2070
2121
|
}
|
|
2071
2122
|
}
|
|
2072
2123
|
let added = 0;
|
|
@@ -2077,16 +2128,30 @@ export class MailxDB {
|
|
|
2077
2128
|
name = CASE WHEN name = '' AND ? != '' THEN ? ELSE name END,
|
|
2078
2129
|
updated_at = ?
|
|
2079
2130
|
WHERE id = ?`);
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2131
|
+
const findStmt = this.db.prepare("SELECT id FROM contacts WHERE source = 'discovered' AND lower(email) = ?");
|
|
2132
|
+
// Write phase — chunked. Each chunk runs via `db.transaction()`
|
|
2133
|
+
// (one synchronous turn, one commit) rather than raw BEGIN/COMMIT
|
|
2134
|
+
// straddling an `await` — the wrapper is nesting-safe (savepoints)
|
|
2135
|
+
// so it can't collide with the sync backfill's own transactions
|
|
2136
|
+
// when the two interleave across the yield below.
|
|
2137
|
+
const WRITE_CHUNK = 500;
|
|
2138
|
+
const entries = [...agg.entries()];
|
|
2139
|
+
for (let i = 0; i < entries.length; i += WRITE_CHUNK) {
|
|
2140
|
+
const slice = entries.slice(i, i + WRITE_CHUNK);
|
|
2141
|
+
this.runInTxn(() => {
|
|
2142
|
+
for (const [email, info] of slice) {
|
|
2143
|
+
const existing = findStmt.get(email);
|
|
2144
|
+
if (!existing) {
|
|
2145
|
+
insStmt.run(info.name, email, info.last, info.cnt, now);
|
|
2146
|
+
added++;
|
|
2147
|
+
}
|
|
2148
|
+
else {
|
|
2149
|
+
updStmt.run(info.cnt, info.last, info.name, info.name, now, existing.id);
|
|
2150
|
+
bumped++;
|
|
2151
|
+
}
|
|
2152
|
+
}
|
|
2153
|
+
});
|
|
2154
|
+
await yieldLoop();
|
|
2090
2155
|
}
|
|
2091
2156
|
if (added > 0 || bumped > 0) {
|
|
2092
2157
|
console.log(` [contacts] seed: ${added} new + ${bumped} refreshed (discovered)`);
|
|
@@ -2104,7 +2169,7 @@ export class MailxDB {
|
|
|
2104
2169
|
* Discovered rows from the file are MERGED with whatever the local
|
|
2105
2170
|
* message-corpus seeder has produced. Each device contributes its
|
|
2106
2171
|
* observed addresses; over time GDrive accumulates the union. */
|
|
2107
|
-
applyContactsConfig(cfg) {
|
|
2172
|
+
async applyContactsConfig(cfg) {
|
|
2108
2173
|
const preferred = Array.isArray(cfg.preferred) ? cfg.preferred : [];
|
|
2109
2174
|
const denylist = Array.isArray(cfg.denylist) ? cfg.denylist : [];
|
|
2110
2175
|
const denylistPatterns = Array.isArray(cfg.denylistPatterns) ? cfg.denylistPatterns : [];
|
|
@@ -2119,41 +2184,65 @@ export class MailxDB {
|
|
|
2119
2184
|
.filter(e => e && e.priority === true && e.email)
|
|
2120
2185
|
.map(e => e.email);
|
|
2121
2186
|
this.setPriorityIndex(prioritySenders, priorityDomains);
|
|
2187
|
+
const VALID = /^[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+$/;
|
|
2188
|
+
const now = Date.now();
|
|
2189
|
+
const denySet = new Set(denylist.map(e => (e || "").trim().toLowerCase()).filter(Boolean));
|
|
2190
|
+
const conflicts = [];
|
|
2191
|
+
const yieldLoop = () => new Promise(r => setImmediate(r));
|
|
2192
|
+
const CHUNK = 500;
|
|
2122
2193
|
// Wipe and rewrite preferred-tier rows owned by contacts.jsonc.
|
|
2123
2194
|
// The address-book UI's legacy `upsertContact` still writes
|
|
2124
2195
|
// source='manual' rows; those are owned by the address-book code
|
|
2125
2196
|
// path, not contacts.jsonc, so we leave them alone here.
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2197
|
+
// ALL writes below run inside transactions and yield the event
|
|
2198
|
+
// loop between chunks. The prior version did one autocommitting
|
|
2199
|
+
// INSERT/UPDATE per row with NO transaction — on a contacts.jsonc
|
|
2200
|
+
// that has accumulated thousands of `discovered` entries across
|
|
2201
|
+
// devices, that was thousands of fsyncs back-to-back, blocking the
|
|
2202
|
+
// daemon for 25-30 s (profiled 2026-05-15: applyContactsConfig was
|
|
2203
|
+
// ~97% of the wedge). It also re-`prepare()`d a `lower(email)`
|
|
2204
|
+
// full-scan SELECT every iteration. Now: one statement prep, one
|
|
2205
|
+
// up-front map of existing discovered rows (kills the N×N scan),
|
|
2206
|
+
// chunked transactions, yields between chunks.
|
|
2129
2207
|
const ins = this.db.prepare(`INSERT OR IGNORE INTO contacts (source, name, email, organization, last_used, use_count, updated_at)
|
|
2130
2208
|
VALUES (?, ?, ?, ?, 0, 0, ?)`);
|
|
2131
|
-
const denySet = new Set(denylist.map(e => (e || "").trim().toLowerCase()).filter(Boolean));
|
|
2132
|
-
const conflicts = [];
|
|
2133
2209
|
let inserted = 0;
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2210
|
+
// runInTxn: nesting-safe and atomic within one synchronous turn, so
|
|
2211
|
+
// these writes can't collide with the sync backfill's transactions
|
|
2212
|
+
// when the two interleave across the yields below.
|
|
2213
|
+
this.runInTxn(() => {
|
|
2214
|
+
this.db.exec("DELETE FROM contacts WHERE source NOT IN ('google', 'discovered', 'manual')");
|
|
2215
|
+
for (const entry of preferred) {
|
|
2216
|
+
if (!entry)
|
|
2217
|
+
continue;
|
|
2218
|
+
const email = (entry.email || "").trim();
|
|
2219
|
+
if (!email || !VALID.test(email))
|
|
2220
|
+
continue;
|
|
2221
|
+
if (denySet.has(email.toLowerCase())) {
|
|
2222
|
+
conflicts.push(email);
|
|
2223
|
+
continue;
|
|
2224
|
+
}
|
|
2225
|
+
const source = (entry.source || "preferred").trim() || "preferred";
|
|
2226
|
+
const name = (entry.name || "").trim();
|
|
2227
|
+
const org = (entry.organization || entry.org || "").trim();
|
|
2228
|
+
try {
|
|
2229
|
+
const r = ins.run(source, name, email, org, now);
|
|
2230
|
+
if (r.changes)
|
|
2231
|
+
inserted++;
|
|
2232
|
+
}
|
|
2233
|
+
catch { /* dup row, skip */ }
|
|
2151
2234
|
}
|
|
2152
|
-
|
|
2153
|
-
|
|
2235
|
+
});
|
|
2236
|
+
await yieldLoop();
|
|
2154
2237
|
// Merge discovered[] from cloud into local cache. For each entry:
|
|
2155
2238
|
// existing row wins on use_count (max), name fills if empty, lastUsed
|
|
2156
2239
|
// is max. Missing rows are inserted. Denylisted entries skipped.
|
|
2240
|
+
// Existing discovered rows are mapped ONCE up front so the merge is
|
|
2241
|
+
// O(N) hash lookups, not O(N) `lower(email)` table scans.
|
|
2242
|
+
const existingDiscovered = new Map();
|
|
2243
|
+
for (const row of this.db.prepare("SELECT id, lower(email) AS le FROM contacts WHERE source = 'discovered'").all()) {
|
|
2244
|
+
existingDiscovered.set(row.le, row.id);
|
|
2245
|
+
}
|
|
2157
2246
|
const insDiscovered = this.db.prepare("INSERT INTO contacts (source, name, email, last_used, use_count, updated_at) VALUES ('discovered', ?, ?, ?, ?, ?)");
|
|
2158
2247
|
const updDiscovered = this.db.prepare(`UPDATE contacts SET use_count = max(use_count, ?),
|
|
2159
2248
|
last_used = max(last_used, ?),
|
|
@@ -2161,36 +2250,44 @@ export class MailxDB {
|
|
|
2161
2250
|
updated_at = ?
|
|
2162
2251
|
WHERE id = ?`);
|
|
2163
2252
|
let discoveredAdded = 0;
|
|
2164
|
-
for (
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2253
|
+
for (let i = 0; i < discovered.length; i += CHUNK) {
|
|
2254
|
+
const slice = discovered.slice(i, i + CHUNK);
|
|
2255
|
+
this.runInTxn(() => {
|
|
2256
|
+
for (const entry of slice) {
|
|
2257
|
+
if (!entry)
|
|
2258
|
+
continue;
|
|
2259
|
+
const email = (entry.email || "").trim();
|
|
2260
|
+
if (!email || !VALID.test(email))
|
|
2261
|
+
continue;
|
|
2262
|
+
const lower = email.toLowerCase();
|
|
2263
|
+
if (denySet.has(lower))
|
|
2264
|
+
continue;
|
|
2265
|
+
if (isJunkContact(lower, entry.name || ""))
|
|
2266
|
+
continue;
|
|
2267
|
+
const name = (entry.name || "").trim();
|
|
2268
|
+
const useCount = Math.max(0, entry.useCount || 0);
|
|
2269
|
+
const lastUsed = Math.max(0, entry.lastUsed || 0);
|
|
2270
|
+
const existingId = existingDiscovered.get(lower);
|
|
2271
|
+
if (existingId === undefined) {
|
|
2272
|
+
insDiscovered.run(name, email, lastUsed, useCount, now);
|
|
2273
|
+
discoveredAdded++;
|
|
2274
|
+
}
|
|
2275
|
+
else {
|
|
2276
|
+
updDiscovered.run(useCount, lastUsed, name, name, now, existingId);
|
|
2277
|
+
}
|
|
2278
|
+
}
|
|
2279
|
+
});
|
|
2280
|
+
await yieldLoop();
|
|
2186
2281
|
}
|
|
2187
2282
|
// Purge discovered rows for any denylisted email.
|
|
2188
2283
|
const purge = this.db.prepare("DELETE FROM contacts WHERE source = 'discovered' AND lower(email) = ?");
|
|
2189
2284
|
let purged = 0;
|
|
2190
|
-
|
|
2191
|
-
const
|
|
2192
|
-
|
|
2193
|
-
|
|
2285
|
+
this.runInTxn(() => {
|
|
2286
|
+
for (const e of denySet) {
|
|
2287
|
+
const r = purge.run(e);
|
|
2288
|
+
purged += Number(r.changes || 0);
|
|
2289
|
+
}
|
|
2290
|
+
});
|
|
2194
2291
|
if (conflicts.length > 0) {
|
|
2195
2292
|
console.warn(` [contacts] config: ${conflicts.length} preferred entries also appear in denylist — denylist wins, entries skipped: ${conflicts.join(", ")}`);
|
|
2196
2293
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bobfrankston/mailx-store",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.28",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
},
|
|
10
10
|
"license": "ISC",
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@bobfrankston/mailx-types": "^0.1.
|
|
12
|
+
"@bobfrankston/mailx-types": "^0.1.14",
|
|
13
13
|
"@bobfrankston/mailx-settings": "^0.1.17",
|
|
14
14
|
"@bobfrankston/mailx-bus": "^0.1.2",
|
|
15
15
|
"mailparser": "^3.7.2"
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
},
|
|
30
30
|
".transformedSnapshot": {
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@bobfrankston/mailx-types": "^0.1.
|
|
32
|
+
"@bobfrankston/mailx-types": "^0.1.14",
|
|
33
33
|
"@bobfrankston/mailx-settings": "^0.1.17",
|
|
34
34
|
"@bobfrankston/mailx-bus": "^0.1.2",
|
|
35
35
|
"mailparser": "^3.7.2"
|
package/parse-serial.js
CHANGED
|
@@ -73,7 +73,10 @@ function getWorker() {
|
|
|
73
73
|
});
|
|
74
74
|
w.on("error", (e) => {
|
|
75
75
|
// Fatal worker crash — fail every in-flight parse, then null the
|
|
76
|
-
// singleton so the next call respawns.
|
|
76
|
+
// singleton so the next call respawns. Logged loudly: a silent
|
|
77
|
+
// respawn loop forces every Nth parse to eat a fresh cold-start,
|
|
78
|
+
// which reads as a random multi-second "loading body" stall.
|
|
79
|
+
console.error(` [parse-worker] CRASHED (${e.message}) — ${_inflight.size} in-flight parse(s) failed, will respawn`);
|
|
77
80
|
for (const entry of _inflight.values())
|
|
78
81
|
entry.reject(e);
|
|
79
82
|
_inflight.clear();
|
|
@@ -81,6 +84,9 @@ function getWorker() {
|
|
|
81
84
|
signalCompletion();
|
|
82
85
|
});
|
|
83
86
|
w.on("exit", (code) => {
|
|
87
|
+
// code 0 = clean exit (shouldn't happen — parentPort keeps it alive);
|
|
88
|
+
// non-zero = crash. Either way the next parse respawns + re-warms.
|
|
89
|
+
console.warn(` [parse-worker] exited (code=${code}), ${_inflight.size} in-flight — next parse respawns`);
|
|
84
90
|
if (_inflight.size > 0) {
|
|
85
91
|
const err = new Error(`parse-worker exited (code=${code}) with ${_inflight.size} in-flight`);
|
|
86
92
|
for (const entry of _inflight.values())
|
package/parse-worker.js
CHANGED
|
@@ -21,18 +21,43 @@ import { simpleParser } from "mailparser";
|
|
|
21
21
|
if (!parentPort) {
|
|
22
22
|
throw new Error("parse-worker: must be spawned as a worker, parentPort is null");
|
|
23
23
|
}
|
|
24
|
-
// Self-warmup: parse a synthetic
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
//
|
|
28
|
-
//
|
|
29
|
-
//
|
|
24
|
+
// Self-warmup: parse a synthetic message at worker startup so V8 JIT,
|
|
25
|
+
// libmime / iconv-lite loading, and mailparser's lazy init all complete
|
|
26
|
+
// *before* the worker accepts its first real request.
|
|
27
|
+
//
|
|
28
|
+
// CRITICAL (Bob 2026-05-15): the warmup message MUST exercise every heavy
|
|
29
|
+
// code path a real email hits, or the cold-start cost just moves to the
|
|
30
|
+
// first real parse. The previous warmup was a trivial text/plain message
|
|
31
|
+
// — it JIT'd the basic path but NOT the HTML pipeline, quoted-printable
|
|
32
|
+
// decode, multipart boundary handling, or attachment extraction. Result:
|
|
33
|
+
// the first real parse (a 96 KB multipart/alternative) took 33 SECONDS
|
|
34
|
+
// in the log — the cold start was never actually absorbed. This warmup
|
|
35
|
+
// message is multipart/mixed → multipart/alternative(text + QP-encoded
|
|
36
|
+
// HTML) + a base64 attachment, with HTML entities and a non-ASCII char,
|
|
37
|
+
// so the first real parse rides warm JIT for all of them.
|
|
30
38
|
const _warmupT0 = Date.now();
|
|
31
|
-
const
|
|
32
|
-
+ "Subject:
|
|
39
|
+
const _warmupMessage = "From: warmup@mailx.local\r\nTo: warmup@mailx.local\r\n"
|
|
40
|
+
+ "Subject: =?UTF-8?Q?warm=E2=80=91up?=\r\nMIME-Version: 1.0\r\n"
|
|
41
|
+
+ "Content-Type: multipart/mixed; boundary=\"MIX\"\r\n\r\n"
|
|
42
|
+
+ "--MIX\r\n"
|
|
43
|
+
+ "Content-Type: multipart/alternative; boundary=\"ALT\"\r\n\r\n"
|
|
44
|
+
+ "--ALT\r\n"
|
|
33
45
|
+ "Content-Type: text/plain; charset=UTF-8\r\n\r\n"
|
|
34
|
-
+ "parse-worker cold-start absorber
|
|
35
|
-
|
|
46
|
+
+ "parse-worker cold-start absorber — discard.\r\n"
|
|
47
|
+
+ "--ALT\r\n"
|
|
48
|
+
+ "Content-Type: text/html; charset=UTF-8\r\n"
|
|
49
|
+
+ "Content-Transfer-Encoding: quoted-printable\r\n\r\n"
|
|
50
|
+
+ "<html><body><p>warm=E2=80=91up & discard</p>"
|
|
51
|
+
+ "<blockquote>quoted</blockquote><a href=3D\"http://x\">link</a></body></html>\r\n"
|
|
52
|
+
+ "--ALT--\r\n"
|
|
53
|
+
+ "--MIX\r\n"
|
|
54
|
+
+ "Content-Type: application/octet-stream; name=\"w.bin\"\r\n"
|
|
55
|
+
+ "Content-Transfer-Encoding: base64\r\n"
|
|
56
|
+
+ "Content-Disposition: attachment; filename=\"w.bin\"\r\n\r\n"
|
|
57
|
+
+ "d2FybXVw\r\n"
|
|
58
|
+
+ "--MIX--\r\n";
|
|
59
|
+
const _warmupPromise = simpleParser(Buffer.from(_warmupMessage, "utf8")).then(() => {
|
|
60
|
+
// Heartbeat so the main thread can log the absorbed cost.
|
|
36
61
|
parentPort.postMessage({ warmupMs: Date.now() - _warmupT0 });
|
|
37
62
|
}).catch(() => { });
|
|
38
63
|
parentPort.on("message", async (msg) => {
|
|
@@ -58,7 +83,17 @@ parentPort.on("message", async (msg) => {
|
|
|
58
83
|
const u = source;
|
|
59
84
|
normalized = Buffer.from(u.buffer, u.byteOffset, u.byteLength);
|
|
60
85
|
}
|
|
86
|
+
const _t0 = Date.now();
|
|
61
87
|
const result = await simpleParser(normalized);
|
|
88
|
+
const _ms = Date.now() - _t0;
|
|
89
|
+
// Worker-side parse time. If THIS is slow, the bug is in simpleParser
|
|
90
|
+
// on a given input; if this is fast but the main thread still saw a
|
|
91
|
+
// multi-second `[parse]` figure, the cost is queue wait / respawn —
|
|
92
|
+
// splitting the two was the open question of the 2026-05-15 hunt.
|
|
93
|
+
if (_ms > 1000) {
|
|
94
|
+
const size = Buffer.isBuffer(normalized) ? normalized.byteLength : String(normalized).length;
|
|
95
|
+
console.warn(` [parse-worker] simpleParser took ${_ms}ms for ${(size / 1024).toFixed(0)} KB (worker-side, not queue wait)`);
|
|
96
|
+
}
|
|
62
97
|
parentPort.postMessage({ id, ok: true, result });
|
|
63
98
|
}
|
|
64
99
|
catch (e) {
|
package/store.d.ts
CHANGED
|
@@ -41,6 +41,15 @@ export interface StoreMessage extends MessageEnvelope {
|
|
|
41
41
|
contentId: string;
|
|
42
42
|
}>;
|
|
43
43
|
cached: boolean;
|
|
44
|
+
/** Disambiguates `cached: false`:
|
|
45
|
+
* - bodyOnDisk false → the .eml is NOT on disk; caller should queue
|
|
46
|
+
* an IMAP/Gmail fetch.
|
|
47
|
+
* - bodyOnDisk true → the .eml IS on disk; a parse is in flight.
|
|
48
|
+
* Caller MUST NOT queue a fetch — just wait for the `bodyAvailable`
|
|
49
|
+
* bus event. Queuing a fetch here caused the 10-Hz "Loading body…"
|
|
50
|
+
* loop (Bob 2026-05-15): cached:false → MailxService fetched →
|
|
51
|
+
* reconciler re-published bodyAvailable → viewer re-called → repeat. */
|
|
52
|
+
bodyOnDisk: boolean;
|
|
44
53
|
deliveredTo: string;
|
|
45
54
|
returnPath: string;
|
|
46
55
|
listUnsubscribe: string;
|
|
@@ -69,6 +78,7 @@ export declare class Store {
|
|
|
69
78
|
private parsedLru;
|
|
70
79
|
private parsedLruGet;
|
|
71
80
|
private parsedLruPut;
|
|
81
|
+
private parseInflight;
|
|
72
82
|
private _allowlistCache;
|
|
73
83
|
private _settingsCache;
|
|
74
84
|
private getCachedAllowlist;
|
package/store.js
CHANGED
|
@@ -95,6 +95,15 @@ export class Store {
|
|
|
95
95
|
this.parsedLru.delete(oldest);
|
|
96
96
|
}
|
|
97
97
|
}
|
|
98
|
+
// In-flight parse coalescing. Concurrent getMessage calls for the same
|
|
99
|
+
// body (same path|mtime cacheKey) must share ONE parse — otherwise a
|
|
100
|
+
// viewer that re-requests while the first parse is still queued enqueues
|
|
101
|
+
// a duplicate, and N retries become N parses stacked in the parse-worker
|
|
102
|
+
// queue. Observed 2026-05-15: the same .eml parsed 3-4× in a burst, and
|
|
103
|
+
// a genuine click then waited 25 s behind the pile-up. The map entry is
|
|
104
|
+
// removed when the parse settles (success OR failure — a failed parse
|
|
105
|
+
// must not poison the key).
|
|
106
|
+
parseInflight = new Map();
|
|
98
107
|
// Allowlist + settings caches. Both files live on the GDrive-mounted
|
|
99
108
|
// shared dir; their sync `readFileSync` calls in `loadAllowlist()` and
|
|
100
109
|
// `loadSettings()` can stall for seconds per call. getMessage runs on
|
|
@@ -222,11 +231,13 @@ export class Store {
|
|
|
222
231
|
hasRemoteContent: false, remoteAllowed: allowRemote,
|
|
223
232
|
attachments: [],
|
|
224
233
|
cached: false,
|
|
234
|
+
bodyOnDisk: false, // overridden to true on the parse-pending return
|
|
225
235
|
deliveredTo: "", returnPath: "",
|
|
226
236
|
listUnsubscribe: "", listUnsubscribeMail: "", listUnsubscribeHttp: "", listUnsubscribeOneClick: false,
|
|
227
237
|
emlPath: "",
|
|
228
238
|
isFlagged,
|
|
229
239
|
};
|
|
240
|
+
// No body file → caller should queue a fetch (bodyOnDisk stays false).
|
|
230
241
|
if (!storedPath)
|
|
231
242
|
return empty;
|
|
232
243
|
if (!await this.bodyStore.hasByPath(storedPath))
|
|
@@ -246,30 +257,46 @@ export class Store {
|
|
|
246
257
|
// body cached; recompute the volatile fields and overlay.
|
|
247
258
|
return { ...cached, remoteAllowed: allowRemote, isFlagged };
|
|
248
259
|
}
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
260
|
+
// Synchronous parse. The .eml is on disk; read + parse it inline
|
|
261
|
+
// and return the fully-rendered message. The parse runs on the
|
|
262
|
+
// parse-worker thread (off the main event loop) — the IPC promise
|
|
263
|
+
// just awaits the worker's reply, ~50-200 ms on a warm worker.
|
|
264
|
+
//
|
|
265
|
+
// 2026-05-15: this REPLACED an async "return envelope now, parse
|
|
266
|
+
// later, emit bodyAvailable" split. That split overloaded
|
|
267
|
+
// `cached:false` (was it "no body file" or "parse pending"?),
|
|
268
|
+
// which made MailxService queue redundant fetches, which churned
|
|
269
|
+
// the .eml mtime, which invalidated the cache key, which spawned
|
|
270
|
+
// duplicate parses — a 10 Hz "Loading body…" loop and 30-second
|
|
271
|
+
// queue-contention parses. Synchronous parse makes the whole
|
|
272
|
+
// class structurally impossible: getMessage either returns the
|
|
273
|
+
// body or returns `cached:false` meaning exactly "fetch it."
|
|
274
|
+
// Coalesce: if another getMessage is already reading+parsing this
|
|
275
|
+
// exact body, await its parse instead of starting a duplicate.
|
|
276
|
+
let parsed;
|
|
277
|
+
const existingParse = this.parseInflight.get(cacheKey);
|
|
278
|
+
if (existingParse) {
|
|
279
|
+
parsed = await existingParse;
|
|
259
280
|
}
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
281
|
+
else {
|
|
282
|
+
const _parseT0 = Date.now();
|
|
283
|
+
const fresh = (async () => {
|
|
284
|
+
const raw = await this.bodyStore.readByPath(storedPath);
|
|
285
|
+
const adjusted = sniffAndFixCharset(raw);
|
|
286
|
+
const result = await parseSerial(adjusted);
|
|
287
|
+
const _parseMs = Date.now() - _parseT0;
|
|
288
|
+
if (_parseMs > 50) {
|
|
289
|
+
console.log(` [parse] simpleParser ${_parseMs}ms for ${(raw.length / 1024).toFixed(0)} KB (${storedPath})`);
|
|
290
|
+
}
|
|
291
|
+
return result;
|
|
292
|
+
})();
|
|
293
|
+
this.parseInflight.set(cacheKey, fresh);
|
|
294
|
+
try {
|
|
295
|
+
parsed = await fresh;
|
|
296
|
+
}
|
|
297
|
+
finally {
|
|
298
|
+
this.parseInflight.delete(cacheKey);
|
|
299
|
+
}
|
|
273
300
|
}
|
|
274
301
|
let bodyHtml = parsed.html || "";
|
|
275
302
|
const bodyText = parsed.text || "";
|
|
@@ -367,19 +394,10 @@ export class Store {
|
|
|
367
394
|
emlPath: this.bodyStore.absolutePath(storedPath),
|
|
368
395
|
isFlagged,
|
|
369
396
|
};
|
|
370
|
-
// Memoize
|
|
371
|
-
//
|
|
372
|
-
//
|
|
373
|
-
|
|
374
|
-
//
|
|
375
|
-
// BUT don't poison the cache with an empty parse — a malformed .eml
|
|
376
|
-
// or a fetch that left a stub file gives bodyHtml === "" AND
|
|
377
|
-
// bodyText === ""; caching that means future views serve emptiness
|
|
378
|
-
// until the daemon restarts. Let the next view try again; the
|
|
379
|
-
// parse cost on a 9 kB .eml is ~20 ms, so re-parsing an oddity
|
|
380
|
-
// is cheap.
|
|
381
|
-
const hasContent = (bodyHtml && bodyHtml.length > 0) || (bodyText && bodyText.length > 0);
|
|
382
|
-
if (mtimeMs > 0 && hasContent)
|
|
397
|
+
// Memoize for instant re-view of the same message. cacheKey is
|
|
398
|
+
// path+mtime so a re-fetch (mtime changes) invalidates naturally.
|
|
399
|
+
// The LRU is a perf tier only — correctness never depends on it.
|
|
400
|
+
if (mtimeMs > 0)
|
|
383
401
|
this.parsedLruPut(cacheKey, result);
|
|
384
402
|
return result;
|
|
385
403
|
}
|