Skip to content
Myr

handler.ts

This file

Path

src/adapter/aws-lambda/handler.ts

504 lines · 14.9 KiB · TypeScript

Last changed by

fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5

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} from './types'1112export type LambdaEvent = APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent1314// When calling HTTP API or Lambda directly through function urls15export interface APIGatewayProxyEventV2 {16  version: string17  routeKey: string18  headers: Record<string, string | undefined>19  multiValueHeaders?: undefined20  cookies?: string[]21  rawPath: string22  rawQueryString: string23  body: string | null24  isBase64Encoded: boolean25  requestContext: ApiGatewayRequestContextV226  queryStringParameters?: {27    [name: string]: string | undefined28  }29  pathParameters?: {30    [name: string]: string | undefined31  }32  stageVariables?: {33    [name: string]: string | undefined34  }35}3637// When calling Lambda through an API Gateway38export interface APIGatewayProxyEvent {39  version: string40  httpMethod: string41  headers: Record<string, string | undefined>42  multiValueHeaders?: {43    [headerKey: string]: string[]44  }45  path: string46  body: string | null47  isBase64Encoded: boolean48  queryStringParameters?: Record<string, string | undefined>49  requestContext: ApiGatewayRequestContext50  resource: string51  multiValueQueryStringParameters?: {52    [parameterKey: string]: string[]53  }54  pathParameters?: Record<string, string>55  stageVariables?: Record<string, string>56}5758// When calling Lambda through an Application Load Balancer59export interface ALBProxyEvent {60  httpMethod: string61  headers?: Record<string, string | undefined>62  multiValueHeaders?: Record<string, string[] | undefined>63  path: string64  body: string | null65  isBase64Encoded: boolean66  queryStringParameters?: Record<string, string | undefined>67  multiValueQueryStringParameters?: {68    [parameterKey: string]: string[]69  }70  requestContext: ALBRequestContext71}7273type WithHeaders = {74  headers: Record<string, string>75  multiValueHeaders?: undefined76}77type WithMultiValueHeaders = {78  headers?: undefined79  multiValueHeaders: Record<string, string[]>80}8182export type APIGatewayProxyResult = {83  statusCode: number84  statusDescription?: string85  body: string86  cookies?: string[]87  isBase64Encoded: boolean88} & (WithHeaders | WithMultiValueHeaders)8990const getRequestContext = (91  event: LambdaEvent92): ApiGatewayRequestContext | ApiGatewayRequestContextV2 | ALBRequestContext => {93  return event.requestContext94}9596const streamToNodeStream = async (97  reader: ReadableStreamDefaultReader<Uint8Array>,98  writer: NodeJS.WritableStream99): Promise<void> => {100  let readResult = await reader.read()101  while (!readResult.done) {102    writer.write(readResult.value)103    readResult = await reader.read()104  }105  writer.end()106}107108export const streamHandle = <109  E extends Env = Env,110  S extends Schema = {},111  BasePath extends string = '/'112>(113  app: Hono<E, S, BasePath>114): Handler => {115  // @ts-expect-error awslambda is not a standard API116  return awslambda.streamifyResponse(117    async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {118      const processor = getProcessor(event)119      try {120        const req = processor.createRequest(event)121        const requestContext = getRequestContext(event)122123        const res = await app.fetch(req, {124          event,125          requestContext,126          context,127        })128129        const headers: Record<string, string> = {}130        const cookies: string[] = []131        res.headers.forEach((value, name) => {132          if (name === 'set-cookie') {133            cookies.push(value)134          } else {135            headers[name] = value136          }137        })138139        // Check content type140        const httpResponseMetadata = {141          statusCode: res.status,142          headers,143          cookies,144        }145146        // Update response stream147        // @ts-expect-error awslambda is not a standard API148        responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)149150        if (res.body) {151          await streamToNodeStream(res.body.getReader(), responseStream)152        } else {153          responseStream.write('')154        }155      } catch (error) {156        console.error('Error processing request:', error)157        responseStream.write('Internal Server Error')158      } finally {159        responseStream.end()160      }161    }162  )163}164165/**166 * Accepts events from API Gateway/ELB(`APIGatewayProxyEvent`) and directly through Function Url(`APIGatewayProxyEventV2`)167 */168export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(169  app: Hono<E, S, BasePath>170): (<L extends LambdaEvent>(171  event: L,172  lambdaContext?: LambdaContext173) => Promise<174  APIGatewayProxyResult &175    (L extends { multiValueHeaders: Record<string, string[]> }176      ? WithMultiValueHeaders177      : WithHeaders)178>) => {179  // @ts-expect-error FIXME: Fix return typing180  return async (event, lambdaContext?) => {181    const processor = getProcessor(event)182183    const req = processor.createRequest(event)184    const requestContext = getRequestContext(event)185186    const res = await app.fetch(req, {187      event,188      requestContext,189      lambdaContext,190    })191192    return processor.createResult(event, res)193  }194}195196export abstract class EventProcessor<E extends LambdaEvent> {197  protected abstract getPath(event: E): string198199  protected abstract getMethod(event: E): string200201  protected abstract getQueryString(event: E): string202203  protected abstract getHeaders(event: E): Headers204205  protected abstract getCookies(event: E, headers: Headers): void206207  protected abstract setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void208209  createRequest(event: E): Request {210    const queryString = this.getQueryString(event)211    const domainName =212      event.requestContext && 'domainName' in event.requestContext213        ? event.requestContext.domainName214        : event.headers?.['host'] ?? event.multiValueHeaders?.['host']?.[0]215    const path = this.getPath(event)216    const urlPath = `https://${domainName}${path}`217    const url = queryString ? `${urlPath}?${queryString}` : urlPath218219    const headers = this.getHeaders(event)220221    const method = this.getMethod(event)222    const requestInit: RequestInit = {223      headers,224      method,225    }226227    if (event.body) {228      requestInit.body = event.isBase64Encoded ? decodeBase64(event.body) : event.body229    }230231    return new Request(url, requestInit)232  }233234  async createResult(event: E, res: Response): Promise<APIGatewayProxyResult> {235    const contentType = res.headers.get('content-type')236    let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false237238    if (!isBase64Encoded) {239      const contentEncoding = res.headers.get('content-encoding')240      isBase64Encoded = isContentEncodingBinary(contentEncoding)241    }242243    const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()244245    const result: APIGatewayProxyResult = {246      body: body,247      statusCode: res.status,248      isBase64Encoded,249      ...(event.multiValueHeaders250        ? {251            multiValueHeaders: {},252          }253        : {254            headers: {},255          }),256    }257258    this.setCookies(event, res, result)259    if (result.multiValueHeaders) {260      res.headers.forEach((value, key) => {261        result.multiValueHeaders[key] = [value]262      })263    } else {264      res.headers.forEach((value, key) => {265        result.headers[key] = value266      })267    }268269    return result270  }271272  setCookies(event: E, res: Response, result: APIGatewayProxyResult) {273    if (res.headers.has('set-cookie')) {274      const cookies = res.headers.getSetCookie275        ? res.headers.getSetCookie()276        : Array.from(res.headers.entries())277            .filter(([k]) => k === 'set-cookie')278            .map(([, v]) => v)279280      if (Array.isArray(cookies)) {281        this.setCookiesToResult(result, cookies)282        res.headers.delete('set-cookie')283      }284    }285  }286}287288export class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {289  protected getPath(event: APIGatewayProxyEventV2): string {290    return event.rawPath291  }292293  protected getMethod(event: APIGatewayProxyEventV2): string {294    return event.requestContext.http.method295  }296297  protected getQueryString(event: APIGatewayProxyEventV2): string {298    return event.rawQueryString299  }300301  protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {302    if (Array.isArray(event.cookies)) {303      headers.set('Cookie', event.cookies.join('; '))304    }305  }306307  protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {308    result.cookies = cookies309  }310311  protected getHeaders(event: APIGatewayProxyEventV2): Headers {312    const headers = new Headers()313    this.getCookies(event, headers)314    if (event.headers) {315      for (const [k, v] of Object.entries(event.headers)) {316        if (v) {317          headers.set(k, v)318        }319      }320    }321    return headers322  }323}324325const v2Processor: EventV2Processor = new EventV2Processor()326327export class EventV1Processor extends EventProcessor<Exclude<LambdaEvent, APIGatewayProxyEventV2>> {328  protected getPath(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {329    return event.path330  }331332  protected getMethod(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {333    return event.httpMethod334  }335336  protected getQueryString(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {337    // In the case of gateway Integration either queryStringParameters or multiValueQueryStringParameters can be present not both338    if (event.multiValueQueryStringParameters) {339      return Object.entries(event.multiValueQueryStringParameters || {})340        .filter(([, value]) => value)341        .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)342        .join('&')343    } else {344      return Object.entries(event.queryStringParameters || {})345        .filter(([, value]) => value)346        .map(([key, value]) => `${key}=${value}`)347        .join('&')348    }349  }350351  protected getCookies(352    // eslint-disable-next-line @typescript-eslint/no-unused-vars353    event: Exclude<LambdaEvent, APIGatewayProxyEventV2>,354    // eslint-disable-next-line @typescript-eslint/no-unused-vars355    headers: Headers356  ): void {357    // nop358  }359360  protected getHeaders(event: APIGatewayProxyEvent): Headers {361    const headers = new Headers()362    this.getCookies(event, headers)363    if (event.headers) {364      for (const [k, v] of Object.entries(event.headers)) {365        if (v) {366          headers.set(k, v)367        }368      }369    }370    if (event.multiValueHeaders) {371      for (const [k, values] of Object.entries(event.multiValueHeaders)) {372        if (values) {373          // avoid duplicating already set headers374          const foundK = headers.get(k)375          values.forEach((v) => (!foundK || !foundK.includes(v)) && headers.append(k, v))376        }377      }378    }379    return headers380  }381382  protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {383    result.multiValueHeaders = {384      'set-cookie': cookies,385    }386  }387}388389const v1Processor: EventV1Processor = new EventV1Processor()390391export class ALBProcessor extends EventProcessor<ALBProxyEvent> {392  protected getHeaders(event: ALBProxyEvent): Headers {393    const headers = new Headers()394    // if multiValueHeaders is present the ALB will use it instead of the headers field395    // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers396    if (event.multiValueHeaders) {397      for (const [key, values] of Object.entries(event.multiValueHeaders)) {398        if (values && Array.isArray(values)) {399          // https://www.rfc-editor.org/rfc/rfc9110.html#name-common-rules-for-defining-f400          headers.set(key, values.join('; '))401        }402      }403    } else {404      for (const [key, value] of Object.entries(event.headers ?? {})) {405        if (value) {406          headers.set(key, value)407        }408      }409    }410    return headers411  }412413  protected getPath(event: ALBProxyEvent): string {414    return event.path415  }416417  protected getMethod(event: ALBProxyEvent): string {418    return event.httpMethod419  }420421  protected getQueryString(event: ALBProxyEvent): string {422    // In the case of ALB Integration either queryStringParameters or multiValueQueryStringParameters can be present not both423    /*424      In other cases like when using the serverless framework, the event object does contain both queryStringParameters and multiValueQueryStringParameters:425      Below is an example event object for this URL: /payment/b8c55e69?select=amount&select=currency426      {427        ...428        queryStringParameters: { select: 'currency' },429        multiValueQueryStringParameters: { select: [ 'amount', 'currency' ] },430      }431      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.432      A simple fix would be to invert the if statement and check the multiValueQueryStringParameters first.433    */434    if (event.multiValueQueryStringParameters) {435      return Object.entries(event.multiValueQueryStringParameters || {})436        .filter(([, value]) => value)437        .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)438        .join('&')439    } else {440      return Object.entries(event.queryStringParameters || {})441        .filter(([, value]) => value)442        .map(([key, value]) => `${key}=${value}`)443        .join('&')444    }445  }446447  protected getCookies(event: ALBProxyEvent, headers: Headers): void {448    let cookie449    if (event.multiValueHeaders) {450      cookie = event.multiValueHeaders['cookie']?.join('; ')451    } else {452      cookie = event.headers ? event.headers['cookie'] : undefined453    }454    if (cookie) {455      headers.append('Cookie', cookie)456    }457  }458459  protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {460    // when multi value headers is enabled461    if (result.multiValueHeaders) {462      result.multiValueHeaders['set-cookie'] = cookies463    } else {464      // otherwise serialize the set-cookie465      result.headers['set-cookie'] = cookies.join(', ')466    }467  }468}469470const albProcessor: ALBProcessor = new ALBProcessor()471472export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {473  if (isProxyEventALB(event)) {474    return albProcessor475  }476  if (isProxyEventV2(event)) {477    return v2Processor478  }479  return v1Processor480}481482const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {483  if (event.requestContext) {484    return Object.hasOwn(event.requestContext, 'elb')485  }486  return false487}488489const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {490  return Object.hasOwn(event, 'rawPath')491}492493export const isContentTypeBinary = (contentType: string) => {494  return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(495    contentType496  )497}498499export const isContentEncodingBinary = (contentEncoding: string | null) => {500  if (contentEncoding === null) {501    return false502  }503  return /^(gzip|deflate|compress|br)/.test(contentEncoding)504}