@bobfrankston/mailx-store 0.1.24 → 0.1.26

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/parse-serial.js CHANGED
@@ -1,40 +1,111 @@
1
1
  /**
2
- * Process-wide serialized simpleParser.
2
+ * Worker-thread-backed simpleParser dispatcher.
3
3
  *
4
4
  * mailparser's `simpleParser` is declared `async` but its work is CPU-bound
5
- * (Node Streams + libmime decoding). When N parses run concurrently on the
6
- * single-threaded event loop they share CPU and each finishes at roughly
7
- * wall-clock. Real evidence (2026-05-13): four near-concurrent parses
8
- * each reported `14691ms for 3 KB` — pure contention, not size.
5
+ * (Node Streams + libmime decoding). When it runs on the main event loop:
6
+ * - The first parse after a fresh process takes 14-25 seconds (cold V8
7
+ * JIT + libmime + iconv-lite + charset-table loading). See log
8
+ * 2026-05-14 01:11:44 simpleParser 14524ms for 5 KB.
9
+ * - Every parse, cold or warm, blocks the IPC stdin pump for its
10
+ * duration. A 200 ms parse delays every queued IPC message by 200 ms.
9
11
  *
10
- * The downstream symptom is the IPC pipe: while the event loop is
11
- * saturated by interleaving parses, unrelated IPC operations (mark-as-spam,
12
- * move, delete) wait their turn and the WebView-side `mailxapi` shim
13
- * times out at 120s with a misleading "stayed in the list" alert.
12
+ * Moving the parse to a `worker_threads` Worker fixes both problems:
13
+ * - The main event loop stays responsive — IPC, sync, timers all run
14
+ * during the parse. Click-to-render latency is bounded by post-message
15
+ * RTT (sub-ms) + parse time on the worker, but the rest of the app
16
+ * stays alive.
17
+ * - The worker absorbs cold-start once. Subsequent parses ride the
18
+ * worker's warm JIT and run in their natural 50-500 ms budget.
14
19
  *
15
- * Serializing through a module-level promise chain bounds the damage with
16
- * minimal plumbing: a single parse runs at full CPU and finishes in its
17
- * natural ~50-500ms budget; the next parse starts when it's done. Each
18
- * UI click produces a clean preview latency instead of a 14-second stall.
20
+ * Priority queue: foreground (UI clicks) jumps over background (sync /
21
+ * prefetch) when more than one parse is pending. Each parse still runs
22
+ * sequentially on the worker the single-worker design intentionally
23
+ * mirrors the prior in-process serialization to keep CPU bounded.
19
24
  *
20
- * Lives in mailx-store rather than mailx-service so both the UI-hot path
21
- * (mailx-service/local-store.ts) and the sync path (mailx-imap) can share
22
- * one queue — otherwise sync-time parses would still contend with UI
23
- * parses through the event loop, just not through this module's chain.
25
+ * Lazy spawn: the worker is created on first call. boot/setup code that
26
+ * runs no parses pays nothing.
27
+ *
28
+ * Worker lifecycle: the worker is process-singleton, never explicitly
29
+ * terminated. Node exits cleanly because the worker is `unref()`d so it
30
+ * doesn't keep the event loop alive.
24
31
  *
25
- * Future work: replace the in-process chain with a `node:worker_threads`
26
- * pool. The chain is the precursor that bounds the worst case while the
27
- * pool is built.
32
+ * Lives in mailx-store rather than mailx-service so both the UI-hot path
33
+ * (mailx-service/local-store.ts) and the sync path (mailx-imap) share one
34
+ * worker otherwise each module would spawn its own (parallel workers
35
+ * would defeat the bound on CPU, and each pays its own cold start).
28
36
  */
29
- import { simpleParser } from "mailparser";
30
- const _head = []; // UI / foreground — drained first
31
- const _tail = []; // sync / background
37
+ import { Worker } from "node:worker_threads";
38
+ import { fileURLToPath } from "node:url";
39
+ import { dirname, join } from "node:path";
40
+ const _head = [];
41
+ const _tail = [];
32
42
  let _pumping = false;
33
- async function pump() {
43
+ let _worker = null;
44
+ let _nextId = 1;
45
+ const _inflight = new Map();
46
+ function getWorker() {
47
+ if (_worker)
48
+ return _worker;
49
+ // Resolve parse-worker.js alongside the compiled parse-serial.js.
50
+ // import.meta.url is the running .js URL after tsc compilation, so
51
+ // the worker resolves cleanly from the package install location.
52
+ const here = dirname(fileURLToPath(import.meta.url));
53
+ const workerPath = join(here, "parse-worker.js");
54
+ const w = new Worker(workerPath);
55
+ w.on("message", (msg) => {
56
+ // Warmup heartbeat (no `id`). Logs the worker cold-start cost so
57
+ // we can confirm the absorber is working on each boot.
58
+ if (typeof msg.warmupMs === "number") {
59
+ console.log(` [parse-worker] cold-start absorbed in worker in ${msg.warmupMs}ms`);
60
+ return;
61
+ }
62
+ if (typeof msg.id !== "number")
63
+ return;
64
+ const entry = _inflight.get(msg.id);
65
+ if (!entry)
66
+ return;
67
+ _inflight.delete(msg.id);
68
+ if (msg.ok)
69
+ entry.resolve(msg.result);
70
+ else
71
+ entry.reject(new Error(msg.error || "parse-worker error"));
72
+ signalCompletion();
73
+ });
74
+ w.on("error", (e) => {
75
+ // Fatal worker crash — fail every in-flight parse, then null the
76
+ // singleton so the next call respawns.
77
+ for (const entry of _inflight.values())
78
+ entry.reject(e);
79
+ _inflight.clear();
80
+ _worker = null;
81
+ signalCompletion();
82
+ });
83
+ w.on("exit", (code) => {
84
+ if (_inflight.size > 0) {
85
+ const err = new Error(`parse-worker exited (code=${code}) with ${_inflight.size} in-flight`);
86
+ for (const entry of _inflight.values())
87
+ entry.reject(err);
88
+ _inflight.clear();
89
+ }
90
+ _worker = null;
91
+ signalCompletion();
92
+ });
93
+ // Don't let the worker prevent process exit.
94
+ w.unref();
95
+ _worker = w;
96
+ return w;
97
+ }
98
+ /** In-main-thread fallback. Used when the worker spawn itself fails (e.g.,
99
+ * a packaged build where parse-worker.js can't be resolved). Falls back
100
+ * to the original behavior — blocks the event loop, but at least works.
101
+ * Lazy-imports mailparser so the main thread doesn't pay the (heavy)
102
+ * module-init cost unless the fallback actually fires. */
103
+ async function pumpInMain() {
34
104
  if (_pumping)
35
105
  return;
36
106
  _pumping = true;
37
107
  try {
108
+ const { simpleParser } = await import("mailparser");
38
109
  for (;;) {
39
110
  const next = _head.shift() ?? _tail.shift();
40
111
  if (!next)
@@ -52,17 +123,78 @@ async function pump() {
52
123
  _pumping = false;
53
124
  }
54
125
  }
55
- /** Serialized wrapper around `mailparser.simpleParser`. `priority` defaults
56
- * to "foreground" only sync/background callers should pass "background"
57
- * so user clicks aren't stuck behind a back-fill. */
126
+ // Notifier the pump awaits to drive the next iteration. When a reply
127
+ // arrives from the worker, completing the in-flight parse, this fires
128
+ // and unblocks the pump so it can pop the next queued parse. Avoids the
129
+ // busy-wait setTimeout-poll version.
130
+ let _completionSignal = null;
131
+ function signalCompletion() {
132
+ const fn = _completionSignal;
133
+ _completionSignal = null;
134
+ if (fn)
135
+ fn();
136
+ }
137
+ async function pumpViaWorker() {
138
+ if (_pumping)
139
+ return;
140
+ _pumping = true;
141
+ try {
142
+ for (;;) {
143
+ const next = _head.shift() ?? _tail.shift();
144
+ if (!next)
145
+ break;
146
+ _inflight.set(next.id, next);
147
+ try {
148
+ getWorker().postMessage({ id: next.id, source: next.source });
149
+ }
150
+ catch (e) {
151
+ _inflight.delete(next.id);
152
+ next.reject(e);
153
+ continue;
154
+ }
155
+ // Wait for THIS parse to complete before sending the next.
156
+ // Preserves the priority order — a foreground entry that arrives
157
+ // after we've already postMessage'd a background parse will be
158
+ // next in line, NOT after several already-queued backgrounds.
159
+ await new Promise(resolve => { _completionSignal = resolve; });
160
+ }
161
+ }
162
+ finally {
163
+ _pumping = false;
164
+ }
165
+ }
166
+ /** Spawn the parse worker early so its cold-start (mailparser module
167
+ * loading, V8 JIT, libmime / iconv-lite tables — empirically 14-25 s)
168
+ * runs in parallel with the rest of boot. Safe to call multiple times;
169
+ * the worker is a process-singleton. Returns immediately; the actual
170
+ * cold-start completes in the worker's internal self-warm. */
171
+ export function prewarmParseWorker() {
172
+ try {
173
+ getWorker();
174
+ }
175
+ catch { /* fallback path handles it on first parseSerial */ }
176
+ }
177
+ /** Serialized wrapper around `mailparser.simpleParser` running in a worker
178
+ * thread. `priority` defaults to "foreground" — only sync/background
179
+ * callers should pass "background" so user clicks aren't stuck behind a
180
+ * back-fill. If the worker can't be spawned (rare), falls back to an
181
+ * in-main-thread serial pump so the system still functions. */
58
182
  export async function parseSerial(source, priority = "foreground") {
59
183
  return new Promise((resolve, reject) => {
60
- const entry = { source, resolve, reject };
184
+ const entry = { id: _nextId++, source, resolve, reject };
61
185
  if (priority === "foreground")
62
186
  _head.push(entry);
63
187
  else
64
188
  _tail.push(entry);
65
- pump();
189
+ // Try the worker first; fall back transparently if the spawn fails.
190
+ try {
191
+ getWorker();
192
+ pumpViaWorker();
193
+ }
194
+ catch (e) {
195
+ console.error(` [parse-serial] worker unavailable, falling back to main-thread parse: ${e instanceof Error ? e.message : String(e)}`);
196
+ pumpInMain();
197
+ }
66
198
  });
67
199
  }
68
200
  //# sourceMappingURL=parse-serial.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=parse-worker.d.ts.map
@@ -0,0 +1,69 @@
1
+ /**
2
+ * mailparser worker thread.
3
+ *
4
+ * Runs simpleParser off the main event loop so a 14-25 second cold-start
5
+ * (or any slow parse) can't block IPC. The main thread's `parse-serial.ts`
6
+ * spawns this worker once at first use, then dispatches every parse here
7
+ * via postMessage and awaits the reply.
8
+ *
9
+ * Protocol:
10
+ * main → worker: { id: number, source: Buffer | string }
11
+ * worker → main: { id: number, ok: true, result: ParsedMail }
12
+ * | { id: number, ok: false, error: string }
13
+ *
14
+ * The worker holds its own mailparser module instance — JIT cost and
15
+ * libmime/iconv-lite loading happen exactly once per worker process. The
16
+ * main thread sees only the postMessage round-trip (~1 ms on local
17
+ * structured-clone of a small Buffer + parsed object).
18
+ */
19
+ import { parentPort } from "node:worker_threads";
20
+ import { simpleParser } from "mailparser";
21
+ if (!parentPort) {
22
+ throw new Error("parse-worker: must be spawned as a worker, parentPort is null");
23
+ }
24
+ // Self-warmup: parse a synthetic RFC 5322 message at worker startup so V8
25
+ // JIT, libmime / iconv-lite module loading, and mailparser's lazy
26
+ // initialisation all complete *before* the worker accepts its first real
27
+ // request. Sub-50 ms parses become the norm even on the first user click,
28
+ // instead of the 14-25 s cold-start observed when this work happened
29
+ // on-demand. Buffered messages received during warmup queue behind it.
30
+ const _warmupT0 = Date.now();
31
+ const _warmupPromise = simpleParser(Buffer.from("From: warmup@mailx.local\r\nTo: warmup@mailx.local\r\n"
32
+ + "Subject: warmup\r\nMIME-Version: 1.0\r\n"
33
+ + "Content-Type: text/plain; charset=UTF-8\r\n\r\n"
34
+ + "parse-worker cold-start absorber. Discard.\r\n", "utf8")).then(() => {
35
+ // Optional: emit a heartbeat so the main thread can log the cost.
36
+ parentPort.postMessage({ warmupMs: Date.now() - _warmupT0 });
37
+ }).catch(() => { });
38
+ parentPort.on("message", async (msg) => {
39
+ const { id, source } = msg;
40
+ // If a real parse arrives during warmup, queue behind it. The await
41
+ // resolves immediately once warmup is done; trivially fast on hot
42
+ // worker since _warmupPromise is already resolved.
43
+ await _warmupPromise;
44
+ try {
45
+ // CRITICAL: `Buffer` sent across `worker_threads.postMessage` arrives
46
+ // as plain `Uint8Array` (Node docs: "Buffer instances passed to
47
+ // Worker.postMessage() are passed as Uint8Array instances when
48
+ // received"). mailparser's `simpleParser` uses `Buffer.isBuffer(input)`
49
+ // to discriminate Buffer / string / Stream. A Uint8Array fails that
50
+ // check and gets routed to the Stream branch, which calls
51
+ // `input.once("end", …)` and immediately throws
52
+ // `input.once is not a function`
53
+ // Re-wrap with `Buffer.from(src.buffer, src.byteOffset, src.byteLength)`
54
+ // — zero-copy view over the same memory, but with the Buffer prototype
55
+ // so `Buffer.isBuffer` is true.
56
+ let normalized = source;
57
+ if (source instanceof Uint8Array && !Buffer.isBuffer(source)) {
58
+ const u = source;
59
+ normalized = Buffer.from(u.buffer, u.byteOffset, u.byteLength);
60
+ }
61
+ const result = await simpleParser(normalized);
62
+ parentPort.postMessage({ id, ok: true, result });
63
+ }
64
+ catch (e) {
65
+ const error = e instanceof Error ? e.message : String(e);
66
+ parentPort.postMessage({ id, ok: false, error });
67
+ }
68
+ });
69
+ //# sourceMappingURL=parse-worker.js.map
package/store.d.ts ADDED
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Store — the nexus. Owns the local database, the .eml file store, the
3
+ * operations API, and the event bus. Single source of truth for everything
4
+ * about a mailx account that lives on this device.
5
+ *
6
+ * UI ──┐ ┌── Sync clients (IMAP, Gmail API, …)
7
+ * │ reads / writes / subscribes │ read pending actions, commit
8
+ * ↓ ↓ server-discovered changes
9
+ * [ Store ]
10
+ *
11
+ * Contract: every method here mutates local-only state. No IMAP, no Gmail,
12
+ * no SMTP, no DNS, no Drive API. Mutations emit on the bus; subscribers
13
+ * (UI in another process, in-process reconciler, etc.) react. Sync clients
14
+ * (mailx-imap, mailx-sync) hold a Store reference and never touch the
15
+ * underlying MailxDB / FileMessageStore directly.
16
+ *
17
+ * This was previously named `Store` and lived in mailx-service. It
18
+ * moved to mailx-store because mailx-imap (and other sync clients) must
19
+ * be able to consume it without depending on mailx-service — that's the
20
+ * "arrow points the right way" property of the architecture.
21
+ */
22
+ import { MailxDB } from "./db.js";
23
+ import { FileMessageStore } from "./file-store.js";
24
+ import type { StoreBus } from "./bus.js";
25
+ import type { MessageEnvelope, MessageQuery, PagedResult } from "@bobfrankston/mailx-types";
26
+ /** What the UI gets back from a body read. Mirrors the historical
27
+ * `getMessage` shape so call-site migration is mechanical. `cached: false`
28
+ * means the body isn't on disk yet — the UI shows a "downloading…"
29
+ * placeholder and listens for `bodyAvailable` to re-render. The reconciler
30
+ * is responsible for actually fetching and emitting the event. */
31
+ export interface StoreMessage extends MessageEnvelope {
32
+ bodyHtml: string;
33
+ bodyText: string;
34
+ hasRemoteContent: boolean;
35
+ remoteAllowed: boolean;
36
+ attachments: Array<{
37
+ id: number;
38
+ filename: string;
39
+ mimeType: string;
40
+ size: number;
41
+ contentId: string;
42
+ }>;
43
+ cached: boolean;
44
+ deliveredTo: string;
45
+ returnPath: string;
46
+ listUnsubscribe: string;
47
+ listUnsubscribeMail: string;
48
+ listUnsubscribeHttp: string;
49
+ listUnsubscribeOneClick: boolean;
50
+ emlPath: string;
51
+ isFlagged: boolean;
52
+ }
53
+ export declare class Store {
54
+ /** SQLite metadata index. Exposed as a public field — sync clients
55
+ * (mailx-imap, mailx-sync) read/write through it during the
56
+ * refactor. Future state: every external mutation routes through
57
+ * a Store method that emits a bus event; raw `store.db.X()` calls
58
+ * shrink to zero. Today, this is read mostly. */
59
+ readonly db: MailxDB;
60
+ /** .eml file backend. Same migration story as `db` — sync clients
61
+ * read/write directly today, will route through Store methods. */
62
+ readonly bodyStore: FileMessageStore;
63
+ /** Event bus for Store mutations. Defaults to the process-singleton
64
+ * so cross-package subscribers (bin/mailx.ts forwarder → WebView,
65
+ * in-process reconciler triggers) see all writes without explicit
66
+ * wiring. Tests can pass a fresh StoreBus for isolation. */
67
+ readonly bus: StoreBus;
68
+ private static readonly PARSED_LRU_CAPACITY;
69
+ private parsedLru;
70
+ private parsedLruGet;
71
+ private parsedLruPut;
72
+ private _allowlistCache;
73
+ private _settingsCache;
74
+ private getCachedAllowlist;
75
+ private getCachedSettings;
76
+ invalidateConfigCaches(): void;
77
+ constructor(
78
+ /** SQLite metadata index. Exposed as a public field — sync clients
79
+ * (mailx-imap, mailx-sync) read/write through it during the
80
+ * refactor. Future state: every external mutation routes through
81
+ * a Store method that emits a bus event; raw `store.db.X()` calls
82
+ * shrink to zero. Today, this is read mostly. */
83
+ db: MailxDB,
84
+ /** .eml file backend. Same migration story as `db` — sync clients
85
+ * read/write directly today, will route through Store methods. */
86
+ bodyStore: FileMessageStore,
87
+ /** Event bus for Store mutations. Defaults to the process-singleton
88
+ * so cross-package subscribers (bin/mailx.ts forwarder → WebView,
89
+ * in-process reconciler triggers) see all writes without explicit
90
+ * wiring. Tests can pass a fresh StoreBus for isolation. */
91
+ bus?: StoreBus);
92
+ /** DB-shape account list (id/name/email/lastSync). The richer
93
+ * AccountConfig (with imap/smtp/etc.) lives in accounts.jsonc and is
94
+ * loaded by mailx-settings, not the DB — that path stays in
95
+ * MailxService until step 3 of the local-first plan. */
96
+ getAccounts(): {
97
+ id: string;
98
+ name: string;
99
+ email: string;
100
+ lastSync: number;
101
+ }[];
102
+ getFolders(accountId: string): any[];
103
+ /** Look up a folder by RFC 6154 specialUse tag (`trash`, `drafts`, `sent`,
104
+ * `junk`, etc.) for the given account. Falls back to a case-insensitive
105
+ * path match for legacy rows where specialUse never got tagged.
106
+ * Returns null when the account has no such folder configured. */
107
+ findSpecialFolder(accountId: string, specialUse: string): {
108
+ id: number;
109
+ path: string;
110
+ } | null;
111
+ /** Single envelope by (account, uid, folder). Null when the row isn't
112
+ * in the DB — caller decides whether to show "deleted" or queue a
113
+ * server lookup via the reconciler. */
114
+ getMessageEnvelope(accountId: string, uid: number, folderId?: number): MessageEnvelope | null;
115
+ /** Paginated message list for a (account, folder, ...) query. */
116
+ getMessages(query: MessageQuery): PagedResult<MessageEnvelope>;
117
+ /** All-Inboxes view: union of every account's INBOX, paginated. */
118
+ getUnifiedInbox(page?: number, pageSize?: number): PagedResult<MessageEnvelope>;
119
+ /** Local FTS5 search. Server-scope search is the reconciler's job. */
120
+ searchMessages(query: string, page?: number, pageSize?: number, accountId?: string, folderId?: number, includeTrashSpam?: boolean): PagedResult<MessageEnvelope>;
121
+ /** Read a fully-parsed message (envelope + body + attachments) entirely
122
+ * from local state. Returns null when the envelope isn't known.
123
+ * Returns `{ ...envelope, cached: false }` when the envelope is known
124
+ * but the body file isn't on disk — UI shows a placeholder and the
125
+ * reconciler queues the fetch.
126
+ *
127
+ * `allowRemote=true` skips HTML sanitization. Used when the user has
128
+ * explicitly allowed remote content for this sender / domain. */
129
+ getMessage(accountId: string, uid: number, allowRemote: boolean, folderId?: number): Promise<StoreMessage | null>;
130
+ getCalendarEvents(accountId: string, fromMs: number, toMs: number): any[];
131
+ getTasks(accountId: string, includeCompleted?: boolean): any[];
132
+ searchContacts(query: string, limit?: number): any[];
133
+ listContacts(query: string, page?: number, pageSize?: number): any;
134
+ /** Update a message's flag set. Local DB write completes synchronously;
135
+ * the server-mirror enqueue is the caller's responsibility (typically
136
+ * via SyncQueue.enqueueFlag) so callers that don't want a server push
137
+ * — pure-local UI state like "pin in pane" — can skip it.
138
+ *
139
+ * Publishes:
140
+ * `message:<uuid>` { kind: "flagsChanged" }
141
+ * `folder:<id>` (auto fan-out)
142
+ */
143
+ updateFlags(accountId: string, uid: number, folderId: number, flags: string[]): void;
144
+ /** Move a message between folders in the same account. Adds a tombstone
145
+ * on the Message-ID so the next sync doesn't re-import the pre-move row
146
+ * in the source folder before the server-side MOVE completes; tombstone
147
+ * is cleared on terminal IMAP failure (see processSyncActions).
148
+ *
149
+ * Returns true if a local row existed and was moved, false otherwise.
150
+ *
151
+ * Publishes:
152
+ * `message:<uuid>` { kind: "messageMoved", folderId: source, targetFolderId }
153
+ * `folder:<source>` and `folder:<target>` (auto fan-out + explicit count)
154
+ */
155
+ moveMessage(accountId: string, uid: number, fromFolderId: number, targetFolderId: number): boolean;
156
+ /** Trash a message. If a trash folder is configured and the message is
157
+ * not already in it, this is a move-to-trash. If the message is already
158
+ * in trash (or no trash exists), it's a hard delete + body unlink.
159
+ *
160
+ * Returns "moved-to-trash" or "expunged" so the caller knows whether
161
+ * to enqueue an IMAP MOVE or a DELETE+EXPUNGE on the queue.
162
+ */
163
+ trashMessage(accountId: string, uid: number, folderId: number, trashFolderId: number | null): "moved-to-trash" | "expunged";
164
+ /** Restore a message from trash back to its original folder. Local-only;
165
+ * caller handles the queue (cancel-pending-MOVE vs queue-counter-MOVE).
166
+ * Returns true if a local row was moved. */
167
+ undeleteMessage(accountId: string, uid: number, trashFolderId: number, originalFolderId: number): boolean;
168
+ }
169
+ //# sourceMappingURL=store.d.ts.map