Lambda - headObject失败(NotFound)虽然objectCreated是事件

时间:2018-02-19 11:44:49

标签: amazon-s3 aws-lambda serverless-framework

在具有事件:s3:ObjectCreated:*的lambda函数中,在创建的对象上调用head对象会返回NotFound错误。

module.exports.handler = async function(event, context, callback) {
    try {
        const Bucket = event.Records[0].s3.bucket.name;
        const Key = event.Records[0].s3.object.key;
        console.log('Bucket', Bucket);
        console.log('Key', Key);

        const objectHead = await s3.headObject({ Bucket, Key }).promise();
        console.log('Alas! I will never discover that the objectHead is:', objectHead);

        callback();
    } catch(err) {
        console.error('Error', err);
        callback(err);
    }
}

这是我得到的错误:

{ 
    NotFound: null
    message: null,
    code: 'NotFound',
    region: null,
    time: 2018-02-19T11:06:35.894Z,
    requestId: 'XXXXXXXXXXX',
    extendedRequestId: 'XXX.....XXX',
    cfId: undefined,
    statusCode: 404,
    retryable: false,
    retryDelay: 77.24564264820208 
}

我注意到它在错误中显示region null。我怀疑这是无关紧要的,因为我99%确定我正确设置了它:

const s3 = new AWS.S3({
    region: 'us-east-1'
});

这里是serverless.yml函数声明,以防任何人感到好奇:

obj_head:
  handler: obj_head.handler
  events:
    - s3:
        bucket: ${self:provider.environment.BUCKET_NAME}
        event: s3:ObjectCreated:*
  role: arn:aws:iam::XXXXXXXXX:role/RoleWithAllS3PermissionsEver

以下是收到活动的示例:

{
    "Records": [
        {
            "eventVersion": "2.0",
            "eventSource": "aws:s3",
            "awsRegion": "us-east-1",
            "eventTime": "2018-02-19T11:03:46.761Z",
            "eventName": "ObjectCreated:Put",
            "userIdentity": {
                "principalId": "AWS:XXX"
            },
            "requestParameters": {
                "sourceIPAddress": "X.X.X.X"
            },
            "responseElements": {
                "x-amz-request-id": "X",
                "x-amz-id-2": "X/X/X"
            },
            "s3": {
                "s3SchemaVersion": "1.0",
                "configurationId": "14122133-28e8-4cd9-907c-af328334c56b",
                "bucket": {
                "name": "BUCKET_NAME",
                "ownerIdentity": {
                    "principalId": "X"
                },
                "arn": "arn:aws:s3:::BUCKET_NAME"
                },
                "object": {
                    "key": "input.key",
                    "size": X,
                    "eTag": "X",
                    "sequencer": "X"
                }
            }
        }
    ]
}

令人费解的是,虽然触发该功能的事件是对象的创建,但找不到对象头。

我做错了吗? 关于在哪里看的任何想法?

1 个答案:

答案 0 :(得分:1)

The object keyname value is URL encoded, and this was causing the issue. This behaviour is documented here

  

s3键提供有关所涉及的存储桶和对象的信息   在这件事上。请注意,对象keyname值是URL编码的。对于   例如“red flower.jpg”变成“red + flower.jpg”。

在处理包含Unicode字符的文件名时,请参阅Alastair McCormack的answer

  

您需要将URL编码的Unicode字符串转换为字节str   在un-urlparsing并解码为UTF-8之前。