@remit/storage-service 0.0.12 → 0.0.14

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/src/storage.ts DELETED
@@ -1,699 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { Readable } from "node:stream";
3
- import { ContentEncoding, StorageType } from "@remit/domain-enums";
4
-
5
- export type StorageTypeValue = (typeof StorageType)[keyof typeof StorageType];
6
- export type ContentEncodingValue =
7
- (typeof ContentEncoding)[keyof typeof ContentEncoding];
8
-
9
- export interface StorageReference {
10
- uri: string;
11
- storageType: StorageTypeValue;
12
- storageLocation: string;
13
- storageKey: string;
14
- sizeBytes: number;
15
- /**
16
- * SHA-256 (hex) of the logical, pre-compression content.
17
- * Identifies the content regardless of how it is stored on the backend,
18
- * and is used by `buildDeduplicatedKey` for content-addressable storage.
19
- * Note: this is NOT the checksum S3 validates against the received bytes —
20
- * S3's own transport-level checksum is handled by the SDK on PUT.
21
- */
22
- checksumSha256: string;
23
- contentEncoding: ContentEncodingValue;
24
- }
25
-
26
- /** Parameters for storing a message body (raw RFC822 content) */
27
- export interface StoreMessageBodyParams {
28
- accountConfigId: string;
29
- accountId: string;
30
- messageId: string;
31
- content: Buffer;
32
- }
33
-
34
- /** Parameters for streaming a message body (raw RFC822 content) to storage */
35
- export interface StoreMessageBodyStreamParams {
36
- accountConfigId: string;
37
- accountId: string;
38
- messageId: string;
39
- /** Readable stream of the raw message bytes; streamed to storage, never buffered whole. */
40
- content: Readable;
41
- }
42
-
43
- /** Parameters for storing a body part (attachment, inline content) */
44
- export interface StoreBodyPartParams {
45
- accountConfigId: string;
46
- accountId: string;
47
- messageId: string;
48
- partPath: string;
49
- content: Buffer;
50
- contentType?: string;
51
- }
52
-
53
- /**
54
- * Parameters for storing a file attached to a draft outbox message.
55
- *
56
- * Deliberately not the deduplicated path: a content-addressed object belongs to
57
- * no single draft, so nothing may delete it when the draft goes. A per-draft key
58
- * dies with the draft.
59
- */
60
- export interface StoreOutboxAttachmentParams {
61
- accountConfigId: string;
62
- accountId: string;
63
- outboxMessageId: string;
64
- outboxAttachmentId: string;
65
- content: Buffer;
66
- }
67
-
68
- /**
69
- * One uploaded object under a draft's attachment prefix. Reservations are not
70
- * here — they live in the ledger, which is the only thing that can say whether
71
- * an object present in storage is an attachment or garbage.
72
- */
73
- export interface OutboxAttachmentListItem {
74
- outboxAttachmentId: string;
75
- key: string;
76
- sizeBytes: number;
77
- }
78
-
79
- /** Somewhere for a client to PUT one file, for a while */
80
- export interface OutboxAttachmentUploadTarget {
81
- /**
82
- * Absolute URL the client PUTs raw bytes to. Opaque by design: block storage
83
- * on one deployment, this deployment's own upload route on another, and a
84
- * client cannot tell which it was handed.
85
- */
86
- uploadUrl: string;
87
- }
88
-
89
- export interface CreateOutboxAttachmentUploadUrlParams {
90
- accountConfigId: string;
91
- accountId: string;
92
- outboxMessageId: string;
93
- outboxAttachmentId: string;
94
- /** Exact byte count the upload may carry. */
95
- sizeBytes: number;
96
- expiresAt: number;
97
- }
98
-
99
- /** Parameters for storing deduplicated content (attachments shared across messages) */
100
- export interface StoreDeduplicatedParams {
101
- accountConfigId: string;
102
- accountId: string;
103
- content: Buffer;
104
- contentType?: string;
105
- }
106
-
107
- /** Metadata for a single attachment in a parsed message body. No binary content. */
108
- export interface ParsedAttachmentMeta {
109
- filename: string | null;
110
- contentType: string;
111
- contentDisposition: string | null;
112
- contentId: string | null;
113
- size: number;
114
- }
115
-
116
- /** Pre-parsed message body cached as parsed.json.gz to skip mailparser on warm reads */
117
- export interface ParsedBody {
118
- text: string | null;
119
- html: string | null;
120
- attachments: ParsedAttachmentMeta[];
121
- }
122
-
123
- /** Parameters for storing a pre-parsed message body */
124
- export interface StoreParsedBodyParams {
125
- accountConfigId: string;
126
- accountId: string;
127
- messageId: string;
128
- parsed: ParsedBody;
129
- }
130
-
131
- export interface StorageService {
132
- /** Store a message body (raw RFC822 content) */
133
- storeMessageBody(params: StoreMessageBodyParams): Promise<StorageReference>;
134
-
135
- /**
136
- * Store a message body from a readable stream, never buffering the whole
137
- * body. Use this on the sync hot path so a ranged FETCH streams straight to
138
- * storage.
139
- */
140
- storeMessageBodyStream(
141
- params: StoreMessageBodyStreamParams,
142
- ): Promise<StorageReference>;
143
-
144
- /** Store a body part (attachment, inline content) */
145
- storeBodyPart(params: StoreBodyPartParams): Promise<StorageReference>;
146
-
147
- /**
148
- * Check whether a body-part object already exists, keyed exactly as
149
- * `storeBodyPart` writes it. Used by the lazy per-part generation path to
150
- * skip leaves already materialized on a prior read, so regeneration is
151
- * idempotent and re-reads stay cheap.
152
- */
153
- bodyPartExists(
154
- accountConfigId: string,
155
- accountId: string,
156
- messageId: string,
157
- partPath: string,
158
- ): Promise<boolean>;
159
-
160
- /**
161
- * Retrieve a body-part's content (attachment or inline leaf) by
162
- * account/message id and IMAP section path; returns null on NoSuchKey.
163
- */
164
- retrieveBodyPart(
165
- accountConfigId: string,
166
- accountId: string,
167
- messageId: string,
168
- partPath: string,
169
- ): Promise<Buffer | null>;
170
-
171
- /**
172
- * Store a file attached to a draft outbox message, uncompressed: the size on
173
- * the backend is then the decoded size the per-message cap is expressed in,
174
- * and `listOutboxAttachments` can total a draft without opening anything.
175
- */
176
- storeOutboxAttachment(
177
- params: StoreOutboxAttachmentParams,
178
- ): Promise<StorageReference>;
179
-
180
- /**
181
- * Every object stored against a draft, paged to the end. Only the sweep reads
182
- * this, and a sweep that stops early leaves exactly the orphan it was called
183
- * to collect — so there is no limit to get wrong.
184
- */
185
- listOutboxAttachments(
186
- accountConfigId: string,
187
- accountId: string,
188
- outboxMessageId: string,
189
- ): Promise<OutboxAttachmentListItem[]>;
190
-
191
- /**
192
- * Remove every file and reservation stored against a draft. Unlike the read
193
- * above this takes no limit and pages to the end: a sweep that stops early
194
- * leaves exactly the orphan it was called to prevent.
195
- */
196
- deleteOutboxAttachments(
197
- accountConfigId: string,
198
- accountId: string,
199
- outboxMessageId: string,
200
- ): Promise<void>;
201
-
202
- /**
203
- * Every draft under an account that has attachment objects in storage,
204
- * including drafts whose row is long gone. The sweep needs the prefixes that
205
- * exist, not the rows that exist — a discarded draft is invisible to the
206
- * database and is exactly the case worth collecting.
207
- */
208
- listOutboxDraftsWithAttachments(
209
- accountConfigId: string,
210
- accountId: string,
211
- ): Promise<string[]>;
212
-
213
- /** Remove one attachment object. */
214
- deleteOutboxAttachment(
215
- accountConfigId: string,
216
- accountId: string,
217
- outboxMessageId: string,
218
- outboxAttachmentId: string,
219
- ): Promise<void>;
220
-
221
- /**
222
- * The size storage actually holds for an attachment, or null when nothing
223
- * was uploaded. This is the only number a completion may believe — the
224
- * client's word for it is not evidence, and on a deployment where the bytes
225
- * went straight to block storage it is the only reading available.
226
- */
227
- statOutboxAttachment(
228
- accountConfigId: string,
229
- accountId: string,
230
- outboxMessageId: string,
231
- outboxAttachmentId: string,
232
- ): Promise<{ sizeBytes: number } | null>;
233
-
234
- /**
235
- * The bytes of one attachment, for building the MIME part it goes out as.
236
- * Null when nothing is stored under the key.
237
- */
238
- retrieveOutboxAttachment(
239
- accountConfigId: string,
240
- accountId: string,
241
- outboxMessageId: string,
242
- outboxAttachmentId: string,
243
- ): Promise<Buffer | null>;
244
-
245
- /**
246
- * Mint somewhere to PUT one file. The backend decides what that is — block
247
- * storage direct, or this deployment's upload route — and the caller never
248
- * branches on which it got. Whatever it returns must bind the size: an
249
- * upload that carries more than was reserved has to fail at the thing
250
- * receiving it, not afterwards.
251
- */
252
- createOutboxAttachmentUploadUrl(
253
- params: CreateOutboxAttachmentUploadUrlParams,
254
- ): Promise<OutboxAttachmentUploadTarget>;
255
-
256
- /** Store deduplicated content (content-addressable, for attachments) */
257
- storeDeduplicated(params: StoreDeduplicatedParams): Promise<StorageReference>;
258
-
259
- /** Store a pre-parsed message body as gzipped JSON (parsed-body cache) */
260
- storeParsedBody(params: StoreParsedBodyParams): Promise<StorageReference>;
261
-
262
- /** Retrieve a pre-parsed message body by account/message id; returns null on NoSuchKey */
263
- retrieveParsedBody(
264
- accountConfigId: string,
265
- accountId: string,
266
- messageId: string,
267
- ): Promise<ParsedBody | null>;
268
-
269
- /** Retrieve a raw message body (RFC822 .eml) by account/message id; returns null on NoSuchKey */
270
- retrieveMessageBody(
271
- accountConfigId: string,
272
- accountId: string,
273
- messageId: string,
274
- ): Promise<Buffer | null>;
275
-
276
- /**
277
- * Retrieve a raw message body as a readable stream of decompressed .eml
278
- * bytes; returns null on NoSuchKey. Use on the export path so a whole
279
- * mailbox is never buffered in memory.
280
- */
281
- retrieveMessageBodyStream(
282
- accountConfigId: string,
283
- accountId: string,
284
- messageId: string,
285
- ): Promise<Readable | null>;
286
-
287
- /** Retrieve content by URI */
288
- retrieve(uri: string): Promise<Buffer>;
289
-
290
- /** Check if content exists */
291
- exists(uri: string): Promise<boolean>;
292
-
293
- /** Delete content by URI */
294
- delete(uri: string): Promise<void>;
295
-
296
- /**
297
- * Stream a finished export archive (already-compressed ZIP) to the export
298
- * key for the given config + request, uncompressed at rest. The body is
299
- * streamed via a multipart upload and never buffered whole. Returns the raw
300
- * storage key, which `getPresignedDownloadUrl` can then sign.
301
- */
302
- storeExportArchiveStream(
303
- accountConfigId: string,
304
- exportRequestId: string,
305
- body: Readable,
306
- ): Promise<string>;
307
-
308
- /**
309
- * Generate a presigned URL that grants temporary GET access to a raw S3 key.
310
- * Use for export archives — the key must already exist in the bucket.
311
- * Not supported on filesystem backends; throws if called there.
312
- */
313
- getPresignedDownloadUrl(
314
- key: string,
315
- expiresInSeconds: number,
316
- ): Promise<string>;
317
- }
318
-
319
- // Path builders - centralized path formatting per RFC 011 + #224.
320
- // The outer segment is `accountConfigId` (Cognito-derived tenant scope) so
321
- // the edge can verify cross-tenant isolation at the URL prefix without
322
- // loading any database record. The inner `accountId` distinguishes between
323
- // multiple IMAP-account records owned by the same tenant.
324
- export const buildMessageBodyKey = (
325
- accountConfigId: string,
326
- accountId: string,
327
- messageId: string,
328
- ): string =>
329
- `accounts/${accountConfigId}/${accountId}/messages/${messageId}/body.eml`;
330
-
331
- export const buildParsedBodyKey = (
332
- accountConfigId: string,
333
- accountId: string,
334
- messageId: string,
335
- ): string =>
336
- `accounts/${accountConfigId}/${accountId}/messages/${messageId}/parsed.json.gz`;
337
-
338
- export const buildBodyPartKey = (
339
- accountConfigId: string,
340
- accountId: string,
341
- messageId: string,
342
- partPath: string,
343
- ): string =>
344
- `accounts/${accountConfigId}/${accountId}/messages/${messageId}/parts/${partPath}`;
345
-
346
- export const buildOutboxAttachmentPrefix = (
347
- accountConfigId: string,
348
- accountId: string,
349
- outboxMessageId: string,
350
- ): string =>
351
- `accounts/${accountConfigId}/${accountId}/outbox/${outboxMessageId}/attachments/`;
352
-
353
- export const buildOutboxAttachmentKey = (
354
- accountConfigId: string,
355
- accountId: string,
356
- outboxMessageId: string,
357
- outboxAttachmentId: string,
358
- ): string =>
359
- `${buildOutboxAttachmentPrefix(accountConfigId, accountId, outboxMessageId)}${outboxAttachmentId}`;
360
-
361
- // Every segment is a generated id, so the shape is closed rather than
362
- // "anything without a slash": `..` matches `[^/]+` and the write side joins
363
- // this key onto a filesystem root. The read side has `resolveContentPath` for
364
- // the same reason (#310 review P1) — a signature should not be the only thing
365
- // standing between a URL and the storage root.
366
- const OUTBOX_ATTACHMENT_KEY =
367
- /^accounts\/([A-Za-z0-9_-]+)\/([A-Za-z0-9_-]+)\/outbox\/([A-Za-z0-9_-]+)\/attachments\/([A-Za-z0-9_-]+)$/;
368
- export interface ParsedOutboxAttachmentKey {
369
- accountConfigId: string;
370
- accountId: string;
371
- outboxMessageId: string;
372
- outboxAttachmentId: string;
373
- }
374
-
375
- /**
376
- * Read the ids back out of an attachment key — the inverse of
377
- * `buildOutboxAttachmentKey`, for the upload route, which is handed a path and
378
- * has to work out what it addresses. Returns null on anything else, including a
379
- * reservation key: bytes are never written to one.
380
- */
381
- export const parseOutboxAttachmentKey = (
382
- storageKey: string,
383
- ): ParsedOutboxAttachmentKey | null => {
384
- const match = storageKey.match(OUTBOX_ATTACHMENT_KEY);
385
- if (!match) return null;
386
- return {
387
- accountConfigId: match[1],
388
- accountId: match[2],
389
- outboxMessageId: match[3],
390
- outboxAttachmentId: match[4],
391
- };
392
- };
393
-
394
- export const buildDeduplicatedKey = (
395
- accountConfigId: string,
396
- accountId: string,
397
- checksumSha256: string,
398
- ): string =>
399
- `accounts/${accountConfigId}/${accountId}/dedup/${checksumSha256.slice(0, 2)}/${checksumSha256}`;
400
-
401
- export interface ParsedContentStorageKey {
402
- accountConfigId: string;
403
- accountId: string;
404
- messageId: string;
405
- }
406
-
407
- /**
408
- * Parse the account/message ids out of a `/content/*` storage key such as
409
- * `accounts/{accountConfigId}/{accountId}/messages/{messageId}/parts/1.2`
410
- * (the inverse of `buildMessageBodyKey`/`buildParsedBodyKey`/`buildBodyPartKey`
411
- * above). Returns null when the shape doesn't match.
412
- */
413
- export const parseContentStorageKey = (
414
- storageKey: string,
415
- ): ParsedContentStorageKey | null => {
416
- const match = storageKey.match(
417
- /^accounts\/([^/]+)\/([^/]+)\/messages\/([^/]+)\//,
418
- );
419
- if (!match) return null;
420
- return {
421
- accountConfigId: match[1],
422
- accountId: match[2],
423
- messageId: match[3],
424
- };
425
- };
426
-
427
- export const computeChecksum = (content: Buffer): string =>
428
- createHash("sha256").update(content).digest("hex");
429
-
430
- export const buildExportArchiveKey = (
431
- accountConfigId: string,
432
- exportRequestId: string,
433
- ): string => `exports/${accountConfigId}/${exportRequestId}/export.zip`;
434
-
435
- export const isStorageNotFoundError = (error: unknown): boolean => {
436
- if (typeof error !== "object" || error === null) return false;
437
- const obj = error as Record<string, unknown>;
438
- if (obj.name === "NoSuchKey") return true;
439
- if (obj.Code === "NoSuchKey") return true;
440
- if (obj.code === "ENOENT") return true;
441
- return false;
442
- };
443
-
444
- export const createMockStorageService = (): StorageService => {
445
- const storage = new Map<string, Buffer>();
446
-
447
- const storeInternal = (key: string, content: Buffer): StorageReference => {
448
- const checksumSha256 = computeChecksum(content);
449
- const uri = `mock://${key}`;
450
- storage.set(uri, content);
451
- return {
452
- uri,
453
- storageType: StorageType.Filesystem,
454
- storageLocation: "mock",
455
- storageKey: key,
456
- sizeBytes: content.length,
457
- checksumSha256,
458
- contentEncoding: ContentEncoding.None,
459
- };
460
- };
461
-
462
- const storeMessageBody: StorageService["storeMessageBody"] = async (
463
- params,
464
- ) => {
465
- const { accountConfigId, accountId, messageId, content } = params;
466
- return storeInternal(
467
- buildMessageBodyKey(accountConfigId, accountId, messageId),
468
- content,
469
- );
470
- };
471
-
472
- const storeMessageBodyStream: StorageService["storeMessageBodyStream"] =
473
- async (params) => {
474
- const { accountConfigId, accountId, messageId, content } = params;
475
- const chunks: Buffer[] = [];
476
- for await (const chunk of content) {
477
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
478
- }
479
- return storeInternal(
480
- buildMessageBodyKey(accountConfigId, accountId, messageId),
481
- Buffer.concat(chunks),
482
- );
483
- };
484
-
485
- const storeBodyPart: StorageService["storeBodyPart"] = async (params) => {
486
- const { accountConfigId, accountId, messageId, partPath, content } = params;
487
- return storeInternal(
488
- buildBodyPartKey(accountConfigId, accountId, messageId, partPath),
489
- content,
490
- );
491
- };
492
-
493
- const storeOutboxAttachment: StorageService["storeOutboxAttachment"] = async (
494
- params,
495
- ) => {
496
- const {
497
- accountConfigId,
498
- accountId,
499
- outboxMessageId,
500
- outboxAttachmentId,
501
- content,
502
- } = params;
503
- return storeInternal(
504
- buildOutboxAttachmentKey(
505
- accountConfigId,
506
- accountId,
507
- outboxMessageId,
508
- outboxAttachmentId,
509
- ),
510
- content,
511
- );
512
- };
513
-
514
- const listOutboxAttachments: StorageService["listOutboxAttachments"] = async (
515
- accountConfigId,
516
- accountId,
517
- outboxMessageId,
518
- ) => {
519
- const prefix = `mock://${buildOutboxAttachmentPrefix(accountConfigId, accountId, outboxMessageId)}`;
520
- const items: OutboxAttachmentListItem[] = [];
521
- for (const [uri, content] of storage.entries()) {
522
- if (!uri.startsWith(prefix)) continue;
523
- items.push({
524
- outboxAttachmentId: uri.slice(prefix.length),
525
- key: uri.slice("mock://".length),
526
- sizeBytes: content.length,
527
- });
528
- }
529
- return items;
530
- };
531
-
532
- const listOutboxDraftsWithAttachments: StorageService["listOutboxDraftsWithAttachments"] =
533
- async (accountConfigId, accountId) => {
534
- const root = `mock://accounts/${accountConfigId}/${accountId}/outbox/`;
535
- const drafts = new Set<string>();
536
- for (const uri of storage.keys()) {
537
- if (!uri.startsWith(root)) continue;
538
- const rest = uri.slice(root.length);
539
- const slash = rest.indexOf("/");
540
- if (slash > 0) drafts.add(rest.slice(0, slash));
541
- }
542
- return [...drafts];
543
- };
544
-
545
- const deleteOutboxAttachment: StorageService["deleteOutboxAttachment"] =
546
- async (accountConfigId, accountId, outboxMessageId, outboxAttachmentId) => {
547
- storage.delete(
548
- `mock://${buildOutboxAttachmentKey(accountConfigId, accountId, outboxMessageId, outboxAttachmentId)}`,
549
- );
550
- };
551
-
552
- const statOutboxAttachment: StorageService["statOutboxAttachment"] = async (
553
- accountConfigId,
554
- accountId,
555
- outboxMessageId,
556
- outboxAttachmentId,
557
- ) => {
558
- const content = storage.get(
559
- `mock://${buildOutboxAttachmentKey(accountConfigId, accountId, outboxMessageId, outboxAttachmentId)}`,
560
- );
561
- return content ? { sizeBytes: content.length } : null;
562
- };
563
-
564
- const retrieveOutboxAttachment: StorageService["retrieveOutboxAttachment"] =
565
- async (accountConfigId, accountId, outboxMessageId, outboxAttachmentId) =>
566
- storage.get(
567
- `mock://${buildOutboxAttachmentKey(accountConfigId, accountId, outboxMessageId, outboxAttachmentId)}`,
568
- ) ?? null;
569
-
570
- const createOutboxAttachmentUploadUrl: StorageService["createOutboxAttachmentUploadUrl"] =
571
- async (params) => ({
572
- uploadUrl: `mock://upload/${buildOutboxAttachmentKey(params.accountConfigId, params.accountId, params.outboxMessageId, params.outboxAttachmentId)}?max=${params.sizeBytes}&exp=${params.expiresAt}`,
573
- });
574
-
575
- const deleteOutboxAttachments: StorageService["deleteOutboxAttachments"] =
576
- async (accountConfigId, accountId, outboxMessageId) => {
577
- const prefix = `mock://${buildOutboxAttachmentPrefix(accountConfigId, accountId, outboxMessageId)}`;
578
- for (const uri of [...storage.keys()]) {
579
- if (uri.startsWith(prefix)) storage.delete(uri);
580
- }
581
- };
582
-
583
- const storeDeduplicated: StorageService["storeDeduplicated"] = async (
584
- params,
585
- ) => {
586
- const { accountConfigId, accountId, content } = params;
587
- const checksumSha256 = computeChecksum(content);
588
- return storeInternal(
589
- buildDeduplicatedKey(accountConfigId, accountId, checksumSha256),
590
- content,
591
- );
592
- };
593
-
594
- const storeParsedBody: StorageService["storeParsedBody"] = async (params) => {
595
- const { accountConfigId, accountId, messageId, parsed } = params;
596
- const content = Buffer.from(JSON.stringify(parsed), "utf8");
597
- return storeInternal(
598
- buildParsedBodyKey(accountConfigId, accountId, messageId),
599
- content,
600
- );
601
- };
602
-
603
- const retrieveParsedBody: StorageService["retrieveParsedBody"] = async (
604
- accountConfigId,
605
- accountId,
606
- messageId,
607
- ) => {
608
- const uri = `mock://${buildParsedBodyKey(accountConfigId, accountId, messageId)}`;
609
- const content = storage.get(uri);
610
- if (!content) return null;
611
- return JSON.parse(content.toString("utf8")) as ParsedBody;
612
- };
613
-
614
- const retrieveBodyPart: StorageService["retrieveBodyPart"] = async (
615
- accountConfigId,
616
- accountId,
617
- messageId,
618
- partPath,
619
- ) => {
620
- const uri = `mock://${buildBodyPartKey(accountConfigId, accountId, messageId, partPath)}`;
621
- return storage.get(uri) ?? null;
622
- };
623
-
624
- const retrieveMessageBody: StorageService["retrieveMessageBody"] = async (
625
- accountConfigId,
626
- accountId,
627
- messageId,
628
- ) => {
629
- const uri = `mock://${buildMessageBodyKey(accountConfigId, accountId, messageId)}`;
630
- return storage.get(uri) ?? null;
631
- };
632
-
633
- const retrieveMessageBodyStream: StorageService["retrieveMessageBodyStream"] =
634
- async (accountConfigId, accountId, messageId) => {
635
- const uri = `mock://${buildMessageBodyKey(accountConfigId, accountId, messageId)}`;
636
- const content = storage.get(uri);
637
- if (!content) return null;
638
- return Readable.from(content);
639
- };
640
-
641
- const bodyPartExists: StorageService["bodyPartExists"] = async (
642
- accountConfigId,
643
- accountId,
644
- messageId,
645
- partPath,
646
- ) => {
647
- const uri = `mock://${buildBodyPartKey(accountConfigId, accountId, messageId, partPath)}`;
648
- return storage.has(uri);
649
- };
650
-
651
- return {
652
- storeMessageBody,
653
- storeMessageBodyStream,
654
- storeBodyPart,
655
- bodyPartExists,
656
- retrieveBodyPart,
657
- storeOutboxAttachment,
658
- listOutboxAttachments,
659
- listOutboxDraftsWithAttachments,
660
- deleteOutboxAttachments,
661
- deleteOutboxAttachment,
662
- statOutboxAttachment,
663
- retrieveOutboxAttachment,
664
- createOutboxAttachmentUploadUrl,
665
- storeDeduplicated,
666
- storeParsedBody,
667
- retrieveParsedBody,
668
- retrieveMessageBody,
669
- retrieveMessageBodyStream,
670
- retrieve: async (uri) => {
671
- const content = storage.get(uri);
672
- if (!content) {
673
- throw Object.assign(new Error(`Not found: ${uri}`), {
674
- name: "NoSuchKey",
675
- });
676
- }
677
- return content;
678
- },
679
- exists: async (uri) => storage.has(uri),
680
- delete: async (uri) => {
681
- storage.delete(uri);
682
- },
683
- storeExportArchiveStream: async (
684
- accountConfigId,
685
- exportRequestId,
686
- body,
687
- ) => {
688
- const key = buildExportArchiveKey(accountConfigId, exportRequestId);
689
- const chunks: Buffer[] = [];
690
- for await (const chunk of body) {
691
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
692
- }
693
- storage.set(`mock://${key}`, Buffer.concat(chunks));
694
- return key;
695
- },
696
- getPresignedDownloadUrl: async (key: string, _expiresInSeconds: number) =>
697
- `mock://presigned/${key}`,
698
- };
699
- };