Skip to content
Myr

handler.ts

This file

Path

src/adapter/aws-lambda/handler.ts

680 lines 路 19.9 KiB 路 TypeScript

Last changed by

chore: bump linter and formatter (#4568)ryubefore adoptionb6f4bcd

History of this file

Take it

1import type { Hono } from '../../hono'2import type { Env, Schema } from '../../types'3import { decodeBase64, encodeBase64 } from '../../utils/encode'4import type {5  ALBRequestContext,6  ApiGatewayRequestContext,7  ApiGatewayRequestContextV2,8  Handler,9  LambdaContext,10  LatticeRequestContextV2,11} from './types'1213function sanitizeHeaderValue(value: string): string {14  // Check if the value contains non-ASCII characters (char codes > 127)15  // eslint-disable-next-line no-control-regex16  const hasNonAscii = /[^\x00-\x7F]/.test(value)17  if (!hasNonAscii) {18    return value19  }20  return encodeURIComponent(value)21}2223export type LambdaEvent =24  | APIGatewayProxyEvent25  | APIGatewayProxyEventV226  | ALBProxyEvent27  | LatticeProxyEventV22829export interface LatticeProxyEventV2 {30  version: string31  path: string32  method: string33  headers: Record<string, string[] | undefined>34  queryStringParameters: Record<string, string[] | undefined>35  body: string | null36  isBase64Encoded: boolean37  requestContext: LatticeRequestContextV238}3940// When calling HTTP API or Lambda directly through function urls41export interface APIGatewayProxyEventV2 {42  version: string43  routeKey: string44  headers: Record<string, string | undefined>45  multiValueHeaders?: undefined46  cookies?: string[]47  rawPath: string48  rawQueryString: string49  body: string | null50  isBase64Encoded: boolean51  requestContext: ApiGatewayRequestContextV252  queryStringParameters?: {53    [name: string]: string | undefined54  }55  pathParameters?: {56    [name: string]: string | undefined57  }58  stageVariables?: {59    [name: string]: string | undefined60  }61}6263// When calling Lambda through an API Gateway64export interface APIGatewayProxyEvent {65  version: string66  httpMethod: string67  headers: Record<string, string | undefined>68  multiValueHeaders?: {69    [headerKey: string]: string[]70  }71  path: string72  body: string | null73  isBase64Encoded: boolean74  queryStringParameters?: Record<string, string | undefined>75  requestContext: ApiGatewayRequestContext76  resource: string77  multiValueQueryStringParameters?: {78    [parameterKey: string]: string[]79  }80  pathParameters?: Record<string, string>81  stageVariables?: Record<string, string>82}8384// When calling Lambda through an Application Load Balancer85export interface ALBProxyEvent {86  httpMethod: string87  headers?: Record<string, string | undefined>88  multiValueHeaders?: Record<string, string[] | undefined>89  path: string90  body: string | null91  isBase64Encoded: boolean92  queryStringParameters?: Record<string, string | undefined>93  multiValueQueryStringParameters?: {94    [parameterKey: string]: string[]95  }96  requestContext: ALBRequestContext97}9899type WithHeaders = {100  headers: Record<string, string>101  multiValueHeaders?: undefined102}103type WithMultiValueHeaders = {104  headers?: undefined105  multiValueHeaders: Record<string, string[]>106}107108export type APIGatewayProxyResult = {109  statusCode: number110  statusDescription?: string111  body: string112  cookies?: string[]113  isBase64Encoded: boolean114} & (WithHeaders | WithMultiValueHeaders)115116const getRequestContext = (117  event: LambdaEvent118):119  | ApiGatewayRequestContext120  | ApiGatewayRequestContextV2121  | ALBRequestContext122  | LatticeRequestContextV2 => {123  return event.requestContext124}125126const streamToNodeStream = async (127  reader: ReadableStreamDefaultReader<Uint8Array>,128  writer: NodeJS.WritableStream129): Promise<void> => {130  let readResult = await reader.read()131  while (!readResult.done) {132    writer.write(readResult.value)133    readResult = await reader.read()134  }135  writer.end()136}137138export const streamHandle = <139  E extends Env = Env,140  S extends Schema = {},141  BasePath extends string = '/',142>(143  app: Hono<E, S, BasePath>144): Handler => {145  // @ts-expect-error awslambda is not a standard API146  return awslambda.streamifyResponse(147    async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {148      const processor = getProcessor(event)149      try {150        const req = processor.createRequest(event)151        const requestContext = getRequestContext(event)152153        const res = await app.fetch(req, {154          event,155          requestContext,156          context,157        })158159        const headers: Record<string, string> = {}160        const cookies: string[] = []161        res.headers.forEach((value, name) => {162          if (name === 'set-cookie') {163            cookies.push(value)164          } else {165            headers[name] = value166          }167        })168169        // Check content type170        const httpResponseMetadata = {171          statusCode: res.status,172          headers,173          cookies,174        }175176        // Update response stream177        // @ts-expect-error awslambda is not a standard API178        responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)179180        if (res.body) {181          await streamToNodeStream(res.body.getReader(), responseStream)182        } else {183          responseStream.write('')184        }185      } catch (error) {186        console.error('Error processing request:', error)187        responseStream.write('Internal Server Error')188      } finally {189        responseStream.end()190      }191    }192  )193}194195type HandleOptions = {196  isContentTypeBinary: ((contentType: string) => boolean) | undefined197}198199/**200 * Converts a Hono application to an AWS Lambda handler.201 *202 * Accepts events from API Gateway (v1 and v2), Application Load Balancer (ALB),203 * and Lambda Function URLs.204 *205 * @param app - The Hono application instance206 * @param options - Optional configuration207 * @param options.isContentTypeBinary - A function to determine if the content type is binary.208 *                                      If not provided, the default function will be used.209 * @returns Lambda handler function210 *211 * @example212 * ```js213 * import { Hono } from 'hono'214 * import { handle } from 'hono/aws-lambda'215 *216 * const app = new Hono()217 *218 * app.get('/', (c) => c.text('Hello from Lambda'))219 * app.get('/json', (c) => c.json({ message: 'Hello JSON' }))220 *221 * export const handler = handle(app)222 * ```223 *224 * @example225 * ```js226 * // With custom binary content type detection227 * import { handle, defaultIsContentTypeBinary } from 'hono/aws-lambda'228 * export const handler = handle(app, {229 *   isContentTypeBinary: (contentType) => {230 *     if (defaultIsContentTypeBinary(contentType)) {231 *       // default logic same as prior to v4.8.4232 *       return true233 *     }234 *     return contentType.startsWith('image/') || contentType === 'application/pdf'235 *   }236 * })237 * ```238 */239export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(240  app: Hono<E, S, BasePath>,241  { isContentTypeBinary }: HandleOptions = { isContentTypeBinary: undefined }242): (<L extends LambdaEvent>(243  event: L,244  lambdaContext?: LambdaContext245) => Promise<246  APIGatewayProxyResult &247    (L extends { multiValueHeaders: Record<string, string[]> }248      ? WithMultiValueHeaders249      : WithHeaders)250>) => {251  // @ts-expect-error FIXME: Fix return typing252  return async (event, lambdaContext?) => {253    const processor = getProcessor(event)254255    const req = processor.createRequest(event)256    const requestContext = getRequestContext(event)257258    const res = await app.fetch(req, {259      event,260      requestContext,261      lambdaContext,262    })263264    return processor.createResult(event, res, { isContentTypeBinary })265  }266}267268export abstract class EventProcessor<E extends LambdaEvent> {269  protected abstract getPath(event: E): string270271  protected abstract getMethod(event: E): string272273  protected abstract getQueryString(event: E): string274275  protected abstract getHeaders(event: E): Headers276277  protected abstract getCookies(event: E, headers: Headers): void278279  protected abstract setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void280281  protected getHeaderValue(headers: E['headers'], key: string): string | undefined {282    const value = headers283      ? Array.isArray(headers[key])284        ? headers[key][0]285        : headers[key]286      : undefined287288    return value289  }290291  protected getDomainName(event: E): string | undefined {292    if (event.requestContext && 'domainName' in event.requestContext) {293      return event.requestContext.domainName294    }295296    const hostFromHeaders = this.getHeaderValue(event.headers, 'host')297298    if (hostFromHeaders) {299      return hostFromHeaders300    }301302    const multiValueHeaders = 'multiValueHeaders' in event ? event.multiValueHeaders : {}303    const hostFromMultiValueHeaders = this.getHeaderValue(multiValueHeaders, 'host')304305    return hostFromMultiValueHeaders306  }307308  createRequest(event: E): Request {309    const queryString = this.getQueryString(event)310    const domainName = this.getDomainName(event)311    const path = this.getPath(event)312    const urlPath = `https://${domainName}${path}`313    const url = queryString ? `${urlPath}?${queryString}` : urlPath314315    const headers = this.getHeaders(event)316317    const method = this.getMethod(event)318    const requestInit: RequestInit = {319      headers,320      method,321    }322323    if (event.body) {324      requestInit.body = event.isBase64Encoded ? decodeBase64(event.body) : event.body325    }326327    return new Request(url, requestInit)328  }329330  async createResult(331    event: E,332    res: Response,333    options: Pick<HandleOptions, 'isContentTypeBinary'>334  ): Promise<APIGatewayProxyResult> {335    // determine whether the response body should be base64 encoded336    const contentType = res.headers.get('content-type')337    const isContentTypeBinary = options.isContentTypeBinary ?? defaultIsContentTypeBinary // overwrite default function if provided338    let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false339340    if (!isBase64Encoded) {341      const contentEncoding = res.headers.get('content-encoding')342      isBase64Encoded = isContentEncodingBinary(contentEncoding)343    }344345    const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()346347    const result: APIGatewayProxyResult = {348      body: body,349      statusCode: res.status,350      isBase64Encoded,351      ...('multiValueHeaders' in event && event.multiValueHeaders352        ? {353            multiValueHeaders: {},354          }355        : {356            headers: {},357          }),358    }359360    this.setCookies(event, res, result)361    if (result.multiValueHeaders) {362      res.headers.forEach((value, key) => {363        result.multiValueHeaders[key] = [value]364      })365    } else {366      res.headers.forEach((value, key) => {367        result.headers[key] = value368      })369    }370371    return result372  }373374  setCookies(event: E, res: Response, result: APIGatewayProxyResult) {375    if (res.headers.has('set-cookie')) {376      const cookies = res.headers.getSetCookie377        ? res.headers.getSetCookie()378        : Array.from(res.headers.entries())379            .filter(([k]) => k === 'set-cookie')380            .map(([, v]) => v)381382      if (Array.isArray(cookies)) {383        this.setCookiesToResult(result, cookies)384        res.headers.delete('set-cookie')385      }386    }387  }388}389390export class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {391  protected getPath(event: APIGatewayProxyEventV2): string {392    return event.rawPath393  }394395  protected getMethod(event: APIGatewayProxyEventV2): string {396    return event.requestContext.http.method397  }398399  protected getQueryString(event: APIGatewayProxyEventV2): string {400    return event.rawQueryString401  }402403  protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {404    if (Array.isArray(event.cookies)) {405      headers.set('Cookie', event.cookies.join('; '))406    }407  }408409  protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {410    result.cookies = cookies411  }412413  protected getHeaders(event: APIGatewayProxyEventV2): Headers {414    const headers = new Headers()415    this.getCookies(event, headers)416    if (event.headers) {417      for (const [k, v] of Object.entries(event.headers)) {418        if (v) {419          headers.set(k, v)420        }421      }422    }423    return headers424  }425}426427const v2Processor: EventV2Processor = new EventV2Processor()428429export class EventV1Processor extends EventProcessor<APIGatewayProxyEvent> {430  protected getPath(event: APIGatewayProxyEvent): string {431    return event.path432  }433434  protected getMethod(event: APIGatewayProxyEvent): string {435    return event.httpMethod436  }437438  protected getQueryString(event: APIGatewayProxyEvent): string {439    // In the case of gateway Integration either queryStringParameters or multiValueQueryStringParameters can be present not both440    // API Gateway passes decoded values, so we need to re-encode them to preserve the original URL441    if (event.multiValueQueryStringParameters) {442      return Object.entries(event.multiValueQueryStringParameters || {})443        .filter(([, value]) => value)444        .map(([key, values]) =>445          values.map((value) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&')446        )447        .join('&')448    } else {449      return Object.entries(event.queryStringParameters || {})450        .filter(([, value]) => value)451        .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value || '')}`)452        .join('&')453    }454  }455456  protected getCookies(457    // eslint-disable-next-line @typescript-eslint/no-unused-vars458    event: APIGatewayProxyEvent,459    // eslint-disable-next-line @typescript-eslint/no-unused-vars460    headers: Headers461  ): void {462    // nop463  }464465  protected getHeaders(event: APIGatewayProxyEvent): Headers {466    const headers = new Headers()467    this.getCookies(event, headers)468    if (event.headers) {469      for (const [k, v] of Object.entries(event.headers)) {470        if (v) {471          headers.set(k, sanitizeHeaderValue(v))472        }473      }474    }475    if (event.multiValueHeaders) {476      for (const [k, values] of Object.entries(event.multiValueHeaders)) {477        if (values) {478          // avoid duplicating already set headers479          const foundK = headers.get(k)480          values.forEach((v) => {481            const sanitizedValue = sanitizeHeaderValue(v)482            return (483              (!foundK || !foundK.includes(sanitizedValue)) && headers.append(k, sanitizedValue)484            )485          })486        }487      }488    }489    return headers490  }491492  protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {493    result.multiValueHeaders = {494      'set-cookie': cookies,495    }496  }497}498499const v1Processor: EventV1Processor = new EventV1Processor()500501export class ALBProcessor extends EventProcessor<ALBProxyEvent> {502  protected getHeaders(event: ALBProxyEvent): Headers {503    const headers = new Headers()504    // if multiValueHeaders is present the ALB will use it instead of the headers field505    // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers506    if (event.multiValueHeaders) {507      for (const [key, values] of Object.entries(event.multiValueHeaders)) {508        if (values && Array.isArray(values)) {509          // https://www.rfc-editor.org/rfc/rfc9110.html#name-common-rules-for-defining-f510          const sanitizedValue = sanitizeHeaderValue(values.join('; '))511          headers.set(key, sanitizedValue)512        }513      }514    } else {515      for (const [key, value] of Object.entries(event.headers ?? {})) {516        if (value) {517          headers.set(key, sanitizeHeaderValue(value))518        }519      }520    }521    return headers522  }523524  protected getPath(event: ALBProxyEvent): string {525    return event.path526  }527528  protected getMethod(event: ALBProxyEvent): string {529    return event.httpMethod530  }531532  protected getQueryString(event: ALBProxyEvent): string {533    // In the case of ALB Integration either queryStringParameters or multiValueQueryStringParameters can be present not both534    /*535      In other cases like when using the serverless framework, the event object does contain both queryStringParameters and multiValueQueryStringParameters:536      Below is an example event object for this URL: /payment/b8c55e69?select=amount&select=currency537      {538        ...539        queryStringParameters: { select: 'currency' },540        multiValueQueryStringParameters: { select: [ 'amount', 'currency' ] },541      }542      The expected results is for select to be an array with two items. However the pre-fix code is only returning one item ('currency') in the array.543      A simple fix would be to invert the if statement and check the multiValueQueryStringParameters first.544    */545    if (event.multiValueQueryStringParameters) {546      return Object.entries(event.multiValueQueryStringParameters || {})547        .filter(([, value]) => value)548        .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)549        .join('&')550    } else {551      return Object.entries(event.queryStringParameters || {})552        .filter(([, value]) => value)553        .map(([key, value]) => `${key}=${value}`)554        .join('&')555    }556  }557558  protected getCookies(event: ALBProxyEvent, headers: Headers): void {559    let cookie560    if (event.multiValueHeaders) {561      cookie = event.multiValueHeaders['cookie']?.join('; ')562    } else {563      cookie = event.headers ? event.headers['cookie'] : undefined564    }565    if (cookie) {566      headers.append('Cookie', cookie)567    }568  }569570  protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {571    // when multi value headers is enabled572    if (result.multiValueHeaders) {573      result.multiValueHeaders['set-cookie'] = cookies574    } else {575      // otherwise serialize the set-cookie576      result.headers['set-cookie'] = cookies.join(', ')577    }578  }579}580581const albProcessor: ALBProcessor = new ALBProcessor()582583export class LatticeV2Processor extends EventProcessor<LatticeProxyEventV2> {584  protected getPath(event: LatticeProxyEventV2): string {585    return event.path586  }587588  protected getMethod(event: LatticeProxyEventV2): string {589    return event.method590  }591592  protected getQueryString(): string {593    return ''594  }595596  protected getHeaders(event: LatticeProxyEventV2): Headers {597    const headers = new Headers()598599    if (event.headers) {600      for (const [k, values] of Object.entries(event.headers)) {601        if (values) {602          // avoid duplicating already set headers603          const foundK = headers.get(k)604          values.forEach((v) => {605            const sanitizedValue = sanitizeHeaderValue(v)606            return (607              (!foundK || !foundK.includes(sanitizedValue)) && headers.append(k, sanitizedValue)608            )609          })610        }611      }612    }613614    return headers615  }616617  protected getCookies(): void {618    // nop619  }620621  protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {622    result.headers = {623      ...result.headers,624      'set-cookie': cookies.join(', '),625    }626  }627}628629const latticeV2Processor: LatticeV2Processor = new LatticeV2Processor()630631export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {632  if (isProxyEventALB(event)) {633    return albProcessor634  }635  if (isProxyEventV2(event)) {636    return v2Processor637  }638  if (isLatticeEventV2(event)) {639    return latticeV2Processor640  }641642  return v1Processor643}644645const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {646  if (event.requestContext) {647    return Object.hasOwn(event.requestContext, 'elb')648  }649  return false650}651652const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {653  return Object.hasOwn(event, 'rawPath')654}655656const isLatticeEventV2 = (event: LambdaEvent): event is LatticeProxyEventV2 => {657  if (event.requestContext) {658    return Object.hasOwn(event.requestContext, 'serviceArn')659  }660  return false661}662663/**664 * Check if the given content type is binary.665 * This is a default function and may be overwritten by the user via `isContentTypeBinary` option in handler().666 * @param contentType The content type to check.667 * @returns True if the content type is binary, false otherwise.668 */669export const defaultIsContentTypeBinary = (contentType: string): boolean => {670  return !/^text\/(?:plain|html|css|javascript|csv)|(?:\/|\+)(?:json|xml)\s*(?:;|$)/.test(671    contentType672  )673}674675export const isContentEncodingBinary = (contentEncoding: string | null) => {676  if (contentEncoding === null) {677    return false678  }679  return /^(gzip|deflate|compress|br)/.test(contentEncoding)680}