Skip to content
Myr

handler.ts

This file

Path

adapters/aws-lambda/src/handler.ts

682 lines · 20.2 KiB · TypeScript

Last changed by

feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827

History of this file

Take it

feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827

lines 1–682why, one step back
1import { pipeline } from 'node:stream/promises'
2import type { Hono } from 'hono'3import type { Env, Schema } from 'hono/types'4import { decodeBase64, encodeBase64 } from 'hono/utils/encode'5import type {6 ALBRequestContext,7 ApiGatewayRequestContext,8 ApiGatewayRequestContextV2,9 Handler,10 LambdaContext,11 LatticeRequestContextV2,12} from './types'1314function sanitizeHeaderValue(value: string): string {15 // Check if the value contains non-ASCII characters (char codes > 127)16 // eslint-disable-next-line no-control-regex17 const hasNonAscii = /[^\x00-\x7F]/.test(value)18 if (!hasNonAscii) {19 return value20 }21 return encodeURIComponent(value)22}2324export type LambdaEvent =25 | APIGatewayProxyEvent26 | APIGatewayProxyEventV227 | ALBProxyEvent28 | LatticeProxyEventV22930export interface LatticeProxyEventV2 {31 version: string32 path: string33 method: string34 headers: Record<string, string[] | undefined>35 queryStringParameters: Record<string, string[] | undefined>36 body: string | null37 isBase64Encoded: boolean38 requestContext: LatticeRequestContextV239}4041// When calling HTTP API or Lambda directly through function urls42export interface APIGatewayProxyEventV2 {43 version: string44 routeKey: string45 headers: Record<string, string | undefined>46 multiValueHeaders?: undefined47 cookies?: string[]48 rawPath: string49 rawQueryString: string50 body: string | null51 isBase64Encoded: boolean52 requestContext: ApiGatewayRequestContextV253 queryStringParameters?: {54 [name: string]: string | undefined55 }56 pathParameters?: {57 [name: string]: string | undefined58 }59 stageVariables?: {60 [name: string]: string | undefined61 }62}6364// When calling Lambda through an API Gateway65export interface APIGatewayProxyEvent {66 version: string67 httpMethod: string68 headers: Record<string, string | undefined>69 multiValueHeaders?: {70 [headerKey: string]: string[]71 }72 path: string73 body: string | null74 isBase64Encoded: boolean75 queryStringParameters?: Record<string, string | undefined>76 requestContext: ApiGatewayRequestContext77 resource: string78 multiValueQueryStringParameters?: {79 [parameterKey: string]: string[]80 }81 pathParameters?: Record<string, string>82 stageVariables?: Record<string, string>83}8485// When calling Lambda through an Application Load Balancer86export interface ALBProxyEvent {87 httpMethod: string88 headers?: Record<string, string | undefined>89 multiValueHeaders?: Record<string, string[] | undefined>90 path: string91 body: string | null92 isBase64Encoded: boolean93 queryStringParameters?: Record<string, string | undefined>94 multiValueQueryStringParameters?: {95 [parameterKey: string]: string[]96 }97 requestContext: ALBRequestContext98}99100type WithHeaders = {101 headers: Record<string, string | string[]>102 multiValueHeaders?: undefined103}104type WithMultiValueHeaders = {105 headers?: undefined106 multiValueHeaders: Record<string, string[]>107}108109export type APIGatewayProxyResult = {110 statusCode: number111 statusDescription?: string112 body: string113 cookies?: string[]114 isBase64Encoded: boolean115} & (WithHeaders | WithMultiValueHeaders)116117const getRequestContext = (118 event: LambdaEvent119):120 | ApiGatewayRequestContext121 | ApiGatewayRequestContextV2122 | ALBRequestContext123 | LatticeRequestContextV2 => {124 return event.requestContext125}126127async function* readWebStream(128 reader: ReadableStreamDefaultReader<Uint8Array>129): AsyncGenerator<Uint8Array> {130 let readResult = await reader.read()131 while (!readResult.done) {132 yield readResult.value133 readResult = await reader.read()134 }135}136137const streamToNodeStream = (138 reader: ReadableStreamDefaultReader<Uint8Array>,139 writer: NodeJS.WritableStream140): Promise<void> => pipeline(readWebStream(reader), writer)141142export const streamHandle = <143 E extends Env = Env,144 S extends Schema = {},145 BasePath extends string = '/',146>(147 app: Hono<E, S, BasePath>148): Handler => {149 // @ts-expect-error awslambda is not a standard API150 return awslambda.streamifyResponse(151 async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {152 const processor = getProcessor(event)153 try {154 const req = processor.createRequest(event)155 const requestContext = getRequestContext(event)156157 const res = await app.fetch(req, {158 event,159 requestContext,160 context,161 })162163 const headers: Record<string, string> = {}164 const cookies: string[] = []165 res.headers.forEach((value, name) => {166 if (name === 'set-cookie') {167 cookies.push(value)168 } else {169 headers[name] = value170 }171 })172173 // Check content type174 const httpResponseMetadata = {175 statusCode: res.status,176 headers,177 cookies,178 }179180 // Update response stream181 // @ts-expect-error awslambda is not a standard API182 responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)183184 if (res.body) {185 await streamToNodeStream(res.body.getReader(), responseStream)186 } else {187 responseStream.write('')188 }189 } catch (error) {190 console.error('Error processing request:', error)191 responseStream.write('Internal Server Error')192 } finally {193 responseStream.end()194 }195 }196 )197}198199type HandleOptions = {200 isContentTypeBinary: ((contentType: string) => boolean) | undefined201}202203/**204 * Converts a Hono application to an AWS Lambda handler.205 *206 * Accepts events from API Gateway (v1 and v2), Application Load Balancer (ALB),207 * and Lambda Function URLs.208 *209 * @param app - The Hono application instance210 * @param options - Optional configuration211 * @param options.isContentTypeBinary - A function to determine if the content type is binary.212 * If not provided, the default function will be used.213 * @returns Lambda handler function214 *215 * @example216 * ```js217 * import { Hono } from 'hono'218 * import { handle } from './index'219 *220 * const app = new Hono()221 *222 * app.get('/', (c) => c.text('Hello from Lambda'))223 * app.get('/json', (c) => c.json({ message: 'Hello JSON' }))224 *225 * export const handler = handle(app)226 * ```227 *228 * @example229 * ```js230 * // With custom binary content type detection231 * import { handle, defaultIsContentTypeBinary } from './index'232 * export const handler = handle(app, {233 * isContentTypeBinary: (contentType) => {234 * if (defaultIsContentTypeBinary(contentType)) {235 * // default logic same as prior to v4.8.4236 * return true237 * }238 * return contentType.startsWith('image/') || contentType === 'application/pdf'239 * }240 * })241 * ```242 */243export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(244 app: Hono<E, S, BasePath>,245 { isContentTypeBinary }: HandleOptions = { isContentTypeBinary: undefined }246): (<L extends LambdaEvent>(247 event: L,248 lambdaContext?: LambdaContext249) => Promise<250 APIGatewayProxyResult &251 (L extends { multiValueHeaders: Record<string, string[]> }252 ? WithMultiValueHeaders253 : WithHeaders)254>) => {255 // @ts-expect-error conditional return type is not inferable256 return async (event, lambdaContext?) => {257 const processor = getProcessor(event)258259 let req, requestContext260 try {261 req = processor.createRequest(event)262 requestContext = getRequestContext(event)263 } catch (error) {264 console.error('Error processing request:', error)265 const errorResponse =266 error instanceof TypeError267 ? new Response('Invalid request', { status: 400 })268 : new Response('Internal Server Error', { status: 500 })269 return processor.createResult(event, errorResponse, { isContentTypeBinary })270 }271272 const res = await app.fetch(req, {273 event,274 requestContext,275 lambdaContext,276 })277278 return processor.createResult(event, res, { isContentTypeBinary })279 }280}281282export abstract class EventProcessor<E extends LambdaEvent> {283 protected abstract getPath(event: E): string284285 protected abstract getMethod(event: E): string286287 protected abstract getQueryString(event: E): string288289 protected abstract getHeaders(event: E): Headers290291 protected abstract getCookies(event: E, headers: Headers): void292293 protected abstract setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void294295 protected getHeaderValue(headers: E['headers'], key: string): string | undefined {296 const value = headers297 ? Array.isArray(headers[key])298 ? headers[key][0]299 : headers[key]300 : undefined301302 return value303 }304305 protected getDomainName(event: E): string | undefined {306 if (event.requestContext && 'domainName' in event.requestContext) {307 return event.requestContext.domainName308 }309310 const hostFromHeaders = this.getHeaderValue(event.headers, 'host')311312 if (hostFromHeaders) {313 return hostFromHeaders314 }315316 const multiValueHeaders = 'multiValueHeaders' in event ? event.multiValueHeaders : {}317 const hostFromMultiValueHeaders = this.getHeaderValue(multiValueHeaders, 'host')318319 return hostFromMultiValueHeaders320 }321322 createRequest(event: E): Request {323 const queryString = this.getQueryString(event)324 const domainName = this.getDomainName(event)325 const path = this.getPath(event)326 const urlPath = `https://${domainName}${path}`327 const url = queryString ? `${urlPath}?${queryString}` : urlPath328329 const headers = this.getHeaders(event)330331 const method = this.getMethod(event)332 const requestInit: RequestInit = {333 headers,334 method,335 }336337 if (event.body) {338 const body = event.isBase64Encoded339 ? decodeBase64(event.body)340 : new TextEncoder().encode(event.body)341 requestInit.body = body342 headers.set('content-length', body.length.toString())343 }344345 return new Request(url, requestInit)346 }347348 async createResult(349 event: E,350 res: Response,351 options: Pick<HandleOptions, 'isContentTypeBinary'>352 ): Promise<APIGatewayProxyResult> {353 // determine whether the response body should be base64 encoded354 const contentType = res.headers.get('content-type')355 const isContentTypeBinary = options.isContentTypeBinary ?? defaultIsContentTypeBinary // overwrite default function if provided356 let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false357358 if (!isBase64Encoded) {359 const contentEncoding = res.headers.get('content-encoding')360 isBase64Encoded = isContentEncodingBinary(contentEncoding)361 }362363 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()364365 const result: APIGatewayProxyResult = {366 body: body,367 statusCode: res.status,368 isBase64Encoded,369 ...('multiValueHeaders' in event && event.multiValueHeaders370 ? {371 multiValueHeaders: {},372 }373 : {374 headers: {},375 }),376 }377378 this.setCookies(event, res, result)379 if (result.multiValueHeaders) {380 res.headers.forEach((value, key) => {381 result.multiValueHeaders[key] = [value]382 })383 } else {384 res.headers.forEach((value, key) => {385 result.headers[key] = value386 })387 }388389 return result390 }391392 setCookies(_event: E, res: Response, result: APIGatewayProxyResult) {393 if (res.headers.has('set-cookie')) {394 const cookies = res.headers.getSetCookie395 ? res.headers.getSetCookie()396 : Array.from(res.headers.entries())397 .filter(([k]) => k === 'set-cookie')398 .map(([, v]) => v)399400 if (Array.isArray(cookies)) {401 this.setCookiesToResult(result, cookies)402 res.headers.delete('set-cookie')403 }404 }405 }406}407408export class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {409 protected getPath(event: APIGatewayProxyEventV2): string {410 return event.rawPath411 }412413 protected getMethod(event: APIGatewayProxyEventV2): string {414 return event.requestContext.http.method415 }416417 protected getQueryString(event: APIGatewayProxyEventV2): string {418 return event.rawQueryString419 }420421 protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {422 if (Array.isArray(event.cookies)) {423 headers.set('Cookie', event.cookies.join('; '))424 }425 }426427 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {428 result.cookies = cookies429 }430431 protected getHeaders(event: APIGatewayProxyEventV2): Headers {432 const headers = new Headers()433 this.getCookies(event, headers)434 if (event.headers) {435 for (const [k, v] of Object.entries(event.headers)) {436 if (v) {437 headers.set(k, v)438 }439 }440 }441 return headers442 }443}444445const v2Processor: EventV2Processor = new EventV2Processor()446447export class EventV1Processor extends EventProcessor<APIGatewayProxyEvent> {448 protected getPath(event: APIGatewayProxyEvent): string {449 return event.path450 }451452 protected getMethod(event: APIGatewayProxyEvent): string {453 return event.httpMethod454 }455456 protected getQueryString(event: APIGatewayProxyEvent): string {457 // In the case of gateway Integration either queryStringParameters or multiValueQueryStringParameters can be present not both458 // API Gateway passes decoded values, so we need to re-encode them to preserve the original URL459 if (event.multiValueQueryStringParameters) {460 return Object.entries(event.multiValueQueryStringParameters || {})461 .filter(([, value]) => value)462 .map(([key, values]) =>463 values.map((value) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&')464 )465 .join('&')466 } else {467 return Object.entries(event.queryStringParameters || {})468 .filter(([, value]) => value !== undefined)469 .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value || '')}`)470 .join('&')471 }472 }473474 protected getCookies(_event: APIGatewayProxyEvent, _headers: Headers): void {475 // nop476 }477478 protected getHeaders(event: APIGatewayProxyEvent): Headers {479 const headers = new Headers()480 this.getCookies(event, headers)481 if (event.multiValueHeaders) {482 for (const [k, values] of Object.entries(event.multiValueHeaders)) {483 if (values) {484 values.forEach((v) => headers.append(k, sanitizeHeaderValue(v)))485 }486 }487 }488 if (event.headers) {489 for (const [k, v] of Object.entries(event.headers)) {490 if (v && !headers.has(k)) {491 headers.set(k, sanitizeHeaderValue(v))492 }493 }494 }495 return headers496 }497498 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {499 result.multiValueHeaders = {500 'set-cookie': cookies,501 }502 }503}504505const v1Processor: EventV1Processor = new EventV1Processor()506507export class ALBProcessor extends EventProcessor<ALBProxyEvent> {508 protected getHeaders(event: ALBProxyEvent): Headers {509 const headers = new Headers()510 // if multiValueHeaders is present the ALB will use it instead of the headers field511 // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers512 if (event.multiValueHeaders) {513 for (const [key, values] of Object.entries(event.multiValueHeaders)) {514 if (values && Array.isArray(values)) {515 // https://www.rfc-editor.org/rfc/rfc9110.html#name-common-rules-for-defining-f516 const sanitizedValue = sanitizeHeaderValue(values.join('; '))517 headers.set(key, sanitizedValue)518 }519 }520 } else {521 for (const [key, value] of Object.entries(event.headers ?? {})) {522 if (value) {523 headers.set(key, sanitizeHeaderValue(value))524 }525 }526 }527 return headers528 }529530 protected getPath(event: ALBProxyEvent): string {531 return event.path532 }533534 protected getMethod(event: ALBProxyEvent): string {535 return event.httpMethod536 }537538 protected getQueryString(event: ALBProxyEvent): string {539 // In the case of ALB Integration either queryStringParameters or multiValueQueryStringParameters can be present not both540 /*541 In other cases like when using the serverless framework, the event object does contain both queryStringParameters and multiValueQueryStringParameters:542 Below is an example event object for this URL: /payment/b8c55e69?select=amount&select=currency543 {544 ...545 queryStringParameters: { select: 'currency' },546 multiValueQueryStringParameters: { select: [ 'amount', 'currency' ] },547 }548 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.549 A simple fix would be to invert the if statement and check the multiValueQueryStringParameters first.550 */551 if (event.multiValueQueryStringParameters) {552 return Object.entries(event.multiValueQueryStringParameters || {})553 .filter(([, value]) => value)554 .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)555 .join('&')556 } else {557 return Object.entries(event.queryStringParameters || {})558 .filter(([, value]) => value !== undefined)559 .map(([key, value]) => `${key}=${value}`)560 .join('&')561 }562 }563564 protected getCookies(event: ALBProxyEvent, headers: Headers): void {565 let cookie566 if (event.multiValueHeaders) {567 cookie = event.multiValueHeaders['cookie']?.join('; ')568 } else {569 cookie = event.headers ? event.headers['cookie'] : undefined570 }571 if (cookie) {572 headers.append('Cookie', cookie)573 }574 }575576 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {577 // when multi value headers is enabled578 if (result.multiValueHeaders) {579 result.multiValueHeaders['set-cookie'] = cookies580 } else {581 result.headers['set-cookie'] = cookies[0]582 }583 }584}585586const albProcessor: ALBProcessor = new ALBProcessor()587588export class LatticeV2Processor extends EventProcessor<LatticeProxyEventV2> {589 protected getPath(event: LatticeProxyEventV2): string {590 return event.path591 }592593 protected getMethod(event: LatticeProxyEventV2): string {594 return event.method595 }596597 protected getQueryString(): string {598 return ''599 }600601 protected getHeaders(event: LatticeProxyEventV2): Headers {602 const headers = new Headers()603604 if (event.headers) {605 for (const [k, values] of Object.entries(event.headers)) {606 if (values) {607 values.forEach((v) => headers.append(k, sanitizeHeaderValue(v)))608 }609 }610 }611612 return headers613 }614615 protected getCookies(): void {616 // nop617 }618619 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {620 result.headers = {621 ...result.headers,622 'set-cookie': cookies,623 }624 }625}626627const latticeV2Processor: LatticeV2Processor = new LatticeV2Processor()628629export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {630 if (isProxyEventALB(event)) {631 return albProcessor632 }633 if (isProxyEventV2(event)) {634 return v2Processor635 }636 if (isLatticeEventV2(event)) {637 return latticeV2Processor638 }639640 return v1Processor641}642643const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {644 if (event.requestContext) {645 return Object.hasOwn(event.requestContext, 'elb')646 }647 return false648}649650const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {651 // A V1 (REST API) event behind a custom domain base path mapping also carries a652 // `rawPath`, so `rawPath` alone is not enough to identify a V2 event. Every V2653 // (HTTP API / function URL) event has an `http` object on its request context.654 return Object.hasOwn(event, 'rawPath') && Object.hasOwn(event.requestContext ?? {}, 'http')655}656657const isLatticeEventV2 = (event: LambdaEvent): event is LatticeProxyEventV2 => {658 if (event.requestContext) {659 return Object.hasOwn(event.requestContext, 'serviceArn')660 }661 return false662}663664/**665 * Check if the given content type is binary.666 * This is a default function and may be overwritten by the user via `isContentTypeBinary` option in handler().667 * @param contentType The content type to check.668 * @returns True if the content type is binary, false otherwise.669 */670export const defaultIsContentTypeBinary = (contentType: string): boolean => {671 if (/^application\/vnd\.(?:apple\.installer|mozilla\.xul)\+xml\s*(?:;|$)/i.test(contentType)) {672 return true673 }674675 return !/^text\/(?:plain|html|css|javascript|csv)|(?:\/|\+)(?:json|xml)\s*(?:;|$)/i.test(676 contentType677 )678}679680export const isContentEncodingBinary = (contentEncoding: string | null) => {681 return !!contentEncoding && !/^identity$/i.test(contentEncoding)682}