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".
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
Provenance
- Commit
9da10ac- Tree
3c897c9- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
548c12b
11 files changed+204 added−301 removed
modified:src/middleware/serve-static/serve-static.ts+1 added-1 removed
13 unmodified lines1415161718181920212225 unmodified lines13 unmodified lines// This middleware is available only on Cloudflare Workers.export const serveStatic = (options: ServeStaticOptions = { root: '' }): Handler<string, Env> => { return async (c: Context, next: Next): Promise<Response | undefined> => { // Do nothing if Response is already set if (c.res && c.res._finalized) { if (c.res && c.finalized) { await next() }
const url = new URL(c.req.url)25 unmodified linesmodified:src/router/trie-router/node.ts+62 added-83 removed
1 unmodified line2 import { METHOD_NAME_ALL } from '../../router'3 import type { Pattern } from '../../utils/url'4 import { splitPath, getPattern } from '../../utils/url'5 6-type Next<T> = {7- nodes: Node<T>[]8- handlerSets: HandlerSet<T>[]9- params: Record<string, string>10-}11-6 type HandlerSet<T> = {7 handler: T8 score: number9 name: string // For debug21 unmodified lines31 children: Record<string, Node<T>>32 patterns: Pattern[]33 order: number = 034 name: string35+ handlerSetCache: Record<string, HandlerSet<T>[]>36 37 constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) {38 this.children = children || {}39 this.methods = []2 unmodified lines42 m[method] = { handler: handler, score: 0, name: this.name }43 this.methods = [m]44 }45 this.patterns = []46+ this.handlerSetCache = {}47 }48 49 insert(method: string, path: string, handler: T): Node<T> {50 this.name = `${method} ${path}`62 unmodified lines113 return curNode114 }115 116 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- })133-134- return handlerSets135- }136-137- 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> = {}141-142- for (let j = 0, len = node.patterns.length; j < len; j++) {143- const pattern = node.patterns[j]144-145- // 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- }155-156- if (part === '') continue157-158- // 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+ })130 174- const nextNode = node.children[part]175-176- 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- }186-187- const next: Next<T> = {188- nodes: nextNodes,189- handlerSets: handlerSets,190- params: params,191- }192- return next131+ return handlerSets132+ })())133 }134 135 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> = {}138 139 // eslint-disable-next-line @typescript-eslint/no-this-alias140 const curNode: Node<T> = this141 let curNodes = [curNode]142 const parts = splitPath(path)143 144 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>[] = []148 149 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]151+152+ for (let k = 0, len3 = node.patterns.length; k < len3; k++) {153+ const pattern = node.patterns[k]154+155+ // 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+ }165+166+ if (part === '') continue167+168+ // 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)183+184+ const nextNode = node.children[part]185+186+ 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 }197 198 curNodes = tempNodes199 }14 unmodified linesmodified:src/utils/url.test.ts-7 removed
6 unmodified lines78910111213141112131422 unmodified lines373839404546474142434462 unmodified lines6 unmodified lines
ps = splitPath('/hello') expect(ps).toStrictEqual(['hello'])
// Is cache OK? ps = splitPath('/hello') expect(ps).toStrictEqual(['hello'])
ps = splitPath('*') expect(ps).toStrictEqual(['*'])
ps = splitPath('/wildcard-abc/*/wildcard-efg')22 unmodified lines let path = getPathFromURL('https://example.com/') expect(path).toBe('/') path = getPathFromURL('https://example.com/hello') expect(path).toBe('/hello') // Is cache OK? path = getPathFromURL('https://example.com/hello') expect(path).toBe('/hello') path = getPathFromURL('https://example.com/hello/hey') expect(path).toBe('/hello/hey') path = getPathFromURL('https://example.com/hello?name=foo') expect(path).toBe('/hello')62 unmodified linesmodified:src/utils/url.ts+5 added-14 removed
1 const URL_REGEXP = /^https?:\/\/[a-zA-Z0-9\-\.:]+(\/?[^?#]*)/2 3 export type Pattern = readonly [string, string, RegExp | true] | '*'4 5-const splitPathCache: Record<string, string[]> = {}5 export 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 }12 13 const patternCache: { [key: string]: Pattern } = {}26 unmodified lines40 type Params = {41 strict: boolean42 }43 50-const pathFromURLCache: Record<string, string> = {}44 export 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 }50 58- let path = pathFromURLCache[url]59- if (path) return path60-51 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 }57 58 export const isAbsoluteURL = (url: string): boolean => {59 const match = url.match(URL_REGEXP)37 unmodified linesmodified:src/compose.test.ts+3 added
1 import { compose } from './compose'2 import { Context } from './context'3+import { extendRequestPrototype } from './request'4 5+extendRequestPrototype()6+7 type C = {8 req: Record<string, string>9 res: Record<string, string>10 }622 unmodified linesmodified:src/compose.ts+1 added-4 removed
17 unmodified lines18 index = i19 if (i === middleware.length && next) handler = next20 21 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 line29 .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 err5 unmodified linesmodified:src/context.test.ts+4 added-9 removed
84 unmodified lines85 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 lines119 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 linesmodified:src/context.ts+46 added-88 removed
1-import { HonoResponse } from './response'1 import type { StatusCode } from './utils/http-status'2 import { isAbsoluteURL } from './utils/url'3 4 type Headers = Record<string, string>2 unmodified lines7 export type Env = Record<string, any>8 9 export class Context<RequestParamKeyType extends string = string, E = Env> {10 req: Request<RequestParamKeyType>12- res: Response11 env: E12 event: FetchEvent | undefined13+ finalized: boolean14 15 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>) => Response22 23 render: (template: string, params?: object, options?: object) => Promise<Response>24- notFound: () => Response | Promise<Response>24 25 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 = req32 37- Object.assign(this, opts)38-39- 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 }40 46- 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+ }44 59- 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.query71-72- 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.queries84-85- return req45+ set res(_res: Response) {46+ this._res = _res47+ this.finalized = true48 }49 50 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 }57 58 status(status: StatusCode): void {59 this._status = status60 }61 62 set(key: string, value: any): void {63+ this._map ||= {}64 this._map[key] = value65 }66 67 get(key: string) {68+ if (!this._map) {69+ return undefined70+ }71 return this._map[key]72 }73 74 pretty(prettyJSON: boolean, space: number = 2): void {75 this._pretty = prettyJSON76 this._prettySpace = space77 }78 109- 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)116-117- return new Response(data, init)90 }91 92 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 }95 96 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 }100 101 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 }108 109 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 }113 114 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 }124+125+ notFound(): Response | Promise<Response> {126+ return this.notFoundHandler(this as any)127+ }128 }modified:src/hono.ts+5 added-39 removed
1 import { compose } from './compose'2 import { Context } from './context'3 import type { Env } from './context'4+import { extendRequestPrototype } from './request'5 import type { Router } from './router'6 import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from './router'7 import { TrieRouter } from './router/trie-router' // Default Router8 import { getPathFromURL, mergePath } from './utils/url'9 9-declare 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-}32-10 export 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 lines69 70 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {71 super()72 73+ extendRequestPrototype() // FIXME: should be executed at a better timing74+75 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 lines161 const method = request.method162 163 const result = this.matchRoute(method, path)164 186- 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?.params166 167 const handlers = result ? result.handlers : [this.notFoundHandler]168 199- 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)170 171 const composed = compose<Context>(handlers, this.errorHandler, this.notFoundHandler)172 let context: Context173 try {30 unmodified linesadded:src/request.ts+77 added
1+declare 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+}22+23+export function extendRequestPrototype() {24+ if (!!Request.prototype.param as boolean) {25+ // already extended26+ return27+ }28+29+ 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']39+40+ 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']51+52+ 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']64+65+ 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-*/5-6-import type { Data } from './context'7-const errorMessage = 'Response is not finalized'8-9-export class HonoResponse implements Response {10- headers: Headers11- ok: boolean12- redirected: boolean13- status: number14- statusText: string15- type: ResponseType16- url: string17- _finalized: boolean18-19- constructor(_data: Data | null, init: ResponseInit) {20- this.headers = new Headers(init.headers)21- this.status = init.status ?? 40422- this._finalized = false23- }24-25- clone(): Response {26- throw new Error(errorMessage)27- }28-29- 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-}