我正在运行一个相对简单的AWS Function以添加对Stripe的订阅。

除非我刚击中它,否则它运行良好。只是尝试在PostMan中一个又一个失败并返回后运行它:

{"errorMessage": "Process exited before completing request"}


这些请求是通过API网关传递的。

该功能配置为30秒超时,大约需要1300ms才能在基本128M RAM上运行(问题可重现256M)。

我以为这正是Lambda旨在避免的事情……我第二次猜测是我决定将Lambda用于(同步)关键任务组件的决定。

编辑:根据要求,这是功能代码:

var stripe = require('stripe');

exports.handler = function (event, context, callback) {
    var self = this;
    stripe = stripe(getKey(event.stage, 'STRIPE_SECRET_KEY'));
    self.createSubscription = createSubscription;
    self.validPayload = validPayload;

    console.log('event: ', event);

    if (self.validPayload(event, context)) {
        self.createSubscription(event, stripe, callback, context);
    }

    /**
     * checks that the necessary payload has been received
     * if YES: returns true and allows process to continue
     * if NO: throws context.fail with useful error message(s)
     * operating under custom error code naming convention of
     * http code + 3 digit ULM error code
     * @param event - from Lambda
     * @param context - from Lambda
     * @returns {boolean} - whether the payload contains the required data
     */
    function validPayload (event, context) {
        var errorResponse = {
            status: 400,
            errors: []
        };

        if (!event.billing_email) {
            errorResponse.errors.push({
                code: 400001,
                message: "No billing email provided."
            })
        }
        if (!event.plan) {
            errorResponse.errors.push({
                code: 400002,
                message: "No plan was selected."
            })
        }
        if (!event.token) {
            errorResponse.errors.push({
                code: 400003,
                message: "A valid credit card was not provided."
            })
        }

        if (!!errorResponse.errors.length) {
            context.fail(JSON.stringify(errorResponse));
            return false;
        } else {
            return true;
        }
    }

    /**
     * Creates a new customer & subscription using stripe package method
     * if success, executes callback with response data
     * if fail, throws context.fail with useful error message(s)
     * @param event - from Lambda
     * @param stripe - probably not necessary...
     * @param callback - from Lambda
     * @param context - probably not necessary...
     */
    function createSubscription (event, stripe, callback, context) {
        stripe.customers.create({
            source: event.token,
            plan: event.plan,
            email: event.billing_email
        }, function (err, customer) {
            if (err) {
                var errorResponse = {
                    status: 400,
                    errors: []
                };

                errorResponse.errors.push({
                    code: 400004,
                    message: err.message
                });

                console.error('Customer/Plan Creation Failed');
                callback(JSON.stringify(errorResponse));
            } else {
                callback(null, {
                    status: 200,
                    customer: customer
                });
            }
        });

    }

    function getKey (stage, keyId) {
        var keys = {
            STRIPE_SECRET_KEY: {
                staging: 'sk_test_123456',
                prod: 'sk_live_123456'
            }
        };

        if (stage === 'prod') {
            return keys[keyId][stage];
        } else {
            return keys[keyId]['staging'];
        }
    }
};


编辑2:深入CloudWatch,发现此错误日志:TypeError: stripe is not a function at exports.handler (/var/task/exports.js:5:14)

最佳答案

@rowanu是正确的,您的问题在此行stripe = stripe(getKey(event.stage, 'STRIPE_SECRET_KEY'));上。由于Lambda会随时处理后续请求,因此传入的每个新请求都会看到handler函数外部声明的任何变量。这应该是一个简单的解决方法,请勿重新定义stripe变量。这样的事情可以解决问题:

var stripe = require('stripe');
var stripeInstance; // undefined on startup

exports.handler = function (event, context, callback) {
  // now define stripeInstance if its not already defined
  if(!stripeInstance) {
    stripeInstance = stripe(getKey(event.stage, 'STRIPE_SECRET_KEY'));
  }
  // now all functions will be able to use the same instance of stripe.
  // This assumes the event.stage is always the same, if you need a new instance for every request then remove the if statement
  // rename all references of stripe to stripeInstance
  ...

关于node.js - 如果每30秒超过1个请求,Lambda将无法通过API网关保持/丢弃请求(在完成请求之前退出流程),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38972826/

10-11 10:35