s3.getObject() does not throw any error. Causes fatal exit in Lambda

`I am having issues with my lambda not being able to getObject from s3 through a stream. When I check the lambda logs, there is no sign of an error what so ever. I see that is doing the getFileStream and logging each file… and then just stops.

Here is my code and I can answer any questions:

import { S3 } from "@aws-sdk/client-s3";
import * as stream from "stream";
import archiver from "archiver";
import type { Context } from "aws-lambda";
import { logger } from "../../utils/logger.js";
import { objectClient } from "../../adapters/object-client.js";
import type { ArtifactsEmailArgs } from "../../domain/ports/email-client.js";
import { emailClient } from "../../adapters/email-client.js";

export interface FilesZipperRequest {
  user_email: string;
  user_alt_email?: string;
  user_first_name: string;
  destination_bucket: string;
  destination_key: string;
  source_files: FilesZipperSourceFiles[];
}

export interface FilesZipperSourceFiles {
  source_bucket: string;
  source_key: string;
}

// Sample Request taken by this lambda
//{
//     "user_email": "[email protected]",
//     "user_first_name": "John",
//     "destination_bucket": "destination-bucket",
//     "destination_key": "zips/myzip.zip",
//     "source_files": [
//         {
//             "source_bucket": "source_bucket",
//             "source_key": "full_path_of_file"
//         }
//     ]
// }

export const handler = async (
  request: FilesZipperRequest,
  context: Context
) => {
  logger.info("Event=" + JSON.stringify(request));
  logger.info("Context=" + JSON.stringify(context));

  const userEmail = request.user_email;
  const userAltEmail = request.user_alt_email;
  const userFirstName = request.user_first_name;
  const bucketName = request.destination_bucket;
  const destinationKey = request.destination_key;
  const fileNames = request.source_files;

  const s3 = new S3({});
  const zipStream = new stream.PassThrough();
  const archive = archiver("zip");
  archive.pipe(zipStream);

  const missingFiles: string[] = [];

  logger.info("*** Obtain users and products for mapping from ids ***");

  try {
    for (const file of fileNames) {
    
      try {
        const fileStream = await getFileStream(
          file.source_bucket,
          file.source_key,
          s3
        );
        archive.append(fileStream, { name: file.source_key });
      } catch (error: any) {
        logger.error(
          `Error fetching file: ${file.source_key} from bucket: ${file.source_bucket}`,
          error
        );
        missingFiles.push(file.source_key);
      }
    }
    archive.finalize();

    const buffer = await streamToBuffer(zipStream);

    await emailArtifactPreSignedUrl(
      bucketName,
      destinationKey,
      userFirstName,
      userEmail,
      missingFiles,
      userAltEmail
    );

    await objectClient.upload(
      bucketName,
      destinationKey,
      buffer,
      "application/zip"
    );

    return;
  } catch (error: any) {
    logger.error("An error occurred during the zip process:", error);
    return {
      statusCode: 500,
      body: JSON.stringify({
        message: "Failed to create zip file",
        error: error.message,
      }),
    };
  }
};

/**
 * Fetches a file from the specified S3 bucket and key.
 *
 * @returns A promise that resolves to a readable stream of the file.
 * @throws Will throw an error if the file is not found or if another error occurs during the fetch.
 */
async function getFileStream(
  bucket: string,
  key: string,
  s3Client: S3
): Promise<stream.Readable> {
  const params = {
    Bucket: bucket,
    Key: key,
  };
  try {
    const data = await s3Client.getObject(params);
    logger.info(`Successfully fetched file: ${key} from bucket: ${bucket}`);
    return data.Body as stream.Readable;
  } catch (error) {
    if ((error as Error).name === "NoSuchKey") {
      throw new Error(`File not found: ${key} in bucket ${bucket}`);
    }
    throw error;
  }
}

/**
 * Converts a stream to a buffer.
 *
 * @param stream - The input stream to be converted.
 * @returns A promise that resolves to a buffer containing the concatenated data from the stream.
 */
function streamToBuffer(stream: stream.PassThrough): Promise<Buffer> {
  const chunks: Buffer[] = [];
  return new Promise((resolve, reject) => {
    stream.on("data", (chunk) => chunks.push(chunk));
    stream.on("error", reject);
    stream.on("end", () => {
      console.log("Zip file created.");
      resolve(Buffer.concat(chunks));
    });
  });
}

const emailArtifactPreSignedUrl = async (
  bucketName: string,
  keyName: string,
  firstName: string,
  email: string,
  missingArtifacts: string[],
  altEmail?: string
) => {
  const preSignedUrl: string = await objectClient.getGetPreSignedUrl(
    bucketName,
    keyName,
    60 * 60 // 1 hour expiry in seconds
  );
  logger.info(`PresignedUrl of zip file is: ${preSignedUrl}`);
  const args: ArtifactsEmailArgs = {
    to: [email],
    cc: altEmail ? [altEmail] : undefined,
    firstName,
    preSignedUrl,
    missingArtifacts,
  };
  logger.info("Emailing the artifact file with missing files information.");
  await emailClient.sendArtifactsEmail(args);
};

This code works perfectly fine when I am getting not that many files, but the moment I try to do this with a lot of files it fails. I am expecting the files to passed in, then we are checking to make sure we have them in the S3(if it isn’t there it’s okay), then we are adding the files one at a time to an S3 which we are using to create a downloadUrl.`

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật