feat: distributed tracing - 2 (#24861)
* feat: distributed tracing 2 * feat: distributed tracing 2 * refactor: feedback * refactor: feedback * fix: type error * fix: trpc error --------- Co-authored-by: Hariom Balhara <[email protected]>
This commit is contained in:
1 parent
19641ffc05
commit
1ff5d57ded
7 files changed
+158
-67
No files matched your search
@@ -11,7 +11,11 @@ describe("defaultResponder", () => {
|
||||
it("should call res.json when response is still writable and result is not null", async () => {
|
||||
const f = vi.fn().mockResolvedValue({});
|
||||
const req = {} as NextApiRequest;
|
||||
const res = { json: vi.fn(), writableEnded: false } as unknown as NextApiResponse;
|
||||
const res = {
|
||||
json: vi.fn(),
|
||||
writableEnded: false,
|
||||
setHeader: vi.fn(),
|
||||
} as unknown as NextApiResponse;
|
||||
await defaultResponder(f)(req, res);
|
||||
expect(res.json).toHaveBeenCalled();
|
||||
});
|
||||
@@ -19,21 +23,33 @@ describe("defaultResponder", () => {
|
||||
it("should not call res.json when response is not writable", async () => {
|
||||
const f = vi.fn().mockResolvedValue({});
|
||||
const req = {} as NextApiRequest;
|
||||
const res = { json: vi.fn(), writableEnded: true } as unknown as NextApiResponse;
|
||||
const res = {
|
||||
json: vi.fn(),
|
||||
writableEnded: true,
|
||||
setHeader: vi.fn(),
|
||||
} as unknown as NextApiResponse;
|
||||
await defaultResponder(f)(req, res);
|
||||
expect(res.json).not.toHaveBeenCalled();
|
||||
});
|
||||
it("should respond with status code 409 for NoAvailableUsersFound", async () => {
|
||||
const f = vi.fn().mockRejectedValue(new Error(ErrorCode.NoAvailableUsersFound));
|
||||
const req = {} as NextApiRequest;
|
||||
const res = { status: vi.fn().mockReturnThis(), json: vi.fn() } as unknown as NextApiResponse;
|
||||
const res = {
|
||||
status: vi.fn().mockReturnThis(),
|
||||
json: vi.fn(),
|
||||
setHeader: vi.fn(),
|
||||
} as unknown as NextApiResponse;
|
||||
await defaultResponder(f)(req, res);
|
||||
expect(res.status).toHaveBeenCalledWith(409);
|
||||
});
|
||||
it("Rate limit should respond with a 429 status code", async () => {
|
||||
const f = vi.fn().mockRejectedValue(new TRPCError({ code: "TOO_MANY_REQUESTS" }));
|
||||
const req = {} as NextApiRequest;
|
||||
const res = { status: vi.fn().mockReturnThis(), json: vi.fn() } as unknown as NextApiResponse;
|
||||
const res = {
|
||||
status: vi.fn().mockReturnThis(),
|
||||
json: vi.fn(),
|
||||
setHeader: vi.fn(),
|
||||
} as unknown as NextApiResponse;
|
||||
await defaultResponder(f)(req, res);
|
||||
expect(res.status).toHaveBeenCalledWith(429);
|
||||
});
|
||||
|
||||
@@ -3,11 +3,19 @@ import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { getHTTPStatusCodeFromError } from "@trpc/server/http";
|
||||
|
||||
import { type TraceContext } from "@calcom/lib/tracing";
|
||||
import { TracedError } from "@calcom/lib/tracing/error";
|
||||
import { distributedTracing } from "@calcom/lib/tracing/factory";
|
||||
|
||||
import { HttpError } from "../http-error";
|
||||
import { getServerErrorFromUnknown } from "./getServerErrorFromUnknown";
|
||||
import { performance } from "./perfObserver";
|
||||
|
||||
type Handle<T> = (req: NextApiRequest, res: NextApiResponse) => Promise<T>;
|
||||
export interface TracedRequest extends NextApiRequest {
|
||||
traceContext: TraceContext;
|
||||
}
|
||||
|
||||
type Handle<T> = (req: TracedRequest, res: NextApiResponse) => Promise<T>;
|
||||
|
||||
/** Allows us to get type inference from API handler responses */
|
||||
export function defaultResponder<T>(
|
||||
@@ -17,22 +25,37 @@ export function defaultResponder<T>(
|
||||
) {
|
||||
return async (req: NextApiRequest, res: NextApiResponse) => {
|
||||
let ok = false;
|
||||
const operation = endpointRoute ? endpointRoute.replace(/^\//, "").replace(/\//g, "_") : "api_request";
|
||||
const traceContext = distributedTracing.createTrace(operation, {
|
||||
meta: {
|
||||
method: req.method || "",
|
||||
url: req.url || "",
|
||||
},
|
||||
});
|
||||
const tracingLogger = distributedTracing.getTracingLogger(traceContext);
|
||||
|
||||
const tracedReq = req as TracedRequest;
|
||||
tracedReq.traceContext = traceContext;
|
||||
|
||||
try {
|
||||
performance.mark("Start");
|
||||
|
||||
let result: T | undefined;
|
||||
if (process.env.NODE_ENV === "development" || !endpointRoute) {
|
||||
result = await f(req, res);
|
||||
result = await f(tracedReq, res);
|
||||
} else {
|
||||
const { wrapApiHandlerWithSentry } = await import("@sentry/nextjs");
|
||||
result = await wrapApiHandlerWithSentry(f, endpointRoute)(req, res);
|
||||
result = await wrapApiHandlerWithSentry(f, endpointRoute)(tracedReq, res);
|
||||
}
|
||||
|
||||
ok = true;
|
||||
if (result && !res.writableEnded) {
|
||||
res.setHeader("X-Trace-Id", traceContext.traceId);
|
||||
return res.json(result);
|
||||
}
|
||||
} catch (err) {
|
||||
tracingLogger.error(`${operation} request failed`, { error: err });
|
||||
const tracedError = TracedError.createFromError(err, traceContext);
|
||||
let error: HttpError;
|
||||
if (err instanceof TRPCError) {
|
||||
const statusCode = getHTTPStatusCodeFromError(err);
|
||||
@@ -44,8 +67,9 @@ export function defaultResponder<T>(
|
||||
if (!(error.statusCode >= 400 && error.statusCode < 500)) {
|
||||
console.error(error);
|
||||
const { captureException } = await import("@sentry/nextjs");
|
||||
captureException(error);
|
||||
captureException(tracedError);
|
||||
}
|
||||
res.setHeader("X-Trace-Id", tracedError.traceId);
|
||||
return res
|
||||
.status(error.statusCode)
|
||||
.json({ message: error.message, url: error.url, method: error.method, data: error?.data || null });
|
||||
|
||||
Reference in new issue
Block a user