@remit/mailbox-service 0.0.49 → 0.0.51

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.
@@ -0,0 +1,498 @@
1
+ import type {
2
+ IOutboxAttachmentRepository,
3
+ IOutboxMessageRepository,
4
+ OutboxAttachmentItem,
5
+ OutboxMessageItem,
6
+ } from "@remit/data-ports";
7
+ import { holdsRoom } from "@remit/data-ports";
8
+ import { ConflictError } from "@remit/data-ports/errors";
9
+ import { base36uuid } from "@remit/data-ports/id";
10
+ import {
11
+ OutboxAttachmentRejectionReason,
12
+ OutboxMessageStatus,
13
+ } from "@remit/domain-enums";
14
+ import type { StorageService } from "@remit/storage-service";
15
+ import {
16
+ buildOutboxAttachmentKey,
17
+ UPLOAD_URL_TTL_SECONDS,
18
+ } from "@remit/storage-service";
19
+ import {
20
+ normalizeAttachmentContentType,
21
+ sanitizeAttachmentFilename,
22
+ } from "./outbox-attachment-filename.js";
23
+
24
+ /**
25
+ * 25 MB is what most receiving servers accept, and base64 inflates it to roughly
26
+ * 34 MB on the wire. The same number caps one file and the sum of a draft's
27
+ * files, so a single file can fill a message.
28
+ */
29
+ export const OUTBOX_ATTACHMENT_MAX_TOTAL_BYTES = 25 * 1024 * 1024;
30
+
31
+ /**
32
+ * A ceiling on how many files one draft can accumulate. The byte cap does not
33
+ * bound the count — a thousand one-byte files stay far under it.
34
+ */
35
+ export const OUTBOX_ATTACHMENT_MAX_COUNT = 25;
36
+
37
+ export type OutboxAttachmentRejectionReasonValue =
38
+ (typeof OutboxAttachmentRejectionReason)[keyof typeof OutboxAttachmentRejectionReason];
39
+
40
+ export interface OutboxAttachmentReservation {
41
+ outboxAttachmentId: string;
42
+ outboxMessageId: string;
43
+ filename: string;
44
+ contentType: string;
45
+ sizeBytes: number;
46
+ uploadUrl: string;
47
+ uploadExpiresAt: number;
48
+ }
49
+
50
+ export interface OutboxAttachmentRejectionDetail {
51
+ reason: OutboxAttachmentRejectionReasonValue;
52
+ message: string;
53
+ limitBytes: number;
54
+ usedBytes: number;
55
+ }
56
+
57
+ type Refused = {
58
+ readonly outcome: "Rejected";
59
+ readonly rejection: OutboxAttachmentRejectionDetail;
60
+ };
61
+
62
+ export type MintOutboxAttachmentOutcome =
63
+ | {
64
+ readonly outcome: "Minted";
65
+ readonly reservation: OutboxAttachmentReservation;
66
+ }
67
+ | Refused;
68
+
69
+ export type CompleteOutboxAttachmentOutcome =
70
+ | { readonly outcome: "Completed"; readonly attachment: OutboxAttachmentItem }
71
+ | Refused;
72
+
73
+ export interface MintOutboxAttachmentInput {
74
+ accountConfigId: string;
75
+ outboxMessageId: string;
76
+ filename: string;
77
+ contentType: string;
78
+ sizeBytes: number;
79
+ }
80
+
81
+ export interface CompleteOutboxAttachmentInput {
82
+ accountConfigId: string;
83
+ outboxMessageId: string;
84
+ outboxAttachmentId: string;
85
+ }
86
+
87
+ export interface OutboxAttachmentConfig {
88
+ outboxMessageService: IOutboxMessageRepository;
89
+ outboxAttachmentService: IOutboxAttachmentRepository;
90
+ storage: StorageService;
91
+ now?: () => number;
92
+ }
93
+
94
+ const formatBytes = (bytes: number): string =>
95
+ `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
96
+
97
+ export class OutboxAttachmentService {
98
+ private readonly outboxMessageService: IOutboxMessageRepository;
99
+ private readonly attachments: IOutboxAttachmentRepository;
100
+ private readonly storage: StorageService;
101
+ private readonly now: () => number;
102
+
103
+ constructor(config: OutboxAttachmentConfig) {
104
+ this.outboxMessageService = config.outboxMessageService;
105
+ this.attachments = config.outboxAttachmentService;
106
+ this.storage = config.storage;
107
+ this.now = config.now ?? (() => Math.floor(Date.now() / 1000));
108
+ }
109
+
110
+ /**
111
+ * Resolve a draft the caller is entitled to act on.
112
+ *
113
+ * Mode "act": the caller has named the draft, so a foreign one is denied with
114
+ * 403 rather than feigned as a 404. An entry that has left draft is a
115
+ * conflict. Both abort the request — only the file itself comes back as a
116
+ * result the composer can render next to the row it refused.
117
+ */
118
+ private getWritableDraft = async (
119
+ accountConfigId: string,
120
+ outboxMessageId: string,
121
+ ): Promise<OutboxMessageItem> => {
122
+ const outbox = await this.outboxMessageService.get(
123
+ accountConfigId,
124
+ outboxMessageId,
125
+ "act",
126
+ );
127
+
128
+ if (outbox.status !== OutboxMessageStatus.draft) {
129
+ throw new ConflictError(
130
+ `This message is already ${outbox.status} and can no longer take an attachment. Start a new message to change it.`,
131
+ );
132
+ }
133
+
134
+ return outbox;
135
+ };
136
+
137
+ private usedBytesOn = async (
138
+ accountConfigId: string,
139
+ outboxMessageId: string,
140
+ ): Promise<number> => {
141
+ const held = await this.attachments.listByOutboxMessage(
142
+ accountConfigId,
143
+ outboxMessageId,
144
+ );
145
+ const nowSeconds = this.now();
146
+ return held
147
+ .filter((item) => holdsRoom(item, nowSeconds))
148
+ .reduce((total, item) => total + item.sizeBytes, 0);
149
+ };
150
+
151
+ private reject = (
152
+ reason: OutboxAttachmentRejectionReasonValue,
153
+ message: string,
154
+ usedBytes: number,
155
+ ): Refused => ({
156
+ outcome: "Rejected",
157
+ rejection: {
158
+ reason,
159
+ message,
160
+ limitBytes: OUTBOX_ATTACHMENT_MAX_TOTAL_BYTES,
161
+ usedBytes,
162
+ },
163
+ });
164
+
165
+ /**
166
+ * Room on a draft for one file, and somewhere to put it.
167
+ *
168
+ * The row is written before the URL is handed out, and writing it is what
169
+ * claims the room — the count and the insert are one database transaction, so
170
+ * two requests arriving together cannot both be told there was space. That is
171
+ * the whole of the cap; nothing above this layer needs to serialize anything.
172
+ */
173
+ mint = async (
174
+ input: MintOutboxAttachmentInput,
175
+ ): Promise<MintOutboxAttachmentOutcome> => {
176
+ const outbox = await this.getWritableDraft(
177
+ input.accountConfigId,
178
+ input.outboxMessageId,
179
+ );
180
+
181
+ const filename = sanitizeAttachmentFilename(input.filename);
182
+ if (filename === null) {
183
+ return this.reject(
184
+ OutboxAttachmentRejectionReason.UnusableFilename,
185
+ "That file's name is empty once path separators and hidden characters are removed. Rename it and try again.",
186
+ await this.usedBytesOn(input.accountConfigId, input.outboxMessageId),
187
+ );
188
+ }
189
+ if (input.sizeBytes <= 0) {
190
+ return this.reject(
191
+ OutboxAttachmentRejectionReason.EmptyFile,
192
+ `"${filename}" is empty, so there is nothing to attach.`,
193
+ await this.usedBytesOn(input.accountConfigId, input.outboxMessageId),
194
+ );
195
+ }
196
+ if (input.sizeBytes > OUTBOX_ATTACHMENT_MAX_TOTAL_BYTES) {
197
+ return this.reject(
198
+ OutboxAttachmentRejectionReason.FileTooLarge,
199
+ `"${filename}" is ${formatBytes(input.sizeBytes)}, over the ${formatBytes(OUTBOX_ATTACHMENT_MAX_TOTAL_BYTES)} a message can carry.`,
200
+ await this.usedBytesOn(input.accountConfigId, input.outboxMessageId),
201
+ );
202
+ }
203
+
204
+ const nowSeconds = this.now();
205
+ const reservationExpiresAt = nowSeconds + UPLOAD_URL_TTL_SECONDS;
206
+ // The id is the row's own, and the key is built from it after the fact, so
207
+ // there is exactly one place an attachment's identity comes from.
208
+ const outboxAttachmentId = base36uuid();
209
+ const storageKey = buildOutboxAttachmentKey(
210
+ input.accountConfigId,
211
+ outbox.accountId,
212
+ input.outboxMessageId,
213
+ outboxAttachmentId,
214
+ );
215
+
216
+ const reserved = await this.attachments.reserve(
217
+ {
218
+ outboxAttachmentId,
219
+ outboxMessageId: input.outboxMessageId,
220
+ accountId: outbox.accountId,
221
+ accountConfigId: input.accountConfigId,
222
+ filename,
223
+ contentType: normalizeAttachmentContentType(input.contentType),
224
+ sizeBytes: input.sizeBytes,
225
+ storageKey,
226
+ reservationExpiresAt,
227
+ },
228
+ {
229
+ maxTotalBytes: OUTBOX_ATTACHMENT_MAX_TOTAL_BYTES,
230
+ maxCount: OUTBOX_ATTACHMENT_MAX_COUNT,
231
+ nowSeconds,
232
+ },
233
+ );
234
+
235
+ if (reserved.outcome === "OverCountCap") {
236
+ return this.reject(
237
+ OutboxAttachmentRejectionReason.TooManyAttachments,
238
+ `This message already carries ${OUTBOX_ATTACHMENT_MAX_COUNT} files, the most one message can hold. Remove one to attach "${filename}".`,
239
+ reserved.usedBytes,
240
+ );
241
+ }
242
+ if (reserved.outcome === "OverByteCap") {
243
+ return this.reject(
244
+ OutboxAttachmentRejectionReason.MessageTooLarge,
245
+ `"${filename}" is ${formatBytes(input.sizeBytes)} and this message already carries ${formatBytes(reserved.usedBytes)}, over the ${formatBytes(OUTBOX_ATTACHMENT_MAX_TOTAL_BYTES)} it can send.`,
246
+ reserved.usedBytes,
247
+ );
248
+ }
249
+
250
+ const target = await this.storage.createOutboxAttachmentUploadUrl({
251
+ accountConfigId: input.accountConfigId,
252
+ accountId: outbox.accountId,
253
+ outboxMessageId: input.outboxMessageId,
254
+ outboxAttachmentId: reserved.item.outboxAttachmentId,
255
+ sizeBytes: input.sizeBytes,
256
+ expiresAt: reservationExpiresAt,
257
+ });
258
+
259
+ return {
260
+ outcome: "Minted",
261
+ reservation: {
262
+ outboxAttachmentId: reserved.item.outboxAttachmentId,
263
+ outboxMessageId: input.outboxMessageId,
264
+ filename: reserved.item.filename,
265
+ contentType: reserved.item.contentType,
266
+ sizeBytes: reserved.item.sizeBytes,
267
+ uploadUrl: target.uploadUrl,
268
+ uploadExpiresAt: reservationExpiresAt,
269
+ },
270
+ };
271
+ };
272
+
273
+ /**
274
+ * Turn an upload into an attachment, on storage's word rather than the
275
+ * client's.
276
+ *
277
+ * On a hosted deployment the bytes went straight to block storage and this is
278
+ * the first the API hears of them, so the size is read back before the row is
279
+ * moved to Stored. An object that is absent, or not the size reserved for it,
280
+ * does not become an attachment — phase 4 sends these bytes, and an
281
+ * attachment recorded over nothing is a message that cannot be built.
282
+ */
283
+ complete = async (
284
+ input: CompleteOutboxAttachmentInput,
285
+ ): Promise<CompleteOutboxAttachmentOutcome> => {
286
+ const outbox = await this.getWritableDraft(
287
+ input.accountConfigId,
288
+ input.outboxMessageId,
289
+ );
290
+
291
+ const held = await this.attachments.listByOutboxMessage(
292
+ input.accountConfigId,
293
+ input.outboxMessageId,
294
+ );
295
+ const nowSeconds = this.now();
296
+ const usedBytes = held
297
+ .filter((item) => holdsRoom(item, nowSeconds))
298
+ .reduce((total, item) => total + item.sizeBytes, 0);
299
+
300
+ const row = held.find(
301
+ (item) => item.outboxAttachmentId === input.outboxAttachmentId,
302
+ );
303
+ if (!row || !holdsRoom(row, nowSeconds)) {
304
+ return this.reject(
305
+ OutboxAttachmentRejectionReason.ReservationExpired,
306
+ "That upload took too long and its reservation has lapsed. Attach the file again.",
307
+ usedBytes,
308
+ );
309
+ }
310
+
311
+ // Completing twice is a retry, not a fault: the second call is told what
312
+ // the first was.
313
+ if (row.state === "Stored") {
314
+ return { outcome: "Completed", attachment: row };
315
+ }
316
+
317
+ const stored = await this.storage.statOutboxAttachment(
318
+ input.accountConfigId,
319
+ outbox.accountId,
320
+ input.outboxMessageId,
321
+ input.outboxAttachmentId,
322
+ );
323
+ if (stored === null) {
324
+ return this.reject(
325
+ OutboxAttachmentRejectionReason.UploadMissing,
326
+ "The file never finished uploading. Attach it again.",
327
+ usedBytes,
328
+ );
329
+ }
330
+ if (stored.sizeBytes !== row.sizeBytes) {
331
+ // What landed is not what was announced. Take the row and the bytes,
332
+ // so the room goes back and nothing points at a file that is not there.
333
+ await this.attachments.deleteMany(input.accountConfigId, [
334
+ input.outboxAttachmentId,
335
+ ]);
336
+ await this.storage.deleteOutboxAttachment(
337
+ input.accountConfigId,
338
+ outbox.accountId,
339
+ input.outboxMessageId,
340
+ input.outboxAttachmentId,
341
+ );
342
+ return this.reject(
343
+ OutboxAttachmentRejectionReason.SizeMismatch,
344
+ "What arrived is not the file that was announced. Attach it again.",
345
+ Math.max(0, usedBytes - row.sizeBytes),
346
+ );
347
+ }
348
+
349
+ const confirmed = await this.attachments.markStored(
350
+ input.accountConfigId,
351
+ input.outboxAttachmentId,
352
+ stored.sizeBytes,
353
+ );
354
+ if (confirmed === null) {
355
+ // Another completion moved it between the read and the update. Read it
356
+ // back rather than guess.
357
+ const settled = await this.attachments.get(
358
+ input.accountConfigId,
359
+ input.outboxAttachmentId,
360
+ );
361
+ return { outcome: "Completed", attachment: settled };
362
+ }
363
+
364
+ return { outcome: "Completed", attachment: confirmed };
365
+ };
366
+
367
+ /**
368
+ * Whether an attachment is still owed its bytes. The self-hosted upload route
369
+ * asks before it writes, so a URL minted before a discard cannot put bytes
370
+ * back under a draft that is gone.
371
+ */
372
+ hasLiveReservation = async (
373
+ accountConfigId: string,
374
+ outboxAttachmentId: string,
375
+ ): Promise<boolean> => {
376
+ const row = await this.attachments
377
+ .get(accountConfigId, outboxAttachmentId)
378
+ .catch(() => null);
379
+ // Pending only. A Stored row has already been confirmed at a size, and its
380
+ // URL stays signed for the rest of its window — accepting a second write
381
+ // would let the same-length bytes behind a confirmed attachment be
382
+ // replaced.
383
+ return (
384
+ row !== null &&
385
+ row.state === "Pending" &&
386
+ row.reservationExpiresAt >= this.now()
387
+ );
388
+ };
389
+
390
+ /**
391
+ * What a draft holds, as the composer should see it: reservations that have
392
+ * lapsed are not files, and showing one with no way to tell it apart is worse
393
+ * than not showing it.
394
+ */
395
+ listFor = async (
396
+ accountConfigId: string,
397
+ outboxMessageId: string,
398
+ ): Promise<OutboxAttachmentItem[]> => {
399
+ const nowSeconds = this.now();
400
+ const held = await this.attachments.listByOutboxMessage(
401
+ accountConfigId,
402
+ outboxMessageId,
403
+ );
404
+ return held.filter((item) => holdsRoom(item, nowSeconds));
405
+ };
406
+
407
+ /**
408
+ * Drop the draft's lapsed reservations and answer with the ids that are still
409
+ * good. The sweep runs this before it decides what to collect: a lapsed row
410
+ * would otherwise keep vouching for bytes nothing will ever send, and the
411
+ * object would never be collected while the row that names it survives.
412
+ */
413
+ reapAndListLive = async (
414
+ accountConfigId: string,
415
+ outboxMessageId: string,
416
+ ): Promise<string[]> => {
417
+ await this.attachments.deleteLapsedReservations(
418
+ accountConfigId,
419
+ outboxMessageId,
420
+ this.now(),
421
+ );
422
+ const held = await this.attachments.listByOutboxMessage(
423
+ accountConfigId,
424
+ outboxMessageId,
425
+ );
426
+ return held.map((item) => item.outboxAttachmentId);
427
+ };
428
+
429
+ /**
430
+ * Keep only the named attachments, deleting the rest with their bytes. This
431
+ * is how a composer removes a file: the update states what the draft keeps.
432
+ */
433
+ retainOnly = async (
434
+ accountConfigId: string,
435
+ accountId: string,
436
+ outboxMessageId: string,
437
+ keepIds: readonly string[],
438
+ ): Promise<void> => {
439
+ const held = await this.attachments.listByOutboxMessage(
440
+ accountConfigId,
441
+ outboxMessageId,
442
+ );
443
+ const keep = new Set(keepIds);
444
+ const drop = held.filter((item) => !keep.has(item.outboxAttachmentId));
445
+ if (drop.length === 0) return;
446
+
447
+ // Bytes first, rows second — the same order as `discardAll`, and for the
448
+ // same reason: while a row exists its object is accounted for, so a
449
+ // failure part-way leaves something the sweep can still finish. One
450
+ // object that will not delete must not strand the rest, so the failures
451
+ // are collected and raised together once the rows are gone.
452
+ const failures: unknown[] = [];
453
+ for (const item of drop) {
454
+ await this.storage
455
+ .deleteOutboxAttachment(
456
+ accountConfigId,
457
+ accountId,
458
+ outboxMessageId,
459
+ item.outboxAttachmentId,
460
+ )
461
+ .catch((error: unknown) => failures.push(error));
462
+ }
463
+
464
+ await this.attachments.deleteMany(
465
+ accountConfigId,
466
+ drop.map((item) => item.outboxAttachmentId),
467
+ );
468
+
469
+ if (failures.length > 0) {
470
+ throw new AggregateError(
471
+ failures,
472
+ `Could not delete ${failures.length} of ${drop.length} attachment objects; their rows are gone and the sweep will collect them`,
473
+ );
474
+ }
475
+ };
476
+
477
+ /**
478
+ * Drop every file a draft holds, rows and bytes, as the draft is retired —
479
+ * a discard, or the APPEND to Sent that removes the row once the message has
480
+ * left. Rows go last: while they exist the objects are accounted for, and a
481
+ * failure part-way leaves the sweep able to finish the job.
482
+ */
483
+ discardAll = async (
484
+ accountConfigId: string,
485
+ accountId: string,
486
+ outboxMessageId: string,
487
+ ): Promise<void> => {
488
+ await this.storage.deleteOutboxAttachments(
489
+ accountConfigId,
490
+ accountId,
491
+ outboxMessageId,
492
+ );
493
+ await this.attachments.deleteByOutboxMessage(
494
+ accountConfigId,
495
+ outboxMessageId,
496
+ );
497
+ };
498
+ }
@@ -8,6 +8,7 @@ import type {
8
8
  import { ConflictError } from "@remit/data-ports/errors";
9
9
  import { OutboxMessageStatus } from "@remit/domain-enums";
10
10
  import { createQueueProducer } from "@remit/sqs-client/producer";
11
+ import type { OutboxAttachmentService } from "./outbox-attachment.js";
11
12
 
12
13
  interface SendMessageEvent {
13
14
  type: "SEND_MESSAGE";
@@ -29,6 +30,7 @@ const noopLogger: OutboxQueueLogger = {
29
30
 
30
31
  export interface OutboxQueueConfig {
31
32
  outboxMessageService: IOutboxMessageRepository;
33
+ outboxAttachmentService: OutboxAttachmentService;
32
34
  accountService: IAccountRepository;
33
35
  sqsSmtpQueueUrl: string;
34
36
  sqsEndpoint?: string;
@@ -76,6 +78,7 @@ const extractDomain = (email: string): string => {
76
78
 
77
79
  export class OutboxQueueService {
78
80
  private outboxMessageService: IOutboxMessageRepository;
81
+ private outboxAttachmentService: OutboxAttachmentService;
79
82
  private accountService: IAccountRepository;
80
83
  private sqs: SQSClient;
81
84
  private queueUrl: string;
@@ -84,11 +87,13 @@ export class OutboxQueueService {
84
87
  constructor(config: OutboxQueueConfig) {
85
88
  const {
86
89
  outboxMessageService,
90
+ outboxAttachmentService,
87
91
  accountService,
88
92
  sqsSmtpQueueUrl,
89
93
  sqsEndpoint,
90
94
  } = config;
91
95
  this.outboxMessageService = outboxMessageService;
96
+ this.outboxAttachmentService = outboxAttachmentService;
92
97
  this.accountService = accountService;
93
98
  this.queueUrl = sqsSmtpQueueUrl;
94
99
  this.log = config.logger ?? noopLogger;
@@ -261,6 +266,16 @@ export class OutboxQueueService {
261
266
  );
262
267
  }
263
268
 
269
+ // Files first, row second. Nothing but this row points at those objects,
270
+ // so a row deleted ahead of a sweep that then fails leaves bytes no one
271
+ // can reach; the other order leaves a draft whose files are gone, which
272
+ // is at least visible. A storage failure aborts the discard outright.
273
+ await this.outboxAttachmentService.discardAll(
274
+ accountConfigId,
275
+ existing.accountId,
276
+ outboxMessageId,
277
+ );
278
+
264
279
  await this.outboxMessageService.delete(accountConfigId, outboxMessageId);
265
280
 
266
281
  this.log.info({ outboxMessageId }, "Deleted outbox message");