@forzalabs/remora 1.0.1 → 1.0.3

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 (34) hide show
  1. package/engines/scheduler/CronScheduler.js +2 -2
  2. package/engines/scheduler/QueueManager.js +2 -2
  3. package/package.json +1 -1
  4. package/settings.js +12 -0
  5. package/documentation/default_resources/schema.json +0 -36
  6. package/drivers/LocalDriver.js +0 -542
  7. package/drivers/S3Driver.js +0 -563
  8. package/drivers/S3SourceDriver.js +0 -132
  9. package/engines/DataframeManager.js +0 -55
  10. package/engines/ParseManager.js +0 -75
  11. package/engines/ProducerEngine.js +0 -160
  12. package/engines/UsageDataManager.js +0 -110
  13. package/engines/UsageManager.js +0 -61
  14. package/engines/Validator.js +0 -157
  15. package/engines/consumer/ConsumerEngine.js +0 -128
  16. package/engines/consumer/PostProcessor.js +0 -253
  17. package/engines/dataset/ParallelDataset.js +0 -184
  18. package/engines/dataset/TransformWorker.js +0 -2
  19. package/engines/dataset/definitions.js +0 -2
  20. package/engines/dataset/example-parallel-transform.js +0 -2
  21. package/engines/dataset/test-parallel.js +0 -2
  22. package/engines/deployment/DeploymentPlanner.js +0 -39
  23. package/engines/execution/ExecutionEnvironment.js +0 -209
  24. package/engines/execution/ExecutionPlanner.js +0 -131
  25. package/engines/file/FileCompiler.js +0 -29
  26. package/engines/file/FileContentBuilder.js +0 -34
  27. package/engines/schema/SchemaEngine.js +0 -33
  28. package/engines/sql/SQLBuilder.js +0 -96
  29. package/engines/sql/SQLCompiler.js +0 -141
  30. package/engines/sql/SQLUtils.js +0 -22
  31. package/workers/FilterWorker.js +0 -62
  32. package/workers/ProjectionWorker.js +0 -63
  33. package/workers/TransformWorker.js +0 -63
  34. package/workers/TsWorker.js +0 -14
@@ -1,563 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __asyncValues = (this && this.__asyncValues) || function (o) {
12
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
- var m = o[Symbol.asyncIterator], i;
14
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
- };
18
- var __importDefault = (this && this.__importDefault) || function (mod) {
19
- return (mod && mod.__esModule) ? mod : { "default": mod };
20
- };
21
- Object.defineProperty(exports, "__esModule", { value: true });
22
- exports.S3SourceDriver = exports.S3DestinationDriver = void 0;
23
- const client_s3_1 = require("@aws-sdk/client-s3");
24
- const Affirm_1 = __importDefault(require("../core/Affirm"));
25
- const SecretManager_1 = __importDefault(require("../engines/SecretManager"));
26
- const readline_1 = __importDefault(require("readline"));
27
- const path_1 = __importDefault(require("path"));
28
- const Algo_1 = __importDefault(require("../core/Algo"));
29
- const xlsx_1 = __importDefault(require("xlsx"));
30
- const XMLParser_1 = __importDefault(require("../engines/parsing/XMLParser")); // Added XMLParser import
31
- const Helper_1 = __importDefault(require("../helper/Helper"));
32
- const ParseHelper_1 = __importDefault(require("../engines/parsing/ParseHelper"));
33
- const FileExporter_1 = __importDefault(require("../engines/file/FileExporter"));
34
- const DriverHelper_1 = __importDefault(require("./DriverHelper"));
35
- const Logger_1 = __importDefault(require("../helper/Logger"));
36
- const Constants_1 = __importDefault(require("../Constants"));
37
- class S3DestinationDriver {
38
- constructor() {
39
- this.init = (source) => __awaiter(this, void 0, void 0, function* () {
40
- this._bucketName = source.authentication['bucket'];
41
- const sessionToken = SecretManager_1.default.replaceSecret(source.authentication['sessionToken']);
42
- const config = {
43
- region: source.authentication['region'],
44
- credentials: {
45
- accessKeyId: SecretManager_1.default.replaceSecret(source.authentication['accessKey']),
46
- secretAccessKey: SecretManager_1.default.replaceSecret(source.authentication['secretKey']),
47
- sessionToken: sessionToken ? sessionToken : undefined
48
- }
49
- };
50
- this._client = new client_s3_1.S3Client(config);
51
- // TODO: is there a way to test if the connection was successful? like a query or scan that I can do?
52
- return this;
53
- });
54
- this.uploadFile = (options) => __awaiter(this, void 0, void 0, function* () {
55
- (0, Affirm_1.default)(options, `Invalid upload options`);
56
- const { content, name } = options;
57
- const commandParams = {
58
- Bucket: this._bucketName,
59
- Key: name,
60
- Body: content
61
- };
62
- const command = new client_s3_1.PutObjectCommand(commandParams);
63
- const res = yield this._client.send(command);
64
- (0, Affirm_1.default)(res.$metadata.httpStatusCode === 200, `Failed to upload the file "${name}" to the bucket "${this._bucketName}": status code ${res.$metadata.httpStatusCode}`);
65
- return { res: true, key: name, bucket: this._bucketName };
66
- });
67
- this.uploadStream = (options) => __awaiter(this, void 0, void 0, function* () {
68
- (0, Affirm_1.default)(options, `Invalid upload options`);
69
- const { dataset, name, recordProjection } = options;
70
- (0, Affirm_1.default)(dataset, 'No streaming dataset');
71
- (0, Affirm_1.default)(name, 'No filename provided for upload stream');
72
- (0, Affirm_1.default)(recordProjection, 'No recordProjection for upload stream');
73
- try {
74
- // Create the multipart upload
75
- const createMultipartUploadRes = yield this._client.send(new client_s3_1.CreateMultipartUploadCommand({
76
- Bucket: this._bucketName,
77
- Key: name
78
- }));
79
- const uploadId = createMultipartUploadRes.UploadId;
80
- (0, Affirm_1.default)(uploadId, 'Failed to initiate multipart upload');
81
- const uploadedParts = [];
82
- let partNumber = 1;
83
- const MIN_PART_SIZE = 5 * 1024 * 1024; // 5MB
84
- let accumulatedBuffer = Buffer.alloc(0);
85
- const uploadPart = (buffer) => __awaiter(this, void 0, void 0, function* () {
86
- const uploadPartRes = yield this._client.send(new client_s3_1.UploadPartCommand({
87
- Bucket: this._bucketName,
88
- Key: name,
89
- UploadId: uploadId,
90
- PartNumber: partNumber,
91
- Body: buffer
92
- }));
93
- uploadedParts.push({
94
- PartNumber: partNumber,
95
- ETag: uploadPartRes.ETag
96
- });
97
- partNumber++;
98
- });
99
- yield dataset.streamBatches((batch) => __awaiter(this, void 0, void 0, function* () {
100
- const chunks = FileExporter_1.default.prepareBatch(batch, options);
101
- for (const chunk of chunks) {
102
- const chunkBuffer = Buffer.from(chunk);
103
- accumulatedBuffer = Buffer.concat([accumulatedBuffer, chunkBuffer]);
104
- // If accumulated buffer is at least 5MB, upload it as a part
105
- if (accumulatedBuffer.length >= MIN_PART_SIZE) {
106
- yield uploadPart(accumulatedBuffer);
107
- accumulatedBuffer = Buffer.alloc(0);
108
- }
109
- }
110
- }));
111
- // Upload any remaining data as the final part (even if smaller than 5MB)
112
- if (accumulatedBuffer.length > 0) {
113
- yield uploadPart(accumulatedBuffer);
114
- }
115
- // Complete the multipart upload
116
- const completeRes = yield this._client.send(new client_s3_1.CompleteMultipartUploadCommand({
117
- Bucket: this._bucketName,
118
- Key: options.name,
119
- UploadId: uploadId,
120
- MultipartUpload: {
121
- Parts: uploadedParts
122
- }
123
- }));
124
- (0, Affirm_1.default)(completeRes.$metadata.httpStatusCode === 200, `Failed to complete multipart upload for "${options.name}": status code ${completeRes.$metadata.httpStatusCode}`);
125
- return { res: true, key: options.name, bucket: this._bucketName };
126
- }
127
- catch (error) {
128
- // If anything fails, make sure to abort the multipart upload
129
- if (error.UploadId) {
130
- yield this._client.send(new client_s3_1.AbortMultipartUploadCommand({
131
- Bucket: this._bucketName,
132
- Key: options.name,
133
- UploadId: error.UploadId
134
- }));
135
- }
136
- throw error;
137
- }
138
- });
139
- this.copyFromS3 = (sourceBucket, sourceFileKey, destinationFileKey) => __awaiter(this, void 0, void 0, function* () {
140
- (0, Affirm_1.default)(this._client, 'S3 client not yet initialized, call "init()" first');
141
- (0, Affirm_1.default)(sourceBucket, 'Invalid source bucket');
142
- (0, Affirm_1.default)(sourceFileKey, 'Invalid source file key');
143
- (0, Affirm_1.default)(destinationFileKey, 'Invalid destination file key');
144
- yield this._client.send(new client_s3_1.CopyObjectCommand({
145
- CopySource: `${sourceBucket}/${sourceFileKey}`,
146
- Bucket: this._bucketName,
147
- Key: destinationFileKey
148
- }));
149
- });
150
- this.saveFile = (fileKey, content) => __awaiter(this, void 0, void 0, function* () {
151
- (0, Affirm_1.default)(this._client, 'S3 client not yet initialized, call "init()" first');
152
- (0, Affirm_1.default)(fileKey, 'Invalid file key');
153
- (0, Affirm_1.default)(content, 'Invalid content');
154
- yield this._client.send(new client_s3_1.PutObjectCommand({
155
- Bucket: this._bucketName,
156
- Key: fileKey,
157
- Body: content
158
- }));
159
- });
160
- }
161
- }
162
- exports.S3DestinationDriver = S3DestinationDriver;
163
- class S3SourceDriver {
164
- constructor() {
165
- this.init = (source) => __awaiter(this, void 0, void 0, function* () {
166
- this._bucketName = source.authentication['bucket'];
167
- const sessionToken = SecretManager_1.default.replaceSecret(source.authentication['sessionToken']);
168
- const config = {
169
- region: source.authentication['region'],
170
- credentials: {
171
- accessKeyId: SecretManager_1.default.replaceSecret(source.authentication['accessKey']),
172
- secretAccessKey: SecretManager_1.default.replaceSecret(source.authentication['secretKey']),
173
- sessionToken: sessionToken ? sessionToken : undefined
174
- }
175
- };
176
- this._client = new client_s3_1.S3Client(config);
177
- // TODO: is there a way to test if the connection was successful? like a query or scan that I can do?
178
- return this;
179
- });
180
- this.readAll = (request) => __awaiter(this, void 0, void 0, function* () {
181
- (0, Affirm_1.default)(this._client, 'S3 client not yet initialized, call "connect()" first');
182
- (0, Affirm_1.default)(request, `Invalid download request`);
183
- (0, Affirm_1.default)(request.fileKey, `Invalid file key for download request`);
184
- const { fileKey } = request;
185
- if (fileKey.includes('%')) {
186
- const allFileKeys = yield this.listFiles(fileKey);
187
- (0, Affirm_1.default)(allFileKeys.length < 50, `Pattern ${fileKey} of producer requested to S3 matches more than 50 files (${allFileKeys.length}), this is more than the S3 allowed limit. Please refine your pattern, remove some files or use a separate bucket.`);
188
- const promises = allFileKeys.map((x, i) => this._get(Object.assign(Object.assign({}, request), { fileKey: x }), i));
189
- const results = yield Promise.all(promises);
190
- return results.flat();
191
- }
192
- else {
193
- return yield this._get(request);
194
- }
195
- });
196
- this.readLinesInRange = (request) => __awaiter(this, void 0, void 0, function* () {
197
- (0, Affirm_1.default)(this._client, 'S3 client not yet initialized, call "connect()" first');
198
- (0, Affirm_1.default)(request, 'Invalid read request');
199
- (0, Affirm_1.default)(request.options, 'Invalid read request options');
200
- const { fileKey } = request;
201
- if (fileKey.includes('%')) {
202
- const allFileKeys = yield this.listFiles(fileKey);
203
- const promises = allFileKeys.map((x, i) => this._get(Object.assign(Object.assign({}, request), { fileKey: x }), i));
204
- const results = yield Promise.all(promises);
205
- return results.flat();
206
- }
207
- else {
208
- return yield this._get(request);
209
- }
210
- });
211
- this.download = (dataset) => __awaiter(this, void 0, void 0, function* () {
212
- (0, Affirm_1.default)(this._client, 'S3 client not yet initialized, call "connect()" first');
213
- (0, Affirm_1.default)(dataset, 'Invalid dataset');
214
- const file = dataset.getFile();
215
- (0, Affirm_1.default)(file, 'Invalid dataset file');
216
- (0, Affirm_1.default)(file.fileKey, 'Invalid file key');
217
- (0, Affirm_1.default)(file.fileType, `Invalid file type`);
218
- const includeSourceFilename = file.includeSourceFilename === true;
219
- const downloadLocally = (fileUrl_1, headerLine_1, ...args_1) => __awaiter(this, [fileUrl_1, headerLine_1, ...args_1], void 0, function* (fileUrl, headerLine, appendMode = false, sourceFilename) {
220
- // Download and validate header in a single stream pass
221
- const command = new client_s3_1.GetObjectCommand({
222
- Bucket: this._bucketName,
223
- Key: fileUrl
224
- });
225
- const response = yield this._client.send(command);
226
- (0, Affirm_1.default)(response.Body, 'Failed to fetch object from S3');
227
- const stream = response.Body;
228
- return DriverHelper_1.default.appendToUnifiedFile({
229
- stream,
230
- fileKey: fileUrl,
231
- destinationPath: dataset.getPath(),
232
- append: appendMode,
233
- headerLine,
234
- fileType: file.fileType,
235
- hasHeaderRow: file.hasHeaderRow,
236
- delimiter: dataset.getDelimiter(),
237
- sourceFilename
238
- });
239
- });
240
- const { fileKey } = file;
241
- if (fileKey.includes('%')) {
242
- const allFileKeys = yield this.listFiles(fileKey);
243
- Logger_1.default.log(`Matched ${allFileKeys.length} files, copying locally and creating unified dataset.`);
244
- Affirm_1.default.hasItems(allFileKeys, `The file key "${fileKey}" doesn't have any matches in bucket "${this._bucketName}".`);
245
- // Get header line from the first file
246
- const firstFileCommand = new client_s3_1.GetObjectCommand({
247
- Bucket: this._bucketName,
248
- Key: allFileKeys[0]
249
- });
250
- const firstFileResponse = yield this._client.send(firstFileCommand);
251
- (0, Affirm_1.default)(firstFileResponse.Body, 'Failed to fetch first file from S3');
252
- const firstFileStream = firstFileResponse.Body;
253
- let headerLine = yield this.getFirstLineFromStream(firstFileStream);
254
- // If including source filename, append a placeholder column name to the header
255
- if (includeSourceFilename) {
256
- headerLine = headerLine + dataset.getDelimiter() + Constants_1.default.SOURCE_FILENAME_COLUMN;
257
- }
258
- dataset.setFirstLine(headerLine);
259
- let totalLineCount = 0;
260
- // Download files sequentially to avoid file conflicts
261
- for (let i = 0; i < allFileKeys.length; i++) {
262
- const currentFileKey = allFileKeys[i];
263
- // Pass the filename (just the basename) if includeSourceFilename is enabled
264
- const sourceFilename = includeSourceFilename ? path_1.default.basename(currentFileKey) : undefined;
265
- totalLineCount += yield downloadLocally(currentFileKey, headerLine, i > 0, sourceFilename); // Append mode for subsequent files
266
- }
267
- dataset.setCount(totalLineCount);
268
- return dataset;
269
- }
270
- else {
271
- // Get header line from the single file
272
- const firstFileCommand = new client_s3_1.GetObjectCommand({
273
- Bucket: this._bucketName,
274
- Key: fileKey
275
- });
276
- const firstFileResponse = yield this._client.send(firstFileCommand);
277
- (0, Affirm_1.default)(firstFileResponse.Body, 'Failed to fetch first file from S3');
278
- const firstFileStream = firstFileResponse.Body;
279
- let headerLine = yield this.getFirstLineFromStream(firstFileStream);
280
- // If including source filename, append a placeholder column name to the header
281
- if (includeSourceFilename) {
282
- headerLine = headerLine + dataset.getDelimiter() + Constants_1.default.SOURCE_FILENAME_COLUMN;
283
- }
284
- dataset.setFirstLine(headerLine);
285
- // Pass the filename if includeSourceFilename is enabled
286
- const sourceFilename = includeSourceFilename ? path_1.default.basename(fileKey) : undefined;
287
- const totalLineCount = yield downloadLocally(fileKey, headerLine, false, sourceFilename);
288
- dataset.setCount(totalLineCount);
289
- return dataset;
290
- }
291
- });
292
- this.getFirstLineFromStream = (stream) => __awaiter(this, void 0, void 0, function* () {
293
- var _a, e_1, _b, _c;
294
- const rl = readline_1.default.createInterface({ input: stream, crlfDelay: Infinity });
295
- let firstLine = '';
296
- try {
297
- for (var _d = true, rl_1 = __asyncValues(rl), rl_1_1; rl_1_1 = yield rl_1.next(), _a = rl_1_1.done, !_a; _d = true) {
298
- _c = rl_1_1.value;
299
- _d = false;
300
- const line = _c;
301
- firstLine = line;
302
- break;
303
- }
304
- }
305
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
306
- finally {
307
- try {
308
- if (!_d && !_a && (_b = rl_1.return)) yield _b.call(rl_1);
309
- }
310
- finally { if (e_1) throw e_1.error; }
311
- }
312
- rl.close();
313
- return firstLine;
314
- });
315
- this.exist = (producer) => __awaiter(this, void 0, void 0, function* () {
316
- var _a;
317
- (0, Affirm_1.default)(this._client, 'S3 client not yet initialized, call "connect()" first');
318
- (0, Affirm_1.default)(producer, 'Invalid read producer');
319
- const bucket = this._bucketName;
320
- const fileKey = producer.settings.fileKey;
321
- (0, Affirm_1.default)(fileKey, `Invalid file key for download request`);
322
- if (fileKey.includes('%')) {
323
- const allFileKeys = yield this.listFiles(fileKey);
324
- return allFileKeys.length > 0;
325
- }
326
- else {
327
- try {
328
- yield this._client.send(new client_s3_1.HeadObjectCommand({ Bucket: bucket, Key: fileKey }));
329
- return true;
330
- }
331
- catch (error) {
332
- if (((_a = error.$metadata) === null || _a === void 0 ? void 0 : _a.httpStatusCode) === 404 || error.name === 'NotFound')
333
- return false;
334
- throw error;
335
- }
336
- }
337
- });
338
- this._readLines = (stream, lineFrom, lineTo) => __awaiter(this, void 0, void 0, function* () {
339
- var _a, e_2, _b, _c;
340
- const reader = readline_1.default.createInterface({ input: stream, crlfDelay: Infinity });
341
- const lines = [];
342
- let lineCounter = 0;
343
- try {
344
- for (var _d = true, reader_1 = __asyncValues(reader), reader_1_1; reader_1_1 = yield reader_1.next(), _a = reader_1_1.done, !_a; _d = true) {
345
- _c = reader_1_1.value;
346
- _d = false;
347
- const line = _c;
348
- if (Algo_1.default.hasVal(lineFrom) && Algo_1.default.hasVal(lineTo)) {
349
- if (lineCounter >= lineFrom && lineCounter < lineTo) {
350
- if (line && line.length > 0)
351
- lines.push(line);
352
- }
353
- lineCounter++;
354
- if (lineCounter >= lineTo)
355
- break;
356
- }
357
- else {
358
- if (line && line.length > 0)
359
- lines.push(line);
360
- }
361
- }
362
- }
363
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
364
- finally {
365
- try {
366
- if (!_d && !_a && (_b = reader_1.return)) yield _b.call(reader_1);
367
- }
368
- finally { if (e_2) throw e_2.error; }
369
- }
370
- reader.close();
371
- return lines;
372
- });
373
- this._readExcelLines = (stream, sheetName, lineFrom, lineTo) => __awaiter(this, void 0, void 0, function* () {
374
- var _a, stream_1, stream_1_1;
375
- var _b, e_3, _c, _d;
376
- (0, Affirm_1.default)(sheetName, `Invalid sheetname`);
377
- const chunks = [];
378
- try {
379
- for (_a = true, stream_1 = __asyncValues(stream); stream_1_1 = yield stream_1.next(), _b = stream_1_1.done, !_b; _a = true) {
380
- _d = stream_1_1.value;
381
- _a = false;
382
- const chunk = _d;
383
- chunks.push(chunk);
384
- }
385
- }
386
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
387
- finally {
388
- try {
389
- if (!_a && !_b && (_c = stream_1.return)) yield _c.call(stream_1);
390
- }
391
- finally { if (e_3) throw e_3.error; }
392
- }
393
- const buffer = Buffer.concat(chunks);
394
- const excel = xlsx_1.default.read(buffer, { type: 'buffer' });
395
- (0, Affirm_1.default)(excel.SheetNames.includes(sheetName), `The sheet "${sheetName}" doesn't exist in the excel (available: ${excel.SheetNames.join(', ')})`);
396
- const sheet = excel.Sheets[sheetName];
397
- const csv = xlsx_1.default.utils.sheet_to_csv(sheet);
398
- const lines = csv.split('\n');
399
- if (Algo_1.default.hasVal(lineFrom) && Algo_1.default.hasVal(lineTo))
400
- return lines.slice(lineFrom, lineTo + 1);
401
- else
402
- return lines;
403
- });
404
- this._readXmlLines = (stream, lineFrom, lineTo) => __awaiter(this, void 0, void 0, function* () {
405
- var _a, stream_2, stream_2_1;
406
- var _b, e_4, _c, _d;
407
- const chunks = [];
408
- try {
409
- for (_a = true, stream_2 = __asyncValues(stream); stream_2_1 = yield stream_2.next(), _b = stream_2_1.done, !_b; _a = true) {
410
- _d = stream_2_1.value;
411
- _a = false;
412
- const chunk = _d;
413
- chunks.push(chunk);
414
- }
415
- }
416
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
417
- finally {
418
- try {
419
- if (!_a && !_b && (_c = stream_2.return)) yield _c.call(stream_2);
420
- }
421
- finally { if (e_4) throw e_4.error; }
422
- }
423
- const buffer = Buffer.concat(chunks);
424
- const jsonData = XMLParser_1.default.xmlToJson(buffer);
425
- // Convert JSON data to string lines. This might need adjustment based on XML structure.
426
- let lines = Array.isArray(jsonData) ? jsonData.map(item => JSON.stringify(item)) : [JSON.stringify(jsonData)];
427
- if (Algo_1.default.hasVal(lineFrom) && Algo_1.default.hasVal(lineTo)) {
428
- lines = lines.slice(lineFrom, lineTo + 1);
429
- }
430
- return lines;
431
- });
432
- this._get = (request, index) => __awaiter(this, void 0, void 0, function* () {
433
- const { fileKey, fileType, options } = request;
434
- const bucket = this._bucketName;
435
- let lineFrom, lineTo, sheetName, hasHeaderRow;
436
- if (options) {
437
- lineFrom = options.lineFrom;
438
- lineTo = options.lineTo;
439
- sheetName = options.sheetName;
440
- hasHeaderRow = options.hasHeaderRow;
441
- }
442
- const response = yield this._client.send(new client_s3_1.GetObjectCommand({
443
- Bucket: bucket,
444
- Key: fileKey
445
- }));
446
- (0, Affirm_1.default)(response.Body, 'Failed to fetch object from S3');
447
- const stream = response.Body;
448
- let lines = [];
449
- switch (fileType) {
450
- case 'CSV':
451
- case 'JSON':
452
- case 'JSONL':
453
- case 'TXT':
454
- if (Algo_1.default.hasVal(lineFrom) && Algo_1.default.hasVal(lineTo))
455
- lines = yield this._readLines(stream, lineFrom, lineTo);
456
- else
457
- lines = yield this._readLines(stream);
458
- break;
459
- case 'XLS':
460
- case 'XLSX':
461
- if (Algo_1.default.hasVal(lineFrom) && Algo_1.default.hasVal(lineTo))
462
- lines = yield this._readExcelLines(stream, sheetName, lineFrom, lineTo);
463
- else
464
- lines = yield this._readExcelLines(stream, sheetName);
465
- break;
466
- case 'XML':
467
- if (Algo_1.default.hasVal(lineFrom) && Algo_1.default.hasVal(lineTo))
468
- lines = yield this._readXmlLines(stream, lineFrom, lineTo);
469
- else
470
- lines = yield this._readXmlLines(stream);
471
- break;
472
- }
473
- // If this is not the first file read in a pattern match AND the file type has an header,
474
- // then I need to remove the header from the resulting lines or the header will be duplicated
475
- if (index > 0 && ParseHelper_1.default.shouldHaveHeader(fileType, hasHeaderRow)) {
476
- lines = lines.slice(1);
477
- }
478
- return lines;
479
- });
480
- this._listFiles = (fileKeyPattern, maxKeys, continuationToken) => __awaiter(this, void 0, void 0, function* () {
481
- var _a;
482
- (0, Affirm_1.default)(this._client, 'S3 client not yet initialized, call "connect()" first');
483
- // Convert SQL-like pattern to prefix and pattern parts for filtering
484
- let prefix = '';
485
- if (fileKeyPattern) {
486
- if (fileKeyPattern.includes('%')) {
487
- const parts = fileKeyPattern.split('%').filter(part => part.length > 0);
488
- // If pattern starts with text before first %, use it as prefix for S3 optimization
489
- if (!fileKeyPattern.startsWith('%') && parts[0]) {
490
- prefix = parts[0];
491
- }
492
- }
493
- else {
494
- // No wildcard, use the entire pattern as prefix
495
- prefix = fileKeyPattern;
496
- }
497
- }
498
- const listParams = {
499
- Bucket: this._bucketName,
500
- Prefix: prefix || undefined,
501
- MaxKeys: maxKeys || 10000,
502
- ContinuationToken: continuationToken
503
- };
504
- try {
505
- const response = yield this._client.send(new client_s3_1.ListObjectsV2Command(listParams));
506
- const files = ((_a = response.Contents) === null || _a === void 0 ? void 0 : _a.map(obj => obj.Key).filter(key => key !== undefined)) || [];
507
- const matchingFiles = Helper_1.default.matchPattern(fileKeyPattern, files);
508
- return {
509
- files: matchingFiles,
510
- nextContinuationToken: response.NextContinuationToken
511
- };
512
- }
513
- catch (error) {
514
- throw new Error(`Failed to list files in bucket "${this._bucketName}": ${error.message}`);
515
- }
516
- });
517
- this.listFiles = (fileKeyPattern, maxKeys) => __awaiter(this, void 0, void 0, function* () {
518
- const allFiles = [];
519
- let continuationToken = undefined;
520
- do {
521
- const result = yield this._listFiles(fileKeyPattern, maxKeys, continuationToken);
522
- allFiles.push(...result.files);
523
- continuationToken = result.nextContinuationToken;
524
- // If maxKeys is specified and we've reached the limit, break
525
- if (maxKeys && allFiles.length >= maxKeys) {
526
- return allFiles.slice(0, maxKeys);
527
- }
528
- } while (continuationToken);
529
- return allFiles;
530
- });
531
- this.downloadFile = (fileKey) => __awaiter(this, void 0, void 0, function* () {
532
- (0, Affirm_1.default)(this._client, 'S3 client not yet initialized, call "init()" first');
533
- (0, Affirm_1.default)(fileKey, 'Invalid file key');
534
- const response = yield this._client.send(new client_s3_1.GetObjectCommand({
535
- Bucket: this._bucketName,
536
- Key: fileKey
537
- }));
538
- (0, Affirm_1.default)(response.Body, 'Failed to fetch object from S3');
539
- const content = yield response.Body.transformToByteArray();
540
- return Buffer.from(content);
541
- });
542
- this.deleteFile = (fileKey) => __awaiter(this, void 0, void 0, function* () {
543
- (0, Affirm_1.default)(this._client, 'S3 client not yet initialized, call "init()" first');
544
- (0, Affirm_1.default)(fileKey, 'Invalid file key');
545
- yield this._client.send(new client_s3_1.DeleteObjectCommand({
546
- Bucket: this._bucketName,
547
- Key: fileKey
548
- }));
549
- });
550
- this.copyFile = (sourceFileKey, destinationBucket, destinationFileKey) => __awaiter(this, void 0, void 0, function* () {
551
- (0, Affirm_1.default)(this._client, 'S3 client not yet initialized, call "init()" first');
552
- (0, Affirm_1.default)(sourceFileKey, 'Invalid source file key');
553
- (0, Affirm_1.default)(destinationBucket, 'Invalid destination bucket');
554
- (0, Affirm_1.default)(destinationFileKey, 'Invalid destination file key');
555
- yield this._client.send(new client_s3_1.CopyObjectCommand({
556
- CopySource: `${this._bucketName}/${sourceFileKey}`,
557
- Bucket: destinationBucket,
558
- Key: destinationFileKey
559
- }));
560
- });
561
- }
562
- }
563
- exports.S3SourceDriver = S3SourceDriver;