@remit/imap-worker 0.0.89 → 0.0.91

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 (171) hide show
  1. package/dist/account-check.d.ts +27 -0
  2. package/dist/account-check.js +70 -0
  3. package/dist/body-sync-gate.d.ts +12 -0
  4. package/dist/body-sync-gate.js +53 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +193 -0
  7. package/dist/config-env.d.ts +5 -0
  8. package/dist/config-env.js +37 -0
  9. package/dist/connection-pool.d.ts +22 -0
  10. package/dist/connection-pool.js +97 -0
  11. package/dist/connection-scope.d.ts +8 -0
  12. package/dist/connection-scope.js +10 -0
  13. package/dist/context.d.ts +46 -0
  14. package/dist/context.js +15 -0
  15. package/dist/e2e-processor-shim.d.ts +2 -0
  16. package/dist/e2e-processor-shim.js +181 -0
  17. package/dist/emit.d.ts +15 -0
  18. package/dist/emit.js +76 -0
  19. package/dist/events.d.ts +203 -0
  20. package/dist/events.js +1 -0
  21. package/dist/failure-kind.d.ts +10 -0
  22. package/{src/failure-kind.ts → dist/failure-kind.js} +6 -6
  23. package/dist/handlers/append-sent-message.d.ts +3 -0
  24. package/dist/handlers/append-sent-message.js +152 -0
  25. package/dist/handlers/delete-account-objects.d.ts +3 -0
  26. package/dist/handlers/delete-account-objects.js +35 -0
  27. package/dist/handlers/empty-trash.d.ts +14 -0
  28. package/dist/handlers/empty-trash.js +217 -0
  29. package/dist/handlers/flag-push.d.ts +38 -0
  30. package/dist/handlers/flag-push.js +195 -0
  31. package/dist/handlers/imported-folder.d.ts +4 -0
  32. package/dist/handlers/imported-folder.js +23 -0
  33. package/dist/handlers/mailbox-management.d.ts +6 -0
  34. package/dist/handlers/mailbox-management.js +294 -0
  35. package/dist/handlers/mailbox-sync-order.d.ts +21 -0
  36. package/dist/handlers/mailbox-sync-order.js +50 -0
  37. package/dist/handlers/message-copy.d.ts +40 -0
  38. package/dist/handlers/message-copy.js +371 -0
  39. package/dist/handlers/message-delete-terminal.d.ts +60 -0
  40. package/dist/handlers/message-delete-terminal.js +77 -0
  41. package/dist/handlers/message-delete.d.ts +57 -0
  42. package/dist/handlers/message-delete.js +520 -0
  43. package/{src/handlers/message-move-terminal.ts → dist/handlers/message-move-terminal.d.ts} +18 -105
  44. package/dist/handlers/message-move-terminal.js +94 -0
  45. package/dist/handlers/message-move.d.ts +146 -0
  46. package/dist/handlers/message-move.js +490 -0
  47. package/dist/handlers/placement-move-push.d.ts +62 -0
  48. package/dist/handlers/placement-move-push.js +307 -0
  49. package/dist/handlers/probe-message-id.d.ts +2 -0
  50. package/dist/handlers/probe-message-id.js +6 -0
  51. package/dist/handlers/sync-mailboxes.d.ts +45 -0
  52. package/dist/handlers/sync-mailboxes.js +233 -0
  53. package/dist/handlers/sync-message-body.d.ts +23 -0
  54. package/dist/handlers/sync-message-body.js +182 -0
  55. package/dist/handlers/sync-messages.d.ts +29 -0
  56. package/dist/handlers/sync-messages.js +285 -0
  57. package/dist/index.d.ts +9 -0
  58. package/dist/index.js +67 -0
  59. package/dist/lambda-context.d.ts +8 -0
  60. package/dist/lambda-context.js +33 -0
  61. package/dist/mailbox-row.d.ts +9 -0
  62. package/dist/mailbox-row.js +6 -0
  63. package/dist/poller.d.ts +1 -0
  64. package/dist/poller.js +51 -0
  65. package/dist/process.d.ts +6 -0
  66. package/dist/process.js +3 -0
  67. package/dist/processor.d.ts +3 -0
  68. package/dist/processor.js +44 -0
  69. package/dist/queues.d.ts +10 -0
  70. package/dist/queues.js +1 -0
  71. package/dist/s3-account-objects.d.ts +3 -0
  72. package/dist/s3-account-objects.js +26 -0
  73. package/dist/scheduler/attachment-sweep.d.ts +11 -0
  74. package/dist/scheduler/attachment-sweep.js +23 -0
  75. package/dist/scheduler/calendar-subscriptions.d.ts +26 -0
  76. package/dist/scheduler/calendar-subscriptions.js +35 -0
  77. package/dist/scheduler/config.d.ts +27 -0
  78. package/{src/scheduler/config.ts → dist/scheduler/config.js} +7 -26
  79. package/{src/scheduler/decide-due.ts → dist/scheduler/decide-due.d.ts} +3 -12
  80. package/dist/scheduler/decide-due.js +17 -0
  81. package/dist/scheduler/handler.d.ts +21 -0
  82. package/{src/scheduler/handler.ts → dist/scheduler/handler.js} +24 -36
  83. package/{src/scheduler/loop.ts → dist/scheduler/loop.d.ts} +7 -23
  84. package/dist/scheduler/loop.js +8 -0
  85. package/dist/scheduler/run-tick.d.ts +62 -0
  86. package/dist/scheduler/run-tick.js +164 -0
  87. package/dist/scheduler/runner.d.ts +2 -0
  88. package/{src/scheduler/runner.ts → dist/scheduler/runner.js} +58 -84
  89. package/dist/scheduler/stranded-placement-redrive.d.ts +16 -0
  90. package/dist/scheduler/stranded-placement-redrive.js +172 -0
  91. package/dist/sqs-queues.d.ts +4 -0
  92. package/dist/sqs-queues.js +22 -0
  93. package/dist/with-oauth-lifecycle-deps.d.ts +5 -0
  94. package/dist/with-oauth-lifecycle-deps.js +17 -0
  95. package/dist/with-oauth-lifecycle.d.ts +56 -0
  96. package/dist/with-oauth-lifecycle.js +92 -0
  97. package/{src/worker-version.ts → dist/worker-version.d.ts} +1 -2
  98. package/dist/worker-version.js +12 -0
  99. package/package.json +75 -69
  100. package/src/account-check.test.ts +0 -149
  101. package/src/account-check.ts +0 -101
  102. package/src/body-sync-gate.test.ts +0 -185
  103. package/src/body-sync-gate.ts +0 -86
  104. package/src/cli.ts +0 -224
  105. package/src/connection-scope.test.ts +0 -266
  106. package/src/connection-scope.ts +0 -314
  107. package/src/credential-less-sync-fence.test.ts +0 -152
  108. package/src/e2e-processor-shim.ts +0 -232
  109. package/src/emit.test.ts +0 -127
  110. package/src/emit.ts +0 -117
  111. package/src/events.ts +0 -252
  112. package/src/failure-kind.test.ts +0 -42
  113. package/src/handlers/append-sent-message.sqlite.test.ts +0 -176
  114. package/src/handlers/append-sent-message.ts +0 -264
  115. package/src/handlers/delete-account-objects.test.ts +0 -128
  116. package/src/handlers/delete-account-objects.ts +0 -94
  117. package/src/handlers/empty-trash.sqlite.test.ts +0 -209
  118. package/src/handlers/empty-trash.ts +0 -352
  119. package/src/handlers/flag-push.ts +0 -285
  120. package/src/handlers/imported-folder.test.ts +0 -63
  121. package/src/handlers/imported-folder.ts +0 -38
  122. package/src/handlers/mailbox-management.sqlite.test.ts +0 -265
  123. package/src/handlers/mailbox-management.ts +0 -486
  124. package/src/handlers/mailbox-sync-order.test.ts +0 -93
  125. package/src/handlers/mailbox-sync-order.ts +0 -65
  126. package/src/handlers/message-copy.sqlite.test.ts +0 -298
  127. package/src/handlers/message-copy.ts +0 -566
  128. package/src/handlers/message-delete-terminal.ts +0 -147
  129. package/src/handlers/message-delete.sqlite.test.ts +0 -291
  130. package/src/handlers/message-delete.ts +0 -885
  131. package/src/handlers/message-move.sqlite.test.ts +0 -271
  132. package/src/handlers/message-move.test.ts +0 -216
  133. package/src/handlers/message-move.ts +0 -752
  134. package/src/handlers/placement-move-push.test.ts +0 -137
  135. package/src/handlers/placement-move-push.ts +0 -475
  136. package/src/handlers/placement-push.sqlite.test.ts +0 -298
  137. package/src/handlers/probe-message-id.sqlite.test.ts +0 -192
  138. package/src/handlers/probe-message-id.ts +0 -15
  139. package/src/handlers/sync-mailboxes.test.ts +0 -183
  140. package/src/handlers/sync-mailboxes.ts +0 -421
  141. package/src/handlers/sync-message-body.sqlite.test.ts +0 -314
  142. package/src/handlers/sync-message-body.test.ts +0 -150
  143. package/src/handlers/sync-message-body.ts +0 -365
  144. package/src/handlers/sync-messages.sqlite.test.ts +0 -183
  145. package/src/handlers/sync-messages.ts +0 -525
  146. package/src/index.test.ts +0 -22
  147. package/src/index.ts +0 -86
  148. package/src/mail-sync-selection.sqlite.test.ts +0 -234
  149. package/src/mailbox-row.ts +0 -20
  150. package/src/pending-sync.sqlite.test.ts +0 -166
  151. package/src/poller.ts +0 -55
  152. package/src/processor.ts +0 -60
  153. package/src/queues.ts +0 -49
  154. package/src/scheduler/attachment-sweep.sqlite.test.ts +0 -75
  155. package/src/scheduler/attachment-sweep.ts +0 -46
  156. package/src/scheduler/calendar-subscriptions.sqlite.test.ts +0 -147
  157. package/src/scheduler/calendar-subscriptions.ts +0 -103
  158. package/src/scheduler/config.test.ts +0 -40
  159. package/src/scheduler/decide-due.test.ts +0 -44
  160. package/src/scheduler/half-deleted-accounts.sqlite.test.ts +0 -196
  161. package/src/scheduler/loop.test.ts +0 -143
  162. package/src/scheduler/run-tick.sqlite.test.ts +0 -191
  163. package/src/scheduler/run-tick.ts +0 -281
  164. package/src/scheduler/stranded-placement-redrive.ts +0 -265
  165. package/src/stranded-placement.sqlite.test.ts +0 -794
  166. package/src/test-helpers/test-world.ts +0 -427
  167. package/src/thread-join.sqlite.test.ts +0 -106
  168. package/src/with-oauth-lifecycle-deps.sqlite.test.ts +0 -269
  169. package/src/with-oauth-lifecycle-deps.ts +0 -71
  170. package/src/with-oauth-lifecycle.ts +0 -158
  171. package/tsconfig.json +0 -8
@@ -1,525 +0,0 @@
1
- import { getClient } from "@remit/backend/client";
2
- import type {
3
- AccountItem,
4
- IAccountRepository,
5
- IAddressRepository,
6
- IEnvelopeRepository,
7
- IMailboxRepository,
8
- IMailboxSpecialUseRepository,
9
- IMessageFlagPushRepository,
10
- IMessageFlagRepository,
11
- IMessageRepository,
12
- IQuarantineRepository,
13
- ISyncWarningRepository,
14
- IThreadMessageRepository,
15
- } from "@remit/data-ports";
16
- import { isNotFoundError } from "@remit/data-ports/errors";
17
- import { SyncPhase } from "@remit/domain-enums";
18
- import type { Logger } from "@remit/logger";
19
- import { recordImapFailure } from "@remit/logger-lambda/metrics";
20
- import { RefreshTokenError } from "@remit/mail-oauth-service";
21
- import {
22
- createManagedConnectionFactory,
23
- isMailboxMutationInFlight,
24
- MailConnectionError,
25
- type MailCredentials,
26
- type ManagedConnectionFactory,
27
- MessageSyncService,
28
- QuarantineService,
29
- type SyncedMessage,
30
- SyncWarningService,
31
- } from "@remit/mailbox-service";
32
- import pMap from "p-map";
33
- import {
34
- isAccountDeleted,
35
- isMailSyncDisabled,
36
- isUnsyncableHost,
37
- } from "../account-check.js";
38
- import { emitEvent, SYNC_MESSAGES_PENDING } from "../emit.js";
39
- import type {
40
- FlagPushEvent,
41
- SyncMessageBodyEvent,
42
- SyncMessagesEvent,
43
- } from "../events.js";
44
- import { withOAuthLifecycle } from "../with-oauth-lifecycle.js";
45
- import { buildLifecycleDeps } from "../with-oauth-lifecycle-deps.js";
46
- import { workerVersion } from "../worker-version.js";
47
-
48
- // One SYNC_MESSAGE_BODY event maps to one ranged UID FETCH on the consumer.
49
- export const BODY_BATCH_SIZE = 200;
50
- const EVENT_EMIT_CONCURRENCY = 10;
51
- const MESSAGE_BATCH_SIZE = 200;
52
-
53
- /** Slice synced messages into body-sync batches, each one ranged FETCH. */
54
- export const batchSyncedMessages = (
55
- syncedMessages: SyncedMessage[],
56
- batchSize: number = BODY_BATCH_SIZE,
57
- ): SyncedMessage[][] => {
58
- const batches: SyncedMessage[][] = [];
59
- for (let i = 0; i < syncedMessages.length; i += batchSize) {
60
- batches.push(syncedMessages.slice(i, i + batchSize));
61
- }
62
- return batches;
63
- };
64
-
65
- export const managedConnectionFor = (
66
- account: Pick<AccountItem, "username" | "imapHost" | "imapPort" | "imapTls">,
67
- credentials: MailCredentials,
68
- ): ManagedConnectionFactory =>
69
- createManagedConnectionFactory({
70
- user: account.username,
71
- credentials,
72
- host: account.imapHost,
73
- port: account.imapPort,
74
- tls: account.imapTls,
75
- });
76
-
77
- export const syncMessages = async (
78
- event: SyncMessagesEvent,
79
- log: Logger,
80
- createConnectionFactory = managedConnectionFor,
81
- ): Promise<void> => {
82
- log.info(
83
- {
84
- event: event.type,
85
- accountId: event.accountId,
86
- mailboxId: event.mailboxId,
87
- },
88
- "Handling event",
89
- );
90
-
91
- const {
92
- account: accountService,
93
- mailbox: mailboxService,
94
- message: messageService,
95
- envelope: envelopeService,
96
- address: addressService,
97
- threadMessage: threadMessageService,
98
- mailboxLock: mailboxLockService,
99
- mailboxSpecialUse: mailboxSpecialUseService,
100
- quarantine: quarantineService,
101
- syncWarning: syncWarningRepository,
102
- flagPush: flagPushMarkerService,
103
- messageFlag: messageFlagService,
104
- secrets,
105
- } = await getClient();
106
-
107
- await mailboxLockService.releaseLock(
108
- event.accountId,
109
- event.mailboxId,
110
- SYNC_MESSAGES_PENDING,
111
- event.eventId,
112
- );
113
-
114
- // A deleted account never has its DDB row purged in lockstep with the queued
115
- // SYNC_MESSAGES triggers, so a trigger can outlive its account. The lookup
116
- // then returns null (or throws a named NotFoundError), which can never succeed
117
- // on retry — it would retry to maxReceiveCount and poison the messages DLQ
118
- // forever (issue #911). Treat a missing account as terminal: ack the event
119
- // with a WARN. Genuinely transient failures (throttle, network) surface as
120
- // other errors and still propagate to be retried.
121
- let account: AccountItem;
122
- const rawAccount = await accountService.get(event.accountId).catch((err) => {
123
- if (isNotFoundError(err)) return null;
124
- throw err;
125
- });
126
- if (!rawAccount) {
127
- log.warn(
128
- {
129
- accountId: event.accountId,
130
- mailboxId: event.mailboxId,
131
- eventId: event.eventId,
132
- },
133
- "Skipping SYNC_MESSAGES: account no longer exists",
134
- );
135
- return;
136
- }
137
- account = rawAccount;
138
-
139
- if (isAccountDeleted(account, log)) {
140
- return;
141
- }
142
-
143
- if (isMailSyncDisabled(account, log)) {
144
- return;
145
- }
146
-
147
- // A reserved/never-resolvable IMAP host (RFC 2606) can never connect, so a
148
- // sync attempt would retry and dead-letter forever. Skip cleanly — ack the
149
- // event without connecting or throwing.
150
- if (isUnsyncableHost(account, log.child({ mailboxId: event.mailboxId }))) {
151
- return;
152
- }
153
-
154
- // A SYNC_MESSAGES trigger can address a folder a mutation still owns: the
155
- // fan-out enqueues one for a folder whose own create has not landed yet, a
156
- // `hasMore` next-batch or a periodic tick outlives a folder the user
157
- // deleted, and a rename in flight leaves the folder on the server but under
158
- // the worker that is moving it. Such an event can never succeed on retry,
159
- // and the account's per-group FIFO ordering lets that one poison message
160
- // stall the whole account's message pipeline for the full visibility window
161
- // (issue #287, #339). A folder with a create, rename or delete outstanding
162
- // is an expected terminal outcome, not an infra failure: ack the event with
163
- // a WARN. The rename case is conservative rather than necessary — syncing it
164
- // would be safe — and keeps the guard a single expression (D12).
165
- if (
166
- await isMailboxMutationInFlight(
167
- mailboxService,
168
- event.accountId,
169
- event.mailboxId,
170
- )
171
- ) {
172
- log.warn(
173
- {
174
- accountId: event.accountId,
175
- mailboxId: event.mailboxId,
176
- eventId: event.eventId,
177
- event: event.type,
178
- },
179
- "Skipping SYNC_MESSAGES: a folder mutation is in flight",
180
- );
181
- return;
182
- }
183
-
184
- // withOAuthLifecycle owns the reauth/ACK contract (skip-if-reauth, resolve
185
- // credentials, flip on terminal auth failure, rethrow transient). The
186
- // mailbox lock and the actual sync run inside the wrapper callback.
187
- await withOAuthLifecycle(
188
- buildLifecycleDeps(secrets, accountService),
189
- account,
190
- log,
191
- async (credentials) => {
192
- // Acquire lock before starting sync operation
193
- const { executed } = await mailboxLockService.withMailboxLock(
194
- event.mailboxId,
195
- "SYNC_MESSAGES",
196
- event.accountId,
197
- async () => {
198
- try {
199
- await syncMailboxMessages(
200
- event,
201
- account,
202
- createConnectionFactory(account, credentials),
203
- {
204
- accountService,
205
- mailboxService,
206
- messageService,
207
- envelopeService,
208
- addressService,
209
- threadMessageService,
210
- mailboxSpecialUseService,
211
- quarantineService,
212
- syncWarningRepository,
213
- flagPushMarkerService,
214
- messageFlagService,
215
- },
216
- log,
217
- );
218
- } catch (err) {
219
- // Auth failures are handled by the wrapper — rethrow untouched.
220
- if (
221
- err instanceof RefreshTokenError ||
222
- (err instanceof MailConnectionError && err.kind === "auth")
223
- ) {
224
- throw err;
225
- }
226
- // The guard above is a check-then-act: a delete asked for while
227
- // this round was in flight lands inside it, and the round then
228
- // fails somewhere deeper — on the row (NotFoundError from the
229
- // service's own re-read) or on the server (the SELECTed folder
230
- // vanished, so the next command runs against no mailbox). Both are
231
- // the same expected outcome as an event that arrived after the
232
- // delete, so they resolve the same way rather than head-of-line
233
- // blocking the account's FIFO group (issue #339). Recording an
234
- // error phase is skipped too: the account is healthy, one of its
235
- // folders is not there.
236
- //
237
- // This read only classifies the failure already in hand, so it must
238
- // never become the failure that is reported. A read that cannot answer
239
- // leaves the round on the loud path below, with the real error and the
240
- // state write that goes with it intact.
241
- const folderIsGone = await isMailboxMutationInFlight(
242
- mailboxService,
243
- event.accountId,
244
- event.mailboxId,
245
- ).catch(() => false);
246
- if (folderIsGone) {
247
- log.warn(
248
- {
249
- accountId: event.accountId,
250
- mailboxId: event.mailboxId,
251
- eventId: event.eventId,
252
- event: event.type,
253
- error: err instanceof Error ? err.message : String(err),
254
- },
255
- "Resolving SYNC_MESSAGES: the folder left the server while the sync was in flight",
256
- );
257
- return;
258
- }
259
- // Record the terminal error phase before crashing (let-it-crash:
260
- // record state, then rethrow so the event is retried/DLQ'd).
261
- const message = err instanceof Error ? err.message : String(err);
262
- await accountService.update(event.accountId, {
263
- syncPhase: SyncPhase.error,
264
- lastError: message,
265
- });
266
- throw err;
267
- }
268
- },
269
- );
270
-
271
- if (!executed) {
272
- log.info(
273
- { mailboxId: event.mailboxId },
274
- "Sync already in progress, skipping",
275
- );
276
- }
277
- },
278
- );
279
- };
280
-
281
- interface SyncDeps {
282
- accountService: IAccountRepository;
283
- mailboxService: IMailboxRepository;
284
- messageService: IMessageRepository;
285
- envelopeService: IEnvelopeRepository;
286
- addressService: IAddressRepository;
287
- threadMessageService: IThreadMessageRepository;
288
- mailboxSpecialUseService: IMailboxSpecialUseRepository;
289
- quarantineService: IQuarantineRepository;
290
- syncWarningRepository: ISyncWarningRepository;
291
- flagPushMarkerService: IMessageFlagPushRepository;
292
- messageFlagService: IMessageFlagRepository;
293
- }
294
-
295
- // Bounds concurrent SQS sends while re-arming stuck flag-push markers —
296
- // markers are expected to be few, but never unbounded (coding-standards.md).
297
- const FLAG_PUSH_DRAIN_CONCURRENCY = 5;
298
-
299
- /**
300
- * Periodic per-mailbox drain point for pending flag-push markers (issue
301
- * #1273, epic #1281). The SQS enqueue in `FlagPushService.flip` is only a
302
- * wake-up hint and may fail freely — a marker left `state: "pending"` means
303
- * that hint never landed (queue down, or a crash between the local write and
304
- * the enqueue). This periodic tick — which already runs per mailbox on a
305
- * schedule regardless of user activity — re-arms every such marker with a
306
- * fresh `FLAG_PUSH` event, closing the gap without the caller ever having to
307
- * retry.
308
- *
309
- * Markers already `queued`/`processing` are left alone: a live SQS message
310
- * (or the single-marker handler currently running) already owns driving them
311
- * forward, and re-arming them too would just duplicate work.
312
- *
313
- * A re-arm failure (the SQS send itself) is caught per-marker and logged
314
- * loudly — it must never fail the surrounding SYNC_MESSAGES batch, which is
315
- * unrelated message-header sync work. The marker stays durable regardless;
316
- * the next periodic tick tries again.
317
- *
318
- * `emit` defaults to the real `emitEvent` (imap-worker's shared SQS
319
- * producer) and is only ever overridden in tests.
320
- */
321
- export const drainPendingFlagPushes = async (
322
- flagPushMarkerService: IMessageFlagPushRepository,
323
- account: AccountItem,
324
- mailboxId: string,
325
- log: Logger,
326
- emit: typeof emitEvent = emitEvent,
327
- ): Promise<void> => {
328
- const markers = await flagPushMarkerService.listByMailboxId(mailboxId);
329
- const stuck = markers.filter((marker) => marker.state === "pending");
330
- if (stuck.length === 0) return;
331
-
332
- log.info(
333
- { mailboxId, count: stuck.length },
334
- "Periodic sync tick found flag-push marker(s) stuck before their wake-up hint; re-arming",
335
- );
336
-
337
- await pMap(
338
- stuck,
339
- (marker) => {
340
- const rearmEvent: Omit<FlagPushEvent, "eventId" | "timestamp"> = {
341
- type: "FLAG_PUSH",
342
- accountId: account.accountId,
343
- accountConfigId: account.accountConfigId,
344
- messageId: marker.messageId,
345
- flagName: marker.flagName,
346
- };
347
- return emit(rearmEvent).catch((error: unknown) => {
348
- log.error(
349
- {
350
- alert: "flag_push_drain_rearm_failed",
351
- mailboxId,
352
- messageId: marker.messageId,
353
- flagName: marker.flagName,
354
- error: error instanceof Error ? error.message : String(error),
355
- },
356
- "Failed to re-arm a stuck pending flag-push marker during the periodic drain",
357
- );
358
- });
359
- },
360
- { concurrency: FLAG_PUSH_DRAIN_CONCURRENCY },
361
- );
362
- };
363
-
364
- /**
365
- * Sync one batch of messages for a mailbox. Runs under the mailbox lock.
366
- */
367
- const syncMailboxMessages = async (
368
- event: SyncMessagesEvent,
369
- account: AccountItem,
370
- connectionFactory: ManagedConnectionFactory,
371
- deps: SyncDeps,
372
- log: Logger,
373
- ): Promise<void> => {
374
- const {
375
- accountService,
376
- mailboxService,
377
- messageService,
378
- envelopeService,
379
- addressService,
380
- threadMessageService,
381
- mailboxSpecialUseService,
382
- quarantineService,
383
- syncWarningRepository,
384
- flagPushMarkerService,
385
- messageFlagService,
386
- } = deps;
387
-
388
- // Get the mailbox - it must exist (should have been created by mailbox sync)
389
- const mailbox = await mailboxService.get(account.accountId, event.mailboxId);
390
- const mailboxId = mailbox.mailboxId;
391
-
392
- // Periodic drain (issue #1273): independent of the IMAP sync below — no
393
- // connection needed, just an SQS re-arm — so it runs regardless of this
394
- // round's sync outcome.
395
- await drainPendingFlagPushes(flagPushMarkerService, account, mailboxId, log);
396
- const isInbox = mailbox.fullPath.toUpperCase() === "INBOX";
397
-
398
- const syncService = new MessageSyncService(
399
- connectionFactory,
400
- mailboxService,
401
- mailboxSpecialUseService,
402
- messageService,
403
- envelopeService,
404
- addressService,
405
- threadMessageService,
406
- new SyncWarningService(syncWarningRepository),
407
- log,
408
- flagPushMarkerService,
409
- messageFlagService,
410
- new QuarantineService(
411
- quarantineService,
412
- mailboxSpecialUseService,
413
- workerVersion(),
414
- log,
415
- ),
416
- );
417
-
418
- // Connect once, reuse for the entire sync operation
419
- const connection = connectionFactory.getConnection();
420
- await connection.connect();
421
-
422
- const result = await syncService
423
- .syncMessages(
424
- mailboxId,
425
- account.accountId,
426
- account.accountConfigId,
427
- MESSAGE_BATCH_SIZE,
428
- )
429
- .finally(() => connectionFactory.close());
430
- log.info(
431
- {
432
- syncedCount: result.syncedCount,
433
- hasMore: result.hasMore,
434
- remainingCount: result.remainingCount,
435
- },
436
- "Message sync batch complete",
437
- );
438
-
439
- // A stalled cursor is the one failure on this path that produces no error:
440
- // unapplicable messages are caught and held back, so the round returns
441
- // normally, the SQS record is deleted, and neither redrive nor the DLQ ever
442
- // engages. Without this counter the mailbox stops syncing behind a worker
443
- // that looks healthy. Per-mailbox detail is in the accompanying ERROR log.
444
- if (result.cursorStalled) {
445
- recordImapFailure("SYNC_MESSAGES_CURSOR_STALLED", "other");
446
- }
447
-
448
- // Emit body sync events for the messages we just synced. Each event carries
449
- // messageId+uid pairs so the consumer issues one ranged FETCH per batch
450
- // without re-resolving UIDs. messageIds stays populated for backward compat.
451
- if (result.syncedMessages.length > 0) {
452
- const batches = batchSyncedMessages(result.syncedMessages);
453
-
454
- log.info(
455
- { count: result.syncedMessages.length, batches: batches.length },
456
- "Emitting SYNC_MESSAGE_BODY events",
457
- );
458
-
459
- await pMap(
460
- batches,
461
- (batch) => {
462
- const bodyEvent: Omit<SyncMessageBodyEvent, "eventId" | "timestamp"> = {
463
- type: "SYNC_MESSAGE_BODY",
464
- accountId: event.accountId,
465
- mailboxId,
466
- messageIds: batch.map((m) => m.messageId),
467
- messages: batch.map((m) => ({ messageId: m.messageId, uid: m.uid })),
468
- };
469
- return emitEvent(bodyEvent);
470
- },
471
- { concurrency: EVENT_EMIT_CONCURRENCY },
472
- );
473
- }
474
-
475
- // If there are more messages to sync, emit another SYNC_MESSAGES event
476
- if (result.hasMore) {
477
- log.info(
478
- { remainingCount: result.remainingCount },
479
- "Emitting SYNC_MESSAGES event for next batch",
480
- );
481
-
482
- const nextSyncEvent: Omit<SyncMessagesEvent, "eventId" | "timestamp"> = {
483
- type: "SYNC_MESSAGES",
484
- accountId: event.accountId,
485
- mailboxId,
486
- };
487
- await emitEvent(nextSyncEvent);
488
- return;
489
- }
490
-
491
- // Mailbox drained. Record the per-mailbox completion marker (used by the
492
- // sync-status endpoint to derive the per-mailbox phase), and count it
493
- // towards mailboxCountSynced — but only once per sync round, so that
494
- // duplicate / no-op SYNC_MESSAGES completions don't inflate the counter.
495
- // The check-then-write is safe: the mailbox lock serializes completions
496
- // per mailbox, and `mailbox` was read under the lock.
497
- const roundStartedAt = account.lastSyncAt ?? 0;
498
- const previousCompletedAt = mailbox.initialSyncCompletedAt ?? 0;
499
- const firstCompletionThisRound =
500
- previousCompletedAt === 0 || previousCompletedAt < roundStartedAt;
501
-
502
- await mailboxService.update(account.accountId, mailboxId, {
503
- initialSyncCompletedAt: Date.now(),
504
- });
505
-
506
- if (!firstCompletionThisRound) {
507
- log.info(
508
- { mailboxId },
509
- "Mailbox already counted as synced this round, skipping increment",
510
- );
511
- return;
512
- }
513
-
514
- const currentAccount = await accountService.get(event.accountId);
515
-
516
- if (isInbox && currentAccount.syncPhase === SyncPhase.syncing_inbox) {
517
- // INBOX is drained; advance to syncing_others
518
- await accountService.update(event.accountId, {
519
- syncPhase: SyncPhase.syncing_others,
520
- });
521
- }
522
-
523
- // Atomically increment mailboxCountSynced; transitions to complete when all done
524
- await accountService.incrementMailboxSynced(event.accountId);
525
- };
package/src/index.test.ts DELETED
@@ -1,22 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { describe, it } from "node:test";
3
- import { parseReceiveCount } from "./index.js";
4
-
5
- describe("parseReceiveCount — SQS ApproximateReceiveCount parsing", () => {
6
- it("parses the raw string attribute", () => {
7
- assert.equal(parseReceiveCount("1"), 1);
8
- assert.equal(parseReceiveCount("3"), 3);
9
- });
10
-
11
- it("defaults to 1 when the attribute is missing", () => {
12
- // A record with no attribute (e.g. an older local harness) is treated as
13
- // a first attempt, not fast-forwarded into retry-exhaustion handling.
14
- assert.equal(parseReceiveCount(undefined), 1);
15
- });
16
-
17
- it("defaults to 1 on a non-numeric or non-positive value", () => {
18
- assert.equal(parseReceiveCount("not-a-number"), 1);
19
- assert.equal(parseReceiveCount("0"), 1);
20
- assert.equal(parseReceiveCount("-1"), 1);
21
- });
22
- });
package/src/index.ts DELETED
@@ -1,86 +0,0 @@
1
- import { createLogger } from "@remit/logger";
2
- import {
3
- queueNameFromEventSource,
4
- recordImapFailure,
5
- recordQueueEvent,
6
- } from "@remit/logger-lambda/metrics";
7
- import { installNodeLogger, withTelemetry } from "@remit/logger-lambda/node";
8
- import type { SQSBatchResponse, SQSEvent, SQSHandler } from "aws-lambda";
9
- import type { WorkerEvent } from "./events.js";
10
- import { imapFailureKind } from "./failure-kind.js";
11
- import { processEvent } from "./processor.js";
12
- import {
13
- setWorkerQueues,
14
- sqsWorkerQueues,
15
- workerQueueUrlsFromEnv,
16
- } from "./queues.js";
17
-
18
- installNodeLogger();
19
- setWorkerQueues(sqsWorkerQueues(workerQueueUrlsFromEnv()));
20
-
21
- const log = createLogger();
22
-
23
- /**
24
- * Parse SQS's `ApproximateReceiveCount` record attribute (1 on first
25
- * delivery). Missing/malformed defaults to 1 so a record with no attribute
26
- * (e.g. an older local harness) is treated as a first attempt rather than
27
- * skipping straight to retry-exhaustion handling.
28
- */
29
- export const parseReceiveCount = (value: string | undefined): number => {
30
- const parsed = Number.parseInt(value ?? "1", 10);
31
- return Number.isFinite(parsed) && parsed > 0 ? parsed : 1;
32
- };
33
-
34
- export const handler: SQSHandler = withTelemetry(
35
- async (event: SQSEvent): Promise<SQSBatchResponse> => {
36
- const batchItemFailures: { itemIdentifier: string }[] = [];
37
-
38
- for (const record of event.Records) {
39
- const imapEvent: WorkerEvent = JSON.parse(record.body);
40
- const receiveCount = parseReceiveCount(
41
- record.attributes?.ApproximateReceiveCount,
42
- );
43
- log.info(
44
- {
45
- eventType: imapEvent.type,
46
- eventId: "eventId" in imapEvent ? imapEvent.eventId : undefined,
47
- receiveCount,
48
- },
49
- "Processing event",
50
- );
51
-
52
- const queue = queueNameFromEventSource(record.eventSourceARN);
53
- const opStart = Date.now();
54
- const failed = await processEvent(imapEvent, log, receiveCount)
55
- .then(() => {
56
- recordQueueEvent({
57
- queue,
58
- eventType: imapEvent.type,
59
- outcome: "success",
60
- durationMs: Date.now() - opStart,
61
- });
62
- return false;
63
- })
64
- .catch((error) => {
65
- log.error(
66
- { error, messageId: record.messageId },
67
- "Event processing failed",
68
- );
69
- recordQueueEvent({
70
- queue,
71
- eventType: imapEvent.type,
72
- outcome: "failure",
73
- durationMs: Date.now() - opStart,
74
- });
75
- recordImapFailure(imapEvent.type, imapFailureKind(error));
76
- return true;
77
- });
78
-
79
- if (failed) {
80
- batchItemFailures.push({ itemIdentifier: record.messageId });
81
- }
82
- }
83
-
84
- return { batchItemFailures };
85
- },
86
- );