handler.ts
This file
Path
src/adapter/aws-lambda/handler.ts
503 lines · 14.8 KiB · TypeScript
Last changed by
fix(aws-lambda): Fix query string handling for v1 (#3717)Hollis Wubefore adoption4af04a6
History of this fileTake it
The walk stopped after 200 commits: lines older than 81a1f07 point at it.
fix(validator): support multipart headers without a space separating boundary (#3286)Ernest Badubefore adoption81a1f07
lines 1–186why, one step back1import 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 Handler,10 LambdaContext,11} from './types'1213// eslint-disable-next-line @typescript-eslint/ban-ts-comment14// @ts-ignore15globalThis.crypto ??= crypto1617export type LambdaEvent = APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent1819// When calling HTTP API or Lambda directly through function urls20export interface APIGatewayProxyEventV2 {21 version: string22 routeKey: string23 headers: Record<string, string | undefined>24 multiValueHeaders?: undefined25 cookies?: string[]26 rawPath: string27 rawQueryString: string28 body: string | null29 isBase64Encoded: boolean30 requestContext: ApiGatewayRequestContextV231 queryStringParameters?: {32 [name: string]: string | undefined33 }34 pathParameters?: {35 [name: string]: string | undefined36 }37 stageVariables?: {38 [name: string]: string | undefined39 }40}4142// When calling Lambda through an API Gateway43export interface APIGatewayProxyEvent {44 version: string45 httpMethod: string46 headers: Record<string, string | undefined>47 multiValueHeaders?: {48 [headerKey: string]: string[]49 }50 path: string51 body: string | null52 isBase64Encoded: boolean53 queryStringParameters?: Record<string, string | undefined>54 requestContext: ApiGatewayRequestContext55 resource: string56 multiValueQueryStringParameters?: {57 [parameterKey: string]: string[]58 }59 pathParameters?: Record<string, string>60 stageVariables?: Record<string, string>61}6263// When calling Lambda through an Application Load Balancer64export interface ALBProxyEvent {65 httpMethod: string66 headers?: Record<string, string | undefined>67 multiValueHeaders?: Record<string, string[] | undefined>68 path: string69 body: string | null70 isBase64Encoded: boolean71 queryStringParameters?: Record<string, string | undefined>72 multiValueQueryStringParameters?: {73 [parameterKey: string]: string[]74 }75 requestContext: ALBRequestContext76}7778export interface APIGatewayProxyResult {79 statusCode: number80 statusDescription?: string81 body: string82 headers: Record<string, string>83 cookies?: string[]84 multiValueHeaders?: {85 [headerKey: string]: string[]86 }87 isBase64Encoded: boolean88}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): ((event: LambdaEvent, lambdaContext?: LambdaContext) => Promise<APIGatewayProxyResult>) => {171 return async (event, lambdaContext?) => {172 const processor = getProcessor(event)173174 const req = processor.createRequest(event)175 const requestContext = getRequestContext(event)176177 const res = await app.fetch(req, {178 event,179 requestContext,180 lambdaContext,181 })182183 return processor.createResult(event, res)184 }185}186fix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
line 187why, one step back187export abstract class EventProcessor<E extends LambdaEvent> {fix(validator): support multipart headers without a space separating boundary (#3286)Ernest Badubefore adoption81a1f07
lines 188–274why, one step back188 protected abstract getPath(event: E): string189190 protected abstract getMethod(event: E): string191192 protected abstract getQueryString(event: E): string193194 protected abstract getHeaders(event: E): Headers195196 protected abstract getCookies(event: E, headers: Headers): void197198 protected abstract setCookiesToResult(199 event: E,200 result: APIGatewayProxyResult,201 cookies: string[]202 ): void203204 createRequest(event: E): Request {205 const queryString = this.getQueryString(event)206 const domainName =207 event.requestContext && 'domainName' in event.requestContext208 ? event.requestContext.domainName209 : event.headers?.['host'] ?? event.multiValueHeaders?.['host']?.[0]210 const path = this.getPath(event)211 const urlPath = `https://${domainName}${path}`212 const url = queryString ? `${urlPath}?${queryString}` : urlPath213214 const headers = this.getHeaders(event)215216 const method = this.getMethod(event)217 const requestInit: RequestInit = {218 headers,219 method,220 }221222 if (event.body) {223 requestInit.body = event.isBase64Encoded ? decodeBase64(event.body) : event.body224 }225226 return new Request(url, requestInit)227 }228229 async createResult(event: E, res: Response): Promise<APIGatewayProxyResult> {230 const contentType = res.headers.get('content-type')231 let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false232233 if (!isBase64Encoded) {234 const contentEncoding = res.headers.get('content-encoding')235 isBase64Encoded = isContentEncodingBinary(contentEncoding)236 }237238 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()239240 const result: APIGatewayProxyResult = {241 body: body,242 headers: {},243 multiValueHeaders: event.multiValueHeaders ? {} : undefined,244 statusCode: res.status,245 isBase64Encoded,246 }247248 this.setCookies(event, res, result)249 res.headers.forEach((value, key) => {250 result.headers[key] = value251 if (event.multiValueHeaders && result.multiValueHeaders) {252 result.multiValueHeaders[key] = [value]253 }254 })255256 return result257 }258259 setCookies(event: E, res: Response, result: APIGatewayProxyResult) {260 if (res.headers.has('set-cookie')) {261 const cookies = res.headers.getSetCookie262 ? res.headers.getSetCookie()263 : Array.from(res.headers.entries())264 .filter(([k]) => k === 'set-cookie')265 .map(([, v]) => v)266267 if (Array.isArray(cookies)) {268 this.setCookiesToResult(event, result, cookies)269 res.headers.delete('set-cookie')270 }271 }272 }273}274fix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
line 275why, one step back275export class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {fix(validator): support multipart headers without a space separating boundary (#3286)Ernest Badubefore adoption81a1f07
lines 276–317why, one step back276 protected getPath(event: APIGatewayProxyEventV2): string {277 return event.rawPath278 }279280 protected getMethod(event: APIGatewayProxyEventV2): string {281 return event.requestContext.http.method282 }283284 protected getQueryString(event: APIGatewayProxyEventV2): string {285 return event.rawQueryString286 }287288 protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {289 if (Array.isArray(event.cookies)) {290 headers.set('Cookie', event.cookies.join('; '))291 }292 }293294 protected setCookiesToResult(295 _: APIGatewayProxyEventV2,296 result: APIGatewayProxyResult,297 cookies: string[]298 ): void {299 result.cookies = cookies300 }301302 protected getHeaders(event: APIGatewayProxyEventV2): Headers {303 const headers = new Headers()304 this.getCookies(event, headers)305 if (event.headers) {306 for (const [k, v] of Object.entries(event.headers)) {307 if (v) {308 headers.set(k, v)309 }310 }311 }312 return headers313 }314}315316const v2Processor: EventV2Processor = new EventV2Processor()317fix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
line 318why, one step back318export class EventV1Processor extends EventProcessor<Exclude<LambdaEvent, APIGatewayProxyEventV2>> {fix(validator): support multipart headers without a space separating boundary (#3286)Ernest Badubefore adoption81a1f07
lines 319–327why, one step back319 protected getPath(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {320 return event.path321 }322323 protected getMethod(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {324 return event.httpMethod325 }326327 protected getQueryString(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {fix(aws-lambda): Fix query string handling for v1 (#3717)Hollis Wubefore adoption4af04a6
lines 328–339why, one step back328 // In the case of gateway Integration either queryStringParameters or multiValueQueryStringParameters can be present not both329 if (event.multiValueQueryStringParameters) {330 return Object.entries(event.multiValueQueryStringParameters || {})331 .filter(([, value]) => value)332 .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)333 .join('&')334 } else {335 return Object.entries(event.queryStringParameters || {})336 .filter(([, value]) => value)337 .map(([key, value]) => `${key}=${value}`)338 .join('&')339 }fix(validator): support multipart headers without a space separating boundary (#3286)Ernest Badubefore adoption81a1f07
lines 340–385why, one step back340 }341342 protected getCookies(343 // eslint-disable-next-line @typescript-eslint/no-unused-vars344 event: Exclude<LambdaEvent, APIGatewayProxyEventV2>,345 // eslint-disable-next-line @typescript-eslint/no-unused-vars346 headers: Headers347 ): void {348 // nop349 }350351 protected getHeaders(event: APIGatewayProxyEvent): Headers {352 const headers = new Headers()353 this.getCookies(event, headers)354 if (event.headers) {355 for (const [k, v] of Object.entries(event.headers)) {356 if (v) {357 headers.set(k, v)358 }359 }360 }361 if (event.multiValueHeaders) {362 for (const [k, values] of Object.entries(event.multiValueHeaders)) {363 if (values) {364 // avoid duplicating already set headers365 const foundK = headers.get(k)366 values.forEach((v) => (!foundK || !foundK.includes(v)) && headers.append(k, v))367 }368 }369 }370 return headers371 }372373 protected setCookiesToResult(374 _: APIGatewayProxyEvent,375 result: APIGatewayProxyResult,376 cookies: string[]377 ): void {378 result.multiValueHeaders = {379 'set-cookie': cookies,380 }381 }382}383384const v1Processor: EventV1Processor = new EventV1Processor()385fix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
line 386why, one step back386export class ALBProcessor extends EventProcessor<ALBProxyEvent> {fix(validator): support multipart headers without a space separating boundary (#3286)Ernest Badubefore adoption81a1f07
lines 387–417why, one step back387 protected getHeaders(event: ALBProxyEvent): Headers {388 const headers = new Headers()389 // if multiValueHeaders is present the ALB will use it instead of the headers field390 // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers391 if (event.multiValueHeaders) {392 for (const [key, values] of Object.entries(event.multiValueHeaders)) {393 if (values && Array.isArray(values)) {394 // https://www.rfc-editor.org/rfc/rfc9110.html#name-common-rules-for-defining-f395 headers.set(key, values.join('; '))396 }397 }398 } else {399 for (const [key, value] of Object.entries(event.headers ?? {})) {400 if (value) {401 headers.set(key, value)402 }403 }404 }405 return headers406 }407408 protected getPath(event: ALBProxyEvent): string {409 return event.path410 }411412 protected getMethod(event: ALBProxyEvent): string {413 return event.httpMethod414 }415416 protected getQueryString(event: ALBProxyEvent): string {417 // In the case of ALB Integration either queryStringParameters or multiValueQueryStringParameters can be present not bothfix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
line 418why, one step back418 /*fix(validator): support multipart headers without a space separating boundary (#3286)Ernest Badubefore adoption81a1f07
lines 419–481why, one step back419 In other cases like when using the serverless framework, the event object does contain both queryStringParameters and multiValueQueryStringParameters:420 Below is an example event object for this URL: /payment/b8c55e69?select=amount&select=currency421 {422 ...423 queryStringParameters: { select: 'currency' },424 multiValueQueryStringParameters: { select: [ 'amount', 'currency' ] },425 }426 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.427 A simple fix would be to invert the if statement and check the multiValueQueryStringParameters first.428 */429 if (event.multiValueQueryStringParameters) {430 return Object.entries(event.multiValueQueryStringParameters || {})431 .filter(([, value]) => value)432 .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)433 .join('&')434 } else {435 return Object.entries(event.queryStringParameters || {})436 .filter(([, value]) => value)437 .map(([key, value]) => `${key}=${value}`)438 .join('&')439 }440 }441442 protected getCookies(event: ALBProxyEvent, headers: Headers): void {443 let cookie444 if (event.multiValueHeaders) {445 cookie = event.multiValueHeaders['cookie']?.join('; ')446 } else {447 cookie = event.headers ? event.headers['cookie'] : undefined448 }449 if (cookie) {450 headers.append('Cookie', cookie)451 }452 }453454 protected setCookiesToResult(455 event: ALBProxyEvent,456 result: APIGatewayProxyResult,457 cookies: string[]458 ): void {459 // when multi value headers is enabled460 if (event.multiValueHeaders && result.multiValueHeaders) {461 result.multiValueHeaders['set-cookie'] = cookies462 } else {463 // otherwise serialize the set-cookie464 result.headers['set-cookie'] = cookies.join(', ')465 }466 }467}468469const albProcessor: ALBProcessor = new ALBProcessor()470471export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {472 if (isProxyEventALB(event)) {473 return albProcessor474 }475 if (isProxyEventV2(event)) {476 return v2Processor477 }478 return v1Processor479}480481const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {fix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
lines 482–485why, one step back482 if (event.requestContext) {483 return Object.hasOwn(event.requestContext, 'elb')484 }485 return falsefix(validator): support multipart headers without a space separating boundary (#3286)Ernest Badubefore adoption81a1f07
lines 486–503why, one step back486}487488const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {489 return Object.hasOwn(event, 'rawPath')490}491492export const isContentTypeBinary = (contentType: string) => {493 return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(494 contentType495 )496}497498export const isContentEncodingBinary = (contentEncoding: string | null) => {499 if (contentEncoding === null) {500 return false501 }502 return /^(gzip|deflate|compress|br)/.test(contentEncoding)503}