MIT License

技术解读

以下内容由 GitRead 中文社区 编辑团队基于项目 README 与官方资料整理, 结合中文开发者的常见使用场景补充技术选型建议。具体以项目官方文档为准。

Dazn Lambda Powertools 深度技术分析

项目背景与痛点

在 Serverless 架构下,AWS Lambda 提供了高效运行无服务器代码的能力。但随之而来的也有种种问题:例如配置混乱、日志格式不统一、难以复用基础组件等。而 Dazn Lambda Powertools 恰恰解决了这些痛点,为 Lambda 函数提供了更加高效和统一的开发、部署流程。它通过一系列工具、中间件及设计模式,提升了 Lambda 函数的可管理性和可维护性。

核心技术揭秘

Dazn Lambda Powertools 采用了一系列强化 Lambda 功能的工具,包括日志记录器、HTTP 客户端、AWS 客户端、中间件及设计模式等。其核心特点在于极高的灵活性和扩展性,用户可以根据需要自由组合使用不同的 Powertools 工具。

在嵌入式设计上,每个工具层都有规范优美的实现,如 logger 提供了灵活的日志收集功能,HTTP 客户端则封装了对 REST API 的请求,AWS 客户端则降低了调用 AWS 服务的门槛,中间件和设计模式进一步增强了 Lambda 函数的抽象复用能力。

下面是一副模拟的数据流图,展示了 Lambda 函数调用 Powertools 组件的数据流转过程:

graph TD A[Lambda 函数入口] --> B{"调用 Powertools 组件"} B -->|"Logger"| C[日志记录] B -->|"HTTP Client"| D[HTTP 请求] B -->|"Middleware"| E[拦截处理] C --> F[发送日志数据] D --> G[响应处理] E --> H[业务逻辑处理]

通过此图可见,各种工具紧密合作,构建了一个完善的 Lambda 执行环境。

功能亮点与差异

相比于其他类似工具,Dazn Lambda Powertools 的特质在于其提供了丰富的配置项和灵活的扩展特性。例如,允许开发者针对业务场景定制各种日志记录格式。同时,Powertools 完美的集成了多种 AWS 服务,降低了 AWS 服务调用难度。此外,通过定义各种中间件和设计模式,适应了 Lambda 函数的业务处理流程。

场景应用与落地建议

在使用 Dazn Lambda Powertools 时,需要充分考虑业务场景的复杂度,合理选择需要的工具组件。在生产环境中,应该格外注意日志的格式和内容,以便于进行有效故障排查和监控。此外,利用 Middleware 可针对多种业务场景设置拦截规则,优化 Lambda 函数的执行性能。

适合的场景包括处理 REST API 请求、调用多种 AWS 服务、实现日志标准化等。

综合评价

优点:

  • 统一日志记录和 AWS 服务调用,简化了 Lambda 函数的开发和维护。
  • 提供丰富的工具组件,易于扩展和定制。

缺点:

  • 设计较为复杂,初学者需花时间理解和上手。
  • 若过度配置,可能引起性能开销。

总体而言,Dazn Lambda Powertools 是具有深度思考的专业工具,能够有效提升 AWS Lambda 函数的开发效率和应用质量,对于服务器开发人员而言是一项不可或缺的工具。

关于

GitHub 原始描述(英文)

Powertools (logger, HTTP client, AWS clients, middlewares, patterns) for Lambda functions.

描述取自 GitHub 官方 API,保持仓库作者书写的原文。

简要分析

热度分
976
价值分
472
活跃状态
归档

语言占比

JavaScript
Shell

Release

README

No longer maintained

⚠️ Deprecated

This repository is no longer actively maintained and has been archived by the Security team. The repository is retained for historical and reference purposes and is read-only while archived. If this repository is required in the future, it can be unarchived. Please raise a request with the CodX team to have it unarchived.

CircleCI

DAZN Lambda Powertools

dazn-lambda-powertools is a collection of middlewares, AWS clients and helper libraries that make working with lambda easier.

Motivation

Writing Lambdas often involves the bootstrapping of specific tooling, like reading and forwarding on correlation-id’s, emitting logs on a lambda timeout, and more.

Re-writing and maintaining this bootstrapping logic into every individual lambda can be a pain, so to prevent this re-work we created dazn-lambda-powertools.

Usage

The quickest way to get setup is to use the opinionated pattern basic package.

npm install @dazn/lambda-powertools-pattern-basic

const wrap = require('@dazn/lambda-powertools-pattern-basic')

module.exports.handler = wrap(async (event, context) => {
  return 42
})

For more control, you can pick and choose from the individual packages.

Powertools and Middy

All of the powertool middlewares use the middy library (v2.x), and therefore adhere to the middy API.

However, the other tools such as the clients are generic.

What’s in Powertools

An integrated suite of powertools for Lambda functions that reduces the effort to implement common lamdba tasks, such as dealing with correlation-ids.

  • support correlation IDs

  • debug logs are turned off in production, and are instead sampled for 1% of invocations

  • debug logging decisions are respected by all the functions on a call chain

  • HTTP requests always report both latency as well as response count metrics

Overview of available tools

  • logger: structured logging with JSON, configurable log levels, and integrates with other tools to support correlation IDs and sampling (only enable debug logs on 1% of invocations)

  • correlation IDs: create and store correlation IDs that follow the DAZN naming convention

  • correlation IDs middleware: automatically extract correlation IDs from the invocation event

  • sample logging middleware: enable debug logging for 1% of invocations, or when upstream caller has made the decision to enable debug logging

  • obfuscater middleware: allows you to obfuscate the invocation event so that sensitive data (e.g. PII) is not logged accidentally

  • log timeout middleware: logs an error message when a function invocation times out

  • stop infinite loop middleware: stops infinite loops

Client libraries

  • http client: HTTP client that automatically forwards any correlation IDs you have captured or created, and records both latency as well as response count metrics

  • CloudWatchEvents client: CloudWatchEvents client that automatically forwards any correlation IDs you have captured or created when you put events to an event bus

  • EventBridge client: EventBridge client that automatically forwards any correlation IDs you have captured or created when you put events to an event bus

  • SNS client: SNS client that automatically forwards any correlation IDs you have captured or created when you publish a message to SNS

  • SQS client: SQS client that automatically forwards any correlation IDs you have captured or created when you publish a message to SQS

  • Kinesis client: Kinesis client that automatically forwards any correlation IDs you have captured or created when you publish record(s) to a Kinesis stream

  • Firehose client: Firehose client that automatically forwards any correlation IDs you have captured or created when you publish record(s) to a Firehose delivery stream

  • Step Functions client: Step Functions client that automatically forwards any correlation IDs you have captured or created when you start an execution

  • Lambda client: Lambda client that automatically forwards any correlation IDs you have captured or created when you invokes a Lambda function directly

  • DynamoDB client: DynamoDB client that automatically forwards any correlation IDs you have captured or created when you perform put or update operations against DynamoDB. These correlation IDs are then available to functions processing these events from the table’s DynamoDB Stream.

Patterns

  • basic template for a function: wrapper for your function that applies and configures the function to work well with datadog metrics and sample logging

  • obfuscate template: basic template (above) + obfuscate the invocation event so sensitive data is obfuscated in the after and onError handlers.

Installing the powertools

via NPM

Package Install command
cloudwatchevents-client npm install @dazn/lambda-powertools-cloudwatchevents-client
correlation-ids npm install @dazn/lambda-powertools-correlation-ids
dynamodb-client npm install @dazn/lambda-powertools-dynamodb-client
eventbridge-client npm install @dazn/lambda-powertools-eventbridge-client
firehose-client npm install @dazn/lambda-powertools-firehose-client
http-client npm install @dazn/lambda-powertools-http-client
kinesis-client npm install @dazn/lambda-powertools-kinesis-client
lambda-client npm install @dazn/lambda-powertools-lambda-client
logger npm install @dazn/lambda-powertools-logger
middleware-correlation-ids npm install @dazn/lambda-powertools-middleware-correlation-ids
middleware-log-timeout npm install @dazn/lambda-powertools-middleware-log-timeout
middleware-obfuscater npm install @dazn/lambda-powertools-middleware-obfuscater
middleware-sample-logging npm install @dazn/lambda-powertools-middleware-sample-logging
middleware-stop-infinite-loop npm install @dazn/lambda-powertools-middleware-stop-infinite-loop
pattern-basic npm install @dazn/lambda-powertools-pattern-basic
pattern-obfuscate npm install @dazn/lambda-powertools-pattern-obfuscate
sns-client npm install @dazn/lambda-powertools-sns-client
sqs-client npm install @dazn/lambda-powertools-sqs-client
step-functions-client npm install @dazn/lambda-powertools-step-functions-client

via Lambda layer

You can also deploy the layer via our SAR app, which you can deploy either via this page (click Deploy and follow the instructions) or using CloudFormation/Serverless framework/AWS SAM:

DaznLambdaPowertoolsLayer:
  Type: AWS::Serverless::Application
  Properties:
    Location:
      ApplicationId: arn:aws:serverlessrepo:us-east-1:570995107280:applications/dazn-lambda-powertools
      SemanticVersion: <enter latest version>

and reference the output Outputs.LayerVersion to get the ARN of the layer to reference in your function. e.g. Fn::GetAtt: [DaznLambdaPowertoolsLayer, Outputs.LayerVersion].

You can find the latest version of the SAR app in the lerna.json file here, in the version property.

Design goal

Compliance with best practices around logging and monitoring should be the default behaviour. These tools make it simple for you to do the right thing and gets out of your way as much as possible.

Individually they are useful in their own right, but together they’re so much more useful!

The middlewares capture incoming correlation IDs, and the logger automatically includes them in every log message, and the other clients (HTTP, Kinesis, SNS, etc.) would also automatically forward them on to external systems.

Even if your function doesn’t do anything with correlation IDs, the tools make sure that it behaves correctly as these correlation IDs flow through it.

Did you consider monkey-patching the clients instead?

Instead of forcing you to use dazn-powertools AWS clients, we could have monkey patched the AWS SDK clients (which we already do in the tests). We could also monkey patch Node’s http module (like what Nock does) to intercept HTTP requests and inject correlation IDs as HTTP headers.

We could apply the monkey patching when you apply the correlation IDs middleware, and your function would “automagically” forward correlation IDs without having to use our own client libraries. That way, as a user of the tools, you could use whatever HTTP client you wish, and can use the standard SDK clients as well.

We did entertain this idea, but I wanted to leave at least one decision for you to make. The rationale is that when things go wrong (e.g. unhandled error, or bug in our wrapper code) or when they don’t work as expected (e.g. you’re using an AWS SDK client that we don’t support yet), at least you have that one decision to start debugging (change the require statement to use the official library instead of our own to see if things things still work).

Useful commands

bootstrapping locally

Because of the inter-dependencies between packages, it can be tricky to test your changes haven’t broken another package.

You can use Lerna CLI to bootstrap all the dependencies with the current local version:

lerna bootstrap

run all tests

npm test

run tests for a specific package

PKG=correlation-ids npm run test-package

create a new package

lerna create <name of package>

and follow the instruction to bootstrap the new project.

Contributing

Please read our contribution guide to see how you can contribute towards this project.

评论

暂无评论