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 fileTake it
The walk stopped after 200 commits: lines older than 8d775dc point at it.
chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 1–72why, one step back1import 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}72fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
lines 73–82why, one step back73type WithHeaders = {74 headers: Record<string, string>75 multiValueHeaders?: undefined76}77type WithMultiValueHeaders = {78 headers?: undefined79 multiValueHeaders: Record<string, string[]>80}8182export type APIGatewayProxyResult = {chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 83–87why, one step back83 statusCode: number84 statusDescription?: string85 body: string86 cookies?: string[]87 isBase64Encoded: booleanfix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
line 88why, one step back88} & (WithHeaders | WithMultiValueHeaders)chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 89–169why, one step back8990const 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>fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
lines 170–179why, one step back170): (<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 typingchore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 180–195why, one step back180 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}195fix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
line 196why, one step back196export abstract class EventProcessor<E extends LambdaEvent> {chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 197–206why, one step back197 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): void206fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
line 207why, one step back207 protected abstract setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): voidchore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 208–248why, one step back208209 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,fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
lines 249–255why, one step back249 ...(event.multiValueHeaders250 ? {251 multiValueHeaders: {},252 }253 : {254 headers: {},255 }),chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 256–258why, one step back256 }257258 this.setCookies(event, res, result)fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
lines 259–260why, one step back259 if (result.multiValueHeaders) {260 res.headers.forEach((value, key) => {chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
line 261why, one step back261 result.multiValueHeaders[key] = [value]fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
lines 262–267why, one step back262 })263 } else {264 res.headers.forEach((value, key) => {265 result.headers[key] = value266 })267 }chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 268–280why, one step back268269 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)) {fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
line 281why, one step back281 this.setCookiesToResult(result, cookies)chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 282–287why, one step back282 res.headers.delete('set-cookie')283 }284 }285 }286}287fix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
line 288why, one step back288export class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 289–306why, one step back289 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 }306fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
line 307why, one step back307 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 308–326why, one step back308 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()326fix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
line 327why, one step back327export class EventV1Processor extends EventProcessor<Exclude<LambdaEvent, APIGatewayProxyEventV2>> {chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 328–336why, one step back328 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 {fix(aws-lambda): Fix query string handling for v1 (#3717)Hollis Wubefore adoption4af04a6
lines 337–348why, one step back337 // 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 }chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 349–381why, one step back349 }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 }381fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
line 382why, one step back382 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 383–390why, one step back383 result.multiValueHeaders = {384 'set-cookie': cookies,385 }386 }387}388389const v1Processor: EventV1Processor = new EventV1Processor()390fix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
line 391why, one step back391export class ALBProcessor extends EventProcessor<ALBProxyEvent> {chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 392–422why, one step back392 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 bothfix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
line 423why, one step back423 /*chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 424–458why, one step back424 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 }458fix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
line 459why, one step back459 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
line 460why, one step back460 // when multi value headers is enabledfix(adapter/aws-lambda): APIGWProxyResult should contain either of headers or multiValueHeaders, not both (#3883)TATSUNO “Taz” Yasuhirobefore adoption0e4dfe5
line 461why, one step back461 if (result.multiValueHeaders) {chore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 462–482why, one step back462 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 => {fix(adapter/aws-lambda): add alb event requestContext undefined check for testing convenience (#3691)Omkar Patilbefore adoption7ebf854
lines 483–486why, one step back483 if (event.requestContext) {484 return Object.hasOwn(event.requestContext, 'elb')485 }486 return falsechore: automatically close issues marked as “not bug” over time (#3611)EdamAmexbefore adoption8d775dc
lines 487–504why, one step back487}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}