timing.ts
This file
Path
src/middleware/timing/timing.ts
257 lines · 6.7 KiB · TypeScript
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–257why, one step back1/**2 * @module3 * Server-Timing Middleware for Hono.4 */56import type { Context } from '../../context'7import type { MiddlewareHandler } from '../../types'8import '../../context'910export type TimingVariables = {11 metric?: {12 headers: string[]13 timers: Map<string, Timer>14 }15}1617interface Timer {18 description?: string19 start: number20}2122interface TimingOptions {23 total?: boolean24 enabled?: boolean | ((c: Context) => boolean)25 totalDescription?: string26 autoEnd?: boolean27 crossOrigin?: boolean | string | ((c: Context) => boolean | string)28}2930const getTime = (): number => {31 try {32 return performance.now()33 } catch {}34 return Date.now()35}3637/**38 * Server-Timing Middleware for Hono.39 *40 * @see {@link https://hono.dev/docs/middleware/builtin/timing}41 *42 * @param {TimingOptions} [config] - The options for the timing middleware.43 * @param {boolean} [config.total=true] - Show the total response time.44 * @param {boolean | ((c: Context) => boolean)} [config.enabled=true] - Whether timings should be added to the headers or not.45 * @param {string} [config.totalDescription=Total Response Time] - Description for the total response time.46 * @param {boolean} [config.autoEnd=true] - If `startTime()` should end automatically at the end of the request.47 * @param {boolean | string | ((c: Context) => boolean | string)} [config.crossOrigin=false] - The origin this timings header should be readable.48 * @returns {MiddlewareHandler} The middleware handler function.49 *50 * @example51 * ```ts52 * const app = new Hono()53 *54 * // add the middleware to your router55 * app.use(timing());56 *57 * app.get('/', async (c) => {58 * // add custom metrics59 * setMetric(c, 'region', 'europe-west3')60 *61 * // add custom metrics with timing, must be in milliseconds62 * setMetric(c, 'custom', 23.8, 'My custom Metric')63 *64 * // start a new timer65 * startTime(c, 'db');66 *67 * const data = await db.findMany(...);68 *69 * // end the timer70 * endTime(c, 'db');71 *72 * return c.json({ response: data });73 * });74 * ```75 */76export const timing = (config?: TimingOptions): MiddlewareHandler => {77 const options: TimingOptions = {78 total: true,79 enabled: true,80 totalDescription: 'Total Response Time',81 autoEnd: true,82 crossOrigin: false,83 ...config,84 }85 return async function timing(c, next) {86 const headers: string[] = []87 const timers = new Map<string, Timer>()8889 if (c.get('metric')) {90 return await next()91 }9293 c.set('metric', { headers, timers })9495 if (options.total) {96 startTime(c, 'total', options.totalDescription)97 }98 await next()99100 if (options.total) {101 endTime(c, 'total')102 }103104 if (options.autoEnd) {105 timers.forEach((_, key) => {106 endTime(c, key)107 })108 }109110 const enabled = typeof options.enabled === 'function' ? options.enabled(c) : options.enabled111112 if (enabled) {113 c.res.headers.append('Server-Timing', headers.join(','))114115 const crossOrigin =116 typeof options.crossOrigin === 'function' ? options.crossOrigin(c) : options.crossOrigin117118 if (crossOrigin) {119 c.res.headers.append(120 'Timing-Allow-Origin',121 typeof crossOrigin === 'string' ? crossOrigin : '*'122 )123 }124 }125 }126}127128interface SetMetric {129 (c: Context, name: string, value: number, description?: string, precision?: number): void130131 (c: Context, name: string, description?: string): void132}133134/**135 * Set a metric for the timing middleware.136 *137 * @param {Context} c - The context of the request.138 * @param {string} name - The name of the metric.139 * @param {number | string} [valueDescription] - The value or description of the metric.140 * @param {string} [description] - The description of the metric.141 * @param {number} [precision] - The precision of the metric value.142 *143 * @example144 * ```ts145 * setMetric(c, 'region', 'europe-west3')146 * setMetric(c, 'custom', 23.8, 'My custom Metric')147 * ```148 */149export const setMetric: SetMetric = (150 c: Context,151 name: string,152 valueDescription: number | string | undefined,153 description?: string,154 precision?: number155) => {156 const metrics = c.get('metric')157 if (!metrics) {158 console.warn('Metrics not initialized! Please add the `timing()` middleware to this route!')159 return160 }161 if (typeof valueDescription === 'number') {162 const dur = valueDescription.toFixed(precision || 1)163164 const metric = description ? `${name};dur=${dur};desc="${description}"` : `${name};dur=${dur}`165166 metrics.headers.push(metric)167 } else {168 // Value-less metric169 const metric = valueDescription ? `${name};desc="${valueDescription}"` : `${name}`170171 metrics.headers.push(metric)172 }173}174175/**176 * Start a timer for the timing middleware.177 *178 * @param {Context} c - The context of the request.179 * @param {string} name - The name of the timer.180 * @param {string} [description] - The description of the timer.181 *182 * @example183 * ```ts184 * startTime(c, 'db')185 * ```186 */187export const startTime = (c: Context, name: string, description?: string) => {188 const metrics = c.get('metric')189 if (!metrics) {190 console.warn('Metrics not initialized! Please add the `timing()` middleware to this route!')191 return192 }193 metrics.timers.set(name, { description, start: getTime() })194}195196/**197 * End a timer for the timing middleware.198 *199 * @param {Context} c - The context of the request.200 * @param {string} name - The name of the timer.201 * @param {number} [precision] - The precision of the timer value.202 *203 * @example204 * ```ts205 * endTime(c, 'db')206 * ```207 */208export const endTime = (c: Context, name: string, precision?: number) => {209 const metrics = c.get('metric')210 if (!metrics) {211 console.warn('Metrics not initialized! Please add the `timing()` middleware to this route!')212 return213 }214 const timer = metrics.timers.get(name)215 if (!timer) {216 console.warn(`Timer "${name}" does not exist!`)217 return218 }219 const { description, start } = timer220221 const duration = getTime() - start222223 setMetric(c, name, duration, description, precision)224 metrics.timers.delete(name)225}226227/**228 * Wrap a Promise to capture its duration.229 * @param {Context} c - The context of the request.230 * @param {string} name - The name of the timer.231 * @param {Promise<T>} callable - The Promise to time.232 * @param {string} [description] - The description of the timer.233 * @param {number} [precision] - The precision of the timer value.234 *235 * @example236 * ```ts237 * // Instead of this:238 * const data = await db.findMany(...);239 *240 * // do this:241 * const data = await wrapTime(c, 'query', db.findMany(...));242 * ```243 * */244export async function wrapTime<T>(245 c: Context,246 name: string,247 callable: Promise<T>,248 description?: string,249 precision?: number250): Promise<T> {251 startTime(c, name, description)252 try {253 return await callable254 } finally {255 endTime(c, name, precision)256 }257}