feat: allows forcing/skipping calendar cache serving (#18224)

* feat: allows forcing/skipping calendar cache serving

Signed-off-by: Omar López <[email protected]>

* Update features.repository.ts

* Added to HNB

* type fixes

* Update packages/prisma/migrations/20241216000000_add_calendar_cache_serve/migration.sql

Co-authored-by: Keith Williams <[email protected]>

* Update packages/prisma/zod-utils.ts

Co-authored-by: Keith Williams <[email protected]>

* Update selectedCalendar.ts

---------

Signed-off-by: Omar López <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
This commit is contained in:
Omar LópezandKeith Williams authored and GitHub committed 2024-12-17 16:54:55 +00:00
1 parent a0f986f949
commit 2eb385af48
24 files changed
+217 -125

No files matched your search

@@ -53,6 +53,8 @@ export const mapBookingToMutationInput = ({
const skipContactOwner = searchParams.get("cal.skipContactOwner") === "true";
const reroutingFormResponses = searchParams.get("cal.reroutingFormResponses");
const isBookingDryRun = searchParams.get("cal.isBookingDryRun") === "true";
const _cacheParam = searchParams?.get("cal.cache");
const _shouldServeCache = _cacheParam ? _cacheParam === "true" : undefined;
return {
...values,
@@ -83,6 +85,7 @@ export const mapBookingToMutationInput = ({
// In case of rerouting, the form responses are actually the responses that we need to update.
reroutingFormResponses: reroutingFormResponses ? JSON.parse(reroutingFormResponses) : undefined,
_isDryRun: isBookingDryRun,
_shouldServeCache,
};
};
@@ -32,6 +32,7 @@ import getICalUID from "@calcom/emails/lib/getICalUID";
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
import { handleWebhookTrigger } from "@calcom/features/bookings/lib/handleWebhookTrigger";
import { isEventTypeLoggingEnabled } from "@calcom/features/bookings/lib/isEventTypeLoggingEnabled";
import { getShouldServeCache } from "@calcom/features/calendar-cache/lib/getShouldServeCache";
import AssignmentReasonRecorder from "@calcom/features/ee/round-robin/assignmentReason/AssignmentReasonRecorder";
import {
allowDisablingAttendeeConfirmationEmails,
@@ -393,6 +394,7 @@ async function handler(
reroutingFormResponses,
routingFormResponseId,
_isDryRun: isDryRun = false,
_shouldServeCache,
...reqBody
} = bookingData;
@@ -414,6 +416,7 @@ async function handler(
const dynamicUserList = Array.isArray(reqBody.user) ? reqBody.user : getUsernameList(reqBody.user);
if (!eventType) throw new HttpError({ statusCode: 404, message: "event_type_not_found" });
const shouldServeCache = await getShouldServeCache(_shouldServeCache, eventType.team?.id);
const isTeamEventType =
!!eventType.schedulingType && ["COLLECTIVE", "ROUND_ROBIN"].includes(eventType.schedulingType);
@@ -569,7 +572,8 @@ async function handler(
timeZone: reqBody.timeZone,
originalRescheduledBooking,
},
loggerWithEventDetails
loggerWithEventDetails,
shouldServeCache
);
}
} else {
@@ -581,7 +585,8 @@ async function handler(
timeZone: reqBody.timeZone,
originalRescheduledBooking,
},
loggerWithEventDetails
loggerWithEventDetails,
shouldServeCache
);
}
}
@@ -596,7 +601,8 @@ async function handler(
timeZone: reqBody.timeZone,
originalRescheduledBooking,
},
loggerWithEventDetails
loggerWithEventDetails,
shouldServeCache
);
const luckyUserPool: IsFixedAwareUser[] = [];
const fixedUserPool: IsFixedAwareUser[] = [];
@@ -696,7 +702,8 @@ async function handler(
timeZone: reqBody.timeZone,
originalRescheduledBooking,
},
loggerWithEventDetails
loggerWithEventDetails,
shouldServeCache
);
}
// if no error, then lucky user is available for the next slots
@@ -52,7 +52,8 @@ export async function ensureAvailableUsers(
users: IsFixedAwareUser[];
},
input: { dateFrom: string; dateTo: string; timeZone: string; originalRescheduledBooking?: BookingType },
loggerWithEventDetails: Logger<unknown>
loggerWithEventDetails: Logger<unknown>,
shouldServeCache?: boolean
// ReturnType hint of at least one IsFixedAwareUser, as it's made sure at least one entry exists
): Promise<[IsFixedAwareUser, ...IsFixedAwareUser[]]> {
const availableUsers: IsFixedAwareUser[] = [];
@@ -91,6 +92,7 @@ export async function ensureAvailableUsers(
beforeEventBuffer: eventType.beforeEventBuffer,
afterEventBuffer: eventType.afterEventBuffer,
bypassBusyCalendarTimes: false,
shouldServeCache,
},
initialData: {
eventType,
@@ -6,6 +6,7 @@ import type { Calendar } from "@calcom/types/Calendar";
import type { ICalendarCacheRepository } from "./calendar-cache.repository.interface";
import { watchCalendarSchema } from "./calendar-cache.repository.schema";
import { getTimeMax, getTimeMin } from "./lib/datesForCache";
const log = logger.getSubLogger({ prefix: ["CalendarCacheRepository"] });
@@ -15,18 +16,6 @@ const MS_PER_DAY = 24 * 60 * 60 * 1000;
const ONE_MONTH_IN_MS = 30 * MS_PER_DAY;
const CACHING_TIME = ONE_MONTH_IN_MS;
/** Expand the start date to the start of the month */
function getTimeMin(timeMin: string) {
const dateMin = new Date(timeMin);
return new Date(dateMin.getFullYear(), dateMin.getMonth(), 1, 0, 0, 0, 0).toISOString();
}
/** Expand the end date to the end of the month */
function getTimeMax(timeMax: string) {
const dateMax = new Date(timeMax);
return new Date(dateMax.getFullYear(), dateMax.getMonth() + 1, 0, 0, 0, 0, 0).toISOString();
}
export function parseKeyForCache(args: FreeBusyArgs): string {
const { timeMin: _timeMin, timeMax: _timeMax, items } = args;
const { timeMin, timeMax } = handleMinMax(_timeMin, _timeMax);
@@ -0,0 +1,16 @@
/** Expand the start date to the beginning of the current month */
export const getTimeMin = (timeMin?: string) => {
const date = timeMin ? new Date(timeMin) : new Date();
date.setDate(1);
date.setHours(0, 0, 0, 0);
return date.toISOString();
};
/** Expand the end date to the end of the next month */
export function getTimeMax(timeMax?: string) {
const date = timeMax ? new Date(timeMax) : new Date();
date.setMonth(date.getMonth() + 2);
date.setDate(0);
date.setHours(0, 0, 0, 0);
return date.toISOString();
}
@@ -0,0 +1,8 @@
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
export async function getShouldServeCache(shouldServeCache?: boolean | undefined, teamId?: number) {
if (typeof shouldServeCache === "boolean") return shouldServeCache;
if (!teamId) return undefined;
const featureRepo = new FeaturesRepository();
return await featureRepo.checkIfTeamHasFeature(teamId, "calendar-cache-serve");
}
+1
View File
@@ -4,6 +4,7 @@
**/
export type AppFlags = {
"calendar-cache": boolean;
"calendar-cache-serve": boolean;
emails: boolean;
insights: boolean;
teams: boolean;
@@ -3,4 +3,5 @@ import type { AppFlags } from "./config";
export interface IFeaturesRepository {
checkIfFeatureIsEnabledGlobally(slug: keyof AppFlags): Promise<boolean>;
checkIfUserHasFeature(userId: number, slug: string): Promise<boolean>;
checkIfTeamHasFeature(teamId: number, slug: keyof AppFlags): Promise<boolean>;
}
@@ -4,6 +4,9 @@ export class MockFeaturesRepository implements IFeaturesRepository {
async checkIfUserHasFeature(userId: number, slug: string) {
return slug === "mock-feature";
}
async checkIfTeamHasFeature(team: number, slug: string) {
return slug === "mock-feature";
}
async checkIfFeatureIsEnabledGlobally() {
return true;
}
@@ -65,4 +65,15 @@ export class FeaturesRepository implements IFeaturesRepository {
throw err;
}
}
async checkIfTeamHasFeature(teamId: number, featureId: keyof AppFlags) {
try {
const teamFeature = await db.teamFeatures.findUnique({
where: { teamId_featureId: { teamId, featureId } },
});
return !!teamFeature;
} catch (err) {
captureException(err);
throw err;
}
}
}
+1
View File
@@ -5,6 +5,7 @@ const initialData: AppFlags = {
organizations: false,
teams: false,
"calendar-cache": false,
"calendar-cache-serve": false,
emails: false,
insights: false,
webhooks: false,
@@ -48,6 +48,8 @@ export const useSchedule = ({
const searchParams = useSearchParams();
const routedTeamMemberIds = searchParams ? getRoutedTeamMemberIdsFromSearchParams(searchParams) : null;
const skipContactOwner = searchParams ? searchParams.get("cal.skipContactOwner") === "true" : false;
const _cacheParam = searchParams?.get("cal.cache");
const shouldServeCache = _cacheParam ? _cacheParam === "true" : undefined;
const input = {
isTeamEvent,
@@ -68,6 +70,7 @@ export const useSchedule = ({
teamMemberEmail,
routedTeamMemberIds,
skipContactOwner,
shouldServeCache,
};
const options = {