对于以下代码,我被要求检查,该问题在AWS Lambda
上运行并执行将文件上传到S3
的简单任务,从aws console
手动运行时随机超时,
但同时按计划运行时,第一次尝试时总是超时,第二次成功运行(第一次失败后立即运行)。
调用s3.getBucketLocation
后,代码似乎总是挂起,永远不会到达getBucketLocation
的回调(第一次尝试!)。
所有VPC's
和NAT
都已正确设置,以便当我从代码中删除s3.getBucketLocation
并直接致电s3Upload.upload(params, cb);
时,代码没有超时的情况下运行。
我真的很想理解为什么第一个函数在尝试从AWS
检索存储桶区域时会失败。
"use strict";
var urlHelper = require('url');
var fs = require('fs');
var AWS = require('aws-sdk');
var exp = {};
function saveToFile(path, content, cb) {
fs.writeFile(path, content, cb);
}
function saveToS3(bucket, key, content, cb) {
var s3 = new AWS.S3({apiVersion: '2006-03-01'});
var params = {
Bucket: bucket
};
s3.getBucketLocation(params, function(err, data) {
console.log('THIS IS NOT REACHED');
if (err) {
return cb(err);
}
var s3Upload = new AWS.S3({
apiVersion: '2006-03-01',
region: data.LocationConstraint
});
var params = {
Bucket: bucket,
Key: key,
Body: content,
ACL: 'public-read',
ContentType: 'text/xml',
CacheControl: 'max-age=60'
};
s3Upload.upload(params, cb);
});
}
exp.upload = function(path, content, cb) {
var url = urlHelper.parse(path);
switch(url.protocol) {
case 'file:':
case null:
saveToFile(path, content, cb);
break;
case 's3:':
saveToS3(url.host, url.pathname.substring(1), content, cb);
break;
default:
console.log('No matching protocol found for upload!');
cb(null, null);
}
};
module.exports = exp;