Adds perf metrics for each tRPC endpoint

pull/3178/head
zomars 2022-06-27 18:38:01 -06:00
parent 2ba8f99302
commit 87befdbdf4
3 changed files with 14 additions and 3 deletions

View File

@ -1,3 +1,5 @@
import { performance } from "@calcom/lib/server/perfObserver";
import * as trpc from "@trpc/server"; import * as trpc from "@trpc/server";
import { Context } from "./createContext"; import { Context } from "./createContext";
@ -6,7 +8,13 @@ import { Context } from "./createContext";
* Helper function to create a router with context * Helper function to create a router with context
*/ */
export function createRouter() { export function createRouter() {
return trpc.router<Context>(); return trpc.router<Context>().middleware(async ({ path, type, next }) => {
performance.mark("Start");
const result = await next();
performance.mark("End");
performance.measure(`[${result.ok ? "OK" : "ERROR"}][$1] ${type} '${path}'`, "Start", "End");
return result;
});
} }
export function createProtectedRouter() { export function createProtectedRouter() {

View File

@ -8,9 +8,11 @@ type Handle<T> = (req: NextApiRequest, res: NextApiResponse) => Promise<T>;
/** Allows us to get type inference from API handler responses */ /** Allows us to get type inference from API handler responses */
function defaultResponder<T>(f: Handle<T>) { function defaultResponder<T>(f: Handle<T>) {
return async (req: NextApiRequest, res: NextApiResponse) => { return async (req: NextApiRequest, res: NextApiResponse) => {
let ok = false;
try { try {
performance.mark("Start"); performance.mark("Start");
const result = await f(req, res); const result = await f(req, res);
ok = true;
if (result) res.json(result); if (result) res.json(result);
} catch (err) { } catch (err) {
const error = getServerErrorFromUnkown(err); const error = getServerErrorFromUnkown(err);
@ -18,7 +20,7 @@ function defaultResponder<T>(f: Handle<T>) {
res.json({ message: error.message }); res.json({ message: error.message });
} finally { } finally {
performance.mark("End"); performance.mark("End");
performance.measure("Measuring endpoint: " + req.url, "Start", "End"); performance.measure(`[${ok ? "OK" : "ERROR"}][$1] ${req.method} '${req.url}'`, "Start", "End");
} }
}; };
} }

View File

@ -8,7 +8,8 @@ export const perfObserver =
globalThis.perfObserver || globalThis.perfObserver ||
new PerformanceObserver((items) => { new PerformanceObserver((items) => {
items.getEntries().forEach((entry) => { items.getEntries().forEach((entry) => {
console.log(entry); // fake call to our custom logging solution // Log entry duration in seconds with four decimal places.
console.log(entry.name.replace("$1", `${(entry.duration / 1000.0).toFixed(4)}s`));
}); });
}); });