@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,137 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { describe, it } from "node:test";
3
- import {
4
- eml,
5
- FakeImapServer,
6
- } from "@remit/mailbox-service/test-helpers/fake-imap";
7
- import { attemptMove } from "./placement-move-push.js";
8
-
9
- const HEADER = "<abc@example.com>";
10
-
11
- /** Junk holds the message at uid 42; INBOX is where the placement sends it. */
12
- const arrange = (
13
- options: { inJunk?: boolean; inInbox?: boolean; inboxExists?: boolean } = {},
14
- ) => {
15
- const server = new FakeImapServer();
16
- server.addFolder("Junk");
17
- if (options.inboxExists !== false) server.addFolder("INBOX");
18
- if (options.inJunk !== false)
19
- server.deliver("Junk", eml({ "Message-ID": HEADER }), { uid: 42 });
20
- if (options.inInbox) server.deliver("INBOX", eml({ "Message-ID": HEADER }));
21
- return server;
22
- };
23
-
24
- const move = (
25
- server: FakeImapServer,
26
- header: string | undefined = HEADER,
27
- source = server.connection(),
28
- ) => attemptMove(source, server.connection(), "Junk", "INBOX", 42, header);
29
-
30
- describe("attemptMove — the IMAP push (issue #1271)", () => {
31
- it("moves the message and returns the uid from the COPYUID map", async () => {
32
- const server = arrange();
33
-
34
- const outcome = await move(server);
35
-
36
- assert.deepEqual(outcome, {
37
- kind: "moved",
38
- newUid: server.uids("INBOX", HEADER)[0],
39
- });
40
- assert.deepEqual(server.uids("Junk"), []);
41
- });
42
-
43
- it("answers trycreate when the destination does not exist yet", async () => {
44
- const server = arrange({ inboxExists: false });
45
-
46
- assert.equal((await move(server)).kind, "trycreate");
47
- });
48
-
49
- it("propagates any other failure untouched for the caller to retry", async () => {
50
- const server = arrange();
51
- server.failNext.MOVE = new Error("ECONNRESET");
52
-
53
- await assert.rejects(move(server), /ECONNRESET/);
54
- });
55
-
56
- // PR #1289 review finding 2: neither a missing COPYUID entry nor an explicit
57
- // not-found is trusted without asking the server.
58
- it("confirms a move by Message-ID when the server sends no COPYUID", async () => {
59
- const server = arrange();
60
- server.uidplus = false;
61
-
62
- const outcome = await move(server);
63
-
64
- assert.deepEqual(outcome, {
65
- kind: "moved",
66
- newUid: server.uids("INBOX", HEADER)[0],
67
- });
68
- });
69
-
70
- it("confirms a move by Message-ID when the server answers NONEXISTENT for one that landed", async () => {
71
- const server = arrange({ inJunk: false, inInbox: true });
72
- server.failNext.MOVE = new Error(
73
- "Command failed: NONEXISTENT no such message",
74
- );
75
-
76
- const outcome = await move(server);
77
-
78
- assert.deepEqual(outcome, {
79
- kind: "moved",
80
- newUid: server.uids("INBOX", HEADER)[0],
81
- });
82
- });
83
-
84
- // Issue #1122: the destination already held an older copy, and the row must
85
- // bind to the one this MOVE delivered.
86
- it("binds to the newest copy when the destination already held an older one", async () => {
87
- const server = arrange({ inInbox: true });
88
- server.uidplus = false;
89
-
90
- const outcome = await move(server);
91
-
92
- assert.deepEqual(outcome, {
93
- kind: "moved",
94
- newUid: Math.max(...server.uids("INBOX", HEADER)),
95
- });
96
- });
97
-
98
- it("never settles a move the destination does not confirm while the source still holds it", async () => {
99
- const server = arrange();
100
- server.uidplus = false;
101
- server.ignoreNext.add("MOVE");
102
-
103
- await assert.rejects(move(server), /unresolved/);
104
- });
105
-
106
- it("never settles when the source FETCH drops the row for a message the server still lists", async () => {
107
- const server = arrange();
108
- server.uidplus = false;
109
- server.ignoreNext.add("MOVE");
110
- const source = server.connection();
111
- source.fetchMessages = async () => [];
112
-
113
- await assert.rejects(move(server, HEADER, source), /unresolved/);
114
- });
115
-
116
- it("answers not-found once neither folder holds the message", async () => {
117
- const server = arrange({ inJunk: false });
118
- server.uidplus = false;
119
-
120
- assert.equal((await move(server)).kind, "not-found");
121
- });
122
-
123
- it("falls back to the source alone without a Message-ID, and still never settles while it holds the message", async () => {
124
- const server = arrange();
125
- server.uidplus = false;
126
- server.ignoreNext.add("MOVE");
127
-
128
- await assert.rejects(move(server, undefined));
129
- });
130
-
131
- it("answers not-found without a Message-ID once the source no longer holds the message", async () => {
132
- const server = arrange({ inJunk: false });
133
- server.uidplus = false;
134
-
135
- assert.equal((await move(server, undefined)).kind, "not-found");
136
- });
137
- });
@@ -1,475 +0,0 @@
1
- import { getClient } from "@remit/backend/client";
2
- import { MessageMutation, MessageSyncStatus } from "@remit/domain-enums";
3
- import type { Logger } from "@remit/logger";
4
- import { recordImapFailure } from "@remit/logger-lambda/metrics";
5
- import {
6
- guardConnectionCursor,
7
- type IImapConnection,
8
- isCursorRebuildNeeded,
9
- isMessageGoneFromOpenMailbox,
10
- MailboxCursorPausedError,
11
- resolveExhaustedPlacementMoveFailure,
12
- restoreSourcePlacement,
13
- } from "@remit/mailbox-service";
14
- import { attemptBudget } from "@remit/sqs-client/attempt-budget";
15
- import { isAccountDeleted } from "../account-check.js";
16
- import { createConnectionScopeWithCredentials } from "../connection-scope.js";
17
- import { emitEvent } from "../emit.js";
18
- import type { PlacementMovePushEvent } from "../events.js";
19
- import { findMailboxRow } from "../mailbox-row.js";
20
- import { withOAuthLifecycle } from "../with-oauth-lifecycle.js";
21
- import { buildLifecycleDeps } from "../with-oauth-lifecycle-deps.js";
22
- import {
23
- buildThreadMessageMoveUpdate,
24
- emitMailboxResync,
25
- emitMoveResync,
26
- searchMailboxForHighestMessageIdUid,
27
- } from "./message-move.js";
28
- import { probeableMessageIdHeader } from "./probe-message-id.js";
29
-
30
- export const getPlacementMoveMaxAttempts = (
31
- processEnv: NodeJS.ProcessEnv = process.env,
32
- ): number => attemptBudget("PLACEMENT_MOVE_MAX_ATTEMPTS", 3, processEnv);
33
-
34
- export const PLACEMENT_MOVE_MAX_ATTEMPTS = getPlacementMoveMaxAttempts();
35
-
36
- interface MoveOutcome {
37
- kind: "moved" | "not-found" | "trycreate";
38
- newUid?: number;
39
- }
40
-
41
- /**
42
- * Attempt the IMAP MOVE.
43
- *
44
- * Takes two connection handles rather than one: `sourceConnection` and
45
- * `destinationConnection` wrap the SAME underlying connection but are each
46
- * cursor-guarded (#1272) against their OWN mailbox — a `guardConnectionCursor`
47
- * wrap binds `openBox` checks to whichever ONE mailbox snapshot it was built
48
- * with, so verifying at the destination must never run through the source's
49
- * guard (it would compare the destination's served UIDVALIDITY against the
50
- * source's stored one and misfire).
51
- *
52
- * - `moved` with a `newUid` — confirmed, either via COPYUID or (see below)
53
- * an explicit destination verification.
54
- * - `trycreate` — the destination mailbox doesn't exist yet; the caller
55
- * creates it and retries.
56
- * - `not-found` — confirmed absent from BOTH source and destination. Only
57
- * this outcome supersedes the pending-move marker (drops it, reconciles
58
- * the row as an external delete).
59
- * - Any other case throws (propagates for SQS retry, or as
60
- * `MailboxCursorPausedError` for the caller's cursor-pause handling) —
61
- * including an UNCONFIRMED move (no COPYUID, or an explicit "not
62
- * found"/NONEXISTENT from the server) whose message is still sitting at
63
- * the source. A MOVE that resolves without a uidMap entry on a
64
- * non-UIDPLUS server is a plausible SUCCESS, not evidence the message is
65
- * gone (PR #1289 review finding 2) — deleting the local row on that
66
- * ambiguity would be data loss. `not-found` is only returned once BOTH a
67
- * destination Message-ID search (when the header is known) misses AND
68
- * {@link isMessageGoneFromOpenMailbox} confirms the message absent from the
69
- * source — a FETCH returning no row does not, on its own, confirm anything.
70
- */
71
- export const attemptMove = async (
72
- sourceConnection: IImapConnection,
73
- destinationConnection: IImapConnection,
74
- sourceMailboxPath: string,
75
- destinationMailboxPath: string,
76
- uid: number,
77
- messageIdHeader: string | undefined,
78
- ): Promise<MoveOutcome> => {
79
- await sourceConnection.openBox(sourceMailboxPath, false);
80
-
81
- const resolved = await sourceConnection
82
- .moveMessages([uid], destinationMailboxPath)
83
- .then((result) => ({ ok: true as const, newUid: result.uidMap.get(uid) }))
84
- .catch((error: unknown) => {
85
- const message = error instanceof Error ? error.message : String(error);
86
- if (message.includes("TRYCREATE")) {
87
- return { ok: false as const, trycreate: true as const };
88
- }
89
- if (message.includes("not found") || message.includes("NONEXISTENT")) {
90
- return { ok: false as const, trycreate: false as const };
91
- }
92
- throw error;
93
- });
94
-
95
- if (resolved.ok && resolved.newUid) {
96
- return { kind: "moved", newUid: resolved.newUid };
97
- }
98
- if (!resolved.ok && resolved.trycreate) {
99
- return { kind: "trycreate" };
100
- }
101
-
102
- // Unconfirmed: either no COPYUID entry, or the server explicitly claimed
103
- // "not found" — never trust either without independent verification. A
104
- // message this MOVE delivered is the newest copy of that Message-ID at the
105
- // destination, so the probe binds to the highest matching uid (#1122).
106
- // Unlike `confirmTrashMoveUid`, this probe is ungated: where the MOVE never
107
- // ran and an older copy filed there earlier is the only match, the marker
108
- // binds to that unrelated mail. Pre-existing, and not narrowed by taking the
109
- // highest — the source is not asked first here, so nothing rules the case
110
- // out.
111
- if (messageIdHeader) {
112
- const destinationUid = await searchMailboxForHighestMessageIdUid(
113
- destinationConnection,
114
- destinationMailboxPath,
115
- messageIdHeader,
116
- );
117
- if (destinationUid) return { kind: "moved", newUid: destinationUid };
118
- }
119
-
120
- await sourceConnection.openBox(sourceMailboxPath, true);
121
- if (!(await isMessageGoneFromOpenMailbox(sourceConnection, uid))) {
122
- throw new Error(
123
- "Placement move unresolved (unconfirmed at destination, still present at source) — retrying",
124
- );
125
- }
126
-
127
- return { kind: "not-found" };
128
- };
129
-
130
- /**
131
- * Handle PLACEMENT_MOVE_PUSH events (issue #1271, epic #1281). Drains ONE
132
- * pending placement-move marker: resolves the UID fresh from the Message row
133
- * (never trusts a captured value — invariant 1), pushes the IMAP MOVE, and
134
- * clears the marker ONLY on confirmed success. Every precedence rule (epic
135
- * invariant 2) is enforced here:
136
- * - Pending Remit move wins on location: nothing in this handler ever
137
- * corrects `message.mailboxId` back toward the source — a resync elsewhere
138
- * (message-sync.ts) never overwrites an existing row's `mailboxId` either
139
- * (create-only-if-not-exists semantics), so the local move is never undone.
140
- * - A NEWER local action superseding this marker (drop without pushing) —
141
- * see the `message.mailboxId !== marker.destinationMailboxId` check below.
142
- * - An external delete supersedes the marker entirely — the `not-found`
143
- * outcome drops the marker and reconciles the stale row.
144
- *
145
- * Cursor-guarded (#1272, epic #1281 invariant 5): both the source and
146
- * destination mailbox are checked for a non-`normal` `cursorState` before
147
- * connecting, and the connection is wrapped per-mailbox via
148
- * `guardConnectionCursor` so no stored UID touches the server while either
149
- * mailbox's axis is being rebuilt. A trip pauses the push (routine, no
150
- * alarm) — the marker stays durable and pushes again on the next event.
151
- */
152
- export const handlePlacementMovePush = async (
153
- event: PlacementMovePushEvent,
154
- log: Logger,
155
- receiveCount = 1,
156
- createConnectionScope = createConnectionScopeWithCredentials,
157
- ): Promise<void> => {
158
- const {
159
- account: accountService,
160
- mailbox: mailboxService,
161
- message: messageService,
162
- threadMessage: threadMessageService,
163
- placementMove: markerService,
164
- secrets,
165
- } = await getClient();
166
-
167
- const { accountId, accountConfigId, messageId } = event;
168
-
169
- const marker = await markerService.find(messageId);
170
- if (!marker) {
171
- log.info(
172
- { messageId, accountId },
173
- "No pending placement-move marker (already confirmed or superseded); nothing to push",
174
- );
175
- return;
176
- }
177
-
178
- const account = await accountService.get(accountId);
179
- if (!account) {
180
- throw new Error(`Account ${accountId} not found`);
181
- }
182
- if (isAccountDeleted(account, log)) {
183
- return;
184
- }
185
-
186
- const message = await messageService.get(messageId);
187
- const placementRead = {
188
- status: message.status,
189
- mailboxId: message.mailboxId,
190
- uid: message.uid,
191
- };
192
-
193
- // A newer local action (drag-and-drop move, auto-moved Undo) already
194
- // changed the message's location away from what this marker still
195
- // promises — that later intent wins locally. Drop the now-stale marker
196
- // without touching IMAP.
197
- if (message.mailboxId !== marker.destinationMailboxId) {
198
- await markerService.delete(messageId);
199
- log.info(
200
- {
201
- messageId,
202
- accountId,
203
- markerDestination: marker.destinationMailboxId,
204
- currentMailboxId: message.mailboxId,
205
- },
206
- "Placement move superseded by a newer local action; marker dropped without pushing",
207
- );
208
- return;
209
- }
210
-
211
- // The worker has picked up the event and is about to actually attempt the
212
- // IMAP MOVE — advance the state engine (pending/queued -> processing).
213
- // Idempotent to call again on a redelivered event (a prior attempt that
214
- // died mid-flight already left it here).
215
- await markerService.updateState(messageId, "processing");
216
-
217
- // No MOVE has left for this marker, so the row is settled, not just unmarked.
218
- const [source, destination] = await Promise.all([
219
- findMailboxRow(mailboxService, accountId, marker.sourceMailboxId),
220
- findMailboxRow(mailboxService, accountId, marker.destinationMailboxId),
221
- ]);
222
- if (source.kind === "gone" || destination.kind === "gone") {
223
- const context = {
224
- alert: "placement_move_mailbox_unreachable",
225
- messageId,
226
- accountId,
227
- sourceMailboxId: marker.sourceMailboxId,
228
- destinationMailboxId: marker.destinationMailboxId,
229
- };
230
- if (source.kind === "gone") {
231
- const reconciled = await messageService.deleteIfPlacement(
232
- messageId,
233
- placementRead,
234
- );
235
- await markerService.delete(messageId);
236
- log.error(
237
- { ...context, reconciled },
238
- "Placement move not pushed: its source folder is gone; the stale row was reconciled",
239
- );
240
- if (destination.kind === "present") {
241
- await emitMailboxResync(emitEvent, {
242
- accountId,
243
- mailboxId: marker.destinationMailboxId,
244
- });
245
- }
246
- return;
247
- }
248
- await restoreSourcePlacement(
249
- { messageService, threadMessageService },
250
- {
251
- accountConfigId,
252
- messageId,
253
- sourceMailboxId: marker.sourceMailboxId,
254
- uid: message.uid,
255
- syncStatus: MessageSyncStatus.synced,
256
- abandonedMutation: MessageMutation.none,
257
- },
258
- );
259
- await markerService.delete(messageId);
260
- log.error(
261
- context,
262
- "Placement move not pushed: its destination folder is gone; the row was handed back to its source",
263
- );
264
- await emitMailboxResync(emitEvent, {
265
- accountId,
266
- mailboxId: marker.sourceMailboxId,
267
- });
268
- return;
269
- }
270
- const sourceMailbox = source.mailbox;
271
- const destinationMailbox = destination.mailbox;
272
-
273
- // Cheap frugal skip (epic #1281 invariant 6): either mailbox already known
274
- // paused never even borrows a connection. Optimization only — the
275
- // guardConnectionCursor wraps below are the structural guarantee (#1272).
276
- if (
277
- isCursorRebuildNeeded(sourceMailbox.cursorState) ||
278
- isCursorRebuildNeeded(destinationMailbox.cursorState)
279
- ) {
280
- log.info(
281
- {
282
- messageId,
283
- accountId,
284
- sourceCursorState: sourceMailbox.cursorState,
285
- destinationCursorState: destinationMailbox.cursorState,
286
- },
287
- "Mailbox cursor not normal; pausing outbound placement-move push this round",
288
- );
289
- return;
290
- }
291
-
292
- await withOAuthLifecycle(
293
- buildLifecycleDeps(secrets, accountService),
294
- account,
295
- log,
296
- async (credentials) => {
297
- const scope = createConnectionScope(account, credentials);
298
-
299
- await scope
300
- .getConnection()
301
- .then(async (rawConnection) => {
302
- // Guard at the openBox choke point (epic #1281 invariants 3 & 5).
303
- // Two independently-scoped wraps around the SAME connection — see
304
- // the attemptMove doc comment for why one guard per mailbox matters.
305
- const sourceConnection = guardConnectionCursor(
306
- rawConnection,
307
- { mailboxService },
308
- accountId,
309
- sourceMailbox,
310
- );
311
- const destinationConnection = guardConnectionCursor(
312
- rawConnection,
313
- { mailboxService },
314
- accountId,
315
- destinationMailbox,
316
- );
317
-
318
- const outcome = await attemptMove(
319
- sourceConnection,
320
- destinationConnection,
321
- sourceMailbox.fullPath,
322
- destinationMailbox.fullPath,
323
- message.uid,
324
- await probeableMessageIdHeader(
325
- threadMessageService,
326
- accountConfigId,
327
- messageId,
328
- ),
329
- );
330
-
331
- if (outcome.kind === "trycreate") {
332
- await destinationConnection.createMailbox(
333
- destinationMailbox.fullPath,
334
- );
335
- throw new Error(
336
- `Destination mailbox ${destinationMailbox.fullPath} did not exist; created, retrying`,
337
- );
338
- }
339
-
340
- if (outcome.kind === "not-found") {
341
- // External delete supersedes the marker entirely (epic invariant 2).
342
- await markerService.delete(messageId);
343
- const reconciled = await messageService.deleteIfPlacement(
344
- messageId,
345
- placementRead,
346
- );
347
- log.info(
348
- {
349
- messageId,
350
- accountId,
351
- uid: message.uid,
352
- sourceMailboxPath: sourceMailbox.fullPath,
353
- reconciled,
354
- },
355
- "Message no longer at its pending-move source (external delete or moved away); marker dropped, stale row reconciled",
356
- );
357
- await emitMoveResync(emitEvent, {
358
- accountId,
359
- sourceMailboxId: marker.sourceMailboxId,
360
- destinationMailboxId: marker.destinationMailboxId,
361
- });
362
- return;
363
- }
364
-
365
- const newUid = outcome.newUid as number;
366
- await messageService.updateUid(
367
- messageId,
368
- newUid,
369
- marker.destinationMailboxId,
370
- );
371
-
372
- const threadMessage = await threadMessageService.findByMessageId(
373
- accountConfigId,
374
- messageId,
375
- );
376
- if (threadMessage) {
377
- const args = buildThreadMessageMoveUpdate(
378
- threadMessage,
379
- newUid,
380
- marker.destinationMailboxId,
381
- );
382
- await threadMessageService.update(
383
- threadMessage.accountConfigId,
384
- threadMessage.threadMessageId,
385
- args.set,
386
- { composites: args.composites },
387
- );
388
- }
389
-
390
- // Confirmed IMAP acknowledgement — the "processed" terminal state.
391
- // Deleted immediately rather than persisted first (epic invariant
392
- // 4: no lingering row once the move is no longer pending) — clears
393
- // ONLY here, never on attempt (the defect issue #1271 fixes).
394
- await markerService.delete(messageId);
395
-
396
- log.info(
397
- {
398
- messageId,
399
- accountId,
400
- oldUid: message.uid,
401
- newUid,
402
- destination: destinationMailbox.fullPath,
403
- },
404
- "Placement move confirmed on IMAP; marker cleared",
405
- );
406
-
407
- await emitMoveResync(emitEvent, {
408
- accountId,
409
- sourceMailboxId: marker.sourceMailboxId,
410
- destinationMailboxId: marker.destinationMailboxId,
411
- });
412
- })
413
- .catch(async (error: unknown) => {
414
- // Expected pause (epic #1281 invariant 3), not a fault: ack and
415
- // skip rather than propagating into SQS retry/DLQ. The marker
416
- // stays durable; the push resumes once the mailbox returns to
417
- // normal (driven by the next PLACEMENT_MOVE_PUSH for this message,
418
- // or the surviving-marker re-enqueue in PlacementMoveService).
419
- if (error instanceof MailboxCursorPausedError) {
420
- log.info(
421
- { messageId, accountId, cursorState: error.state },
422
- "UIDVALIDITY changed; mailbox cursor tripped, pausing outbound placement-move push",
423
- );
424
- return;
425
- }
426
-
427
- if (receiveCount < PLACEMENT_MOVE_MAX_ATTEMPTS) {
428
- // Transient push failure — expected (connections drop). No alarm;
429
- // SQS redelivery retries from the still-durable marker.
430
- throw error;
431
- }
432
-
433
- // Redelivery budget exhausted: resolve into exactly one of the two
434
- // terminal outcomes (epic invariant 3) instead of dead-lettering
435
- // with no diagnosis.
436
- const { outcome } = await resolveExhaustedPlacementMoveFailure(
437
- { markerService, messageService, threadMessageService, log },
438
- {
439
- placement: {
440
- status: message.status,
441
- mailboxId: message.mailboxId,
442
- uid: message.uid,
443
- },
444
- accountId,
445
- accountConfigId,
446
- messageId,
447
- uid: message.uid,
448
- sourceMailboxId: marker.sourceMailboxId,
449
- sourceMailboxPath: sourceMailbox.fullPath,
450
- getConnection: scope.getConnection,
451
- },
452
- );
453
-
454
- if (outcome === "reconciled") {
455
- await emitMoveResync(emitEvent, {
456
- accountId,
457
- sourceMailboxId: marker.sourceMailboxId,
458
- destinationMailboxId: marker.destinationMailboxId,
459
- });
460
- return;
461
- }
462
-
463
- // Terminal and never re-thrown, so the handler-outcome series
464
- // records this record as a success. Counted here or it is invisible.
465
- recordImapFailure("PLACEMENT_MOVE_EXHAUSTED", "other");
466
- log.error(
467
- { error: error instanceof Error ? error.message : String(error) },
468
- "Placement move retry exhausted; message still exists at its source",
469
- );
470
- // Terminal — never re-thrown, so the caller acks either way.
471
- })
472
- .finally(() => scope.disconnect());
473
- },
474
- );
475
- };