@remit/imap-worker 0.0.57 → 0.0.59

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remit/imap-worker",
3
- "version": "0.0.57",
3
+ "version": "0.0.59",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "exports": {
@@ -31,6 +31,7 @@
31
31
  },
32
32
  "dependencies": {
33
33
  "@aws-sdk/client-s3": "^3.1055.0",
34
+ "@remit/config-transfer": "*",
34
35
  "@remit/data-ports": "*",
35
36
  "@remit/smtp-service": "*",
36
37
  "@remit/logger-lambda": "*",
@@ -2,9 +2,11 @@ import assert from "node:assert/strict";
2
2
  import { describe, it } from "node:test";
3
3
  import {
4
4
  DEFAULT_MAILBOX_FRESHNESS_MS,
5
+ emitSyncMessagesEvents,
5
6
  MAILBOX_FRESHNESS_MS,
6
7
  mailboxNeedsSync,
7
8
  resolveMailboxFreshnessMs,
9
+ splitInboxFirst,
8
10
  } from "./sync-mailboxes.js";
9
11
 
10
12
  const NOW = 1_700_000_000_000;
@@ -84,3 +86,99 @@ describe("resolveMailboxFreshnessMs", () => {
84
86
  );
85
87
  });
86
88
  });
89
+
90
+ describe("splitInboxFirst", () => {
91
+ it("pulls INBOX out of the list whatever case it is spelled in", () => {
92
+ const { inbox, rest } = splitInboxFirst([
93
+ { mailboxId: "mb-sent", fullPath: "Sent" },
94
+ { mailboxId: "mb-inbox", fullPath: "Inbox" },
95
+ { mailboxId: "mb-junk", fullPath: "Junk" },
96
+ ]);
97
+
98
+ assert.equal(inbox?.mailboxId, "mb-inbox");
99
+ assert.deepEqual(
100
+ rest.map((mailbox) => mailbox.mailboxId),
101
+ ["mb-sent", "mb-junk"],
102
+ );
103
+ });
104
+
105
+ it("leaves an account without an INBOX intact", () => {
106
+ const { inbox, rest } = splitInboxFirst([
107
+ { mailboxId: "mb-sent", fullPath: "Sent" },
108
+ ]);
109
+
110
+ assert.equal(inbox, undefined);
111
+ assert.deepEqual(
112
+ rest.map((mailbox) => mailbox.mailboxId),
113
+ ["mb-sent"],
114
+ );
115
+ });
116
+ });
117
+
118
+ describe("emitSyncMessagesEvents", () => {
119
+ // Every event of an account shares one FIFO group, so arrival order is
120
+ // service order. pMap only bounds concurrency: it used to race all the
121
+ // emits, letting INBOX queue behind up to nineteen other folders while a
122
+ // person waited for their new mail.
123
+ it("emits INBOX before any other folder", async () => {
124
+ const emitted: string[] = [];
125
+ const mailboxes = Array.from({ length: 25 }, (_, index) => ({
126
+ mailboxId: `mb-${index}`,
127
+ fullPath: `Folder ${index}`,
128
+ }));
129
+ mailboxes.push({ mailboxId: "mb-inbox", fullPath: "INBOX" });
130
+
131
+ await emitSyncMessagesEvents("acc-1", mailboxes, async (event) => {
132
+ emitted.push(event.mailboxId);
133
+ });
134
+
135
+ assert.equal(emitted[0], "mb-inbox");
136
+ assert.equal(emitted.length, 26);
137
+ });
138
+
139
+ // Emitting INBOX and awaiting it is the whole fix: a fire-and-forget emit
140
+ // would leave it racing the fan-out again.
141
+ it("waits for the INBOX emit to resolve before emitting the rest", async () => {
142
+ const emitted: string[] = [];
143
+ let releaseInbox: () => void = () => {};
144
+ const inboxEmitted = new Promise<void>((resolve) => {
145
+ releaseInbox = resolve;
146
+ });
147
+
148
+ const done = emitSyncMessagesEvents(
149
+ "acc-1",
150
+ [
151
+ { mailboxId: "mb-inbox", fullPath: "INBOX" },
152
+ { mailboxId: "mb-sent", fullPath: "Sent" },
153
+ ],
154
+ async (event) => {
155
+ emitted.push(event.mailboxId);
156
+ if (event.mailboxId === "mb-inbox") await inboxEmitted;
157
+ },
158
+ );
159
+
160
+ await new Promise((resolve) => setImmediate(resolve));
161
+ assert.deepEqual(emitted, ["mb-inbox"]);
162
+
163
+ releaseInbox();
164
+ await done;
165
+ assert.deepEqual(emitted, ["mb-inbox", "mb-sent"]);
166
+ });
167
+
168
+ it("emits every folder for an account with no INBOX", async () => {
169
+ const emitted: string[] = [];
170
+
171
+ await emitSyncMessagesEvents(
172
+ "acc-1",
173
+ [
174
+ { mailboxId: "mb-sent", fullPath: "Sent" },
175
+ { mailboxId: "mb-junk", fullPath: "Junk" },
176
+ ],
177
+ async (event) => {
178
+ emitted.push(event.mailboxId);
179
+ },
180
+ );
181
+
182
+ assert.deepEqual(emitted.sort(), ["mb-junk", "mb-sent"]);
183
+ });
184
+ });
@@ -1,10 +1,16 @@
1
1
  import { getClient } from "@remit/backend/client";
2
+ import { writeFolderRoleAppointment } from "@remit/backend/folder-role-appointments";
3
+ import {
4
+ bindImportedFolders,
5
+ type ConfigBinderDeps,
6
+ } from "@remit/config-transfer";
2
7
  import type {
3
8
  AccountItem,
4
9
  IAccountRepository,
5
10
  IMailboxRepository,
6
11
  IMailboxSpecialUseRepository,
7
12
  } from "@remit/data-ports";
13
+ import type { CanonicalMailboxRoleValue } from "@remit/data-ports/folder-role";
8
14
  import { SyncPhase } from "@remit/domain-enums";
9
15
  import type { Logger } from "@remit/logger-lambda";
10
16
  import { RefreshTokenError } from "@remit/mail-oauth-service";
@@ -31,9 +37,9 @@ const EVENT_EMIT_CONCURRENCY = 20;
31
37
  * client produces when it loads (`GET /config` triggers a sync per account)
32
38
  * into one round of IMAP work.
33
39
  *
34
- * The web client floors its automatic poll at this same window
35
- * (`MIN_POLL_INTERVAL_MS` in useStaleAccountSync), so the one caller that
36
- * skips this gate on a timer still cannot drive a fan-out faster than it.
40
+ * This gates side-effect triggers only. The web client's automatic poll asks
41
+ * by name and so skips it; what bounds that one is its own floor
42
+ * (`MIN_POLL_INTERVAL_MS` in useStaleAccountSync, 30s).
37
43
  */
38
44
  export const DEFAULT_MAILBOX_FRESHNESS_MS = 60_000;
39
45
 
@@ -82,12 +88,25 @@ export const syncMailboxes = async (
82
88
  event: SyncMailboxesEvent,
83
89
  log: Logger,
84
90
  ): Promise<void> => {
91
+ const client = await getClient();
85
92
  const {
86
93
  account: accountService,
87
94
  mailbox: mailboxService,
88
95
  mailboxSpecialUse: mailboxSpecialUseService,
89
96
  secrets,
90
- } = await getClient();
97
+ } = client;
98
+ const binder: ConfigBinderDeps = {
99
+ repositories: client,
100
+ appointFolderRole: (configId, accountId, role, mailboxId, lastKnownPath) =>
101
+ writeFolderRoleAppointment(
102
+ client.accountSetting,
103
+ configId,
104
+ accountId,
105
+ role as CanonicalMailboxRoleValue,
106
+ mailboxId,
107
+ lastKnownPath,
108
+ ),
109
+ };
91
110
 
92
111
  const { accountId } = event;
93
112
  log.info({ event: event.type, accountId }, "Handling event");
@@ -125,6 +144,7 @@ export const syncMailboxes = async (
125
144
  mailboxService,
126
145
  mailboxSpecialUseService,
127
146
  accountService,
147
+ binder,
128
148
  log,
129
149
  );
130
150
  } catch (err) {
@@ -157,6 +177,7 @@ const syncMailboxesForAccount = async (
157
177
  mailboxService: IMailboxRepository,
158
178
  mailboxSpecialUseService: IMailboxSpecialUseRepository,
159
179
  accountService: IAccountRepository,
180
+ binder: ConfigBinderDeps,
160
181
  log: Logger,
161
182
  ): Promise<void> => {
162
183
  const { accountId } = account;
@@ -194,6 +215,20 @@ const syncMailboxesForAccount = async (
194
215
 
195
216
  log.info({ result }, "Mailbox sync complete");
196
217
 
218
+ // The folder list this account holds is now known, which is the one thing a
219
+ // configuration import could not know when it ran: every folder in a file is
220
+ // named by IMAP path, and the ids are minted here. Binding what is bindable
221
+ // belongs at exactly this point, and is idempotent, so a later discovery
222
+ // simply finds nothing left to do.
223
+ const bound = await bindImportedFolders(
224
+ binder,
225
+ account.accountConfigId,
226
+ accountId,
227
+ );
228
+ if (bound.bound > 0 || bound.stillPending > 0) {
229
+ log.info({ accountId, ...bound }, "Bound imported folder references");
230
+ }
231
+
197
232
  const allMailboxes = await collectAllMailboxes(accountId, mailboxService);
198
233
 
199
234
  // This fan-out is where an account's IMAP work is decided: one SEARCH per
@@ -264,20 +299,54 @@ const syncMailboxesForAccount = async (
264
299
  mailboxCountSynced: skipped,
265
300
  });
266
301
 
267
- // Emit events in parallel with concurrency limit
268
- // INBOX is first in the sorted list, so it gets priority
269
- await pMap(
270
- mailboxes,
271
- ({ mailboxId }) => {
272
- const syncEvent: Omit<SyncMessagesEvent, "eventId" | "timestamp"> = {
273
- type: "SYNC_MESSAGES",
274
- accountId,
275
- mailboxId,
276
- };
277
- return emitEvent(syncEvent);
278
- },
279
- { concurrency: EVENT_EMIT_CONCURRENCY },
302
+ await emitSyncMessagesEvents(accountId, mailboxes, emitEvent);
303
+ };
304
+
305
+ type SyncMessagesInput = Omit<SyncMessagesEvent, "eventId" | "timestamp">;
306
+
307
+ /**
308
+ * Separate INBOX from the rest of the fan-out. `collectAllMailboxes` sorts it
309
+ * first, but sort order alone decides nothing once the emits go out together.
310
+ */
311
+ export const splitInboxFirst = <T extends { fullPath: string }>(
312
+ mailboxes: readonly T[],
313
+ ): { inbox: T | undefined; rest: T[] } => {
314
+ const at = mailboxes.findIndex(
315
+ (mailbox) => mailbox.fullPath.toUpperCase() === "INBOX",
280
316
  );
317
+ if (at === -1) return { inbox: undefined, rest: [...mailboxes] };
318
+ return {
319
+ inbox: mailboxes[at],
320
+ rest: mailboxes.filter((_, index) => index !== at),
321
+ };
322
+ };
323
+
324
+ /**
325
+ * Emit INBOX's SYNC_MESSAGES event and wait for it before emitting the rest.
326
+ *
327
+ * Every event of an account shares one FIFO group (`MessageGroupId =
328
+ * accountId`), so the queue serves them strictly in arrival order. Emitting
329
+ * the whole list through `pMap` only bounds concurrency — it races the writes,
330
+ * and INBOX could land behind up to `EVENT_EMIT_CONCURRENCY - 1` other
331
+ * folders. The mail a person pressed refresh for then arrived only after every
332
+ * one of those folders had finished syncing.
333
+ */
334
+ export const emitSyncMessagesEvents = async (
335
+ accountId: string,
336
+ mailboxes: readonly { mailboxId: string; fullPath: string }[],
337
+ emit: (event: SyncMessagesInput) => Promise<unknown>,
338
+ ): Promise<void> => {
339
+ const eventFor = (mailboxId: string): SyncMessagesInput => ({
340
+ type: "SYNC_MESSAGES",
341
+ accountId,
342
+ mailboxId,
343
+ });
344
+
345
+ const { inbox, rest } = splitInboxFirst(mailboxes);
346
+ if (inbox) await emit(eventFor(inbox.mailboxId));
347
+ await pMap(rest, ({ mailboxId }) => emit(eventFor(mailboxId)), {
348
+ concurrency: EVENT_EMIT_CONCURRENCY,
349
+ });
281
350
  };
282
351
 
283
352
  type MailboxSortEntry = {