当前位置:网站首页>On lambda powertools typescript

On lambda powertools typescript

2022-04-23 16:57:00 Amazon cloud developer

Statement :

In this paper, from DEV Community Website , Article translation is provided by the developer community ;

Click on the link below , Check the English text :

2022 year 1 month 5 Japan ,AWS Senior solution architect Sara Gerion announce ,Lambda Powertools TypeScript It has entered the public testing stage .Lambda Powertools It's a by AWS Sponsored open source projects , Designed to use AWS Lambda Optimize the developer experience and adopt best practices .Lambda Powertools TypeScript Joined the Java and Python Lambda Powertools library .

Catalog

Node.js Tooling for Lambda

I am a TypeScript Fans of , In fact, I co authored a book on TypeScript The book of . I don't use it very often Java or Python, therefore , Although I am Lambda Powertools Very interested , But I haven't tried to use it until now .Lambda Powertools TypeScript、middy and DAZN Lambda Powertools It's all running Node.js Of Lambda Tools .Lambda Powertools TypeScript Two differences from similar libraries are , The former is made up of AWS Sponsored by , And support decorator.

Lambda Powertools TypeScript Support at the same time JavaScript AWS SDK v2 and v3 edition , Examples of both versions will be given .

Decorators

Everyone to decorator Different views , But I think they are useful abstractions , And in object-oriented TypeScript Medium to large use . However , stay TypeScript There is a considerable constraint in , That's it decorator Can be placed on class methods , But you can't put it on a function . It means , Code like this can't be implemented yet .

That's a pity , Because it can provide a good developer experience . In order to doSomethingGreat decorator Add to our handler , We need to write some code like the following .

This is an additional five lines of code , Maybe it's not a big problem . No matter what ,Powertools There's not much a team can do , Because the function supports decorator It may have to wait a few years before . please remember , If we choose to Lambda Use in decorator And the class , We need to be careful Refer to this document .

( If not used deno)Lambda China does not support it. decorator and TypeScript, So if you want to run decorator and TypeScript, We also need a translation step . Fortunately, , about AWS CDK、AWS SAM For users without a server framework , This problem has been basically solved . If you plan or need to launch your own decorator and TypeScript,esbuild It's a good start , Seems to be the first choice bundler.

Don't use Decorators

We might as well choose not to use classes or transcoders .Lambda Powertools TypeScript May not be used decorator, In fact, you don't need TypeScript. We can go through vanilla Node.js Use the library .

Lambda Powertools TypeScript  file very nice , There are several examples ,GitHub  There are more examples on .

function

Three versions Lambda Powertools All will Metrics、Logger and Tracer As a core tool .Lambda Powertools Python Contains a Event Handler And some other useful tools , Support batch processing 、 Ineffectiveness 、 Validation etc. .

Lambda Powertools Each version of is developed independently , Its function is customized according to the different needs of different running times . The difference lies in ,AWS CDK Use jsii Publish the same structure to multiple runtimes . While waiting for certain features can be frustrating , But that's the right thing to do , Because if you compile general code into custom code that can decorate multiple runtime , It just adds complexity .

For testing , I implemented... In a sample project Lambda Powertools TypeScript All three utilities . I chose  CDK Async Testing  project , Because it contains several Lambda function , And by EventBridge and Step Functions Asynchronous workflow .

You can click on the here Check out my instrument Code .

Tracer

To pass through Tracer Come on instrument My function , I need to rewrite them as classes . I chose to use decorator, Because I haven't decided whether to use all classes , So I need to explore . I started from collect.ts Start , The following is the initial of the function 11 Line code .

The following is to include Tracer And refactoring .

The function now has 25 Line code , It's not terrible . Join in Metrics and Logger After the tool , It turns out to be 33 That's ok . Of course , My function will be bigger , Because it has more functions . We should think of this increase as an addition , Not multiplication . my 11 The line of code function becomes 25 That's ok . If it initially had 111 That's ok , It will increase to 125 That's ok , Instead of doubling .

that , What's the result ?Tracer The module encapsulates AWS X-Ray SDK( As a horizontal dependency ). It doesn't add any new features , But to make SDK Easier to use . According to my experience , This SDK It's a bit of a hassle to use , So it's worth it . We can decorate class methods , Introduce a new trace segment in one line of code . We can also use the form of commands to add new traces where we think it appropriate . We can capture AWS client , But it will expose X-Ray SDK.

There is still one point that has not been resolved , That's using X-Ray SDK and DynamoDB DocumentClient It's weird . In the use of DocumentClient and X-Ray when , We need a little flexibility , because SDK Need to access DocumentClient Service properties , But this is not reflected in the type . The following is my solution to this problem .

to update ! The question is 0.5.0 It has been solved in the version ! The above code can now be written like this :

Thank you very much for this rapid improvement ! Now my DX It's better , Here's my app .

Original text

Not only did I get a great service map , And detailed tracking .

Tracer The module is adding... On these screenshots ##index.handler part . I want to add more tracking to make better use of this tool . in general , It is quite impressive to get these detailed traces of the application through all functions and services , It's also very useful . Most of the work is done by X-Ray complete , But a better developer experience means we have to instrument More apps , This is certainly a good thing .

What I want to say here is , Tracking also includes logs ,instrument The log of the program segment is located at CloudWatch Tracking in .

That's also great . I can do it in a distributed way 、 Write application code using single purpose functions , But be able to control the whole situation when executing the program .

As long as we set a sampling rate for high-throughput applications ,X-Ray The price of the service will be very low . Pricing seems to be based on tracking , So adding extra code snippets to the trace doesn't increase the cost .

Logger

Logger The tool can directly replace any recorder , Including the console .Logger The added value of is to be able to Lambda Context is injected into all log information . When we use @logger.injectLambdaContext() to handler method add comments of explanations , And then use logger.info, We will see the following log message :

If we plan to extract logs into the search index , Or if you just want to use CloudWatch Logs Insights, It's really convenient , Because this structure helps us search and filter log information . On the other hand , If we just look up a small amount of log information , It may be a little complicated . We should remember , Any log service ( Include CloudWatch) It's all billed by volume , Extremely lengthy logs can be costly .

Consider this ,Logger The tool has many good functions , We can build logs as we like . Besides ,Logger It also includes a sampling rate function , To reduce costs .

By default , The logger method requires one or more parameters . The first parameter is a string or an object with a message key . I find , If I take a string as a subsequent parameter , Then the string will be converted into an array of characters and printed out , So this point needs attention .

Metrics

Metrics The purpose of the tool is to publish custom CloudWatch indicators . Even though Lambda Some useful indicators will be published automatically , Like delay 、 Concurrent execution 、 Throttling, etc , However, user-defined indicators can add related business events to the indicators , Achieve observability .

Tracking reliability is very important , But it doesn't mean all ! User defined indicators should be the most important indicators . How many customers have registered this week ? How many of them can complete valuable workflows ? The answers to these questions are in the code , If we send a custom indicator , They will also appear in our dashboard .

User defined indicators Pricing structure It can be very expensive . Embedded indicator format Help manage costs , And is made up of Lambda Powertools TypeScript Support . This document Is also very clear , I don't need to elaborate too much . Let's take a look at the actual experience . I give collectionSuccess The function adds a "collectionSuccess " Custom metrics for . In my hypothetical application , Will collect part of the payment , Here I mark whether the collection can be paid .

add to @metrics.logMetrics Will cause any indicators we send to be recorded in CloudWatch.( Considering the cost ) We may hope that , Or maybe not . To add a custom indicator , We just need to use metrics.addMetric.

I've done... On my app instrument, To launch the cold start index , And other custom indicators that describe important events in the application , For example, success / Failed payments / collection . Because the focus of my application is to demonstrate integration testing , So I also set custom indicators , To display the running time of the test .

These indicators can be found in CloudWatch Metrics Find , Located on the instrument panel or through API Export to third-party tools .

Package Size

Increased capacity of all tools added to the project , Uncompressed is 600kb, After compression is 200kb. Consider its value and link some dependencies to AWS SDK or X-Ray SDK The need in , It seems reasonable , And the team has done a good job in implementing its lean purpose .

summary

Lambda Powertools Focus on the tools that developers really need , Ability to optimize applications and follow best practices . The core modules focus on observability , This is necessary , It is also commendable . The team developed API, Whether it's for the use of decorator The developer of the , Still don't use decorator All developers are attractive .

I hope this library can be popularized as soon as possible , I will pay attention to The roadmap , Follow up progress , And get involved .

The authors :Matt Morgan

Matt Morgan for AWS Community Builders

版权声明
本文为[Amazon cloud developer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231338177752.html