|
| 1 | +import nodeTimesPromises from "node:timers/promises"; |
| 2 | +import nodeFsPromises from "node:fs/promises"; |
| 3 | +import nodePath from "node:path"; |
| 4 | + |
| 5 | +export type FetchBenchmark = { |
| 6 | + calls: number[]; |
| 7 | + average: number; |
| 8 | +}; |
| 9 | + |
| 10 | +export type BenchmarkingResults = { |
| 11 | + name: string; |
| 12 | + path: string; |
| 13 | + fetchBenchmark: FetchBenchmark; |
| 14 | +}[]; |
| 15 | + |
| 16 | +/** |
| 17 | + * Benchmarks the response time of an application end-to-end by: |
| 18 | + * - building the application |
| 19 | + * - deploying it |
| 20 | + * - and fetching from it (multiple times) |
| 21 | + * |
| 22 | + * @param options.build function implementing how the application is to be built |
| 23 | + * @param options.deploy function implementing how the application is deployed (returning the url of the deployment) |
| 24 | + * @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...) |
| 25 | + * @returns the benchmarking results for the application |
| 26 | + */ |
| 27 | +export async function benchmarkApplicationResponseTime({ |
| 28 | + build, |
| 29 | + deploy, |
| 30 | + fetch, |
| 31 | +}: { |
| 32 | + build: () => Promise<void>; |
| 33 | + deploy: () => Promise<string>; |
| 34 | + fetch: (deploymentUrl: string) => Promise<Response>; |
| 35 | +}): Promise<FetchBenchmark> { |
| 36 | + await build(); |
| 37 | + const deploymentUrl = await deploy(); |
| 38 | + return benchmarkFetch(deploymentUrl, { fetch }); |
| 39 | +} |
| 40 | + |
| 41 | +type BenchmarkFetchOptions = { |
| 42 | + numberOfCalls?: number; |
| 43 | + randomDelayMax?: number; |
| 44 | + fetch: (deploymentUrl: string) => Promise<Response>; |
| 45 | +}; |
| 46 | + |
| 47 | +const defaultOptions: Required<Omit<BenchmarkFetchOptions, "fetch">> = { |
| 48 | + numberOfCalls: 20, |
| 49 | + randomDelayMax: 15_000, |
| 50 | +}; |
| 51 | + |
| 52 | +/** |
| 53 | + * Benchmarks a fetch operation by running it multiple times and computing the average time (in milliseconds) such fetch operation takes. |
| 54 | + * |
| 55 | + * @param url The url to fetch from |
| 56 | + * @param options options for the benchmarking |
| 57 | + * @returns the computed average alongside all the single call times |
| 58 | + */ |
| 59 | +async function benchmarkFetch(url: string, options: BenchmarkFetchOptions): Promise<FetchBenchmark> { |
| 60 | + const benchmarkFetchCall = async () => { |
| 61 | + const preTime = performance.now(); |
| 62 | + const resp = await options.fetch(url); |
| 63 | + const postTime = performance.now(); |
| 64 | + |
| 65 | + if (!resp.ok) { |
| 66 | + throw new Error(`Error: Failed to fetch from "${url}"`); |
| 67 | + } |
| 68 | + |
| 69 | + return postTime - preTime; |
| 70 | + }; |
| 71 | + |
| 72 | + const calls = await Promise.all( |
| 73 | + new Array(options?.numberOfCalls ?? defaultOptions.numberOfCalls).fill(null).map(async () => { |
| 74 | + // let's add a random delay before we make the fetch |
| 75 | + await nodeTimesPromises.setTimeout( |
| 76 | + Math.round(Math.random() * (options?.randomDelayMax ?? defaultOptions.randomDelayMax)) |
| 77 | + ); |
| 78 | + |
| 79 | + return benchmarkFetchCall(); |
| 80 | + }) |
| 81 | + ); |
| 82 | + |
| 83 | + const average = calls.reduce((time, sum) => sum + time) / calls.length; |
| 84 | + |
| 85 | + return { |
| 86 | + calls, |
| 87 | + average, |
| 88 | + }; |
| 89 | +} |
| 90 | + |
| 91 | +/** |
| 92 | + * Saves benchmarking results in a local json file |
| 93 | + * |
| 94 | + * @param results the benchmarking results to save |
| 95 | + * @returns the path to the created json file |
| 96 | + */ |
| 97 | +export async function saveResultsToDisk(results: BenchmarkingResults): Promise<string> { |
| 98 | + const date = new Date(); |
| 99 | + |
| 100 | + const fileName = `${date.toISOString().split(".")[0]!.replace("T", "_").replaceAll(":", "-")}.json`; |
| 101 | + |
| 102 | + const outputFile = nodePath.resolve(`./results/${fileName}`); |
| 103 | + |
| 104 | + await nodeFsPromises.mkdir(nodePath.dirname(outputFile), { recursive: true }); |
| 105 | + |
| 106 | + const resultStr = JSON.stringify(results, null, 2); |
| 107 | + await nodeFsPromises.writeFile(outputFile, resultStr); |
| 108 | + |
| 109 | + return outputFile; |
| 110 | +} |
0 commit comments