Skip to content
Myr

perf: Various performance tuning (#292)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Revert "perf(util): cache regex result for URL path(s) (#284)" This reverts commit eaef358debad34125be0dacf2692c859a4f84dcd. * Extend Request.prototype. * Tweaks constructor of Context. * Optimize context.ts * Lazy initialization. * Skip runtime type checking. * Use spread operator for creating temporary record. * Reduce object creation. * Automatic finalize flag when res is updated. * Define interface and init function for Request in request.ts * Tweaks context.text.ts. * Remove unused member "handlersCache".

authored by Taku Amano · committed by GitHub · parent 548c12b · Browse files · 11 files+204 added−301 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+204 added−301 removed

  • tests:+7 added−16 removed
  • other:+197 added−285 removed

11 files+204 added−301 removed

modified:src/middleware/serve-static/serve-static.ts+1 added-1 removed
modified:src/router/trie-router/node.ts+62 added-83 removed
1 unmodified line
2import { METHOD_NAME_ALL } from '../../router'3import type { Pattern } from '../../utils/url'4import { splitPath, getPattern } from '../../utils/url'56type Next<T> = {7 nodes: Node<T>[]8 handlerSets: HandlerSet<T>[]9 params: Record<string, string>10}116type HandlerSet<T> = {7 handler: T8 score: number9 name: string // For debug
21 unmodified lines
31 children: Record<string, Node<T>>32 patterns: Pattern[]33 order: number = 034 name: string35 handlerSetCache: Record<string, HandlerSet<T>[]>3637 constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) {38 this.children = children || {}39 this.methods = []
2 unmodified lines
42 m[method] = { handler: handler, score: 0, name: this.name }43 this.methods = [m]44 }45 this.patterns = []46 this.handlerSetCache = {}47 }4849 insert(method: string, path: string, handler: T): Node<T> {50 this.name = `${method} ${path}`
62 unmodified lines
113 return curNode114 }115116 private getHandlerSets(node: Node<T>, method: string, wildcard?: boolean): HandlerSet<T>[] {121 const handlerSets: HandlerSet<T>[] = []122 node.methods.map((m) => {123 const handlerSet = m[method] || m[METHOD_NAME_ALL]124 if (handlerSet !== undefined) {125 const hs = { ...handlerSet }126 if (wildcard) {127 hs.score = handlerSet.score - 1128 }129 handlerSets.push(hs)130 return131 }132 })133134 return handlerSets135 }136137 private next(node: Node<T>, part: string, method: string, isLast: boolean): Next<T> {138 const handlerSets: HandlerSet<T>[] = []139 const nextNodes: Node<T>[] = []140 const params: Record<string, string> = {}141142 for (let j = 0, len = node.patterns.length; j < len; j++) {143 const pattern = node.patterns[j]144145 // Wildcard146 // '/hello/*/foo' => match /hello/bar/foo147 if (pattern === '*') {148 const astNode = node.children['*']149 if (astNode) {150 handlerSets.push(...this.getHandlerSets(astNode, method))151 nextNodes.push(astNode)152 }153 continue154 }155156 if (part === '') continue157158 // Named match159 // `/posts/:id` => match /posts/123160 const [key, name, matcher] = pattern161 if (matcher === true || (matcher instanceof RegExp && matcher.test(part))) {162 if (typeof key === 'string') {163 if (isLast === true) {164 handlerSets.push(...this.getHandlerSets(node.children[key], method))117 return (node.handlerSetCache[`${method}:${wildcard ? '1' : '0'}`] ||= (() => {118 const handlerSets: HandlerSet<T>[] = []119 node.methods.map((m) => {120 const handlerSet = m[method] || m[METHOD_NAME_ALL]121 if (handlerSet !== undefined) {122 const hs = { ...handlerSet }123 if (wildcard) {124 hs.score = handlerSet.score - 1125 }166 nextNodes.push(node.children[key])126 handlerSets.push(hs)127 return128 }168 if (typeof name === 'string') {169 params[name] = part170 }171 }172 }129 })130174 const nextNode = node.children[part]175176 if (nextNode) {177 if (isLast === true) {178 // '/hello/*' => match '/hello'179 if (nextNode.children['*']) {180 handlerSets.push(...this.getHandlerSets(nextNode.children['*'], method, true))181 }182 handlerSets.push(...this.getHandlerSets(nextNode, method))183 }184 nextNodes.push(nextNode)185 }186187 const next: Next<T> = {188 nodes: nextNodes,189 handlerSets: handlerSets,190 params: params,191 }192 return next131 return handlerSets132 })())133 }134135 search(method: string, path: string): Result<T> | null {136 const handlerSets: HandlerSet<T>[] = []197 let params: Record<string, string> = {}137 const params: Record<string, string> = {}138139 // eslint-disable-next-line @typescript-eslint/no-this-alias140 const curNode: Node<T> = this141 let curNodes = [curNode]142 const parts = splitPath(path)143144 for (let i = 0, len = parts.length; i < len; i++) {205 const p: string = parts[i]145 const part: string = parts[i]146 const isLast = i === len - 1147 const tempNodes: Node<T>[] = []148149 for (let j = 0, len2 = curNodes.length; j < len2; j++) {210 const res = this.next(curNodes[j], p, method, isLast)211 if (res.nodes.length === 0) {212 continue150 const node = curNodes[j]151152 for (let k = 0, len3 = node.patterns.length; k < len3; k++) {153 const pattern = node.patterns[k]154155 // Wildcard156 // '/hello/*/foo' => match /hello/bar/foo157 if (pattern === '*') {158 const astNode = node.children['*']159 if (astNode) {160 handlerSets.push(...this.getHandlerSets(astNode, method))161 tempNodes.push(astNode)162 }163 continue164 }165166 if (part === '') continue167168 // Named match169 // `/posts/:id` => match /posts/123170 const [key, name, matcher] = pattern171 if (matcher === true || (matcher instanceof RegExp && matcher.test(part))) {172 if (typeof key === 'string') {173 if (isLast === true) {174 handlerSets.push(...this.getHandlerSets(node.children[key], method))175 }176 tempNodes.push(node.children[key])177 }178 if (typeof name === 'string') {179 params[name] = part180 }181 }182 }214 handlerSets.push(...res.handlerSets)215 params = { ...params, ...res.params }216 tempNodes.push(...res.nodes)183184 const nextNode = node.children[part]185186 if (nextNode) {187 if (isLast === true) {188 // '/hello/*' => match '/hello'189 if (nextNode.children['*']) {190 handlerSets.push(...this.getHandlerSets(nextNode.children['*'], method, true))191 }192 handlerSets.push(...this.getHandlerSets(nextNode, method))193 }194 tempNodes.push(nextNode)195 }196 }197198 curNodes = tempNodes199 }
14 unmodified lines
modified:src/utils/url.test.ts-7 removed
modified:src/utils/url.ts+5 added-14 removed
1const URL_REGEXP = /^https?:\/\/[a-zA-Z0-9\-\.:]+(\/?[^?#]*)/23export type Pattern = readonly [string, string, RegExp | true] | '*'45const splitPathCache: Record<string, string[]> = {}5export const splitPath = (path: string): string[] => {7 let paths = splitPathCache[path]8 if (paths) {9 return paths10 }11 paths = path.split(/\//) // faster than path.split('/')6 const paths = path.split(/\//) // faster than path.split('/')7 if (paths[0] === '') {8 paths.shift()9 }15 splitPathCache[path] = paths10 return paths11}1213const patternCache: { [key: string]: Pattern } = {}
26 unmodified lines
40type Params = {41 strict: boolean42}4350const pathFromURLCache: Record<string, string> = {}44export const getPathFromURL = (url: string, params: Params = { strict: true }): string => {45 // if strict routing is false => `/hello/hey/` and `/hello/hey` are treated the same46 // default is true47 if (params.strict === false && url.endsWith('/')) {48 url = url.slice(0, -1)49 }5058 let path = pathFromURLCache[url]59 if (path) return path6051 const match = url.match(URL_REGEXP)62 path = match ? match[1] : ''63 pathFromURLCache[url] = path64 return path52 if (match) {53 return match[1]54 }55 return ''56}5758export const isAbsoluteURL = (url: string): boolean => {59 const match = url.match(URL_REGEXP)
37 unmodified lines
modified:src/compose.test.ts+3 added
1import { compose } from './compose'2import { Context } from './context'3import { extendRequestPrototype } from './request'45extendRequestPrototype()67type C = {8 req: Record<string, string>9 res: Record<string, string>10}
622 unmodified lines
modified:src/compose.ts+1 added-4 removed
17 unmodified lines
18 index = i19 if (i === middleware.length && next) handler = next2021 if (!handler) {22 if (context instanceof Context && context.res._finalized === false && onNotFound) {22 if (context instanceof Context && context.finalized === false && onNotFound) {23 context.res = onNotFound(context)24 context.res._finalized = true24 }25 return Promise.resolve(context)26 }27
1 unmodified line
29 .then(async (res: Response) => {30 // If handler return Response like `return c.text('foo')`31 if (res && context instanceof Context) {32 context.res = res34 context.res._finalized = true33 }34 return context35 })36 .catch((err) => {37 if (context instanceof Context && onError) {38 if (err instanceof Error) {39 context.res = onError(err, context)42 context.res._finalized = true40 }41 return context42 } else {43 throw err
5 unmodified lines
modified:src/context.test.ts+4 added-9 removed
84 unmodified lines
85 it('Has headers and status', async () => {86 c.header('x-custom1', 'Message1')87 c.header('x-custom2', 'Message2')88 c.status(200)89 const res = c.newResponse('this is body', {90 status: 201,91 headers: {92 'x-custom3': 'Message3',93 'x-custom2': 'Message2-Override',94 },89 const res = c.newResponse('this is body', 201, {90 'x-custom3': 'Message3',91 'x-custom2': 'Message2-Override',92 })93 expect(res.headers.get('x-Custom1')).toBe('Message1')94 expect(res.headers.get('x-Custom2')).toBe('Message2-Override')95 expect(res.headers.get('x-Custom3')).toBe('Message3')
23 unmodified lines
119 it('Should be able read env', async () => {120 const req = new Request('http://localhost/')121 const key = 'a-secret-key'122 const ctx = new Context(req, {126 env: {127 API_KEY: key,123 API_KEY: key,128 },124 })125 expect(ctx.env.API_KEY).toBe(key)126 })127
18 unmodified lines
modified:src/context.ts+46 added-88 removed
1import { HonoResponse } from './response'1import type { StatusCode } from './utils/http-status'2import { isAbsoluteURL } from './utils/url'34type Headers = Record<string, string>
2 unmodified lines
7export type Env = Record<string, any>89export class Context<RequestParamKeyType extends string = string, E = Env> {10 req: Request<RequestParamKeyType>12 res: Response11 env: E12 event: FetchEvent | undefined13 finalized: boolean1415 private _status: StatusCode = 20016 private _pretty: boolean = false17 private _prettySpace: number = 219 private _map: {20 [key: string]: any21 }18 private _map: Record<string, any> | undefined19 private _headers: Record<string, string> | undefined20 private _res: Response | undefined21 private notFoundHandler: (c: Context<string, E>) => Response2223 render: (template: string, params?: object, options?: object) => Promise<Response>24 notFound: () => Response | Promise<Response>2425 constructor(26 req: Request<RequestParamKeyType>,28 opts: { env?: Env; event?: FetchEvent; res?: Response | HonoResponse } = {29 env: {},30 event: undefined,31 res: undefined,32 }27 env: E | undefined = undefined,28 event: FetchEvent | undefined = undefined,29 notFoundHandler: (c: Context<string, E>) => Response = () => new Response()30 ) {34 this.req = this.initRequest<RequestParamKeyType>(req)35 this._map = {}31 this.req = req3237 Object.assign(this, opts)3839 if (!this.res) {40 const res = new HonoResponse(null, { status: 404 })41 res._finalized = false42 this.res = res33 if (env) {34 this.env = env35 }36 this.event = event37 this.notFoundHandler = notFoundHandler38 this.finalized = false39 }4046 private initRequest<T extends string>(req: Request<T>): Request<T> {47 req.header = ((name?: string): string | Record<string, string> | null => {48 if (name) {49 return req.headers.get(name)50 } else {51 const result: Record<string, string> = {}52 for (const [key, value] of req.headers) {53 result[key] = value54 }55 return result56 }57 }) as typeof req.header41 get res(): Response {42 return (this._res ||= new Response())43 }4459 req.query = ((key?: string): string | Record<string, string> | null => {60 const url = new URL(req.url)61 if (key) {62 return url.searchParams.get(key)63 } else {64 const result: Record<string, string> = {}65 for (const key of url.searchParams.keys()) {66 result[key] = url.searchParams.get(key) || ''67 }68 return result69 }70 }) as typeof req.query7172 req.queries = ((key?: string): string[] | Record<string, string[]> => {73 const url = new URL(req.url)74 if (key) {75 return url.searchParams.getAll(key)76 } else {77 const result: Record<string, string[]> = {}78 for (const key of url.searchParams.keys()) {79 result[key] = url.searchParams.getAll(key)80 }81 return result82 }83 }) as typeof req.queries8485 return req45 set res(_res: Response) {46 this._res = _res47 this.finalized = true48 }4950 header(name: string, value: string): void {51 this._headers ||= {}52 this._headers[name] = value53 if (this.finalized) {89 this.res.headers.set(name, value)54 this.res.headers.set(name, value)55 }56 }5758 status(status: StatusCode): void {59 this._status = status60 }6162 set(key: string, value: any): void {63 this._map ||= {}64 this._map[key] = value65 }6667 get(key: string) {68 if (!this._map) {69 return undefined70 }71 return this._map[key]72 }7374 pretty(prettyJSON: boolean, space: number = 2): void {75 this._pretty = prettyJSON76 this._prettySpace = space77 }78109 newResponse(data: Data | null, init: ResponseInit = {}): Response {110 init.status = init.status || this._status || 200111 const headers: Record<string, string> = {}112 this.res.headers.forEach((v, k) => {113 headers[k] = v79 newResponse(data: Data | null, status: StatusCode, headers: Headers = {}): Response {80 const _headers = { ...this._headers, ...headers }81 if (this._res) {82 this._res.headers.forEach((v, k) => {83 _headers[k] = v84 })85 }86 return new Response(data, {87 status: status || this._status || 200,88 headers: _headers,89 })115 init.headers = Object.assign(headers, init.headers)116117 return new Response(data, init)90 }9192 body(data: Data | null, status: StatusCode = this._status, headers: Headers = {}): Response {121 return this.newResponse(data, {122 status: status,123 headers: headers,124 })93 return this.newResponse(data, status, headers)94 }9596 text(text: string, status: StatusCode = this._status, headers: Headers = {}): Response {128 if (typeof text !== 'string') {129 throw new TypeError('text method arg must be a string!')130 }97 headers['Content-Type'] ||= 'text/plain; charset=UTF-8'98 return this.body(text, status, headers)99 }100101 json(object: object, status: StatusCode = this._status, headers: Headers = {}): Response {136 if (typeof object !== 'object') {137 throw new TypeError('json method arg must be an object!')138 }102 const body = this._pretty103 ? JSON.stringify(object, null, this._prettySpace)104 : JSON.stringify(object)105 headers['Content-Type'] ||= 'application/json; charset=UTF-8'106 return this.body(body, status, headers)107 }108109 html(html: string, status: StatusCode = this._status, headers: Headers = {}): Response {147 if (typeof html !== 'string') {148 throw new TypeError('html method arg must be a string!')149 }110 headers['Content-Type'] ||= 'text/html; charset=UTF-8'111 return this.body(html, status, headers)112 }113114 redirect(location: string, status: StatusCode = 302): Response {155 if (typeof location !== 'string') {156 throw new TypeError('location must be a string!')157 }115 if (!isAbsoluteURL(location)) {116 const url = new URL(this.req.url)117 url.pathname = location118 location = url.toString()119 }163 return this.newResponse(null, {164 status: status,165 headers: {166 Location: location,167 },120 return this.newResponse(null, status, {121 Location: location,122 })123 }124125 notFound(): Response | Promise<Response> {126 return this.notFoundHandler(this as any)127 }128}
modified:src/hono.ts+5 added-39 removed
1import { compose } from './compose'2import { Context } from './context'3import type { Env } from './context'4import { extendRequestPrototype } from './request'5import type { Router } from './router'6import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from './router'7import { TrieRouter } from './router/trie-router' // Default Router8import { getPathFromURL, mergePath } from './utils/url'99declare global {10 interface Request<ParamKeyType extends string = string> {11 param: {12 (key: ParamKeyType): string13 (): Record<ParamKeyType, string>14 }15 query: {16 (key: string): string17 (): Record<string, string>18 }19 queries: {20 (key: string): string[]21 (): Record<string, string[]>22 }23 header: {24 (name: string): string25 (): Record<string, string>26 }27 }28 interface Response {29 _finalized: boolean30 }31}3210export type Handler<RequestParamKeyType extends string = string, E = Env> = (11 c: Context<RequestParamKeyType, E>,12 next: Next13) => Response | Promise<Response> | Promise<void> | Promise<Response | undefined>
55 unmodified lines
6970 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {71 super()7273 extendRequestPrototype() // FIXME: should be executed at a better timing7475 const allMethods = [...methods, METHOD_NAME_ALL_LOWERCASE]76 allMethods.map((method) => {77 this[method] = <Path extends string = ''>(78 args1: Path | Handler<ParamKeys<Path>, E>,
82 unmodified lines
161 const method = request.method162163 const result = this.matchRoute(method, path)164186 request.param = ((key?: string): string | Record<string, string> | null => {187 if (result) {188 if (key) {189 return result.params[key]190 } else {191 return result.params192 }193 }194 return null195 }) as typeof request.param165 request.paramData = result?.params166167 const handlers = result ? result.handlers : [this.notFoundHandler]168199 const c = new Context<string, E>(request, {200 env: env,201 event: event,202 })203 c.notFound = () => this.notFoundHandler(c)169 const c = new Context<string, E>(request, env, event, this.notFoundHandler)170171 const composed = compose<Context>(handlers, this.errorHandler, this.notFoundHandler)172 let context: Context173 try {
30 unmodified lines
added:src/request.ts+77 added
1declare global {2 interface Request<ParamKeyType extends string = string> {3 param: {4 (key: ParamKeyType): string5 (): Record<ParamKeyType, string>6 }7 paramData?: Record<ParamKeyType, string>8 query: {9 (key: string): string10 (): Record<string, string>11 }12 queries: {13 (key: string): string[]14 (): Record<string, string[]>15 }16 header: {17 (name: string): string18 (): Record<string, string>19 }20 }21}2223export function extendRequestPrototype() {24 if (!!Request.prototype.param as boolean) {25 // already extended26 return27 }2829 Request.prototype.param = function (this: Request, key?: string) {30 if (this.paramData) {31 if (key) {32 return this.paramData[key]33 } else {34 return this.paramData35 }36 }37 return null38 } as InstanceType<typeof Request>['param']3940 Request.prototype.header = function (this: Request, name?: string) {41 if (name) {42 return this.headers.get(name)43 } else {44 const result: Record<string, string> = {}45 for (const [key, value] of this.headers) {46 result[key] = value47 }48 return result49 }50 } as InstanceType<typeof Request>['header']5152 Request.prototype.query = function (this: Request, key?: string) {53 const url = new URL(this.url)54 if (key) {55 return url.searchParams.get(key)56 } else {57 const result: Record<string, string> = {}58 for (const key of url.searchParams.keys()) {59 result[key] = url.searchParams.get(key) || ''60 }61 return result62 }63 } as InstanceType<typeof Request>['query']6465 Request.prototype.queries = function (this: Request, key?: string) {66 const url = new URL(this.url)67 if (key) {68 return url.searchParams.getAll(key)69 } else {70 const result: Record<string, string[]> = {}71 for (const key of url.searchParams.keys()) {72 result[key] = url.searchParams.getAll(key)73 }74 return result75 }76 } as InstanceType<typeof Request>['queries']77}
deleted:src/response.ts-56 removed
1/*2 This Response object is for better performance.3 This object is used in a Context before the Handler dispatches.4*/56import type { Data } from './context'7const errorMessage = 'Response is not finalized'89export class HonoResponse implements Response {10 headers: Headers11 ok: boolean12 redirected: boolean13 status: number14 statusText: string15 type: ResponseType16 url: string17 _finalized: boolean1819 constructor(_data: Data | null, init: ResponseInit) {20 this.headers = new Headers(init.headers)21 this.status = init.status ?? 40422 this._finalized = false23 }2425 clone(): Response {26 throw new Error(errorMessage)27 }2829 body: ReadableStream<Uint8Array> | null30 bodyUsed: boolean31 arrayBuffer(): Promise<ArrayBuffer>32 arrayBuffer(): Promise<ArrayBuffer>33 arrayBuffer(): Promise<ArrayBuffer> {34 throw new Error(errorMessage)35 }36 blob(): Promise<Blob>37 blob(): Promise<Blob>38 blob(): Promise<Blob> {39 throw new Error(errorMessage)40 }41 formData(): Promise<FormData>42 formData(): Promise<FormData>43 formData(): Promise<FormData> {44 throw new Error(errorMessage)45 }46 json(): Promise<any>47 json<T>(): Promise<T>48 json<T>(): Promise<any> | Promise<T> {49 throw new Error(errorMessage)50 }51 text(): Promise<string>52 text(): Promise<string>53 text(): Promise<string> {54 throw new Error(errorMessage)55 }56}