perf: Don't process date overrides outside of requested boundaries (#13495)

* perf: Don't process date overrides outside of requested boundaries

* Added ability to skip override calculations when not used

* Only instantiating utc date for overrides once

* Removed performance tracing

* Cleanup

* Fixed broken tests

* Fix type

* In process of fixing types

* Types

* Fixed types

* Removed unnecessary performance.now() call

* Changed override date check to use isBetween

* Attempting to fix availability test

* Put code back to test availability

* Put back isBetween because confirmed it wasn't triggering the new test failures

* Removed date check to see if this is breaking it

* Put the code back since the test failed without it too

* Skipping test to unblock pipeline unless research is done

* Removed steps to test

* Removing the piece around the troubleshooter

* 1 more try

* Adding an extra wait

* Took out the boolean check to see if that's the issue

* Put back the check

* Trying to isolate the problem

* Changed how the test loads the troubleshooter

* Changed to OR to capture range better

* Using the proper date instead of 1/1/1970

* Update availability.e2e.ts
This commit is contained in:
Keith Williams authored and GitHub committed 2024-02-07 03:21:43 +00:00
1 parent e884348807
commit 0990549e7f
9 files changed
+84 -46

No files matched your search

+2
View File
@@ -197,6 +197,7 @@ async function handler(req: NextApiRequest) {
dateTo,
eventTypeId,
userId,
returnDateOverrides: true,
});
const team = await prisma.team.findUnique({
where: { id: teamId },
@@ -232,6 +233,7 @@ async function handler(req: NextApiRequest) {
dateFrom,
dateTo,
eventTypeId,
returnDateOverrides: true,
}),
};
});
+17 -23
View File
@@ -21,29 +21,23 @@ test.describe("Availablity tests", () => {
});
test("Date Overrides", async ({ page }) => {
await test.step("Can add a date override", async () => {
await page.getByTestId("schedules").first().click();
await page.getByTestId("add-override").click();
await page.locator('[id="modal-title"]').waitFor();
await page.getByTestId("incrementMonth").click();
await page.locator('[data-testid="day"][data-disabled="false"]').first().click();
await page.getByTestId("date-override-mark-unavailable").click();
await page.getByTestId("add-override-submit-btn").click();
await page.getByTestId("dialog-rejection").click();
await expect(page.locator('[data-testid="date-overrides-list"] > li')).toHaveCount(1);
await page.locator('[form="availability-form"][type="submit"]').click();
});
await test.step("Date override is displayed in troubleshooter", async () => {
const response = await page.waitForResponse("**/api/trpc/availability/schedule.update?batch=1");
const json = await response.json();
// @ts-expect-error trust me bro
const date = json[0].result.data.json.schedule.availability.find((a) => !!a.date);
const troubleshooterURL = `/availability/troubleshoot?date=${dayjs(date.date).format("YYYY-MM-DD")}`;
await page.goto(troubleshooterURL);
await page.waitForLoadState("networkidle");
await expect(page.locator('[data-testid="troubleshooter-busy-time"]')).toHaveCount(1);
});
await page.getByTestId("schedules").first().click();
await page.getByTestId("add-override").click();
await page.locator('[id="modal-title"]').waitFor();
await page.getByTestId("incrementMonth").click();
await page.locator('[data-testid="day"][data-disabled="false"]').first().click();
await page.getByTestId("date-override-mark-unavailable").click();
await page.getByTestId("add-override-submit-btn").click();
await page.getByTestId("dialog-rejection").click();
await expect(page.locator('[data-testid="date-overrides-list"] > li')).toHaveCount(1);
await page.locator('[form="availability-form"][type="submit"]').click();
const response = await page.waitForResponse("**/api/trpc/availability/schedule.update?batch=1");
const json = await response.json();
const nextMonth = dayjs().add(1, "month").startOf("month");
const troubleshooterURL = `/availability/troubleshoot?date=${nextMonth.format("YYYY-MM-DD")}`;
await page.goto(troubleshooterURL);
await page.waitForLoadState("networkidle");
await expect(page.locator('[data-testid="troubleshooter-busy-time"]')).toHaveCount(1);
});
test("Schedule listing", async ({ page }) => {
+36 -10
View File
@@ -24,6 +24,7 @@ import type {
IntervalLimit,
IntervalLimitUnit,
} from "@calcom/types/Calendar";
import type { TimeRange } from "@calcom/types/schedule";
import { getBusyTimes } from "./getBusyTimes";
import monitorCallbackAsync, { monitorCallbackSync } from "./sentryWrapper";
@@ -40,6 +41,7 @@ const availabilitySchema = z
beforeEventBuffer: z.number().optional(),
duration: z.number().optional(),
withSource: z.boolean().optional(),
returnDateOverrides: z.boolean(),
})
.refine((data) => !!data.username || !!data.userId, "Either username or userId should be filled in.");
@@ -161,6 +163,7 @@ const _getUserAvailability = async function getUsersWorkingHoursLifeTheUniverseA
afterEventBuffer?: number;
beforeEventBuffer?: number;
duration?: number;
returnDateOverrides: boolean;
},
initialData?: {
user?: User;
@@ -179,8 +182,17 @@ const _getUserAvailability = async function getUsersWorkingHoursLifeTheUniverseA
busyTimesFromLimitsBookings: EventBusyDetails[];
}
) {
const { username, userId, dateFrom, dateTo, eventTypeId, afterEventBuffer, beforeEventBuffer, duration } =
availabilitySchema.parse(query);
const {
username,
userId,
dateFrom,
dateTo,
eventTypeId,
afterEventBuffer,
beforeEventBuffer,
duration,
returnDateOverrides,
} = availabilitySchema.parse(query);
if (!dateFrom.isValid() || !dateTo.isValid()) {
throw new HttpError({ statusCode: 400, message: "Invalid time range given." });
@@ -294,16 +306,30 @@ const _getUserAvailability = async function getUsersWorkingHoursLifeTheUniverseA
const endGetWorkingHours = performance.now();
const dateOverrides = availability
.filter((availability) => !!availability.date)
.map((override) => {
const dateOverrides: TimeRange[] = [];
// NOTE: getSchedule is currently calling this function for every user in a team event
// but not using these values at all, wasting CPU. Adding this check here temporarily to avoid a larger refactor
// since other callers do using this data.
if (returnDateOverrides) {
const availabilityWithDates = availability.filter((availability) => !!availability.date);
for (let i = 0; i < availabilityWithDates.length; i++) {
const override = availabilityWithDates[i];
const startTime = dayjs.utc(override.startTime);
const endTime = dayjs.utc(override.endTime);
return {
start: dayjs.utc(override.date).hour(startTime.hour()).minute(startTime.minute()).toDate(),
end: dayjs.utc(override.date).hour(endTime.hour()).minute(endTime.minute()).toDate(),
};
});
const overrideStartDate = dayjs.utc(override.date).hour(startTime.hour()).minute(startTime.minute());
const overrideEndDate = dayjs.utc(override.date).hour(endTime.hour()).minute(endTime.minute());
if (
overrideStartDate.isBetween(dateFrom, dateTo, null, "[]") ||
overrideEndDate.isBetween(dateFrom, dateTo, null, "[]")
) {
dateOverrides.push({
start: overrideStartDate.toDate(),
end: overrideEndDate.toDate(),
});
}
}
}
const dateRanges = buildDateRanges({
dateFrom,
@@ -479,6 +479,7 @@ export async function ensureAvailableUsers(
userId: user.id,
eventTypeId: eventType.id,
duration: originalBookingDuration,
returnDateOverrides: false,
...input,
},
{
+1 -1
View File
@@ -224,7 +224,7 @@ describe("processDateOverrides", () => {
// 2023-06-12T20:00:00-04:00 (America/New_York)
const timeZone = "America/New_York";
const result = processDateOverride({ item, timeZone });
const result = processDateOverride({ item, itemDateAsUtc: dayjs.utc(item.date), timeZone });
expect(result.start.format()).toEqual(dayjs("2023-06-12T12:00:00Z").tz(timeZone).format());
expect(result.end.format()).toEqual(dayjs("2023-06-12T21:00:00Z").tz(timeZone).format());
+19 -8
View File
@@ -61,21 +61,28 @@ export function processWorkingHours({
return results;
}
export function processDateOverride({ item, timeZone }: { item: DateOverride; timeZone: string }) {
const startDate = dayjs
.utc(item.date)
.startOf("day")
export function processDateOverride({
item,
itemDateAsUtc,
timeZone,
}: {
item: DateOverride;
itemDateAsUtc: Dayjs;
timeZone: string;
}) {
const itemDateStartOfDay = itemDateAsUtc.startOf("day");
const startDate = itemDateStartOfDay
.add(item.startTime.getUTCHours(), "hours")
.add(item.startTime.getUTCMinutes(), "minutes")
.second(0)
.tz(timeZone, true);
const endDate = dayjs
.utc(item.date)
.startOf("day")
const endDate = itemDateStartOfDay
.add(item.endTime.getUTCHours(), "hours")
.add(item.endTime.getUTCMinutes(), "minutes")
.second(0)
.tz(timeZone, true);
return {
start: startDate,
end: endDate,
@@ -104,10 +111,14 @@ export function buildDateRanges({
return processed;
}, [])
);
const groupedDateOverrides = groupByDate(
availability.reduce((processed: DateRange[], item) => {
if ("date" in item && !!item.date) {
processed.push(processDateOverride({ item, timeZone }));
const itemDateAsUtc = dayjs.utc(item.date);
if (itemDateAsUtc.isBetween(dateFrom, dateTo, null, "[]")) {
processed.push(processDateOverride({ item, itemDateAsUtc, timeZone }));
}
}
return processed;
}, [])
@@ -11,5 +11,5 @@ type UserOptions = {
};
export const userHandler = async ({ input }: UserOptions) => {
return getUserAvailability(input, undefined);
return getUserAvailability({ returnDateOverrides: true, ...input }, undefined);
};
@@ -407,7 +407,7 @@ export async function getAvailableSlots({ input, ctx }: GetScheduleOptions) {
}
/* We get all users working hours and busy slots */
const userAvailability = await Promise.all(
const allUsersAvailability = await Promise.all(
usersWithCredentials.map(async (currentUser) => {
const {
busy,
@@ -424,6 +424,7 @@ export async function getAvailableSlots({ input, ctx }: GetScheduleOptions) {
afterEventBuffer: eventType.afterEventBuffer,
beforeEventBuffer: eventType.beforeEventBuffer,
duration: input.duration || 0,
returnDateOverrides: false,
},
{
user: currentUser,
@@ -471,15 +472,17 @@ export async function getAvailableSlots({ input, ctx }: GetScheduleOptions) {
const checkForAvailabilityTime = 0;
const getSlotsCount = 0;
const checkForAvailabilityCount = 0;
const aggregatedAvailability = getAggregatedAvailability(allUsersAvailability, eventType.schedulingType);
const timeSlots = getSlots({
inviteeDate: startTime,
eventLength: input.duration || eventType.length,
offsetStart: eventType.offsetStart,
dateRanges: getAggregatedAvailability(userAvailability, eventType.schedulingType),
dateRanges: aggregatedAvailability,
minimumBookingNotice: eventType.minimumBookingNotice,
frequency: eventType.slotInterval || input.duration || eventType.length,
organizerTimeZone: eventType.timeZone || eventType?.schedule?.timeZone || userAvailability?.[0]?.timeZone,
organizerTimeZone:
eventType.timeZone || eventType?.schedule?.timeZone || allUsersAvailability?.[0]?.timeZone,
});
let availableTimeSlots: typeof timeSlots = [];
@@ -45,6 +45,7 @@ export const getMemberAvailabilityHandler = async ({ ctx, input }: GetMemberAvai
username: member.user.username,
dateFrom: input.dateFrom,
dateTo: input.dateTo,
returnDateOverrides: true,
},
{ user: member.user, busyTimesFromLimitsBookings: [] }
);