npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@stone-ton/lambda-handlers

v2.1.2

Published

Handlers for lambdas with otlp

Downloads

697

Readme

Lambda Handlers

Descrição

Esta biblioteca fornece um handler para facilitar o manejo das funções Lambda no AWS. Com a integração do OpenTelemetry, permite uma visibilidade clara das requisições, melhorando a capacidade de monitoramento e rastreamento.

Principais Características.

  • Integração nativa com OpenTelemetry para rastreamento de requisições.
  • Capacidade de adicionar body e headers de request e response ao span de um trace através da variável de ambiente OTLP_LAMBDA_DEBUG.

Como Usar

Instalação:

Para instalar via npm:

npm install @stone-ton/lambda-handlers --save

Lambda trigada pela API Gateway como proxy (múltiplas rotas numa lambda)

import { LambdaApiProxyHandler, Controller } from '@stone-ton/lambda-handlers'
import { APIGatewayProxyHandler } from 'aws-lambda'
import authentication from './authentication'
import foo from './controllers/foo'

const api = new LambdaApiProxyHandler({
  base: process.env.ADMIN_API_BASE_PATH,
})

const foo: Controller = (req) => {
  return Promise.resolve({
    body: {
      message: 'Hello World'
    },
  })
}

export const handler: APIGatewayProxyHandler = async (
  event,
  context,
) => {
  api.addRoute({
    method: 'GET',
    path: '/',
    run: foo,
    auth: authentication(['admin']),
  })

  return api.handler(event, context)
}

Lambda trigada pela API Gateway como proxy (uma rota por lambda)

import { Controller, LambdaApiHandler } from '@stone-ton/lambda-handlers'
import { APIGatewayProxyHandler } from 'aws-lambda'

const getUserController: Controller = async (request) => {
  const user = await getUser(request.params.id)

  return {
    body: user,
  }
}

const apiHandler = new LambdaApiHandler(getUserController)

export const handler: APIGatewayProxyHandler = async (
  event,
  context,
) => {
  return apiHandler.handler(event, context)
}

Lambda trigada por SQS

import { LambdaSqsHandler, Worker } from '@stone-ton/lambda-handlers'
import { SQSHandler } from 'aws-lambda'

interface CreateUserMessage {
  user_id: string
}

const workerCreateUser: Worker<CreateUserMessage> = async (messages) => {
  for (const { body } of messages) {
    const user = await getUser(body.user_id)
  }
}

const sqsHandler = new LambdaSqsHandler(workerCreateUser)

export const handler: SQSHandler = async (event, context) => {
  return sqsHandler.handler(event, context)
}

Lambda trigada por SQS (Worker com processamento em paralelo)

import { LambdaSqsHandlerV2, WorkerV2 } from '@stone-ton/lambda-handlers'
import { SQSHandler } from 'aws-lambda'

interface CreateUserMessage {
  user_id: string
}

const workerCreateUser: WorkerV2<CreateUserMessage> = async (message, logger) => {
  logger.debug('Start create user')
  const user = await getUser(body.user_id)
}

const sqsHandler = new LambdaSqsHandler({
  worker: workerCreateUser,
  parallel: false,
  service: 'migraton',
})

export const handler: SQSHandler = async (event, context) => {
  return sqsHandler.handler(event, context)
}

A LambdaSqsHandlerV2 precisa ter o Report Batch Item Failures habilitado. Abaixo exemplo com terraform:

resource "aws_lambda_event_source_mapping" "event_handler" {
  event_source_arn        = module.sqs_event_handler.sqs_arn
  function_name           = module.event_handler.arn
  batch_size              = 1
  function_response_types = ["ReportBatchItemFailures"]
}

Lambda trigada pelo sdk

import { LambdaInvokeHandler, InvokeHandler } from '@stone-ton/lambda-handlers'
import { Handler } from 'aws-lambda'

interface CreateUserRequest {
  user_id: string
}

interface CreateUserResponse {
  message: string
}

const createUserInvoke: InvokeHandler<CreateUserRequest, CreateUserResponse> = async (event, context) => {
  return {
    message: event.user_id
  }
}

const invokeHandler = new LambdaInvokeHandler(createUserInvoke)

export const handler: Handler<CreateUserRequest, CreateUserResponse> = async (event, context) => {
  return invokeHandler.handler(event, context)
}

Lambda trigada pelo cloudwatch events (cron)

import { LambdaCloudwatchHandler, CloudwatchHandler } from '@stone-ton/lambda-handlers'
import { ScheduledHandler } from 'aws-lambda'

const main: CloudwatchHandler = async (event, context) => {
}

const cwHandler = new LambdaCloudwatchHandler(main)

export const handler: ScheduledHandler = async (event, context) => {
  return cwHandler.handler(event, context)
}

Opentelemetry

Antes de começar a usar a biblioteca, certifique-se de definir as variáveis de ambiente necessárias:

  • OTLP: Deve ser definido como true para habilitar o rastreamento com OpenTelemetry.
  • OTLP_TIMEOUT: Define o limite máximo de espera em milissegundos para o envio do trace pela lambda, com o valor padrão de 200ms caso não seja definido.
  • OTLP_TRACE_URL: Deve ser definido com a URL do servidor OpenTelemetry Collector, por exemplo, localhost:4318.
  • OTLP_LAMBDA_DEBUG: Quando definido como true, acrescenta detalhes de requisição e resposta HTTP, incluindo body e headers, aos spans do handler da Lambda. Atenção à possível presença de dados sensíveis.