jpsim / AWSPics

An AWS CloudFormation stack to run a serverless password-protected photo gallery
https://awspics.net
MIT License
219 stars 60 forks source link

node.js 20 Resize Function #54

Open tylerapplebaum opened 7 months ago

tylerapplebaum commented 7 months ago

@agstevens I see there's a new Lambda layer for node.js 20. I don't know node well enough to competently translate the Resize function to code that is compatible with node.js 20. I was wondering if your own code was up-to-date, and if so, could you share it?

AWS has retired older runtimes, so sticking with older versions won't be an option for long.

agstevens commented 7 months ago

I'm using a node.js 20 based lambda layer. I just downloaded this zip file here (as I wrote in the documentation):

"The best practice for image magick for the resize function is now is to create your own lambda layer. Download this zip file from here: https://github.com/CyprusCodes/imagemagick-aws-lambda-2/tree/master/archive"

Then upload that as a lambda layer in your account and reference it in the resize application (either manually or using the ARN in your .yaml file after you create it). It's ok that the architecture is ARM, the resize function isn't architecture specific.

Here's what the reference looks like in my resize lamdba function:

Screenshot 2024-03-22 at 8 30 15 PM

You can upgrade your layer by uploading that exact zip file (as a new layer or a new layer version) from the Lambda management console, and then reference it by incrementing the layer reference number referenced in your lambda function (if already deployed) or updating the ARN reference in the .yaml file (if not yet deployed).

tylerapplebaum commented 7 months ago

Thanks for the response! The layer itself is simple enough to interact with. I have no issue with that.

However, the resizepics Lambda function has to be migrated to Node 20 which uses AWS SDK v3. Ok, it doesn't have to be, but it should be now that its 2024 and AWS has sunset the v2 SDK and older Node runtimes.

I have so far unsuccessfully attempted to modernize the resizepics function to work with the newer platform. I can't seem to get my s3.send command to execute.

My function below is slightly different, I have changed the crop gravity to North and added an extra thumbnail size.

const { S3Client, GetObjectCommand, PutObjectCommand } = require("@aws-sdk/client-s3");
const async = require("async");
const gm = require("gm").subClass({ imageMagick: true });

const s3 = new S3Client({ region: 'us-west-2', signatureVersion: 'v4' }); // Update with your region

const DEFAULT_PICS_ORIGINAL_PATH = 'pics/original/';

function getPicsOriginalPath() {
  return process.env.PICS_ORIGINAL_PATH || DEFAULT_PICS_ORIGINAL_PATH;
}

function getImageType(objectContentType) {
  if (objectContentType === "image/jpeg") {
    return "jpeg";
  } else if (objectContentType === "image/png") {
    return "png";
  } else {
    throw new Error("unsupported objectContentType " + objectContentType);
  }
}

function cross(left, right) {
  var res = [];
  left.forEach(function(l) {
    right.forEach(function(r) {
      res.push([l, r]);
    });
  });
  return res;
}

exports.handler = async function(event, context) {
  console.log("event ", JSON.stringify(event));
  try {
    var images = async.mapLimit(event.Records, 4, async function(record) {
      console.log("Processing record:", record);
      const originalKey = decodeURIComponent(record.s3.object.key.replace(/\+/g, " "));
      console.log("originalKey ", originalKey);
      try {
        var data = await s3.send(new GetObjectCommand({
            Bucket: record.s3.bucket.name,
            Key: originalKey
        }));
        console.log("data ", JSON.stringify(data));
      } catch (error) {
        console.log("error ", error);
        throw error;
      }
      var buffer = await streamToBuffer(data.Body);
      return {
        originalKey: originalKey,
        contentType: data.ContentType,
        imageType: getImageType(data.ContentType),
        buffer: buffer,
        record: record
      };
    });

    const resizePairs = cross(["1200x750", "600x375", "360x225"], images);

    await async.eachLimit(resizePairs, 4, async function(resizePair) {
      const config = resizePair[0];
      const image = resizePair[1];
      const width = config.split('x')[0];
      const height = config.split('x')[1];
      let operation = gm(image.buffer).autoOrient().resize(width, height, '^');
      if (config == "360x225") {
        operation = operation.gravity('North').crop(width, height);
      }
      var buffer = await fromNode(callback => {
        operation.toBuffer(image.imageType, (err, buffer) => {
          if (err) callback(err);
          else callback(null, buffer);
        });
      });
      await s3.send(new PutObjectCommand({
        Bucket: process.env.RESIZED_BUCKET,
        Key: "pics/resized/" + config + "/" + image.originalKey.replace(getPicsOriginalPath(), ""),
        Body: buffer,
        ContentType: image.contentType,
        CacheControl: "max-age=86400"
      }));
    });

    context.succeed();
  } catch (error) {
    context.fail(error);
  }
};

async function streamToBuffer(stream) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    stream.on('data', chunk => chunks.push(chunk));
    stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
    stream.on('error', err => reject(err));
  });
}