@remit/mailbox-service 0.0.1

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.
Files changed (124) hide show
  1. package/README.md +147 -0
  2. package/package.json +65 -0
  3. package/src/account-credentials.ts +128 -0
  4. package/src/adversarial-mime.e2e.test.ts +311 -0
  5. package/src/attribute-mapper.test.ts +78 -0
  6. package/src/attribute-mapper.ts +147 -0
  7. package/src/body-part-mapper.property.test.ts +354 -0
  8. package/src/body-part-mapper.ts +360 -0
  9. package/src/body-sync-queue.test.ts +124 -0
  10. package/src/body-sync-queue.ts +131 -0
  11. package/src/body-sync-terminal.test.ts +265 -0
  12. package/src/body-sync-terminal.ts +172 -0
  13. package/src/body-sync.ts +1202 -0
  14. package/src/connection-factory.ts +102 -0
  15. package/src/connection-test.ts +208 -0
  16. package/src/credentials.test.ts +181 -0
  17. package/src/filters/match.test.ts +181 -0
  18. package/src/filters/match.ts +143 -0
  19. package/src/filters/pipeline.ts +243 -0
  20. package/src/flag-push-terminal.test.ts +156 -0
  21. package/src/flag-push-terminal.ts +106 -0
  22. package/src/flag-push.test.ts +408 -0
  23. package/src/flag-push.ts +198 -0
  24. package/src/flag-queue.ts +500 -0
  25. package/src/heuristics/classifyByHeaders.test.ts +578 -0
  26. package/src/heuristics/classifyByHeaders.ts +369 -0
  27. package/src/heuristics/classifyPlacement.ts +96 -0
  28. package/src/heuristics/socialDomains.ts +23 -0
  29. package/src/heuristics/transactionalDomains.ts +26 -0
  30. package/src/imapflow-connect-retry.test.ts +108 -0
  31. package/src/imapflow-connection.e2e.test.ts +355 -0
  32. package/src/imapflow-connection.integ.test.ts +327 -0
  33. package/src/imapflow-connection.test.ts +161 -0
  34. package/src/imapflow-connection.ts +1374 -0
  35. package/src/index.ts +214 -0
  36. package/src/mailbox-cursor-rebuild.test.ts +171 -0
  37. package/src/mailbox-cursor-rebuild.ts +146 -0
  38. package/src/mailbox-cursor.test.ts +249 -0
  39. package/src/mailbox-cursor.ts +177 -0
  40. package/src/mailbox-management.test.ts +103 -0
  41. package/src/mailbox-management.ts +235 -0
  42. package/src/mailbox-queue.ts +258 -0
  43. package/src/mailbox-sync.test.ts +153 -0
  44. package/src/mailbox-sync.ts +590 -0
  45. package/src/message-move.ts +825 -0
  46. package/src/message-parser.ts +26 -0
  47. package/src/message-sync.ts +1021 -0
  48. package/src/mime-walker.test.ts +311 -0
  49. package/src/mime-walker.ts +305 -0
  50. package/src/outbox-queue.ts +294 -0
  51. package/src/pass-through-unit-of-work.ts +17 -0
  52. package/src/placement-move-terminal.test.ts +179 -0
  53. package/src/placement-move-terminal.ts +104 -0
  54. package/src/placement-move.ts +224 -0
  55. package/src/snippet.test.ts +213 -0
  56. package/src/snippet.ts +152 -0
  57. package/src/stale-message-reconcile.test.ts +82 -0
  58. package/src/stale-message-reconcile.ts +55 -0
  59. package/src/test-helpers/isolated-mailbox.ts +44 -0
  60. package/src/test-helpers/mailfuzz-connection.ts +27 -0
  61. package/src/test-helpers/mime-tree-generator.ts +461 -0
  62. package/src/text/normalizer.test.ts +223 -0
  63. package/src/text/normalizer.ts +140 -0
  64. package/src/types/mailparser-augment.d.ts +15 -0
  65. package/src/types/natural-porter-stemmer.d.ts +50 -0
  66. package/src/types/stopword.d.ts +69 -0
  67. package/src/types.ts +349 -0
  68. package/test/fixtures/mime/01-flat-text-plain.bodyparts.json +8 -0
  69. package/test/fixtures/mime/01-flat-text-plain.eml +10 -0
  70. package/test/fixtures/mime/01-flat-text-plain.expected.json +10 -0
  71. package/test/fixtures/mime/02-flat-text-html.bodyparts.json +8 -0
  72. package/test/fixtures/mime/02-flat-text-html.eml +10 -0
  73. package/test/fixtures/mime/02-flat-text-html.expected.json +10 -0
  74. package/test/fixtures/mime/03-alternative-text-html.bodyparts.json +20 -0
  75. package/test/fixtures/mime/03-alternative-text-html.eml +19 -0
  76. package/test/fixtures/mime/03-alternative-text-html.expected.json +16 -0
  77. package/test/fixtures/mime/04-mixed-html-pdf-attachment.bodyparts.json +22 -0
  78. package/test/fixtures/mime/04-mixed-html-pdf-attachment.eml +20 -0
  79. package/test/fixtures/mime/04-mixed-html-pdf-attachment.expected.json +16 -0
  80. package/test/fixtures/mime/05-mixed-html-octet-stream-pdf.bodyparts.json +22 -0
  81. package/test/fixtures/mime/05-mixed-html-octet-stream-pdf.eml +21 -0
  82. package/test/fixtures/mime/05-mixed-html-octet-stream-pdf.expected.json +16 -0
  83. package/test/fixtures/mime/06-related-html-cid-image.bodyparts.json +23 -0
  84. package/test/fixtures/mime/06-related-html-cid-image.eml +21 -0
  85. package/test/fixtures/mime/06-related-html-cid-image.expected.json +16 -0
  86. package/test/fixtures/mime/07-mixed-alternative-related-attachment.bodyparts.json +55 -0
  87. package/test/fixtures/mime/07-mixed-alternative-related-attachment.eml +47 -0
  88. package/test/fixtures/mime/07-mixed-alternative-related-attachment.expected.json +34 -0
  89. package/test/fixtures/mime/08-two-pdfs-same-filename.bodyparts.json +30 -0
  90. package/test/fixtures/mime/08-two-pdfs-same-filename.eml +26 -0
  91. package/test/fixtures/mime/08-two-pdfs-same-filename.expected.json +22 -0
  92. package/test/fixtures/mime/09-attachment-no-filename.bodyparts.json +21 -0
  93. package/test/fixtures/mime/09-attachment-no-filename.eml +20 -0
  94. package/test/fixtures/mime/09-attachment-no-filename.expected.json +16 -0
  95. package/test/fixtures/mime/10-calendar-invite.bodyparts.json +22 -0
  96. package/test/fixtures/mime/10-calendar-invite.eml +33 -0
  97. package/test/fixtures/mime/10-calendar-invite.expected.json +16 -0
  98. package/test/fixtures/mime/11-quoted-printable-text.bodyparts.json +8 -0
  99. package/test/fixtures/mime/11-quoted-printable-text.eml +10 -0
  100. package/test/fixtures/mime/11-quoted-printable-text.expected.json +10 -0
  101. package/test/fixtures/mime/12-base64-binary.bodyparts.json +22 -0
  102. package/test/fixtures/mime/12-base64-binary.eml +20 -0
  103. package/test/fixtures/mime/12-base64-binary.expected.json +16 -0
  104. package/test/fixtures/mime/13-message-rfc822-forward.bodyparts.json +22 -0
  105. package/test/fixtures/mime/13-message-rfc822-forward.eml +28 -0
  106. package/test/fixtures/mime/13-message-rfc822-forward.expected.json +16 -0
  107. package/test/fixtures/mime/14-deeply-nested-5-levels.bodyparts.json +38 -0
  108. package/test/fixtures/mime/14-deeply-nested-5-levels.eml +34 -0
  109. package/test/fixtures/mime/14-deeply-nested-5-levels.expected.json +10 -0
  110. package/test/fixtures/mime/15-empty-text-part.bodyparts.json +21 -0
  111. package/test/fixtures/mime/15-empty-text-part.eml +18 -0
  112. package/test/fixtures/mime/15-empty-text-part.expected.json +16 -0
  113. package/test/fixtures/mime/16-empty-non-text-part.bodyparts.json +30 -0
  114. package/test/fixtures/mime/16-empty-non-text-part.eml +24 -0
  115. package/test/fixtures/mime/16-empty-non-text-part.expected.json +22 -0
  116. package/test/fixtures/mime-adversarial-e2e/01-octet-stream-pdf.eml +21 -0
  117. package/test/fixtures/mime-adversarial-e2e/02-nested-related-cid-image.eml +31 -0
  118. package/test/fixtures/mime-adversarial-e2e/03-calendar-invite.eml +33 -0
  119. package/test/fixtures/mime-adversarial-e2e/04-forwarded-rfc822-with-attachments.eml +42 -0
  120. package/test/fixtures/mime-adversarial-e2e/05-tnef-winmail.eml +25 -0
  121. package/test/fixtures/mime-adversarial-e2e/06-8bit-non-ascii.eml +15 -0
  122. package/test/fixtures/mime-adversarial-e2e/07-quoted-printable-soft-breaks.eml +17 -0
  123. package/test/fixtures/mime-adversarial-e2e/08-alternative-empty-text.eml +18 -0
  124. package/tsconfig.json +8 -0
@@ -0,0 +1,265 @@
1
+ import assert from "node:assert/strict";
2
+ import { describe, it } from "node:test";
3
+ import type {
4
+ IMessageRepository,
5
+ IThreadMessageRepository,
6
+ } from "@remit/data-ports";
7
+ import type {
8
+ StorageService,
9
+ StoreBodyPartParams,
10
+ } from "@remit/storage-service";
11
+ import type { BodySyncLogger } from "./body-sync.js";
12
+ import {
13
+ isMessageBodySyncBroken,
14
+ type ResolveExhaustedBodySyncDeps,
15
+ resolveExhaustedBodySyncFailures,
16
+ } from "./body-sync-terminal.js";
17
+ import type { IImapConnection } from "./types.js";
18
+
19
+ interface LogEntry {
20
+ obj: Record<string, unknown>;
21
+ msg: string;
22
+ }
23
+
24
+ const buildLogger = (): {
25
+ log: BodySyncLogger;
26
+ infos: LogEntry[];
27
+ errors: LogEntry[];
28
+ } => {
29
+ const infos: LogEntry[] = [];
30
+ const errors: LogEntry[] = [];
31
+ return {
32
+ log: {
33
+ info: (obj, msg) => infos.push({ obj, msg: msg ?? "" }),
34
+ error: (obj, msg) => errors.push({ obj, msg: msg ?? "" }),
35
+ },
36
+ infos,
37
+ errors,
38
+ };
39
+ };
40
+
41
+ /** Message rows keyed by messageId; `uid` is the only field the resolver reads. */
42
+ const buildMessageService = (
43
+ uidByMessageId: Record<string, number>,
44
+ deleted: string[],
45
+ ): Pick<IMessageRepository, "get" | "delete"> =>
46
+ ({
47
+ get: async (messageId: string) => {
48
+ const uid = uidByMessageId[messageId];
49
+ if (uid === undefined) {
50
+ throw new Error(`no fixture uid for ${messageId}`);
51
+ }
52
+ return { messageId, uid };
53
+ },
54
+ delete: async (messageId: string) => {
55
+ deleted.push(messageId);
56
+ },
57
+ }) as unknown as Pick<IMessageRepository, "get" | "delete">;
58
+
59
+ const buildThreadMessageService = (
60
+ deletedKeys: Array<{ accountConfigId: string; threadMessageId: string }>,
61
+ ): Pick<IThreadMessageRepository, "findAllByMessageId" | "deleteMany"> =>
62
+ ({
63
+ findAllByMessageId: async (accountConfigId: string, messageId: string) => [
64
+ {
65
+ accountConfigId,
66
+ threadMessageId: `tm-${messageId}`,
67
+ messageId,
68
+ },
69
+ ],
70
+ deleteMany: async (
71
+ keys: Array<{ accountConfigId: string; threadMessageId: string }>,
72
+ ) => {
73
+ deletedKeys.push(...keys);
74
+ },
75
+ }) as unknown as Pick<
76
+ IThreadMessageRepository,
77
+ "findAllByMessageId" | "deleteMany"
78
+ >;
79
+
80
+ const buildStorageService = (
81
+ brokenAlready: Set<string> = new Set(),
82
+ ): {
83
+ storageService: Pick<StorageService, "storeBodyPart" | "bodyPartExists">;
84
+ stored: StoreBodyPartParams[];
85
+ } => {
86
+ const stored: StoreBodyPartParams[] = [];
87
+ return {
88
+ stored,
89
+ storageService: {
90
+ storeBodyPart: async (params: StoreBodyPartParams) => {
91
+ stored.push(params);
92
+ brokenAlready.add(params.messageId);
93
+ return {} as never;
94
+ },
95
+ bodyPartExists: async (
96
+ _accountConfigId: string,
97
+ _accountId: string,
98
+ messageId: string,
99
+ partPath: string,
100
+ ) => partPath === ".sync-failed" && brokenAlready.has(messageId),
101
+ },
102
+ };
103
+ };
104
+
105
+ /** A connection whose `fetchMessages` returns a hit for every uid in `present`. */
106
+ const buildConnection = (present: Set<number>): IImapConnection =>
107
+ ({
108
+ openBox: async () => ({}) as never,
109
+ fetchMessages: async (uids: number[]) =>
110
+ uids
111
+ .filter((uid) => present.has(uid))
112
+ .map((uid) => ({ uid }) as unknown as never),
113
+ }) as unknown as IImapConnection;
114
+
115
+ describe("resolveExhaustedBodySyncFailures — the two terminal outcomes", () => {
116
+ it("outcome 1 (EXPECTED): a uid missing from IMAP reconciles the stale row, no alarm", async () => {
117
+ const deletedMessages: string[] = [];
118
+ const deletedThreadMessages: Array<{
119
+ accountConfigId: string;
120
+ threadMessageId: string;
121
+ }> = [];
122
+ const { storageService, stored } = buildStorageService();
123
+ const { log, infos, errors } = buildLogger();
124
+
125
+ const deps: ResolveExhaustedBodySyncDeps = {
126
+ messageService: buildMessageService({ "msg-gone": 101 }, deletedMessages),
127
+ threadMessageService: buildThreadMessageService(deletedThreadMessages),
128
+ storageService,
129
+ log,
130
+ };
131
+
132
+ const result = await resolveExhaustedBodySyncFailures(deps, {
133
+ accountId: "acc-1",
134
+ accountConfigId: "cfg-1",
135
+ mailboxId: "mbx-1",
136
+ mailboxPath: "INBOX",
137
+ failedMessageIds: ["msg-gone"],
138
+ getConnection: async () => buildConnection(new Set()),
139
+ });
140
+
141
+ assert.deepEqual(result.reconciledMessageIds, ["msg-gone"]);
142
+ assert.deepEqual(result.brokenMessageIds, []);
143
+ assert.deepEqual(deletedMessages, ["msg-gone"]);
144
+ assert.deepEqual(deletedThreadMessages, [
145
+ { accountConfigId: "cfg-1", threadMessageId: "tm-msg-gone" },
146
+ ]);
147
+ // No sentinel written, no alert-shaped log for the expected case.
148
+ assert.equal(stored.length, 0);
149
+ assert.equal(errors.length, 0);
150
+ assert.ok(
151
+ infos.some((e) => e.obj.metric === "body_sync_stale_row_reconciled"),
152
+ "expects an info-level metric log, not an alert",
153
+ );
154
+ });
155
+
156
+ it("outcome 2 (BROKEN): a uid IMAP still has persists the failed-forever sentinel and alerts", async () => {
157
+ const deletedMessages: string[] = [];
158
+ const { storageService, stored } = buildStorageService();
159
+ const { log, errors } = buildLogger();
160
+
161
+ const deps: ResolveExhaustedBodySyncDeps = {
162
+ messageService: buildMessageService(
163
+ { "msg-broken": 202 },
164
+ deletedMessages,
165
+ ),
166
+ threadMessageService: buildThreadMessageService([]),
167
+ storageService,
168
+ log,
169
+ };
170
+
171
+ const result = await resolveExhaustedBodySyncFailures(deps, {
172
+ accountId: "acc-1",
173
+ accountConfigId: "cfg-1",
174
+ mailboxId: "mbx-1",
175
+ mailboxPath: "INBOX",
176
+ failedMessageIds: ["msg-broken"],
177
+ getConnection: async () => buildConnection(new Set([202])),
178
+ });
179
+
180
+ assert.deepEqual(result.brokenMessageIds, ["msg-broken"]);
181
+ assert.deepEqual(result.reconciledMessageIds, []);
182
+ // The row is never deleted for a broken (still-real) message.
183
+ assert.deepEqual(deletedMessages, []);
184
+ assert.equal(stored.length, 1);
185
+ assert.equal(stored[0]?.partPath, ".sync-failed");
186
+ assert.ok(
187
+ errors.some((e) => e.obj.alert === "body_sync_message_broken"),
188
+ "expects an alert-shaped error log for the broken case",
189
+ );
190
+ });
191
+
192
+ it("resolves a mixed batch into both outcomes independently", async () => {
193
+ const deletedMessages: string[] = [];
194
+ const { storageService } = buildStorageService();
195
+ const { log } = buildLogger();
196
+
197
+ const deps: ResolveExhaustedBodySyncDeps = {
198
+ messageService: buildMessageService(
199
+ { "msg-gone": 1, "msg-broken": 2 },
200
+ deletedMessages,
201
+ ),
202
+ threadMessageService: buildThreadMessageService([]),
203
+ storageService,
204
+ log,
205
+ };
206
+
207
+ const result = await resolveExhaustedBodySyncFailures(deps, {
208
+ accountId: "acc-1",
209
+ accountConfigId: "cfg-1",
210
+ mailboxId: "mbx-1",
211
+ mailboxPath: "INBOX",
212
+ failedMessageIds: ["msg-gone", "msg-broken"],
213
+ getConnection: async () => buildConnection(new Set([2])),
214
+ });
215
+
216
+ assert.deepEqual(result.reconciledMessageIds, ["msg-gone"]);
217
+ assert.deepEqual(result.brokenMessageIds, ["msg-broken"]);
218
+ });
219
+
220
+ it("no failed ids is a no-op — never opens a connection", async () => {
221
+ const { storageService } = buildStorageService();
222
+ const { log } = buildLogger();
223
+ let connectionRequested = false;
224
+
225
+ const deps: ResolveExhaustedBodySyncDeps = {
226
+ messageService: buildMessageService({}, []),
227
+ threadMessageService: buildThreadMessageService([]),
228
+ storageService,
229
+ log,
230
+ };
231
+
232
+ const result = await resolveExhaustedBodySyncFailures(deps, {
233
+ accountId: "acc-1",
234
+ accountConfigId: "cfg-1",
235
+ mailboxId: "mbx-1",
236
+ mailboxPath: "INBOX",
237
+ failedMessageIds: [],
238
+ getConnection: async () => {
239
+ connectionRequested = true;
240
+ return buildConnection(new Set());
241
+ },
242
+ });
243
+
244
+ assert.deepEqual(result, {
245
+ reconciledMessageIds: [],
246
+ brokenMessageIds: [],
247
+ });
248
+ assert.equal(connectionRequested, false);
249
+ });
250
+ });
251
+
252
+ describe("isMessageBodySyncBroken", () => {
253
+ it("delegates to bodyPartExists with the sentinel path", async () => {
254
+ const { storageService } = buildStorageService(new Set(["msg-1"]));
255
+
256
+ assert.equal(
257
+ await isMessageBodySyncBroken(storageService, "cfg-1", "acc-1", "msg-1"),
258
+ true,
259
+ );
260
+ assert.equal(
261
+ await isMessageBodySyncBroken(storageService, "cfg-1", "acc-1", "msg-2"),
262
+ false,
263
+ );
264
+ });
265
+ });
@@ -0,0 +1,172 @@
1
+ import type { IMessageRepository } from "@remit/data-ports";
2
+ import type { StorageService } from "@remit/storage-service";
3
+ import type { BodySyncLogger } from "./body-sync.js";
4
+ import {
5
+ reconcileStaleMessage,
6
+ type StaleMessageReconcileDeps,
7
+ } from "./stale-message-reconcile.js";
8
+ import type { IImapConnection } from "./types.js";
9
+
10
+ /**
11
+ * Body-part sentinel path a permanently-broken message's failure context is
12
+ * written under, mirroring the `.materialized` deferred-parts sentinel in
13
+ * `body-sync.ts`. Using the existing per-message body-part storage (instead
14
+ * of a new Message-row column) means no schema change: the read path checks
15
+ * for it with the same `bodyPartExists` HEAD it already issues.
16
+ */
17
+ const BODY_SYNC_FAILED_MARKER_PATH = ".sync-failed";
18
+
19
+ export interface ResolveExhaustedBodySyncDeps
20
+ extends StaleMessageReconcileDeps {
21
+ messageService: Pick<IMessageRepository, "get" | "delete">;
22
+ storageService: Pick<StorageService, "storeBodyPart" | "bodyPartExists">;
23
+ log: BodySyncLogger;
24
+ }
25
+
26
+ export interface ResolveExhaustedBodySyncInput {
27
+ accountId: string;
28
+ accountConfigId: string;
29
+ mailboxId: string;
30
+ mailboxPath: string;
31
+ failedMessageIds: string[];
32
+ getConnection: () => Promise<IImapConnection>;
33
+ }
34
+
35
+ export interface ResolveExhaustedBodySyncResult {
36
+ /** Outcome 1 (EXPECTED): message gone upstream, row deleted. */
37
+ reconciledMessageIds: string[];
38
+ /** Outcome 2 (BROKEN): message exists but is unfetchable/unparseable. */
39
+ brokenMessageIds: string[];
40
+ }
41
+
42
+ /**
43
+ * Whether a message's body-sync has already been marked permanently failed
44
+ * (outcome 2 of {@link resolveExhaustedBodySyncFailures}). The read path
45
+ * calls this before attempting or re-arming any fetch so a client that opens
46
+ * a broken message gets the explicit unrecoverable error immediately instead
47
+ * of looping through another 202 or another IMAP round-trip.
48
+ */
49
+ export const isMessageBodySyncBroken = (
50
+ storageService: Pick<StorageService, "bodyPartExists">,
51
+ accountConfigId: string,
52
+ accountId: string,
53
+ messageId: string,
54
+ ): Promise<boolean> =>
55
+ storageService.bodyPartExists(
56
+ accountConfigId,
57
+ accountId,
58
+ messageId,
59
+ BODY_SYNC_FAILED_MARKER_PATH,
60
+ );
61
+
62
+ const markMessageBodySyncFailed = async (
63
+ storageService: Pick<StorageService, "storeBodyPart">,
64
+ accountConfigId: string,
65
+ accountId: string,
66
+ messageId: string,
67
+ context: Record<string, unknown>,
68
+ ): Promise<void> => {
69
+ await storageService.storeBodyPart({
70
+ accountConfigId,
71
+ accountId,
72
+ messageId,
73
+ partPath: BODY_SYNC_FAILED_MARKER_PATH,
74
+ content: Buffer.from(JSON.stringify({ ...context, failedAt: Date.now() })),
75
+ contentType: "application/json",
76
+ });
77
+ };
78
+
79
+ /**
80
+ * Resolve every SYNC_MESSAGE_BODY failure that has exhausted the body
81
+ * queue's redelivery budget (see `BODY_SYNC_MAX_ATTEMPTS` in
82
+ * `sync-message-body.ts`) into exactly one of the two terminal outcomes
83
+ * issue #1270 / epic #1281 invariant 3 require. There is no third, softer
84
+ * outcome — every failed id lands in one of the two result lists.
85
+ *
86
+ * 1. EXPECTED — the message no longer exists on IMAP (expunged, or a
87
+ * UIDVALIDITY change moved it, #1272). The stale row is deleted via
88
+ * {@link reconcileStaleMessage} so the existing missing-row 404 path
89
+ * takes over. Callers should emit a metric only — this is routine, not an
90
+ * incident.
91
+ * 2. BROKEN — the message still exists on IMAP but its body could not be
92
+ * fetched or parsed. The failure is persisted as a body-part sentinel
93
+ * (survives across invocations and warm/cold starts) and logged with an
94
+ * `alert`-shaped entry so an operator alarm can key off it. Callers
95
+ * should treat this as loud: the message is unrecoverable until an
96
+ * operator investigates.
97
+ *
98
+ * Neither outcome re-enqueues: both are terminal, so the caller acks the SQS
99
+ * message either way — retrying a stale or broken message can never succeed.
100
+ */
101
+ export const resolveExhaustedBodySyncFailures = async (
102
+ deps: ResolveExhaustedBodySyncDeps,
103
+ input: ResolveExhaustedBodySyncInput,
104
+ ): Promise<ResolveExhaustedBodySyncResult> => {
105
+ const {
106
+ accountId,
107
+ accountConfigId,
108
+ mailboxId,
109
+ mailboxPath,
110
+ failedMessageIds,
111
+ getConnection,
112
+ } = input;
113
+
114
+ const reconciledMessageIds: string[] = [];
115
+ const brokenMessageIds: string[] = [];
116
+
117
+ if (failedMessageIds.length === 0) {
118
+ return { reconciledMessageIds, brokenMessageIds };
119
+ }
120
+
121
+ const connection = await getConnection();
122
+ await connection.openBox(mailboxPath);
123
+
124
+ for (const messageId of failedMessageIds) {
125
+ const message = await deps.messageService.get(messageId);
126
+ const found = await connection.fetchMessages([message.uid]);
127
+
128
+ if (found.length === 0) {
129
+ const { threadMessagesDeleted } = await reconcileStaleMessage(
130
+ deps,
131
+ accountConfigId,
132
+ messageId,
133
+ );
134
+ deps.log.info(
135
+ {
136
+ metric: "body_sync_stale_row_reconciled",
137
+ accountId,
138
+ accountConfigId,
139
+ mailboxId,
140
+ messageId,
141
+ uid: message.uid,
142
+ threadMessagesDeleted,
143
+ },
144
+ "Message no longer exists on IMAP after retry exhaustion; stale row reconciled",
145
+ );
146
+ reconciledMessageIds.push(messageId);
147
+ continue;
148
+ }
149
+
150
+ await markMessageBodySyncFailed(
151
+ deps.storageService,
152
+ accountConfigId,
153
+ accountId,
154
+ messageId,
155
+ { accountId, accountConfigId, mailboxId, messageId, uid: message.uid },
156
+ );
157
+ deps.log.error?.(
158
+ {
159
+ alert: "body_sync_message_broken",
160
+ accountId,
161
+ accountConfigId,
162
+ mailboxId,
163
+ messageId,
164
+ uid: message.uid,
165
+ },
166
+ "Message body could not be fetched/parsed after retry exhaustion; message exists on IMAP but is unrecoverable",
167
+ );
168
+ brokenMessageIds.push(messageId);
169
+ }
170
+
171
+ return { reconciledMessageIds, brokenMessageIds };
172
+ };