@remit/mailbox-service 0.0.48 → 0.0.50

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/mailbox-service",
3
- "version": "0.0.48",
3
+ "version": "0.0.50",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
package/src/index.ts CHANGED
@@ -217,6 +217,7 @@ export {
217
217
  type ResolveExhaustedPlacementMoveResult,
218
218
  resolveExhaustedPlacementMoveFailure,
219
219
  } from "./placement-move-terminal.js";
220
+ export { isPlacementUnsettled } from "./placement-settled.js";
220
221
  export {
221
222
  type QuarantineContext,
222
223
  QuarantinedUids,
@@ -14,7 +14,11 @@ import type {
14
14
  UpdateMailboxInput,
15
15
  UpdateThreadMessageInput,
16
16
  } from "@remit/data-ports";
17
- import { MailboxCursorState, MessageSystemFlag } from "@remit/domain-enums";
17
+ import {
18
+ MailboxCursorState,
19
+ MessageKeywordFlag,
20
+ MessageSystemFlag,
21
+ } from "@remit/domain-enums";
18
22
  import type { ManagedConnectionFactory } from "./connection-factory.js";
19
23
  import type { FlagPushService } from "./flag-push.js";
20
24
  import { FlagQueueService } from "./flag-queue.js";
@@ -112,6 +116,8 @@ interface Harness {
112
116
  /** The canonical flag record after the round. */
113
117
  flagStore: Set<string>;
114
118
  messageFlagService: IMessageFlagRepository;
119
+ /** Method names invoked on the top-level address repository. */
120
+ addressCalls: string[];
115
121
  }
116
122
 
117
123
  const buildHarness = (options: HarnessOptions): Harness => {
@@ -241,12 +247,29 @@ const buildHarness = (options: HarnessOptions): Harness => {
241
247
  },
242
248
  } as unknown as IMessageFlagRepository;
243
249
 
250
+ // The existing-message path (applyChange -> applyServerFlags) never
251
+ // touches this repository. Recording every call, rather than leaving the
252
+ // stub as `{}`, is what makes "$Junk stays message state" an assertion
253
+ // instead of an assumption a future change could silently break.
254
+ const addressCalls: string[] = [];
255
+ const addressRepository = new Proxy(
256
+ {},
257
+ {
258
+ get:
259
+ (_target, prop: string) =>
260
+ (..._args: unknown[]) => {
261
+ addressCalls.push(prop);
262
+ throw new Error(`unexpected IAddressRepository.${prop} call`);
263
+ },
264
+ },
265
+ ) as IAddressRepository;
266
+
244
267
  const service = new MessageSyncService(
245
268
  connectionFactory,
246
269
  mailboxService,
247
270
  {} as IMessageRepository,
248
271
  {} as IEnvelopeRepository,
249
- {} as IAddressRepository,
272
+ addressRepository,
250
273
  threadMessageService,
251
274
  logger,
252
275
  unitOfWork,
@@ -263,6 +286,7 @@ const buildHarness = (options: HarnessOptions): Harness => {
263
286
  errors,
264
287
  flagStore,
265
288
  messageFlagService,
289
+ addressCalls,
266
290
  };
267
291
  };
268
292
 
@@ -603,6 +627,71 @@ describe("MessageSyncService CHANGEDSINCE path", () => {
603
627
  });
604
628
  });
605
629
 
630
+ // $Junk/$NotJunk mirroring (report-spam epic, message-state slice). This
631
+ // mailbox is never remit-only — Apple Mail or another IMAP client is
632
+ // routinely connected too — so a keyword another client set is message
633
+ // state only. It must never become a standing rule about the sender.
634
+ describe("MessageSyncService mirrors $Junk/$NotJunk keywords", () => {
635
+ it("mirrors a server-side $Junk into the canonical flag record", async () => {
636
+ const harness = buildHarness({
637
+ mailbox: mailbox(),
638
+ supportsCondstore: true,
639
+ changed: [serverMessage({ flags: [MessageKeywordFlag.Junk] })],
640
+ storedRows: [storedRow()],
641
+ storedFlags: [],
642
+ });
643
+
644
+ await syncOnce(harness);
645
+
646
+ assert.ok(harness.flagStore.has(MessageKeywordFlag.Junk));
647
+ });
648
+
649
+ it("mirrors a server-side $NotJunk into the canonical flag record", async () => {
650
+ const harness = buildHarness({
651
+ mailbox: mailbox(),
652
+ supportsCondstore: true,
653
+ changed: [serverMessage({ flags: [MessageKeywordFlag.NotJunk] })],
654
+ storedRows: [storedRow()],
655
+ storedFlags: [],
656
+ });
657
+
658
+ await syncOnce(harness);
659
+
660
+ assert.ok(harness.flagStore.has(MessageKeywordFlag.NotJunk));
661
+ });
662
+
663
+ it("leaves $Junk alone while its local flip is still owed to IMAP", async () => {
664
+ const harness = buildHarness({
665
+ mailbox: mailbox(),
666
+ supportsCondstore: true,
667
+ // Server has not seen the local flip yet.
668
+ changed: [serverMessage({ flags: [] })],
669
+ storedRows: [storedRow()],
670
+ storedFlags: [MessageKeywordFlag.Junk],
671
+ pendingFlags: new Set([MessageKeywordFlag.Junk]),
672
+ });
673
+
674
+ await syncOnce(harness);
675
+
676
+ assert.ok(harness.flagStore.has(MessageKeywordFlag.Junk));
677
+ });
678
+
679
+ it("mirroring $Junk leaves the sender's Address record completely untouched", async () => {
680
+ const harness = buildHarness({
681
+ mailbox: mailbox(),
682
+ supportsCondstore: true,
683
+ changed: [serverMessage({ flags: [MessageKeywordFlag.Junk] })],
684
+ storedRows: [storedRow()],
685
+ storedFlags: [],
686
+ });
687
+
688
+ await syncOnce(harness);
689
+
690
+ assert.ok(harness.flagStore.has(MessageKeywordFlag.Junk));
691
+ assert.deepEqual(harness.addressCalls, []);
692
+ });
693
+ });
694
+
606
695
  describe("MessageSyncService without CONDSTORE", () => {
607
696
  it("falls back to full enumeration and never issues CHANGEDSINCE", async () => {
608
697
  const harness = buildHarness({
@@ -23,6 +23,7 @@ import {
23
23
  import {
24
24
  AddressRole,
25
25
  MailboxCursorState,
26
+ MessageKeywordFlag,
26
27
  MessageSystemFlag,
27
28
  StarColor,
28
29
  } from "@remit/domain-enums";
@@ -1025,8 +1026,9 @@ export class MessageSyncService {
1025
1026
  }
1026
1027
 
1027
1028
  /**
1028
- * Bring a stored row's read and star state in line with the server's
1029
- * flags.
1029
+ * Bring a stored row's read and star state, and the $Junk/$NotJunk
1030
+ * keywords on the canonical MessageFlag record, in line with the
1031
+ * server's flags.
1030
1032
  *
1031
1033
  * A field with a pending outbound push is left alone: the user flipped it
1032
1034
  * locally, IMAP has not been told yet, and the server's answer is
@@ -1073,6 +1075,17 @@ export class MessageSyncService {
1073
1075
  }
1074
1076
  }
1075
1077
 
1078
+ await this.mirrorKeywordFlag(
1079
+ existing.messageId,
1080
+ MessageKeywordFlag.Junk,
1081
+ flags,
1082
+ );
1083
+ await this.mirrorKeywordFlag(
1084
+ existing.messageId,
1085
+ MessageKeywordFlag.NotJunk,
1086
+ flags,
1087
+ );
1088
+
1076
1089
  if (Object.keys(updates).length === 0) return;
1077
1090
 
1078
1091
  // MessageFlag is the canonical flag record — `FlagQueueService` reads it
@@ -1157,6 +1170,32 @@ export class MessageSyncService {
1157
1170
  return marker !== null;
1158
1171
  }
1159
1172
 
1173
+ /**
1174
+ * Mirror one RFC 5788 keyword ($Junk / $NotJunk) from the server into the
1175
+ * canonical MessageFlag record, guarded the same way as the system flags:
1176
+ * a pending local push wins over the server's known-stale answer.
1177
+ *
1178
+ * This mailbox is never remit-only — Apple Mail or another IMAP client is
1179
+ * routinely connected too — so the keyword is message state, nothing
1180
+ * more. It never reaches the Address model: reading another client's
1181
+ * keyword as a standing rule about the sender is the exact fight this
1182
+ * mirror must not pick.
1183
+ */
1184
+ private async mirrorKeywordFlag(
1185
+ messageId: string,
1186
+ flagName: string,
1187
+ serverFlags: string[],
1188
+ ): Promise<void> {
1189
+ if (!this.messageFlagService) return;
1190
+ if (await this.hasPendingPush(messageId, flagName)) return;
1191
+
1192
+ const present = serverFlags.includes(flagName);
1193
+ const hasFlag = await this.messageFlagService.hasFlag(messageId, flagName);
1194
+ if (hasFlag === present) return;
1195
+
1196
+ await this.setMessageFlag(messageId, flagName, present);
1197
+ }
1198
+
1160
1199
  /**
1161
1200
  * Fetch a batch of messages using the managed connection.
1162
1201
  * Assumes mailbox is already open from fetchUidsToSync.
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Issue #496's rule applied to the placement move's own re-entry: a second
3
+ * verdict, for a different destination, arriving while the first move is still
4
+ * unconfirmed. The row then names the first destination but still carries the
5
+ * uid of the folder before it, so binding a fresh marker to that pair sends the
6
+ * reconciler to move the destination folder's OWN message at that uid.
7
+ */
8
+
9
+ import assert from "node:assert/strict";
10
+ import { afterEach, beforeEach, describe, it, mock } from "node:test";
11
+ import { SQSClient } from "@aws-sdk/client-sqs";
12
+ import type {
13
+ IMessagePlacementMoveRepository,
14
+ IMessageRepository,
15
+ IThreadMessageRepository,
16
+ MessageItem,
17
+ MessagePlacementMoveItem,
18
+ PutMessagePlacementMoveInput,
19
+ UpdateMessageMoveInput,
20
+ } from "@remit/data-ports";
21
+ import { PlacementMoveService } from "./placement-move.js";
22
+
23
+ const ACCOUNT_ID = "acc-pm";
24
+ const ACCOUNT_CONFIG_ID = "cfg-pm";
25
+ const MESSAGE_ID = "msg-pm";
26
+ const INBOX_ID = "mbx-inbox";
27
+ const ARCHIVE_ID = "mbx-archive";
28
+ const JUNK_ID = "mbx-junk";
29
+ const INBOX_UID = 42;
30
+
31
+ interface Harness {
32
+ service: PlacementMoveService;
33
+ row: MessageItem;
34
+ puts: PutMessagePlacementMoveInput[];
35
+ marker: MessagePlacementMoveItem | null;
36
+ }
37
+
38
+ const buildHarness = (): Harness => {
39
+ const row = {
40
+ messageId: MESSAGE_ID,
41
+ accountConfigId: ACCOUNT_CONFIG_ID,
42
+ mailboxId: INBOX_ID,
43
+ uid: INBOX_UID,
44
+ status: "active",
45
+ syncStatus: "synced",
46
+ } as unknown as MessageItem;
47
+
48
+ const puts: PutMessagePlacementMoveInput[] = [];
49
+ const harness = { row, puts, marker: null } as Harness;
50
+
51
+ const messageService = {
52
+ get: async () => row,
53
+ updateForMove: async (
54
+ _messageId: string,
55
+ input: UpdateMessageMoveInput,
56
+ ) => {
57
+ Object.assign(row, input);
58
+ return row;
59
+ },
60
+ } as unknown as IMessageRepository;
61
+
62
+ const threadMessageService = {
63
+ getByMessageId: async () => ({
64
+ accountConfigId: ACCOUNT_CONFIG_ID,
65
+ threadMessageId: "tm-pm",
66
+ sentDate: 1,
67
+ mailboxId: row.mailboxId,
68
+ isRead: false,
69
+ isDeleted: false,
70
+ hasStars: false,
71
+ hasAttachment: false,
72
+ }),
73
+ update: async () => {},
74
+ } as unknown as IThreadMessageRepository;
75
+
76
+ const markerService = {
77
+ put: async (input: PutMessagePlacementMoveInput) => {
78
+ puts.push(input);
79
+ harness.marker = {
80
+ ...input,
81
+ state: "pending",
82
+ createdAt: Date.now(),
83
+ } as unknown as MessagePlacementMoveItem;
84
+ return harness.marker;
85
+ },
86
+ find: async () => harness.marker,
87
+ updateState: async (
88
+ _messageId: string,
89
+ state: MessagePlacementMoveItem["state"],
90
+ ) => {
91
+ if (!harness.marker) throw new Error("no marker");
92
+ harness.marker.state = state;
93
+ return harness.marker;
94
+ },
95
+ delete: async () => {
96
+ harness.marker = null;
97
+ },
98
+ } as unknown as IMessagePlacementMoveRepository;
99
+
100
+ harness.service = new PlacementMoveService({
101
+ messageService,
102
+ threadMessageService,
103
+ markerService,
104
+ sqsQueueUrl: "https://sqs.eu-west-1.amazonaws.com/000/message-mgmt",
105
+ moveSettleTimeoutMs: 200,
106
+ moveSettlePollMs: 10,
107
+ });
108
+
109
+ return harness;
110
+ };
111
+
112
+ describe("PlacementMoveService — a second destination while the first move is unsettled (#496)", () => {
113
+ let harness: Harness;
114
+
115
+ beforeEach(() => {
116
+ mock.method(SQSClient.prototype, "send", async () => ({}));
117
+ harness = buildHarness();
118
+ });
119
+
120
+ afterEach(() => mock.restoreAll());
121
+
122
+ it("binds to the settled row once the earlier move confirms", async () => {
123
+ await harness.service.moveMessage(
124
+ ACCOUNT_CONFIG_ID,
125
+ MESSAGE_ID,
126
+ ARCHIVE_ID,
127
+ ACCOUNT_ID,
128
+ );
129
+ assert.equal(harness.row.status, "moving");
130
+ assert.equal(harness.row.uid, INBOX_UID);
131
+
132
+ // What the reconciler writes when the IMAP move lands: Archive's own
133
+ // COPYUID, and the status back to active.
134
+ setTimeout(() => {
135
+ Object.assign(harness.row, { uid: 907, status: "active" });
136
+ harness.marker = null;
137
+ }, 30);
138
+
139
+ await harness.service.moveMessage(
140
+ ACCOUNT_CONFIG_ID,
141
+ MESSAGE_ID,
142
+ JUNK_ID,
143
+ ACCOUNT_ID,
144
+ );
145
+
146
+ assert.equal(harness.puts.length, 2);
147
+ assert.equal(
148
+ harness.puts[1]?.sourceMailboxId,
149
+ ARCHIVE_ID,
150
+ "the source is where the confirmed move left the message",
151
+ );
152
+ assert.equal(harness.row.originalUid, 907, "and its confirmed uid");
153
+ });
154
+
155
+ it("does not apply the move when the earlier one never settles", async () => {
156
+ await harness.service.moveMessage(
157
+ ACCOUNT_CONFIG_ID,
158
+ MESSAGE_ID,
159
+ ARCHIVE_ID,
160
+ ACCOUNT_ID,
161
+ );
162
+
163
+ await assert.rejects(
164
+ () =>
165
+ harness.service.moveMessage(
166
+ ACCOUNT_CONFIG_ID,
167
+ MESSAGE_ID,
168
+ JUNK_ID,
169
+ ACCOUNT_ID,
170
+ ),
171
+ /has not settled/,
172
+ );
173
+
174
+ assert.equal(harness.puts.length, 1, "no second marker was written");
175
+ assert.equal(
176
+ harness.puts[0]?.sourceMailboxId,
177
+ INBOX_ID,
178
+ "the surviving marker still names the folder the message is actually in",
179
+ );
180
+ assert.equal(harness.marker?.destinationMailboxId, ARCHIVE_ID);
181
+ });
182
+
183
+ it("drives a surviving pending marker for the same destination forward", async () => {
184
+ await harness.service.moveMessage(
185
+ ACCOUNT_CONFIG_ID,
186
+ MESSAGE_ID,
187
+ ARCHIVE_ID,
188
+ ACCOUNT_ID,
189
+ );
190
+ // The enqueue failed on the earlier call, so the marker never advanced.
191
+ if (harness.marker) harness.marker.state = "pending";
192
+
193
+ await harness.service.moveMessage(
194
+ ACCOUNT_CONFIG_ID,
195
+ MESSAGE_ID,
196
+ ARCHIVE_ID,
197
+ ACCOUNT_ID,
198
+ );
199
+
200
+ assert.equal(harness.puts.length, 1, "the local move is never re-derived");
201
+ assert.equal(harness.marker?.state, "queued");
202
+ });
203
+
204
+ it("moves a settled row normally", async () => {
205
+ await harness.service.moveMessage(
206
+ ACCOUNT_CONFIG_ID,
207
+ MESSAGE_ID,
208
+ ARCHIVE_ID,
209
+ ACCOUNT_ID,
210
+ );
211
+ Object.assign(harness.row, { uid: 907, status: "active" });
212
+ harness.marker = null;
213
+
214
+ await harness.service.moveMessage(
215
+ ACCOUNT_CONFIG_ID,
216
+ MESSAGE_ID,
217
+ JUNK_ID,
218
+ ACCOUNT_ID,
219
+ );
220
+
221
+ assert.equal(harness.puts.length, 2);
222
+ assert.equal(harness.puts[1]?.sourceMailboxId, ARCHIVE_ID);
223
+ assert.equal(harness.puts[1]?.destinationMailboxId, JUNK_ID);
224
+ });
225
+ });
@@ -7,6 +7,10 @@ import type {
7
7
  } from "@remit/data-ports";
8
8
  import { MessageStatus, MessageSyncStatus } from "@remit/domain-enums";
9
9
  import { createQueueProducer } from "@remit/sqs-client/producer";
10
+ import {
11
+ isPlacementUnsettled,
12
+ waitForPlacementToSettle,
13
+ } from "./placement-settled.js";
10
14
 
11
15
  /**
12
16
  * Event the reconciler (imap-worker `handlePlacementMovePush`) drains. Carries
@@ -41,8 +45,13 @@ export interface PlacementMoveConfig {
41
45
  sqsQueueUrl: string;
42
46
  sqsEndpoint?: string;
43
47
  logger?: PlacementMoveLogger;
48
+ moveSettleTimeoutMs?: number;
49
+ moveSettlePollMs?: number;
44
50
  }
45
51
 
52
+ const DEFAULT_MOVE_SETTLE_TIMEOUT_MS = 5_000;
53
+ const DEFAULT_MOVE_SETTLE_POLL_MS = 250;
54
+
46
55
  /**
47
56
  * Local-first mover for a classification-driven placement move (issue #1271,
48
57
  * epic #1281). Distinct from {@link MessageMoveService} (user-initiated
@@ -78,6 +87,8 @@ export class PlacementMoveService {
78
87
  private sqs: SQSClient;
79
88
  private queueUrl: string;
80
89
  private log: PlacementMoveLogger;
90
+ private moveSettleTimeoutMs: number;
91
+ private moveSettlePollMs: number;
81
92
 
82
93
  constructor(config: PlacementMoveConfig) {
83
94
  this.messageService = config.messageService;
@@ -85,6 +96,10 @@ export class PlacementMoveService {
85
96
  this.markerService = config.markerService;
86
97
  this.queueUrl = config.sqsQueueUrl;
87
98
  this.log = config.logger ?? noopLogger;
99
+ this.moveSettleTimeoutMs =
100
+ config.moveSettleTimeoutMs ?? DEFAULT_MOVE_SETTLE_TIMEOUT_MS;
101
+ this.moveSettlePollMs =
102
+ config.moveSettlePollMs ?? DEFAULT_MOVE_SETTLE_POLL_MS;
88
103
  this.sqs = createQueueProducer({
89
104
  queueUrl: config.sqsQueueUrl,
90
105
  endpoint: config.sqsEndpoint,
@@ -97,8 +112,7 @@ export class PlacementMoveService {
97
112
  destinationMailboxId: string,
98
113
  accountId: string,
99
114
  ): Promise<void> => {
100
- const message = await this.messageService.get(messageId);
101
- const sourceMailboxId = message.mailboxId;
115
+ let message = await this.messageService.get(messageId);
102
116
 
103
117
  // Recovery: a marker already exists for THIS message and destination —
104
118
  // from an earlier (possibly partially-failed) call. The marker's STATE,
@@ -128,6 +142,28 @@ export class PlacementMoveService {
128
142
  return;
129
143
  }
130
144
 
145
+ // A different destination, decided while an earlier move is still
146
+ // unconfirmed (issue #496): the row names that move's destination but its
147
+ // `uid` still belongs to the folder before it, so a marker bound to the
148
+ // pair as it stands sends the reconciler to move the destination folder's
149
+ // OWN message at that uid. Wait for the earlier move to confirm and bind
150
+ // to the settled row (docs/architecture/imap-mutations.md R2). Blocking is
151
+ // cheap — a move settles in well under a second — and on timeout the
152
+ // dependent write is simply not made.
153
+ if (isPlacementUnsettled(message)) {
154
+ message = await waitForPlacementToSettle(this.messageService, messageId, {
155
+ timeoutMs: this.moveSettleTimeoutMs,
156
+ pollMs: this.moveSettlePollMs,
157
+ });
158
+ if (isPlacementUnsettled(message)) {
159
+ throw new Error(
160
+ `Placement move for ${messageId} to ${destinationMailboxId} not applied: an earlier move has not settled`,
161
+ );
162
+ }
163
+ }
164
+
165
+ const sourceMailboxId = message.mailboxId;
166
+
131
167
  // Genuine no-op: nothing pending for this destination, and the message
132
168
  // is already there (a duplicate verdict recomputed after a confirmed
133
169
  // move).
@@ -0,0 +1,47 @@
1
+ import type { MessageItem } from "@remit/data-ports";
2
+ import { MessageStatus } from "@remit/domain-enums";
3
+
4
+ /**
5
+ * Whether the message row's placement is still an unconfirmed local write
6
+ * (issue #496). While a move is in flight the row carries the destination in
7
+ * `mailboxId` but the SOURCE folder's `uid` — the pair is only made consistent
8
+ * when the IMAP move confirms and `updateUid` writes the destination's COPYUID.
9
+ * Any dependent mutation that resolves a folder and a uid from such a row
10
+ * therefore addresses the destination's OWN message at that uid: a different
11
+ * message, on a mailbox Remit is never the only client of.
12
+ *
13
+ * `syncStatus` is not the signal. An ordinary freshly-synced inbound row is
14
+ * `pending` forever (nothing on the inbound path promotes it), so keying off it
15
+ * defers every outbound mutation in the product. `status` is set to `moving`
16
+ * only by an actual move and cleared only once that move settles.
17
+ */
18
+ export const isPlacementUnsettled = (
19
+ message: Pick<MessageItem, "status">,
20
+ ): boolean => message.status === MessageStatus.moving;
21
+
22
+ export interface PlacementSettleOptions {
23
+ timeoutMs: number;
24
+ pollMs: number;
25
+ }
26
+
27
+ /**
28
+ * Block a dependent mutation until the row's placement settles, then hand back
29
+ * the confirmed row — the wait half of docs/architecture/imap-mutations.md R2.
30
+ * A move ordinarily settles in well under a second, so blocking is the cheap
31
+ * option the doc's default guidance names. The row comes back still unsettled
32
+ * when the deadline passes; the caller decides what a dependency that never
33
+ * settled means for it.
34
+ */
35
+ export const waitForPlacementToSettle = async (
36
+ messageService: { get(messageId: string): Promise<MessageItem> },
37
+ messageId: string,
38
+ { timeoutMs, pollMs }: PlacementSettleOptions,
39
+ ): Promise<MessageItem> => {
40
+ const deadline = Date.now() + timeoutMs;
41
+ let message = await messageService.get(messageId);
42
+ while (isPlacementUnsettled(message) && Date.now() < deadline) {
43
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
44
+ message = await messageService.get(messageId);
45
+ }
46
+ return message;
47
+ };