@remit/storage-service 0.0.1

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,524 @@
1
+ import { createHash } from "node:crypto";
2
+ import { PassThrough, type Readable } from "node:stream";
3
+ import { pipeline } from "node:stream/promises";
4
+ import { createGunzip, createGzip, gunzipSync, gzipSync } from "node:zlib";
5
+ import {
6
+ DeleteObjectCommand,
7
+ GetObjectCommand,
8
+ HeadObjectCommand,
9
+ ListObjectsV2Command,
10
+ PutObjectCommand,
11
+ type S3Client,
12
+ } from "@aws-sdk/client-s3";
13
+ import { Upload } from "@aws-sdk/lib-storage";
14
+ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
15
+ import { ContentEncoding, StorageType } from "@remit/domain-enums";
16
+ import type {
17
+ ExtractedTextListItem,
18
+ ParsedBody,
19
+ StorageReference,
20
+ StorageService,
21
+ } from "../storage.js";
22
+ import {
23
+ buildBodyPartKey,
24
+ buildDeduplicatedKey,
25
+ buildExportArchiveKey,
26
+ buildExtractedPrefix,
27
+ buildExtractedSkippedKey,
28
+ buildExtractedTextKey,
29
+ buildMessageBodyKey,
30
+ buildParsedBodyKey,
31
+ computeChecksum,
32
+ isStorageNotFoundError,
33
+ } from "../storage.js";
34
+ import { parseStorageUri } from "../uri.js";
35
+
36
+ interface StoreParams {
37
+ key: string;
38
+ content: Buffer;
39
+ contentType?: string;
40
+ compress?: boolean;
41
+ }
42
+
43
+ export const createS3StorageService = (
44
+ client: S3Client,
45
+ bucketName: string,
46
+ ): StorageService => {
47
+ const storeInternal = async (
48
+ params: StoreParams,
49
+ ): Promise<StorageReference> => {
50
+ const { key, content, contentType, compress = true } = params;
51
+ const contentChecksumSha256 = computeChecksum(content);
52
+ const contentEncoding = compress
53
+ ? ContentEncoding.Gzip
54
+ : ContentEncoding.None;
55
+ const body = compress ? gzipSync(content) : content;
56
+
57
+ await client.send(
58
+ new PutObjectCommand({
59
+ Bucket: bucketName,
60
+ Key: key,
61
+ Body: body,
62
+ ContentType: contentType,
63
+ ContentEncoding: compress ? "gzip" : undefined,
64
+ }),
65
+ );
66
+
67
+ return {
68
+ uri: `s3://${bucketName}/${key}`,
69
+ storageType: StorageType.S3,
70
+ storageLocation: bucketName,
71
+ storageKey: key,
72
+ sizeBytes: body.length,
73
+ checksumSha256: contentChecksumSha256,
74
+ contentEncoding,
75
+ };
76
+ };
77
+
78
+ const storeMessageBody: StorageService["storeMessageBody"] = (params) => {
79
+ const { accountConfigId, accountId, messageId, content } = params;
80
+ return storeInternal({
81
+ key: buildMessageBodyKey(accountConfigId, accountId, messageId),
82
+ content,
83
+ contentType: "message/rfc822",
84
+ });
85
+ };
86
+
87
+ const storeMessageBodyStream: StorageService["storeMessageBodyStream"] =
88
+ async (params) => {
89
+ const { accountConfigId, accountId, messageId, content } = params;
90
+ const key = buildMessageBodyKey(accountConfigId, accountId, messageId);
91
+
92
+ // Hash the logical (pre-gzip) bytes as they flow, gzip them, and feed
93
+ // the gzipped stream to a multipart Upload — the whole body is never
94
+ // held in memory. `Upload` buffers only one part at a time.
95
+ const hash = createHash("sha256");
96
+ const hashTap = new PassThrough();
97
+ hashTap.on("data", (chunk: Buffer) => hash.update(chunk));
98
+
99
+ const gzip = createGzip();
100
+ const uploadBody = new PassThrough();
101
+
102
+ let storedBytes = 0;
103
+ uploadBody.on("data", (chunk: Buffer) => {
104
+ storedBytes += chunk.length;
105
+ });
106
+
107
+ const upload = new Upload({
108
+ client,
109
+ params: {
110
+ Bucket: bucketName,
111
+ Key: key,
112
+ Body: uploadBody,
113
+ ContentType: "message/rfc822",
114
+ ContentEncoding: "gzip",
115
+ },
116
+ });
117
+
118
+ const pumped = pipeline(content, hashTap, gzip, uploadBody);
119
+ await Promise.all([upload.done(), pumped]).catch(async (error) => {
120
+ // Abort the multipart upload so a failed pump doesn't leak parts.
121
+ await upload.abort().catch(() => {});
122
+ throw error;
123
+ });
124
+
125
+ return {
126
+ uri: `s3://${bucketName}/${key}`,
127
+ storageType: StorageType.S3,
128
+ storageLocation: bucketName,
129
+ storageKey: key,
130
+ sizeBytes: storedBytes,
131
+ checksumSha256: hash.digest("hex"),
132
+ contentEncoding: ContentEncoding.Gzip,
133
+ };
134
+ };
135
+
136
+ const storeBodyPart: StorageService["storeBodyPart"] = (params) => {
137
+ const {
138
+ accountConfigId,
139
+ accountId,
140
+ messageId,
141
+ partPath,
142
+ content,
143
+ contentType,
144
+ } = params;
145
+ return storeInternal({
146
+ key: buildBodyPartKey(accountConfigId, accountId, messageId, partPath),
147
+ content,
148
+ contentType,
149
+ });
150
+ };
151
+
152
+ const bodyPartExists: StorageService["bodyPartExists"] = (
153
+ accountConfigId,
154
+ accountId,
155
+ messageId,
156
+ partPath,
157
+ ) => {
158
+ const key = buildBodyPartKey(
159
+ accountConfigId,
160
+ accountId,
161
+ messageId,
162
+ partPath,
163
+ );
164
+ return client
165
+ .send(new HeadObjectCommand({ Bucket: bucketName, Key: key }))
166
+ .then(() => true)
167
+ .catch(() => false);
168
+ };
169
+
170
+ const retrieveBodyPart: StorageService["retrieveBodyPart"] = async (
171
+ accountConfigId,
172
+ accountId,
173
+ messageId,
174
+ partPath,
175
+ ) => {
176
+ const key = buildBodyPartKey(
177
+ accountConfigId,
178
+ accountId,
179
+ messageId,
180
+ partPath,
181
+ );
182
+
183
+ const response = await client
184
+ .send(new GetObjectCommand({ Bucket: bucketName, Key: key }))
185
+ .catch((error: unknown) => {
186
+ if (isStorageNotFoundError(error)) return null;
187
+ throw error;
188
+ });
189
+
190
+ if (!response) return null;
191
+ if (!response.Body) {
192
+ throw new Error(`Empty response body for body part: ${key}`);
193
+ }
194
+
195
+ const body = await response.Body.transformToByteArray();
196
+ const buffer = Buffer.from(body);
197
+ return response.ContentEncoding === "gzip" ? gunzipSync(buffer) : buffer;
198
+ };
199
+
200
+ const storeExtractedText: StorageService["storeExtractedText"] = (params) => {
201
+ const { accountConfigId, accountId, messageId, partPath, text } = params;
202
+ return storeInternal({
203
+ key: buildExtractedTextKey(
204
+ accountConfigId,
205
+ accountId,
206
+ messageId,
207
+ partPath,
208
+ ),
209
+ content: Buffer.from(text, "utf8"),
210
+ contentType: "text/plain; charset=utf-8",
211
+ });
212
+ };
213
+
214
+ const storeExtractedSkipped: StorageService["storeExtractedSkipped"] = (
215
+ params,
216
+ ) => {
217
+ const { accountConfigId, accountId, messageId, partPath, marker } = params;
218
+ return storeInternal({
219
+ key: buildExtractedSkippedKey(
220
+ accountConfigId,
221
+ accountId,
222
+ messageId,
223
+ partPath,
224
+ ),
225
+ content: Buffer.from(JSON.stringify(marker), "utf8"),
226
+ contentType: "application/json",
227
+ compress: false,
228
+ });
229
+ };
230
+
231
+ const extractedResultExists: StorageService["extractedResultExists"] = async (
232
+ accountConfigId,
233
+ accountId,
234
+ messageId,
235
+ partPath,
236
+ ) => {
237
+ const textKey = buildExtractedTextKey(
238
+ accountConfigId,
239
+ accountId,
240
+ messageId,
241
+ partPath,
242
+ );
243
+ const skippedKey = buildExtractedSkippedKey(
244
+ accountConfigId,
245
+ accountId,
246
+ messageId,
247
+ partPath,
248
+ );
249
+
250
+ const headExists = (key: string): Promise<boolean> =>
251
+ client
252
+ .send(new HeadObjectCommand({ Bucket: bucketName, Key: key }))
253
+ .then(() => true)
254
+ .catch(() => false);
255
+
256
+ const [textExists, skippedExists] = await Promise.all([
257
+ headExists(textKey),
258
+ headExists(skippedKey),
259
+ ]);
260
+ return textExists || skippedExists;
261
+ };
262
+
263
+ const retrieveExtractedText: StorageService["retrieveExtractedText"] = async (
264
+ accountConfigId,
265
+ accountId,
266
+ messageId,
267
+ partPath,
268
+ ) => {
269
+ const key = buildExtractedTextKey(
270
+ accountConfigId,
271
+ accountId,
272
+ messageId,
273
+ partPath,
274
+ );
275
+
276
+ const response = await client
277
+ .send(new GetObjectCommand({ Bucket: bucketName, Key: key }))
278
+ .catch((error: unknown) => {
279
+ if (isStorageNotFoundError(error)) return null;
280
+ throw error;
281
+ });
282
+
283
+ if (!response) return null;
284
+ if (!response.Body) {
285
+ throw new Error(`Empty response body for extracted text: ${key}`);
286
+ }
287
+
288
+ const body = await response.Body.transformToByteArray();
289
+ const buffer = Buffer.from(body);
290
+ const decoded =
291
+ response.ContentEncoding === "gzip" ? gunzipSync(buffer) : buffer;
292
+ return decoded.toString("utf8");
293
+ };
294
+
295
+ const listExtractedTexts: StorageService["listExtractedTexts"] = async (
296
+ accountConfigId,
297
+ accountId,
298
+ messageId,
299
+ ) => {
300
+ const prefix = buildExtractedPrefix(accountConfigId, accountId, messageId);
301
+ const suffix = ".txt.gz";
302
+ const items: ExtractedTextListItem[] = [];
303
+ let continuationToken: string | undefined;
304
+
305
+ do {
306
+ const response = await client.send(
307
+ new ListObjectsV2Command({
308
+ Bucket: bucketName,
309
+ Prefix: prefix,
310
+ ContinuationToken: continuationToken,
311
+ }),
312
+ );
313
+ for (const object of response.Contents ?? []) {
314
+ if (!object.Key || !object.Key.endsWith(suffix)) continue;
315
+ items.push({
316
+ partPath: object.Key.slice(prefix.length, -suffix.length),
317
+ key: object.Key,
318
+ });
319
+ }
320
+ continuationToken = response.IsTruncated
321
+ ? response.NextContinuationToken
322
+ : undefined;
323
+ } while (continuationToken);
324
+
325
+ return items;
326
+ };
327
+
328
+ const storeDeduplicated: StorageService["storeDeduplicated"] = (params) => {
329
+ const { accountConfigId, accountId, content, contentType } = params;
330
+ const checksumSha256 = computeChecksum(content);
331
+ return storeInternal({
332
+ key: buildDeduplicatedKey(accountConfigId, accountId, checksumSha256),
333
+ content,
334
+ contentType,
335
+ });
336
+ };
337
+
338
+ const storeParsedBody: StorageService["storeParsedBody"] = (params) => {
339
+ const { accountConfigId, accountId, messageId, parsed } = params;
340
+ const content = Buffer.from(JSON.stringify(parsed), "utf8");
341
+ return storeInternal({
342
+ key: buildParsedBodyKey(accountConfigId, accountId, messageId),
343
+ content,
344
+ contentType: "application/json",
345
+ });
346
+ };
347
+
348
+ const retrieveParsedBody: StorageService["retrieveParsedBody"] = async (
349
+ accountConfigId,
350
+ accountId,
351
+ messageId,
352
+ ) => {
353
+ const key = buildParsedBodyKey(accountConfigId, accountId, messageId);
354
+
355
+ const response = await client
356
+ .send(new GetObjectCommand({ Bucket: bucketName, Key: key }))
357
+ .catch((error: unknown) => {
358
+ if (isStorageNotFoundError(error)) return null;
359
+ throw error;
360
+ });
361
+
362
+ if (!response) return null;
363
+ if (!response.Body) {
364
+ throw new Error(`Empty response body for parsed body: ${key}`);
365
+ }
366
+
367
+ const body = await response.Body.transformToByteArray();
368
+ const buffer = Buffer.from(body);
369
+ const decoded =
370
+ response.ContentEncoding === "gzip" ? gunzipSync(buffer) : buffer;
371
+ return JSON.parse(decoded.toString("utf8")) as ParsedBody;
372
+ };
373
+
374
+ const retrieve = async (uri: string): Promise<Buffer> => {
375
+ const { storageKey } = parseStorageUri(uri);
376
+
377
+ const response = await client.send(
378
+ new GetObjectCommand({
379
+ Bucket: bucketName,
380
+ Key: storageKey,
381
+ }),
382
+ );
383
+
384
+ if (!response.Body) {
385
+ throw new Error(`Empty response body for: ${uri}`);
386
+ }
387
+
388
+ const body = await response.Body.transformToByteArray();
389
+ const buffer = Buffer.from(body);
390
+
391
+ if (response.ContentEncoding === "gzip") {
392
+ return gunzipSync(buffer);
393
+ }
394
+
395
+ return buffer;
396
+ };
397
+
398
+ const retrieveMessageBody: StorageService["retrieveMessageBody"] = async (
399
+ accountConfigId,
400
+ accountId,
401
+ messageId,
402
+ ) => {
403
+ const key = buildMessageBodyKey(accountConfigId, accountId, messageId);
404
+
405
+ const response = await client
406
+ .send(new GetObjectCommand({ Bucket: bucketName, Key: key }))
407
+ .catch((error: unknown) => {
408
+ if (isStorageNotFoundError(error)) return null;
409
+ throw error;
410
+ });
411
+
412
+ if (!response) return null;
413
+ if (!response.Body) {
414
+ throw new Error(`Empty response body for message body: ${key}`);
415
+ }
416
+
417
+ const body = await response.Body.transformToByteArray();
418
+ const buffer = Buffer.from(body);
419
+ return response.ContentEncoding === "gzip" ? gunzipSync(buffer) : buffer;
420
+ };
421
+
422
+ const retrieveMessageBodyStream: StorageService["retrieveMessageBodyStream"] =
423
+ async (accountConfigId, accountId, messageId) => {
424
+ const key = buildMessageBodyKey(accountConfigId, accountId, messageId);
425
+
426
+ const response = await client
427
+ .send(new GetObjectCommand({ Bucket: bucketName, Key: key }))
428
+ .catch((error: unknown) => {
429
+ if (isStorageNotFoundError(error)) return null;
430
+ throw error;
431
+ });
432
+
433
+ if (!response) return null;
434
+ if (!response.Body) {
435
+ throw new Error(`Empty response body for message body: ${key}`);
436
+ }
437
+
438
+ const source = response.Body as Readable;
439
+ if (response.ContentEncoding === "gzip") {
440
+ return source.pipe(createGunzip());
441
+ }
442
+ return source;
443
+ };
444
+
445
+ const exists = async (uri: string): Promise<boolean> => {
446
+ const { storageKey } = parseStorageUri(uri);
447
+
448
+ return client
449
+ .send(
450
+ new HeadObjectCommand({
451
+ Bucket: bucketName,
452
+ Key: storageKey,
453
+ }),
454
+ )
455
+ .then(() => true)
456
+ .catch(() => false);
457
+ };
458
+
459
+ const del = async (uri: string): Promise<void> => {
460
+ const { storageKey } = parseStorageUri(uri);
461
+
462
+ await client.send(
463
+ new DeleteObjectCommand({
464
+ Bucket: bucketName,
465
+ Key: storageKey,
466
+ }),
467
+ );
468
+ };
469
+
470
+ const storeExportArchiveStream = async (
471
+ accountConfigId: string,
472
+ exportRequestId: string,
473
+ body: Readable,
474
+ ): Promise<string> => {
475
+ const key = buildExportArchiveKey(accountConfigId, exportRequestId);
476
+ const upload = new Upload({
477
+ client,
478
+ params: {
479
+ Bucket: bucketName,
480
+ Key: key,
481
+ Body: body,
482
+ ContentType: "application/zip",
483
+ },
484
+ });
485
+ await upload.done().catch(async (error) => {
486
+ await upload.abort().catch(() => {});
487
+ throw error;
488
+ });
489
+ return key;
490
+ };
491
+
492
+ const getPresignedDownloadUrl = (
493
+ key: string,
494
+ expiresInSeconds: number,
495
+ ): Promise<string> =>
496
+ getSignedUrl(
497
+ client,
498
+ new GetObjectCommand({ Bucket: bucketName, Key: key }),
499
+ { expiresIn: expiresInSeconds },
500
+ );
501
+
502
+ return {
503
+ storeMessageBody,
504
+ storeMessageBodyStream,
505
+ storeBodyPart,
506
+ bodyPartExists,
507
+ retrieveBodyPart,
508
+ storeDeduplicated,
509
+ storeParsedBody,
510
+ retrieveParsedBody,
511
+ storeExtractedText,
512
+ storeExtractedSkipped,
513
+ extractedResultExists,
514
+ retrieveExtractedText,
515
+ listExtractedTexts,
516
+ retrieveMessageBody,
517
+ retrieveMessageBodyStream,
518
+ retrieve,
519
+ exists,
520
+ delete: del,
521
+ storeExportArchiveStream,
522
+ getPresignedDownloadUrl,
523
+ };
524
+ };
@@ -0,0 +1 @@
1
+ export { createFilesystemStorageService } from "./backends/filesystem.js";
package/src/index.ts ADDED
@@ -0,0 +1,34 @@
1
+ export {
2
+ buildBodyPartKey,
3
+ buildDeduplicatedKey,
4
+ buildExportArchiveKey,
5
+ buildExtractedPrefix,
6
+ buildExtractedSkippedKey,
7
+ buildExtractedTextKey,
8
+ buildMessageBodyKey,
9
+ buildParsedBodyKey,
10
+ type ContentEncodingValue,
11
+ computeChecksum,
12
+ createMockStorageService,
13
+ type ExtractedTextListItem,
14
+ type ExtractedTextMarker,
15
+ isStorageNotFoundError,
16
+ type ParsedAttachmentMeta,
17
+ type ParsedBody,
18
+ type ParsedContentStorageKey,
19
+ parseContentStorageKey,
20
+ type StorageReference,
21
+ type StorageService,
22
+ type StorageTypeValue,
23
+ type StoreBodyPartParams,
24
+ type StoreDeduplicatedParams,
25
+ type StoreExtractedSkippedParams,
26
+ type StoreExtractedTextParams,
27
+ type StoreMessageBodyParams,
28
+ type StoreParsedBodyParams,
29
+ } from "./storage.js";
30
+ export {
31
+ buildStorageUri,
32
+ type ParsedStorageUri,
33
+ parseStorageUri,
34
+ } from "./uri.js";
package/src/s3.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { S3Client } from "@aws-sdk/client-s3";
2
+ import { createFilesystemStorageService } from "./backends/filesystem.js";
3
+ import { createS3StorageService } from "./backends/s3.js";
4
+ import type { StorageService } from "./storage.js";
5
+
6
+ export { createS3StorageService } from "./backends/s3.js";
7
+
8
+ export const createStorageService = (): StorageService => {
9
+ const bucketName = process.env.S3_BUCKET_NAME;
10
+
11
+ if (bucketName) {
12
+ const client = new S3Client({
13
+ endpoint: process.env.S3_ENDPOINT,
14
+ });
15
+ return createS3StorageService(client, bucketName);
16
+ }
17
+
18
+ const basePath = process.env.STORAGE_LOCAL_PATH ?? ".remit/storage";
19
+ return createFilesystemStorageService(basePath);
20
+ };