aws lambda
by John McKim
約翰·麥金(John McKim)
如何通過在本地模擬AWS Lambda來加速無服務器開發 (How you can speed up serverless development by simulating AWS Lambda locally)
Designing AWS Lambda functions can be a frustrating experience. Each time you make a change, you have to deploy your code to AWS before you can test it. Well, my friend and I finally decided to do something about this.
設計AWS Lambda函數可能會令人沮喪。 每次進行更改時,都必須先將代碼部署到AWS,然后才能對其進行測試。 好吧, 我和我的朋友終于決定對此做些事情。
The end result is the Serverless Simulate Plugin. This plugin is an AWS Lambda and API Gateway simulator for the Serverless Framework.
最終結果是無服務器模擬插件 。 該插件是用于無服務器框架的AWS Lambda和API網關模擬器。
I’m going to walk you through how we built this and how you can start using it when you develop serverless apps.
我將向您介紹我們如何構建它以及如何在開發無服務器應用程序時開始使用它。
模擬API網關 (Simulating API Gateway)
API Gateway provides HTTP endpoints that invoke Lambda functions in response to requests.
API網關提供HTTP終結點,以響應請求來調用Lambda函數。
API Gateway maps the incoming HTTP request to an event payload for Lambda. When the Lambda function returns a result, the result is mapped to a HTTP response.
API網關將傳入的HTTP請求映射到Lambda的事件有效負載。 當Lambda函數返回結果時,該結果將映射到HTTP響應。
While API Gateway has a lot of features, most developers only use a few of them. We chose to only implement the features commonly used by Serverless developers.
雖然API Gateway具有許多功能,但大多數開發人員僅使用其中的一些功能。 我們選擇僅實現無服務器開發人員常用的功能。
HTTP服務器 (HTTP Server)
To simulate API Gateway the plugin creates a HTTP server with express. The plugin reads the Serverless config file and creates endpoints from the HTTP events.
為了模擬API Gateway,該插件使用express創建一個HTTP服務器。 該插件讀取Serverless配置文件,并根據HTTP事件創建端點。
If the endpoint has enabled CORS, the plugin will add CORS Middleware to the endpoint.
如果端點已啟用CORS,則插件會將CORS中間件添加到端點。
定制授權人 (Custom Authorizers)
API Gateway can Authorize endpoints in a few different ways. A common approach is to use a Custom Authorizer.
API網關可以通過幾種不同的方式授權端點。 一種常見的方法是使用自定義授權器 。
To simulate Custom Authorizers, we created an express js middleware function. The middleware creates the Lambda event with authorization information from the request. The Authorizer function is then invoked locally.
為了模擬自定義授權者,我們創建了一個快速的js中間件功能。 中間件使用來自請求的授權信息創建Lambda事件。 然后在本地調用Authorizer函數。
Custom Authorizers allow or deny requests based on a policy document. The middleware reads the policy document returned by the Authorizer. If the request is not allowed to access an endpoint, the middleware will return an Unauthorized response.
定制授權者基于策略文檔允許或拒絕請求。 中間件讀取授權者返回的策略文檔。 如果不允許該請求訪問端點,則中間件將返回未經授權的響應。
Lambda整合 (Lambda Integration)
API Gateway has two integrations with AWS Lambda. The original Lambda integration and the newer Lambda Proxy.
API Gateway與AWS Lambda有兩個集成。 原始的Lambda集成和更新的Lambda代理 。
Both integrations map HTTP requests to a Lambda event. When Lambda returns a result, the integration maps the result to a HTTP response.
兩種集成都將HTTP請求映射到Lambda事件。 當Lambda返回結果時,集成會將結果映射到HTTP響應。
We developed two mapping functions that mimic Lambda and Lambda Proxy. The server selects the integration based on the HTTP event configuration in serverless.yml
.
我們開發了兩個模仿Lambda和Lambda Proxy的映射功能。 服務器根據serverless.yml
的HTTP事件配置選擇集成。
When a request is received, the server performs the same mapping process as API Gateway. A simplified version of the code is below.
收到請求后,服務器將執行與API網關相同的映射過程。 下面是該代碼的簡化版本。
function(req, res) { integration.event(req) .then(event => lambda.invoke(context, event)) .then(result => integration.response(req, result)) .then(response => respond(res, response))}
The end result is an express server that behaves like API Gateway.
最終結果是表現得像API網關的Express服務器。
使用API??網關模擬器 (Using the API Gateway Simulator)
To use the API Gateway simulator you need to install the plugin into your Serverless project. Please read the docs for instructions.
要使用API??網關模擬器,您需要將插件安裝到無服務器項目中。 請閱讀文檔以獲取說明。
To start the API Gateway simulator run the following command:
要啟動API網關模擬器,請運行以下命令:
sls simulate apigateway -p 5000
sls simulate apigateway -p 5000
This will start a HTTP server that you can use to test your endpoints and functions locally.
這將啟動HTTP服務器,您可以使用該服務器在本地測試端點和功能。
The API Gateway simulation is similar to other offline plugins for the Serverless Framework. The real difference with Serverless Simulate is how we simulate Lambda locally.
API Gateway模擬類似于Serverless Framework的其他脫機插件。 無服務器模擬的真正區別在于我們如何在本地模擬Lambda。
模擬AWS Lambda (Simulating AWS Lambda)
AWS Lambda is powered by a HTTP API. Functions are invoked through a HTTP request to the Lambda API.
AWS Lambda由HTTP API驅動。 通過對Lambda API的HTTP請求調用函數。
When the Invoke API is called, the Lambda service runs your code inside a container. For more details see the docs.
調用Invoke API時,Lambda服務在容器內運行您的代碼。 有關更多詳細信息,請參閱文檔 。
While AWS Lambda is a complex service, the core elements are reasonably easy to simulate. To simulate it locally we implemented three services, function runtimes, a function registry and HTTP API.
盡管AWS Lambda是一項復雜的服務,但其核心元素相當容易模擬。 為了在本地模擬它,我們實現了三個服務,函數運行時,函數注冊表和HTTP API。
函數運行時 (Function Runtimes)
We use a Docker image created by Michael Hart to create the function runtime. Using Docker allows us to control the environment and enforce memory limits and timeouts.
我們使用由Michael Hart創建的Docker映像來創建函數運行時。 使用Docker可讓我們控制環境并強制執行內存限制和超時。
功能注冊表 (Function Registry)
The Function Registry is a local JSON database powered by lowdb. The registry stores information about the function configuration and location.
Function Registry是一個由lowdb支持的本地JSON數據庫。 注冊表存儲有關功能配置和位置的信息。
This allows the server to lookup the details of a function when a request is received by the API.
當API收到請求時,這允許服務器查找功能的詳細信息。
HTTP API (HTTP API)
The HTTP API provides a registration endpoint for clients. The registration endpoint is used by the plugin to register functions.
HTTP API為客戶端提供注冊端點。 插件使用注冊端點來注冊功能。
The HTTP API also provides an endpoint to invoke functions. The invoke endpoint mimics the AWS Lambda API. This allows clients to use an AWS SDK to invoke functions.
HTTP API還提供了一個調用函數的端點。 調用端點模仿AWS Lambda API。 這允許客戶端使用AWS開發工具包調用功能。
為什么使用Lambda Simulator (Why use the Lambda Simulator)
The Lambda simulator allows you to invoke Lambda functions locally from other services. That might include another Lambda function in a different Serverless service. Or it could include a completely different application.
Lambda模擬器允許您從其他服務本地調用Lambda函數。 這可能在其他無服務器服務中包括另一個Lambda函數。 或者它可能包含一個完全不同的應用程序。
This is useful if you are chaining Lambda functions or migrating an existing application to AWS Lambda.
如果您要鏈接Lambda函數或將現有應用程序遷移到AWS Lambda,這將很有用。
For example, this function invokes another Lambda function locally. Without the Lambda Simulator, the second function would be invoked in AWS.
例如,此函數在本地調用另一個Lambda函數。 如果沒有Lambda Simulator,則第二個函數將在AWS中調用。
// If offline use the local registryconst endpoint = process.env.SERVERLESS_SIMULATE ? process.env.SERVERLESS_SIMULATE_LAMBDA_ENDPOINT : undefined
// configure the AWS SDK to use the local endpointconst lambda = new AWS.Lambda({ endpoint })
const handler = (event, context, callback) => { const params = { FunctionName: 'my-other-function', Payload: JSON.stringify({ foo: 'bar' }) }
lambda.invoke(params, (err, result) => { if (err) { return callback(err) } callback(null, { statusCode: 200, body: result.Payload }) })}
使用Lambda模擬器 (Using the Lambda Simulator)
To use the Lambda simulator you need to install the plugin into your Serverless project. Please read the docs for instructions.
要使用Lambda模擬器,您需要將插件安裝到無服務器項目中。 請閱讀文檔以獲取說明。
To start the Lambda simulator run the following command:
要啟動Lambda模擬器,請運行以下命令:
sls simulate lambda -p 4000
sls simulate lambda -p 4000
To use the Lambda Simulator with the API Gateway, run the API Gateway command with --lambda-port
argument.
要將Lambda Simulator與API網關一起使用,請運行帶有--lambda-port
參數的API Gateway命令。
sls simulate apigateway -p 5000 --lambda-port
sls simulate apigateway -p 5000 --lambda-port
When using the --lambda-port
argument, the API Gateway simulator invokes functions via the HTTP API.
使用--lambda-port
參數時,API網關模擬器會通過HTTP API調用函數。
This allows you to simulate complex architectures locally before deploying to the cloud.
這使您可以在部署到云之前在本地模擬復雜的體系結構。
與其他插件的比較 (Comparison to Other Plugins)
Serverless Offline is the most popular plugin for the Serverless Framework. Unfortunately, the design of Serverless Offline limits the quality of the simulation.
Serverless Offline是Serverless Framework最受歡迎的插件。 不幸的是,無服務器脫機的設計限制了仿真的質量。
This plugin simulates API Gateway and executes functions in the plugin process. The downsides of this decision include:
該插件模擬API網關并在插件過程中執行功能。 該決定的缺點包括:
- No Python support 不支援Python
- It uses whatever NodeJS version you are running, which may not be the same NodeJS version as AWS Lambda 它使用您正在運行的任何NodeJS版本,該版本可能與AWS Lambda不同。
- It does not enforce memory limits or timeouts 它不強制執行內存限制或超時
- There is no way to chain Lambda function calls 無法鏈接Lambda函數調用
We designed Serverless Simulate to solve these problems.
我們設計了無服務器模擬來解決這些問題。
繼續建造 (Go forth and build)
This plugin will help solve a big problem for myself and the team at A Cloud Guru. Unit tests and local executions reduce the time we spend waiting for deployments to the cloud.
該插件將幫助我自己和A Cloud Guru團隊解決一個大問題。 單元測試和本地執行減少了我們花費在等待部署到云上的時間。
The Serverless Framework and Serverless Simulate are both Open Source projects. If you want to get involved, you can help by creating issues or submitting a pull request.
無服務器框架和無服務器模擬都是開源項目。 如果您想參與其中,可以通過創建問題或提交拉取請求來提供幫助。
I hope that it will help you save time when you are testing Lambda functions locally.
我希望它可以幫助您在本地測試Lambda函數時節省時間。
If you have any questions about this project or Serverless in general you can contact me on Medium or Twitter. I’ll be running a workshop at ServerlessConf Austin if you want to meet me in person.
如果您對此項目或一般無服務器有任何疑問,可以通過Medium或Twitter與我聯系。 如果您想親自見我,我將在ServerlessConf Austin舉辦一個研討會。
翻譯自: https://www.freecodecamp.org/news/how-you-can-speed-up-serverless-development-by-simulating-aws-lambda-locally-41c61a60fbae/
aws lambda