refactor: Uses withReporting to force named functions for tracing (#21219)

This commit is contained in:
Omar López authored and GitHub committed 2025-05-12 13:22:52 -04:00
1 parent 79d695236f
commit b3d3cb1dee
35 files changed
+853 -393

No files matched your search

@@ -3,6 +3,7 @@ import {
getNormalizedHostsWithDelegationCredentials,
} from "@calcom/lib/bookings/getRoutedUsers";
import type { EventType } from "@calcom/lib/bookings/getRoutedUsers";
import { withReporting } from "@calcom/lib/sentryWrapper";
import type { SelectedCalendar } from "@calcom/prisma/client";
import type { SchedulingType } from "@calcom/prisma/enums";
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
@@ -46,7 +47,7 @@ const isFixedHost = <T extends { isFixed: boolean }>(host: T): host is T & { isF
return host.isFixed;
};
export const findQualifiedHostsWithDelegationCredentials = async <
const _findQualifiedHostsWithDelegationCredentials = async <
T extends {
email: string;
id: number;
@@ -206,3 +207,8 @@ export const findQualifiedHostsWithDelegationCredentials = async <
fixedHosts,
};
};
export const findQualifiedHostsWithDelegationCredentials = withReporting(
_findQualifiedHostsWithDelegationCredentials,
"findQualifiedHostsWithDelegationCredentials"
);
+7 -4
View File
@@ -9,6 +9,7 @@ import { intervalLimitKeyToUnit } from "@calcom/lib/intervalLimits/intervalLimit
import type { IntervalLimit } from "@calcom/lib/intervalLimits/intervalLimitSchema";
import logger from "@calcom/lib/logger";
import { getPiiFreeBooking } from "@calcom/lib/piiFreeData";
import { withReporting } from "@calcom/lib/sentryWrapper";
import { performance } from "@calcom/lib/server/perfObserver";
import prisma from "@calcom/prisma";
import type { SelectedCalendar } from "@calcom/prisma/client";
@@ -19,7 +20,7 @@ import type { CredentialForCalendarService } from "@calcom/types/Credential";
import { getDefinedBufferTimes } from "../features/eventtypes/lib/getDefinedBufferTimes";
import { BookingRepository as BookingRepo } from "./server/repository/booking";
export async function getBusyTimes(params: {
const _getBusyTimes = async (params: {
credentials: CredentialForCalendarService[];
userId: number;
userEmail: string;
@@ -46,7 +47,7 @@ export async function getBusyTimes(params: {
| null;
bypassBusyCalendarTimes: boolean;
shouldServeCache?: boolean;
}) {
}) => {
const {
credentials,
userId,
@@ -244,7 +245,9 @@ export async function getBusyTimes(params: {
})
);
return busyTimes;
}
};
export const getBusyTimes = withReporting(_getBusyTimes, "getBusyTimes");
export function getStartEndDateforLimitCheck(
startDate: string,
@@ -359,4 +362,4 @@ export async function getBusyTimesForLimitChecks(params: {
return busyTimes;
}
export default getBusyTimes;
export default withReporting(_getBusyTimes, "getBusyTimes");
+17 -36
View File
@@ -35,7 +35,7 @@ import type { EventBusyDetails, IntervalLimitUnit } from "@calcom/types/Calendar
import type { TimeRange } from "@calcom/types/schedule";
import { getBusyTimes } from "./getBusyTimes";
import monitorCallbackAsync, { monitorCallbackSync } from "./sentryWrapper";
import { withReporting } from "./sentryWrapper";
const log = logger.getSubLogger({ prefix: ["getUserAvailability"] });
const availabilitySchema = z
@@ -55,12 +55,6 @@ const availabilitySchema = z
})
.refine((data) => !!data.username || !!data.userId, "Either username or userId should be filled in.");
const getEventType = async (
...args: Parameters<typeof _getEventType>
): Promise<ReturnType<typeof _getEventType>> => {
return monitorCallbackAsync(_getEventType, ...args);
};
const _getEventType = async (id: number) => {
const eventType = await prisma.eventType.findUnique({
where: { id },
@@ -150,17 +144,17 @@ const _getEventType = async (id: number) => {
};
};
export type EventType = Awaited<ReturnType<typeof getEventType>>;
export type EventType = Awaited<ReturnType<typeof _getEventType>>;
const getUser = async (...args: Parameters<typeof _getUser>): Promise<ReturnType<typeof _getUser>> => {
return monitorCallbackAsync(_getUser, ...args);
};
export const getEventType = withReporting(_getEventType, "getEventType");
const _getUser = async (where: Prisma.UserWhereInput) => {
return findUsersForAvailabilityCheck({ where });
};
type GetUser = Awaited<ReturnType<typeof getUser>>;
type GetUser = Awaited<ReturnType<typeof _getUser>>;
const getUser = withReporting(_getUser, "getUser");
export type GetUserAvailabilityInitialData = {
user?: GetUser;
@@ -213,12 +207,6 @@ type GetUserAvailabilityQuery = {
shouldServeCache?: boolean;
};
export const getCurrentSeats = async (
...args: Parameters<typeof _getCurrentSeats>
): Promise<ReturnType<typeof _getCurrentSeats>> => {
return monitorCallbackAsync(_getCurrentSeats, ...args);
};
const _getCurrentSeats = async (
eventType: {
id?: number;
@@ -274,13 +262,9 @@ const _getCurrentSeats = async (
});
};
export type CurrentSeats = Awaited<ReturnType<typeof getCurrentSeats>>;
export type CurrentSeats = Awaited<ReturnType<typeof _getCurrentSeats>>;
export const getUserAvailability = async (
...args: Parameters<typeof _getUserAvailability>
): Promise<GetUserAvailabilityResult> => {
return monitorCallbackAsync(_getUserAvailability, ...args);
};
export const getCurrentSeats = withReporting(_getCurrentSeats, "getCurrentSeats");
type GetUserAvailabilityResult = ReturnType<typeof _getUserAvailability>;
@@ -416,7 +400,7 @@ const _getUserAvailability = async function getUsersWorkingHoursLifeTheUniverseA
? EventTypeRepository.getSelectedCalendarsFromUser({ user, eventTypeId: eventType.id })
: user.userLevelSelectedCalendars;
const busyTimes = await monitorCallbackAsync(getBusyTimes, {
const busyTimes = await getBusyTimes({
credentials: user.credentials,
startTime: getBusyTimesStart,
endTime: getBusyTimesEnd,
@@ -613,18 +597,14 @@ const _getUserAvailability = async function getUsersWorkingHoursLifeTheUniverseA
return result;
};
export const getPeriodStartDatesBetween = (
...args: Parameters<typeof _getPeriodStartDatesBetween>
): ReturnType<typeof _getPeriodStartDatesBetween> => {
return monitorCallbackSync(_getPeriodStartDatesBetween, ...args);
};
export const getUserAvailability = withReporting(_getUserAvailability, "getUserAvailability");
const _getPeriodStartDatesBetween = (
dateFrom: Dayjs,
dateTo: Dayjs,
period: IntervalLimitUnit,
timeZone?: string
) => {
): Dayjs[] => {
const dates = [];
let startDate = timeZone ? dayjs(dateFrom).tz(timeZone).startOf(period) : dayjs(dateFrom).startOf(period);
const endDate = timeZone ? dayjs(dateTo).tz(timeZone).endOf(period) : dayjs(dateTo).endOf(period);
@@ -636,6 +616,11 @@ const _getPeriodStartDatesBetween = (
return dates;
};
export const getPeriodStartDatesBetween = withReporting(
_getPeriodStartDatesBetween,
"getPeriodStartDatesBetween"
);
interface GetUserAvailabilityParamsDTO {
availability: (DateOverride | WorkingHours)[];
}
@@ -735,8 +720,4 @@ const _getUsersAvailability = async ({ users, query, initialData }: GetUsersAvai
);
};
export const getUsersAvailability = async (
...args: Parameters<typeof _getUsersAvailability>
): Promise<Awaited<GetUserAvailabilityResult>[]> => {
return monitorCallbackAsync(_getUsersAvailability, ...args);
};
export const getUsersAvailability = withReporting(_getUsersAvailability, "getUsersAvailability");
@@ -1,6 +1,7 @@
import dayjs from "@calcom/dayjs";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { HttpError } from "@calcom/lib/http-error";
import { withReporting } from "@calcom/lib/sentryWrapper";
import { BookingRepository } from "@calcom/lib/server/repository/booking";
import prisma from "@calcom/prisma";
import { BookingStatus } from "@calcom/prisma/enums";
@@ -9,7 +10,7 @@ import { ascendingLimitKeys, intervalLimitKeyToUnit } from "../intervalLimit";
import type { IntervalLimit, IntervalLimitKey } from "../intervalLimitSchema";
import { parseBookingLimit } from "../isBookingLimits";
export async function checkBookingLimits(
async function _checkBookingLimits(
bookingLimits: IntervalLimit,
eventStartDate: Date,
eventId: number,
@@ -40,7 +41,9 @@ export async function checkBookingLimits(
}
}
export async function checkBookingLimit({
export const checkBookingLimits = withReporting(_checkBookingLimits, "checkBookingLimits");
async function _checkBookingLimit({
eventStartDate,
eventId,
key,
@@ -110,3 +113,5 @@ export async function checkBookingLimit({
});
}
}
export const checkBookingLimit = withReporting(_checkBookingLimit, "checkBookingLimit");
@@ -3,7 +3,7 @@ import dayjs from "@calcom/dayjs";
import { getStartEndDateforLimitCheck } from "@calcom/lib/getBusyTimes";
import type { EventType } from "@calcom/lib/getUserAvailability";
import { getPeriodStartDatesBetween } from "@calcom/lib/getUserAvailability";
import monitorCallbackAsync from "@calcom/lib/sentryWrapper";
import { withReporting } from "@calcom/lib/sentryWrapper";
import { performance } from "@calcom/lib/server/perfObserver";
import { getTotalBookingDuration } from "@calcom/lib/server/queries";
import { BookingRepository } from "@calcom/lib/server/repository/booking";
@@ -15,12 +15,6 @@ import LimitManager from "../limitManager";
import { isBookingWithinPeriod } from "../utils";
import { checkBookingLimit } from "./checkBookingLimits";
export const getBusyTimesFromLimits = async (
...args: Parameters<typeof _getBusyTimesFromLimits>
): Promise<ReturnType<typeof _getBusyTimesFromLimits>> => {
return monitorCallbackAsync(_getBusyTimesFromLimits, ...args);
};
const _getBusyTimesFromLimits = async (
bookingLimits: IntervalLimit | null,
durationLimits: IntervalLimit | null,
@@ -78,12 +72,6 @@ const _getBusyTimesFromLimits = async (
return limitManager.getBusyTimes();
};
const getBusyTimesFromBookingLimits = async (
...args: Parameters<typeof _getBusyTimesFromBookingLimits>
): Promise<ReturnType<typeof _getBusyTimesFromBookingLimits>> => {
return monitorCallbackAsync(_getBusyTimesFromBookingLimits, ...args);
};
const _getBusyTimesFromBookingLimits = async (params: {
bookings: EventBusyDetails[];
bookingLimits: IntervalLimit;
@@ -161,13 +149,6 @@ const _getBusyTimesFromBookingLimits = async (params: {
}
}
};
const getBusyTimesFromDurationLimits = async (
...args: Parameters<typeof _getBusyTimesFromDurationLimits>
): Promise<ReturnType<typeof _getBusyTimesFromDurationLimits>> => {
return monitorCallbackAsync(_getBusyTimesFromDurationLimits, ...args);
};
const _getBusyTimesFromDurationLimits = async (
bookings: EventBusyDetails[],
durationLimits: IntervalLimit,
@@ -231,11 +212,10 @@ const _getBusyTimesFromDurationLimits = async (
}
};
export const getBusyTimesFromTeamLimits = async (
...args: Parameters<typeof _getBusyTimesFromTeamLimits>
): Promise<ReturnType<typeof _getBusyTimesFromTeamLimits>> => {
return monitorCallbackAsync(_getBusyTimesFromTeamLimits, ...args);
};
const getBusyTimesFromDurationLimits = withReporting(
_getBusyTimesFromDurationLimits,
"getBusyTimesFromDurationLimits"
);
const _getBusyTimesFromTeamLimits = async (
user: { id: number; email: string },
@@ -287,3 +267,15 @@ const _getBusyTimesFromTeamLimits = async (
return limitManager.getBusyTimes();
};
export const getBusyTimesFromLimits = withReporting(_getBusyTimesFromLimits, "getBusyTimesFromLimits");
export const getBusyTimesFromBookingLimits = withReporting(
_getBusyTimesFromBookingLimits,
"getBusyTimesFromBookingLimits"
);
export const getBusyTimesFromTeamLimits = withReporting(
_getBusyTimesFromTeamLimits,
"getBusyTimesFromTeamLimits"
);
+178
View File
@@ -0,0 +1,178 @@
import { describe, it, expect } from "vitest";
import { redactSensitiveData } from "./redactSensitiveData";
describe("redactSensitiveData", () => {
it("should return non-object values as is", () => {
expect(redactSensitiveData(null)).toMatchInlineSnapshot(`null`);
expect(redactSensitiveData(undefined)).toMatchInlineSnapshot(`undefined`);
expect(redactSensitiveData("string")).toMatchInlineSnapshot(`"string"`);
expect(redactSensitiveData(123)).toMatchInlineSnapshot(`123`);
expect(redactSensitiveData(true)).toMatchInlineSnapshot(`true`);
});
it("should redact sensitive fields from flat objects", () => {
const input = {
username: "test",
password: "secret123",
apiKey: "key123",
token: "token123",
normalField: "value",
};
expect(redactSensitiveData(input)).toMatchInlineSnapshot(`
{
"apiKey": "[REDACTED]",
"normalField": "value",
"password": "[REDACTED]",
"token": "[REDACTED]",
"username": "test",
}
`);
});
it("should redact sensitive fields from nested objects", () => {
const input = {
user: {
name: "John",
password: "secret123",
credentials: {
apiKey: "key123",
token: "token123",
},
},
settings: {
theme: "dark",
auth: {
secret: "secret123",
},
},
};
expect(redactSensitiveData(input)).toMatchInlineSnapshot(`
{
"settings": {
"auth": "[REDACTED]",
"theme": "dark",
},
"user": {
"credentials": {
"apiKey": "[REDACTED]",
"token": "[REDACTED]",
},
"name": "John",
"password": "[REDACTED]",
},
}
`);
});
it("should handle arrays of objects", () => {
const input = {
users: [
{ name: "John", password: "pass1", token: "token1" },
{ name: "Jane", password: "pass2", token: "token2" },
],
config: {
apiKey: "key123",
items: [
{ id: 1, secret: "secret1" },
{ id: 2, secret: "secret2" },
],
},
};
expect(redactSensitiveData(input)).toMatchInlineSnapshot(`
{
"config": {
"apiKey": "[REDACTED]",
"items": [
{
"id": 1,
"secret": "[REDACTED]",
},
{
"id": 2,
"secret": "[REDACTED]",
},
],
},
"users": [
{
"name": "John",
"password": "[REDACTED]",
"token": "[REDACTED]",
},
{
"name": "Jane",
"password": "[REDACTED]",
"token": "[REDACTED]",
},
],
}
`);
});
it("should handle all sensitive field variations", () => {
const input = {
accessToken: "token1",
api_key: "key1",
apiKey: "key2",
auth: "auth1",
authorization: "auth2",
client_id: "id1",
client_secret: "secret1",
credential: "cred1",
hash: "hash1",
key: "key3",
password: "pass1",
refreshToken: "token2",
secret: "secret2",
token: "token3",
normalField: "value",
};
expect(redactSensitiveData(input)).toMatchInlineSnapshot(`
{
"accessToken": "[REDACTED]",
"apiKey": "[REDACTED]",
"api_key": "[REDACTED]",
"auth": "[REDACTED]",
"authorization": "[REDACTED]",
"client_id": "[REDACTED]",
"client_secret": "[REDACTED]",
"credential": "[REDACTED]",
"hash": "[REDACTED]",
"key": "[REDACTED]",
"normalField": "value",
"password": "[REDACTED]",
"refreshToken": "[REDACTED]",
"secret": "[REDACTED]",
"token": "[REDACTED]",
}
`);
});
it("should handle circular references gracefully", () => {
const input: any = { name: "test" };
input.self = input;
expect(redactSensitiveData(input)).toMatchInlineSnapshot(`
{
"name": "test",
"self": "[Circular]",
}
`);
});
it("should handle invalid JSON data gracefully", () => {
const input = {
name: "test",
invalid: {
toJSON: () => {
throw new Error("Invalid JSON");
},
},
};
expect(redactSensitiveData(input)).toMatchInlineSnapshot(`
{
"error": "Redaction failed",
}
`);
});
});
+84
View File
@@ -0,0 +1,84 @@
import logger from "./logger";
// Fields that might contain sensitive data
const SENSITIVE_FIELDS = [
"accessToken",
"api_key",
"apiKey",
"auth",
"authorization",
"client_id",
"client_secret",
"credential",
"hash",
"key",
"password",
"refreshToken",
"secret",
"token",
];
// Create a Set for efficient O(1) average time complexity lookups
const SENSITIVE_FIELDS_SET = new Set<string>(SENSITIVE_FIELDS);
/**
* Creates a replacer function for JSON.stringify that redacts sensitive fields.
* This approach is more efficient as it leverages native JSON serialization.
*/
function createReplacer(): (key: string, value: unknown) => unknown {
// Use a WeakSet to track circular references
const seen = new WeakSet();
return function replacer(key: string, value: unknown): unknown {
// Handle circular references
if (value && typeof value === "object") {
if (seen.has(value)) {
return "[Circular]";
}
seen.add(value);
}
// Redact sensitive fields
if (SENSITIVE_FIELDS_SET.has(key)) {
return "[REDACTED]";
}
// Handle Error objects specially to preserve their structure
if (value instanceof Error) {
const errorObj: Record<string, unknown> = {
name: value.name,
message: value.message,
};
if (value.stack) {
errorObj.stack = value.stack;
}
// Handle cause property safely
if ("cause" in value && value.cause !== undefined) {
errorObj.cause = value.cause;
}
return errorObj;
}
return value;
};
}
/**
* Redacts sensitive data from an object by replacing sensitive fields with a placeholder.
* Uses JSON.stringify's replacer function for efficient serialization and redaction.
*/
export function redactSensitiveData(data: unknown): unknown {
if (!data || typeof data !== "object") return data;
try {
const replacer = createReplacer();
const jsonString = JSON.stringify(data, replacer);
return JSON.parse(jsonString);
} catch (error) {
logger.error("Failed to redact sensitive data", error);
return { error: "Redaction failed" };
}
}
+89
View File
@@ -1,5 +1,7 @@
import { startSpan, captureException } from "@sentry/nextjs";
import { redactSensitiveData } from "./redactSensitiveData";
/*
WHEN TO USE
We ran a script that performs a simple mathematical calculation within a loop of 1000000 iterations.
@@ -10,6 +12,10 @@ For smaller loops, the cost incurred may not be very significant on an absolute
considering that a million monitored iterations only took roughly 8 seconds when monitored.
*/
/**
* @deprecated Use withReporting instead. This function will be removed in a future version.
* Example: withReporting(myFunction, "myFunction")(...args)
*/
const monitorCallbackAsync = async <T extends (...args: any[]) => any>(
cb: T,
...args: Parameters<T>
@@ -30,6 +36,10 @@ const monitorCallbackAsync = async <T extends (...args: any[]) => any>(
});
};
/**
* @deprecated Use withReporting instead. This function will be removed in a future version.
* Example: withReporting(myFunction, "myFunction")(...args)
*/
const monitorCallbackSync = <T extends (...args: any[]) => any>(
cb: T,
...args: Parameters<T>
@@ -49,5 +59,84 @@ const monitorCallbackSync = <T extends (...args: any[]) => any>(
});
};
/**
* Type guard to check if a value is a Promise
*/
function isPromise<T>(value: unknown): value is Promise<T> {
return value instanceof Promise;
}
/**
* Creates an error handler that captures the error in Sentry with context
*/
function createErrorHandler(name: string, args: unknown[]) {
return (error: unknown) => {
const context = {
functionName: name,
args: redactSensitiveData(args),
};
if (error instanceof Error) {
(error as any).context = context;
}
captureException(error, {
extra: context,
tags: { functionName: name },
});
throw error;
};
}
/**
* Recommended way to wrap functions for Sentry reporting.
* Properly handles both sync and async functions with proper error context capture.
*
* @example
* // Async function
* const myAsyncFunction = withReporting(async (arg1: string, arg2: number) => {
* // async implementation
* }, "myAsyncFunction");
*
* // Sync function
* const mySyncFunction = withReporting((arg1: string, arg2: number) => {
* // sync implementation
* }, "mySyncFunction");
*/
export function withReporting<T extends any[], R>(func: (...args: T) => R, name: string): (...args: T) => R {
if (!name?.trim()) {
throw new Error("withReporting requires a non-empty name parameter");
}
// Early return if Sentry is not configured
if (!process.env.NEXT_PUBLIC_SENTRY_DSN || !process.env.SENTRY_TRACES_SAMPLE_RATE) {
return func;
}
return (...args: T): R => {
return startSpan({ name }, () => {
const onError = createErrorHandler(name, args);
try {
const result = func(...args);
// Handle Promise case with proper type guard
if (isPromise(result)) {
return result.catch(onError) as R;
}
// Handle sync case
return result;
} catch (error) {
onError(error);
// This line is technically unreachable due to onError throwing,
// but TypeScript needs it for type safety
throw error;
}
});
};
}
export default monitorCallbackAsync;
export { monitorCallbackSync };
+3 -5
View File
@@ -18,7 +18,7 @@ import type { FormResponse } from "@calcom/app-store/routing-forms/types/types";
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
import { isAuthorizedToViewFormOnOrgDomain } from "@calcom/features/routing-forms/lib/isAuthorizedToViewForm";
import logger from "@calcom/lib/logger";
import monitorCallbackAsync from "@calcom/lib/sentryWrapper";
import { withReporting } from "@calcom/lib/sentryWrapper";
import { RoutingFormRepository } from "@calcom/lib/server/repository/routingForm";
import { UserRepository } from "@calcom/lib/server/repository/user";
@@ -36,10 +36,6 @@ function hasEmbedPath(pathWithQuery: string) {
return onlyPath.endsWith("/embed") || onlyPath.endsWith("/embed/");
}
export const getRoutedUrl = (context: Pick<GetServerSidePropsContext, "query" | "req">) => {
return monitorCallbackAsync(_getRoutedUrl, context);
};
const _getRoutedUrl = async (context: Pick<GetServerSidePropsContext, "query" | "req">) => {
const queryParsed = querySchema.safeParse(context.query);
const isEmbed = hasEmbedPath(context.req.url || "");
@@ -221,3 +217,5 @@ const _getRoutedUrl = async (context: Pick<GetServerSidePropsContext, "query" |
},
};
};
export const getRoutedUrl = withReporting(_getRoutedUrl, "getRoutedUrl");
+7 -1
View File
@@ -1,6 +1,7 @@
import { Prisma } from "@prisma/client";
import type { FormResponse } from "@calcom/app-store/routing-forms/types/types";
import { withReporting } from "@calcom/lib/sentryWrapper";
import prisma, { bookingMinimalSelect } from "@calcom/prisma";
import type { Booking } from "@calcom/prisma/client";
import { BookingStatus } from "@calcom/prisma/enums";
@@ -165,7 +166,7 @@ export class BookingRepository {
});
}
static async findAllExistingBookingsForEventTypeBetween({
private static async _findAllExistingBookingsForEventTypeBetween({
eventTypeId,
seatedEvent = false,
startDate,
@@ -277,6 +278,11 @@ export class BookingRepository {
return [...resultOne, ...resultTwoWithOrganizersRemoved, ...resultThree];
}
static findAllExistingBookingsForEventTypeBetween = withReporting(
BookingRepository._findAllExistingBookingsForEventTypeBetween,
"findAllExistingBookingsForEventTypeBetween"
);
static async getAllBookingsForRoundRobin({
users,
eventTypeId,
+2 -1
View File
@@ -1,6 +1,7 @@
import type { Dayjs } from "@calcom/dayjs";
import dayjs from "@calcom/dayjs";
import type { IFromUser, IOutOfOfficeData, IToUser } from "@calcom/lib/getUserAvailability";
import { withReporting } from "@calcom/lib/sentryWrapper";
import type { DateRange } from "./date-ranges";
import { getTimeZone } from "./dayjs";
@@ -168,4 +169,4 @@ const getSlots = ({
});
};
export default getSlots;
export default withReporting(getSlots, "getSlots");