handler.ts
This file
Path
src/adapter/aws-lambda/handler.ts
675 lines 路 19.7 KiB 路 TypeScript
Last changed by
chore(builld): tsconfig project references (#4797)Jonathan Hainesbefore adoptiond69deb8
History of this fileTake 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(_event: APIGatewayProxyEvent, _headers: Headers): void {457 // nop458 }459460 protected getHeaders(event: APIGatewayProxyEvent): Headers {461 const headers = new Headers()462 this.getCookies(event, headers)463 if (event.headers) {464 for (const [k, v] of Object.entries(event.headers)) {465 if (v) {466 headers.set(k, sanitizeHeaderValue(v))467 }468 }469 }470 if (event.multiValueHeaders) {471 for (const [k, values] of Object.entries(event.multiValueHeaders)) {472 if (values) {473 // avoid duplicating already set headers474 const foundK = headers.get(k)475 values.forEach((v) => {476 const sanitizedValue = sanitizeHeaderValue(v)477 return (478 (!foundK || !foundK.includes(sanitizedValue)) && headers.append(k, sanitizedValue)479 )480 })481 }482 }483 }484 return headers485 }486487 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {488 result.multiValueHeaders = {489 'set-cookie': cookies,490 }491 }492}493494const v1Processor: EventV1Processor = new EventV1Processor()495496export class ALBProcessor extends EventProcessor<ALBProxyEvent> {497 protected getHeaders(event: ALBProxyEvent): Headers {498 const headers = new Headers()499 // if multiValueHeaders is present the ALB will use it instead of the headers field500 // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers501 if (event.multiValueHeaders) {502 for (const [key, values] of Object.entries(event.multiValueHeaders)) {503 if (values && Array.isArray(values)) {504 // https://www.rfc-editor.org/rfc/rfc9110.html#name-common-rules-for-defining-f505 const sanitizedValue = sanitizeHeaderValue(values.join('; '))506 headers.set(key, sanitizedValue)507 }508 }509 } else {510 for (const [key, value] of Object.entries(event.headers ?? {})) {511 if (value) {512 headers.set(key, sanitizeHeaderValue(value))513 }514 }515 }516 return headers517 }518519 protected getPath(event: ALBProxyEvent): string {520 return event.path521 }522523 protected getMethod(event: ALBProxyEvent): string {524 return event.httpMethod525 }526527 protected getQueryString(event: ALBProxyEvent): string {528 // In the case of ALB Integration either queryStringParameters or multiValueQueryStringParameters can be present not both529 /*530 In other cases like when using the serverless framework, the event object does contain both queryStringParameters and multiValueQueryStringParameters:531 Below is an example event object for this URL: /payment/b8c55e69?select=amount&select=currency532 {533 ...534 queryStringParameters: { select: 'currency' },535 multiValueQueryStringParameters: { select: [ 'amount', 'currency' ] },536 }537 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.538 A simple fix would be to invert the if statement and check the multiValueQueryStringParameters first.539 */540 if (event.multiValueQueryStringParameters) {541 return Object.entries(event.multiValueQueryStringParameters || {})542 .filter(([, value]) => value)543 .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)544 .join('&')545 } else {546 return Object.entries(event.queryStringParameters || {})547 .filter(([, value]) => value)548 .map(([key, value]) => `${key}=${value}`)549 .join('&')550 }551 }552553 protected getCookies(event: ALBProxyEvent, headers: Headers): void {554 let cookie555 if (event.multiValueHeaders) {556 cookie = event.multiValueHeaders['cookie']?.join('; ')557 } else {558 cookie = event.headers ? event.headers['cookie'] : undefined559 }560 if (cookie) {561 headers.append('Cookie', cookie)562 }563 }564565 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {566 // when multi value headers is enabled567 if (result.multiValueHeaders) {568 result.multiValueHeaders['set-cookie'] = cookies569 } else {570 // otherwise serialize the set-cookie571 result.headers['set-cookie'] = cookies.join(', ')572 }573 }574}575576const albProcessor: ALBProcessor = new ALBProcessor()577578export class LatticeV2Processor extends EventProcessor<LatticeProxyEventV2> {579 protected getPath(event: LatticeProxyEventV2): string {580 return event.path581 }582583 protected getMethod(event: LatticeProxyEventV2): string {584 return event.method585 }586587 protected getQueryString(): string {588 return ''589 }590591 protected getHeaders(event: LatticeProxyEventV2): Headers {592 const headers = new Headers()593594 if (event.headers) {595 for (const [k, values] of Object.entries(event.headers)) {596 if (values) {597 // avoid duplicating already set headers598 const foundK = headers.get(k)599 values.forEach((v) => {600 const sanitizedValue = sanitizeHeaderValue(v)601 return (602 (!foundK || !foundK.includes(sanitizedValue)) && headers.append(k, sanitizedValue)603 )604 })605 }606 }607 }608609 return headers610 }611612 protected getCookies(): void {613 // nop614 }615616 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {617 result.headers = {618 ...result.headers,619 'set-cookie': cookies.join(', '),620 }621 }622}623624const latticeV2Processor: LatticeV2Processor = new LatticeV2Processor()625626export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {627 if (isProxyEventALB(event)) {628 return albProcessor629 }630 if (isProxyEventV2(event)) {631 return v2Processor632 }633 if (isLatticeEventV2(event)) {634 return latticeV2Processor635 }636637 return v1Processor638}639640const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {641 if (event.requestContext) {642 return Object.hasOwn(event.requestContext, 'elb')643 }644 return false645}646647const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {648 return Object.hasOwn(event, 'rawPath')649}650651const isLatticeEventV2 = (event: LambdaEvent): event is LatticeProxyEventV2 => {652 if (event.requestContext) {653 return Object.hasOwn(event.requestContext, 'serviceArn')654 }655 return false656}657658/**659 * Check if the given content type is binary.660 * This is a default function and may be overwritten by the user via `isContentTypeBinary` option in handler().661 * @param contentType The content type to check.662 * @returns True if the content type is binary, false otherwise.663 */664export const defaultIsContentTypeBinary = (contentType: string): boolean => {665 return !/^text\/(?:plain|html|css|javascript|csv)|(?:\/|\+)(?:json|xml)\s*(?:;|$)/.test(666 contentType667 )668}669670export const isContentEncodingBinary = (contentEncoding: string | null) => {671 if (contentEncoding === null) {672 return false673 }674 return /^(gzip|deflate|compress|br)/.test(contentEncoding)675}