|
| 1 | +import nodeTimesPromises from "node:timers/promises"; |
| 2 | +import nodeFsPromises from "node:fs/promises"; |
| 3 | +import nodePath from "node:path"; |
| 4 | +import { getPercentile } from "./utils"; |
| 5 | + |
| 6 | +export type FetchBenchmark = { |
| 7 | + iterationsMs: number[]; |
| 8 | + averageMs: number; |
| 9 | + p90Ms: number; |
| 10 | +}; |
| 11 | + |
| 12 | +export type BenchmarkingResults = { |
| 13 | + name: string; |
| 14 | + path: string; |
| 15 | + fetchBenchmark: FetchBenchmark; |
| 16 | +}[]; |
| 17 | + |
| 18 | +type BenchmarkFetchOptions = { |
| 19 | + numberOfIterations?: number; |
| 20 | + maxRandomDelayMs?: number; |
| 21 | + fetch: (deploymentUrl: string) => Promise<Response>; |
| 22 | +}; |
| 23 | + |
| 24 | +const defaultOptions: Required<Omit<BenchmarkFetchOptions, "fetch">> = { |
| 25 | + numberOfIterations: 20, |
| 26 | + maxRandomDelayMs: 15_000, |
| 27 | +}; |
| 28 | + |
| 29 | +/** |
| 30 | + * Benchmarks the response time of an application end-to-end by: |
| 31 | + * - building the application |
| 32 | + * - deploying it |
| 33 | + * - and fetching from it (multiple times) |
| 34 | + * |
| 35 | + * @param options.build function implementing how the application is to be built |
| 36 | + * @param options.deploy function implementing how the application is deployed (returning the url of the deployment) |
| 37 | + * @param options.fetch function indicating how to fetch from the application (in case a specific route needs to be hit, cookies need to be applied, etc...) |
| 38 | + * @returns the benchmarking results for the application |
| 39 | + */ |
| 40 | +export async function benchmarkApplicationResponseTime({ |
| 41 | + build, |
| 42 | + deploy, |
| 43 | + fetch, |
| 44 | +}: { |
| 45 | + build: () => Promise<void>; |
| 46 | + deploy: () => Promise<string>; |
| 47 | + fetch: (deploymentUrl: string) => Promise<Response>; |
| 48 | +}): Promise<FetchBenchmark> { |
| 49 | + await build(); |
| 50 | + const deploymentUrl = await deploy(); |
| 51 | + return benchmarkFetch(deploymentUrl, { fetch }); |
| 52 | +} |
| 53 | + |
| 54 | +/** |
| 55 | + * Benchmarks a fetch operation by running it multiple times and computing the average time (in milliseconds) such fetch operation takes. |
| 56 | + * |
| 57 | + * @param url The url to fetch from |
| 58 | + * @param options options for the benchmarking |
| 59 | + * @returns the computed average alongside all the single call times |
| 60 | + */ |
| 61 | +async function benchmarkFetch(url: string, options: BenchmarkFetchOptions): Promise<FetchBenchmark> { |
| 62 | + const benchmarkFetchCall = async () => { |
| 63 | + const preTimeMs = performance.now(); |
| 64 | + const resp = await options.fetch(url); |
| 65 | + const postTimeMs = performance.now(); |
| 66 | + |
| 67 | + if (!resp.ok) { |
| 68 | + throw new Error(`Error: Failed to fetch from "${url}"`); |
| 69 | + } |
| 70 | + |
| 71 | + return postTimeMs - preTimeMs; |
| 72 | + }; |
| 73 | + |
| 74 | + const resolvedOptions = { ...defaultOptions, ...options }; |
| 75 | + |
| 76 | + const iterationsMs = await Promise.all( |
| 77 | + new Array(resolvedOptions.numberOfIterations).fill(null).map(async () => { |
| 78 | + // let's add a random delay before we make the fetch |
| 79 | + await nodeTimesPromises.setTimeout(Math.round(Math.random() * resolvedOptions.maxRandomDelayMs)); |
| 80 | + |
| 81 | + return benchmarkFetchCall(); |
| 82 | + }) |
| 83 | + ); |
| 84 | + |
| 85 | + const averageMs = iterationsMs.reduce((time, sum) => sum + time) / iterationsMs.length; |
| 86 | + |
| 87 | + const p90Ms = getPercentile(iterationsMs, 90); |
| 88 | + |
| 89 | + return { |
| 90 | + iterationsMs, |
| 91 | + averageMs, |
| 92 | + p90Ms, |
| 93 | + }; |
| 94 | +} |
| 95 | + |
| 96 | +/** |
| 97 | + * Saves benchmarking results in a local json file |
| 98 | + * |
| 99 | + * @param results the benchmarking results to save |
| 100 | + * @returns the path to the created json file |
| 101 | + */ |
| 102 | +export async function saveResultsToDisk(results: BenchmarkingResults): Promise<string> { |
| 103 | + const date = new Date(); |
| 104 | + |
| 105 | + const fileName = `${toSimpleDateString(date)}.json`; |
| 106 | + |
| 107 | + const outputFile = nodePath.resolve(`./results/${fileName}`); |
| 108 | + |
| 109 | + await nodeFsPromises.mkdir(nodePath.dirname(outputFile), { recursive: true }); |
| 110 | + |
| 111 | + const resultStr = JSON.stringify(results, null, 2); |
| 112 | + await nodeFsPromises.writeFile(outputFile, resultStr); |
| 113 | + |
| 114 | + return outputFile; |
| 115 | +} |
| 116 | + |
| 117 | +/** |
| 118 | + * Takes a date and coverts it to a simple format that can be used as |
| 119 | + * a filename (which is human readable and doesn't contain special |
| 120 | + * characters) |
| 121 | + * |
| 122 | + * The format being: `YYYY-MM-DD_hh-mm-ss` |
| 123 | + * |
| 124 | + * @param date the date to convert |
| 125 | + * @returns a string representing the date |
| 126 | + */ |
| 127 | +function toSimpleDateString(date: Date): string { |
| 128 | + const isoString = date.toISOString(); |
| 129 | + const isoDate = isoString.split(".")[0]!; |
| 130 | + |
| 131 | + return isoDate.replace("T", "_").replaceAll(":", "-"); |
| 132 | +} |
0 commit comments