2016-03-02 60 views
0

我在Lambda中有一个函数,只有在对象发生更改时才会将元数据标题添加到s3上的对象。AWS Lambda函数和S3 - 仅当对象发生更改时才更改S3中的对象的元数据

ContentType: 'application/javascript' 
 
CacheControl: 'max-age=600'

但事实证明,LAMBDA检查大约100倍桶在秒,不仅如果对象改变了,其成本了很多。

访问日志上S3:

b6234e2652b93344f7 aa [02/Mar/2016:11:00:55 +0000] 54.0.0.209 arn:aws:sts::718436:assumed-role/lambda_s3_exec_role/awslambda_642_201609 805 REST.COPY.OBJECT /local.js "PUT /local.js HTTP/1.1" 200 - 234 4404 50 24 "-" "aws-sdk-nodejs/2.2.32 linux/v0.10.36" - 
 
b6234ee5f9cf0344f7 aa [02/Mar/2016:11:00:55 +0000] 54.0.0.209 arn:aws:sts::71836:assumed-role/lambda_s3_exec_role/awslambda_642_209 890005 REST.COPY.OBJECT_GET local.js - 200 - - 4404 - - - - -

功能:

console.log('Loading function'); 
 

 
var aws = require('aws-sdk'); 
 
var s3 = new aws.S3({ apiVersion: '2006-03-01' }); 
 

 
exports.handler = function(event, context) { 
 
    //console.log('Received event:', JSON.stringify(event, null, 2)); 
 

 
    // Get the object from the event and show its content type 
 
    var bucket = event.Records[0].s3.bucket.name; 
 
    var key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); 
 
    var params = { 
 
     Bucket: bucket, 
 
     Key: key, 
 
     CopySource: encodeURIComponent(bucket+"/"+key), 
 
     ContentType: 'application/javascript', 
 
     CacheControl: 'max-age=600', 
 
     "Metadata":{ 
 
     }, 
 
     MetadataDirective: 'REPLACE' 
 
    }; 
 
    //s3.getObject(params, function(err, data) { 
 
    s3.copyObject(params, function(err, data) { 
 
     if (err) { 
 
      console.log(err); 
 
      var message = "Error getting object " + key + " from bucket " + bucket + 
 
       ". Make sure they exist and your bucket is in the same region as this function."; 
 
      console.log(message); 
 
      context.fail(message); 
 
     } else { 
 
      console.log('CONTENT TYPE:', data.ContentType); 
 
      context.succeed(data.ContentType); 
 
     } 
 
    }); 
 
};

我需要改变,以便在功能WIL什么l只有当对象在s3中改变时才工作?

感谢先进!

回答

3

您为自己创建了一个无限循环错误! Lambda函数在对象发生更改时触发,并且通过更改元数据并使用copyObject更改对象,从而再次加载Lambda函数。您立即达到了100个并发请求的Lambda限制,以确保您现在不必支付一百万欧元,因为您编写了无限循环。

为了规避这一点,您需要重新考虑您的架构。有多种选择,但最简单的是我认为的这个:

在您的Lambda代码中,首先执行s3.getObject并检查您要更改的标头是否已经存在。如果是这样,关闭Lambda函数。这样您每次编辑只执行两次Lambda函数。不是100%的理想,但对于实际应用而言足够好。

+0

'while(+1){...}'heh。一个建议是只获取对象元数据 - 而不是整个对象。 –