Skip to content
Myr

handler.ts

This file

Path

src/adapter/aws-lambda/handler.ts

483 lines 路 14.0 KiB 路 TypeScript

Last changed by

Merge pull request #2769 from honojs/nextYusuke Wadabefore adoptionacd3634

History of this file

Take it

1import crypto from 'node:crypto'2import type { Hono } from '../../hono'3import type { Env, Schema } from '../../types'4import { decodeBase64, encodeBase64 } from '../../utils/encode'5import type {6  ALBRequestContext,7  ApiGatewayRequestContext,8  ApiGatewayRequestContextV2,9} from './custom-context'10import type { Handler, LambdaContext } from './types'1112// eslint-disable-next-line @typescript-eslint/ban-ts-comment13// @ts-ignore14globalThis.crypto ??= crypto1516export type LambdaEvent = APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent1718// When calling HTTP API or Lambda directly through function urls19export interface APIGatewayProxyEventV2 {20  version: string21  routeKey: string22  headers: Record<string, string | undefined>23  multiValueHeaders?: undefined24  cookies?: string[]25  rawPath: string26  rawQueryString: string27  body: string | null28  isBase64Encoded: boolean29  requestContext: ApiGatewayRequestContextV230  queryStringParameters?: {31    [name: string]: string | undefined32  }33  pathParameters?: {34    [name: string]: string | undefined35  }36  stageVariables?: {37    [name: string]: string | undefined38  }39}4041// When calling Lambda through an API Gateway42export interface APIGatewayProxyEvent {43  version: string44  httpMethod: string45  headers: Record<string, string | undefined>46  multiValueHeaders?: {47    [headerKey: string]: string[]48  }49  path: string50  body: string | null51  isBase64Encoded: boolean52  queryStringParameters?: Record<string, string | undefined>53  requestContext: ApiGatewayRequestContext54  resource: string55  multiValueQueryStringParameters?: {56    [parameterKey: string]: string[]57  }58  pathParameters?: Record<string, string>59  stageVariables?: Record<string, string>60}6162// When calling Lambda through an Application Load Balancer63export interface ALBProxyEvent {64  httpMethod: string65  headers?: Record<string, string | undefined>66  multiValueHeaders?: Record<string, string[] | undefined>67  path: string68  body: string | null69  isBase64Encoded: boolean70  queryStringParameters?: Record<string, string | undefined>71  multiValueQueryStringParameters?: {72    [parameterKey: string]: string[]73  }74  requestContext: ALBRequestContext75}7677export interface APIGatewayProxyResult {78  statusCode: number79  statusDescription?: string80  body: string81  headers: Record<string, string>82  cookies?: string[]83  multiValueHeaders?: {84    [headerKey: string]: string[]85  }86  isBase64Encoded: boolean87}8889const getRequestContext = (90  event: LambdaEvent91): ApiGatewayRequestContext | ApiGatewayRequestContextV2 | ALBRequestContext => {92  return event.requestContext93}9495const streamToNodeStream = async (96  reader: ReadableStreamDefaultReader<Uint8Array>,97  writer: NodeJS.WritableStream98) => {99  let readResult = await reader.read()100  while (!readResult.done) {101    writer.write(readResult.value)102    readResult = await reader.read()103  }104  writer.end()105}106107export const streamHandle = <108  E extends Env = Env,109  S extends Schema = {},110  BasePath extends string = '/'111>(112  app: Hono<E, S, BasePath>113): Handler => {114  // @ts-expect-error awslambda is not a standard API115  return awslambda.streamifyResponse(116    async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {117      const processor = getProcessor(event)118      try {119        const req = processor.createRequest(event)120        const requestContext = getRequestContext(event)121122        const res = await app.fetch(req, {123          event,124          requestContext,125          context,126        })127128        // Check content type129        const httpResponseMetadata = {130          statusCode: res.status,131          headers: Object.fromEntries(res.headers.entries()),132        }133134        // Update response stream135        // @ts-expect-error awslambda is not a standard API136        responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)137138        if (res.body) {139          await streamToNodeStream(res.body.getReader(), responseStream)140        } else {141          responseStream.write('')142        }143      } catch (error) {144        console.error('Error processing request:', error)145        responseStream.write('Internal Server Error')146      } finally {147        responseStream.end()148      }149    }150  )151}152153/**154 * Accepts events from API Gateway/ELB(`APIGatewayProxyEvent`) and directly through Function Url(`APIGatewayProxyEventV2`)155 */156export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(157  app: Hono<E, S, BasePath>158): ((event: LambdaEvent, lambdaContext?: LambdaContext) => Promise<APIGatewayProxyResult>) => {159  return async (event, lambdaContext?) => {160    const processor = getProcessor(event)161162    const req = processor.createRequest(event)163    const requestContext = getRequestContext(event)164165    const res = await app.fetch(req, {166      event,167      requestContext,168      lambdaContext,169    })170171    return processor.createResult(event, res)172  }173}174175abstract class EventProcessor<E extends LambdaEvent> {176  protected abstract getPath(event: E): string177178  protected abstract getMethod(event: E): string179180  protected abstract getQueryString(event: E): string181182  protected abstract getHeaders(event: E): Headers183184  protected abstract getCookies(event: E, headers: Headers): void185186  protected abstract setCookiesToResult(187    event: E,188    result: APIGatewayProxyResult,189    cookies: string[]190  ): void191192  createRequest(event: E): Request {193    const queryString = this.getQueryString(event)194    const domainName =195      event.requestContext && 'domainName' in event.requestContext196        ? event.requestContext.domainName197        : event.headers?.['host'] ?? event.multiValueHeaders?.['host']?.[0]198    const path = this.getPath(event)199    const urlPath = `https://${domainName}${path}`200    const url = queryString ? `${urlPath}?${queryString}` : urlPath201202    const headers = this.getHeaders(event)203204    const method = this.getMethod(event)205    const requestInit: RequestInit = {206      headers,207      method,208    }209210    if (event.body) {211      requestInit.body = event.isBase64Encoded ? decodeBase64(event.body) : event.body212    }213214    return new Request(url, requestInit)215  }216217  async createResult(event: E, res: Response): Promise<APIGatewayProxyResult> {218    const contentType = res.headers.get('content-type')219    let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false220221    if (!isBase64Encoded) {222      const contentEncoding = res.headers.get('content-encoding')223      isBase64Encoded = isContentEncodingBinary(contentEncoding)224    }225226    const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()227228    const result: APIGatewayProxyResult = {229      body: body,230      headers: {},231      multiValueHeaders: event.multiValueHeaders ? {} : undefined,232      statusCode: res.status,233      isBase64Encoded,234    }235236    this.setCookies(event, res, result)237    res.headers.forEach((value, key) => {238      result.headers[key] = value239      if (event.multiValueHeaders && result.multiValueHeaders) {240        result.multiValueHeaders[key] = [value]241      }242    })243244    return result245  }246247  setCookies(event: E, res: Response, result: APIGatewayProxyResult) {248    if (res.headers.has('set-cookie')) {249      const cookies = res.headers.get('set-cookie')?.split(', ')250      if (Array.isArray(cookies)) {251        this.setCookiesToResult(event, result, cookies)252        res.headers.delete('set-cookie')253      }254    }255  }256}257258class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {259  protected getPath(event: APIGatewayProxyEventV2): string {260    return event.rawPath261  }262263  protected getMethod(event: APIGatewayProxyEventV2): string {264    return event.requestContext.http.method265  }266267  protected getQueryString(event: APIGatewayProxyEventV2): string {268    return event.rawQueryString269  }270271  protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {272    if (Array.isArray(event.cookies)) {273      headers.set('Cookie', event.cookies.join('; '))274    }275  }276277  protected setCookiesToResult(278    _: APIGatewayProxyEventV2,279    result: APIGatewayProxyResult,280    cookies: string[]281  ): void {282    result.cookies = cookies283  }284285  protected getHeaders(event: APIGatewayProxyEventV2): Headers {286    const headers = new Headers()287    this.getCookies(event, headers)288    if (event.headers) {289      for (const [k, v] of Object.entries(event.headers)) {290        if (v) {291          headers.set(k, v)292        }293      }294    }295    return headers296  }297}298299const v2Processor: EventV2Processor = new EventV2Processor()300301class EventV1Processor extends EventProcessor<Exclude<LambdaEvent, APIGatewayProxyEventV2>> {302  protected getPath(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {303    return event.path304  }305306  protected getMethod(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {307    return event.httpMethod308  }309310  protected getQueryString(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {311    return Object.entries(event.queryStringParameters || {})312      .filter(([, value]) => value)313      .map(([key, value]) => `${key}=${value}`)314      .join('&')315  }316317  protected getCookies(318    // eslint-disable-next-line @typescript-eslint/no-unused-vars319    event: Exclude<LambdaEvent, APIGatewayProxyEventV2>,320    // eslint-disable-next-line @typescript-eslint/no-unused-vars321    headers: Headers322  ): void {323    // nop324  }325326  protected getHeaders(event: APIGatewayProxyEvent): Headers {327    const headers = new Headers()328    this.getCookies(event, headers)329    if (event.headers) {330      for (const [k, v] of Object.entries(event.headers)) {331        if (v) {332          headers.set(k, v)333        }334      }335    }336    if (event.multiValueHeaders) {337      for (const [k, values] of Object.entries(event.multiValueHeaders)) {338        if (values) {339          // avoid duplicating already set headers340          const foundK = headers.get(k)341          values.forEach((v) => (!foundK || !foundK.includes(v)) && headers.append(k, v))342        }343      }344    }345    return headers346  }347348  protected setCookiesToResult(349    _: APIGatewayProxyEvent,350    result: APIGatewayProxyResult,351    cookies: string[]352  ): void {353    result.multiValueHeaders = {354      'set-cookie': cookies,355    }356  }357}358359const v1Processor: EventV1Processor = new EventV1Processor()360361class ALBProcessor extends EventProcessor<ALBProxyEvent> {362  protected getHeaders(event: ALBProxyEvent): Headers {363    const headers = new Headers()364    // if multiValueHeaders is present the ALB will use it instead of the headers field365    // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers366    if (event.multiValueHeaders) {367      for (const [key, values] of Object.entries(event.multiValueHeaders)) {368        if (values && Array.isArray(values)) {369          // https://www.rfc-editor.org/rfc/rfc9110.html#name-common-rules-for-defining-f370          headers.set(key, values.join('; '))371        }372      }373    } else {374      for (const [key, value] of Object.entries(event.headers ?? {})) {375        if (value) {376          headers.set(key, value)377        }378      }379    }380    return headers381  }382  protected setHeadersToResult(383    event: ALBProxyEvent,384    result: APIGatewayProxyResult,385    headers: Headers386  ): void {387    // When multiValueHeaders is present in event set multiValueHeaders in result388    if (event.multiValueHeaders) {389      const multiValueHeaders: { [key: string]: string[] } = {}390      for (const [key, value] of headers.entries()) {391        multiValueHeaders[key] = [value]392      }393      result.multiValueHeaders = multiValueHeaders394    } else {395      const singleValueHeaders: Record<string, string> = {}396      for (const [key, value] of headers.entries()) {397        singleValueHeaders[key] = value398      }399      result.headers = singleValueHeaders400    }401  }402  protected getPath(event: ALBProxyEvent): string {403    return event.path404  }405406  protected getMethod(event: ALBProxyEvent): string {407    return event.httpMethod408  }409410  protected getQueryString(event: ALBProxyEvent): string {411    // In the case of ALB Integration either queryStringParameters or multiValueQueryStringParameters can be present not both412    if (event.queryStringParameters) {413      return Object.entries(event.queryStringParameters || {})414        .filter(([, value]) => value)415        .map(([key, value]) => `${key}=${value}`)416        .join('&')417    } else {418      return Object.entries(event.multiValueQueryStringParameters || {})419        .filter(([, value]) => value)420        .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)421        .join('&')422    }423  }424425  protected getCookies(event: ALBProxyEvent, headers: Headers): void {426    let cookie427    if (event.multiValueHeaders) {428      cookie = event.multiValueHeaders['cookie']?.join('; ')429    } else {430      cookie = event.headers ? event.headers['cookie'] : undefined431    }432    if (cookie) {433      headers.append('Cookie', cookie)434    }435  }436437  protected setCookiesToResult(438    event: ALBProxyEvent,439    result: APIGatewayProxyResult,440    cookies: string[]441  ): void {442    // when multi value headers is enabled443    if (event.multiValueHeaders && result.multiValueHeaders) {444      result.multiValueHeaders['set-cookie'] = cookies445    } else {446      // otherwise serialize the set-cookie447      result.headers['set-cookie'] = cookies.join(', ')448    }449  }450}451452const albProcessor: ALBProcessor = new ALBProcessor()453454export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {455  if (isProxyEventALB(event)) {456    return albProcessor457  }458  if (isProxyEventV2(event)) {459    return v2Processor460  }461  return v1Processor462}463464const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {465  return Object.prototype.hasOwnProperty.call(event.requestContext, 'elb')466}467468const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {469  return Object.prototype.hasOwnProperty.call(event, 'rawPath')470}471472export const isContentTypeBinary = (contentType: string) => {473  return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(474    contentType475  )476}477478export const isContentEncodingBinary = (contentEncoding: string | null) => {479  if (contentEncoding === null) {480    return false481  }482  return /^(gzip|deflate|compress|br)/.test(contentEncoding)483}