refactor: Remove all code related to the old cache system (#25284)

* chore: Remove all code related to the old cache system

* Removed some redundant tests, some type fixes

* Further type fixes

* More type fixes re. tests

* Next iteration, couple of fixes remaining

* Remove cache from CredentialActionsDropdown

* Fix tests by mocking credential, instead of db queries

* Remove Cache DI wiring from v2

* Make sure apiv2 build passes

* Remove another cache cron

* Remove old tokens for calendar-cache v1
This commit is contained in:
Alex van Andel authored and GitHub committed 2025-11-20 18:02:18 +02:00
1 parent d1184f65e2
commit ae7fd0cae2
45 files changed
+58 -2765

No files matched your search

@@ -3,7 +3,6 @@
import { useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { GOOGLE_CALENDAR_TYPE } from "@calcom/platform-constants";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { ConfirmationDialogContent } from "@calcom/ui/components/dialog";
@@ -19,8 +18,6 @@ import { showToast } from "@calcom/ui/components/toast";
interface CredentialActionsDropdownProps {
credentialId: number;
integrationType: string;
cacheUpdatedAt?: Date | null;
onSuccess?: () => void;
delegationCredentialId?: string | null;
disableConnectionModification?: boolean;
@@ -28,27 +25,14 @@ interface CredentialActionsDropdownProps {
export default function CredentialActionsDropdown({
credentialId,
integrationType,
cacheUpdatedAt,
onSuccess,
delegationCredentialId,
disableConnectionModification,
}: CredentialActionsDropdownProps) {
const { t } = useLocale();
const [dropdownOpen, setDropdownOpen] = useState(false);
const [deleteModalOpen, setDeleteModalOpen] = useState(false);
const [disconnectModalOpen, setDisconnectModalOpen] = useState(false);
const deleteCacheMutation = trpc.viewer.calendars.deleteCache.useMutation({
onSuccess: () => {
showToast(t("cache_deleted_successfully"), "success");
onSuccess?.();
},
onError: () => {
showToast(t("error_deleting_cache"), "error");
},
});
const utils = trpc.useUtils();
const disconnectMutation = trpc.viewer.credentials.delete.useMutation({
onSuccess: () => {
@@ -64,11 +48,9 @@ export default function CredentialActionsDropdown({
},
});
const isGoogleCalendar = integrationType === GOOGLE_CALENDAR_TYPE;
const canDisconnect = !delegationCredentialId && !disableConnectionModification;
const hasCache = isGoogleCalendar && cacheUpdatedAt;
if (!canDisconnect && !hasCache) {
if (!canDisconnect) {
return null;
}
@@ -79,37 +61,6 @@ export default function CredentialActionsDropdown({
<Button type="button" variant="icon" color="secondary" StartIcon="ellipsis" />
</DropdownMenuTrigger>
<DropdownMenuContent>
{hasCache && (
<>
<DropdownMenuItem className="focus:ring-muted">
<div className="px-2 py-1">
<div className="text-sm font-medium text-gray-900 dark:text-white">{t("cache_status")}</div>
<div className="text-xs text-gray-500 dark:text-white">
{t("cache_last_updated", {
timestamp: new Intl.DateTimeFormat("en-US", {
dateStyle: "short",
timeStyle: "short",
}).format(new Date(cacheUpdatedAt)),
interpolation: { escapeValue: false },
})}
</div>
</div>
</DropdownMenuItem>
<DropdownMenuItem className="outline-none">
<DropdownItem
type="button"
color="destructive"
StartIcon="trash"
onClick={() => {
setDeleteModalOpen(true);
setDropdownOpen(false);
}}>
{t("delete_cached_data")}
</DropdownItem>
</DropdownMenuItem>
</>
)}
{canDisconnect && hasCache && <hr className="my-1" />}
{canDisconnect && (
<DropdownMenuItem className="outline-none">
<DropdownItem
@@ -127,19 +78,6 @@ export default function CredentialActionsDropdown({
</DropdownMenuContent>
</Dropdown>
<Dialog open={deleteModalOpen} onOpenChange={setDeleteModalOpen}>
<ConfirmationDialogContent
variety="danger"
title={t("delete_cached_data")}
confirmBtnText={t("yes_delete_cache")}
onConfirm={() => {
deleteCacheMutation.mutate({ credentialId });
setDeleteModalOpen(false);
}}>
{t("confirm_delete_cache")}
</ConfirmationDialogContent>
</Dialog>
<Dialog open={disconnectModalOpen} onOpenChange={setDisconnectModalOpen}>
<ConfirmationDialogContent
variety="danger"
@@ -1,7 +1,6 @@
import { RegularBookingService } from "@calcom/features/bookings/lib/service/RegularBookingService";
import { bindModuleToClassOnToken, createModule } from "@calcom/features/di/di";
import { moduleLoader as bookingRepositoryModuleLoader } from "@calcom/features/di/modules/Booking";
import { moduleLoader as cacheModuleLoader } from "@calcom/features/di/modules/Cache";
import { moduleLoader as checkBookingAndDurationLimitsModuleLoader } from "@calcom/features/di/modules/CheckBookingAndDurationLimits";
import { moduleLoader as luckyUserServiceModuleLoader } from "@calcom/features/di/modules/LuckyUser";
import { moduleLoader as userRepositoryModuleLoader } from "@calcom/features/di/modules/User";
@@ -20,7 +19,6 @@ const loadModule = bindModuleToClassOnToken({
depsMap: {
// TODO: In a followup PR, we aim to remove prisma dependency and instead inject the repositories as dependencies.
prismaClient: prismaModuleLoader,
cacheService: cacheModuleLoader,
checkBookingAndDurationLimitsService: checkBookingAndDurationLimitsModuleLoader,
bookingRepository: bookingRepositoryModuleLoader,
luckyUserService: luckyUserServiceModuleLoader,
@@ -34,7 +34,6 @@ import { handlePayment } from "@calcom/features/bookings/lib/handlePayment";
import { handleWebhookTrigger } from "@calcom/features/bookings/lib/handleWebhookTrigger";
import { isEventTypeLoggingEnabled } from "@calcom/features/bookings/lib/isEventTypeLoggingEnabled";
import { BookingEventHandlerService } from "@calcom/features/bookings/lib/onBookingEvents/BookingEventHandlerService";
import type { CacheService } from "@calcom/features/calendar-cache/lib/getShouldServeCache";
import { getSpamCheckService } from "@calcom/features/di/watchlist/containers/SpamCheckService.container";
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
import AssignmentReasonRecorder from "@calcom/features/ee/round-robin/assignmentReason/AssignmentReasonRecorder";
@@ -410,7 +409,6 @@ function formatAvailabilitySnapshot(data: {
}
export interface IBookingServiceDependencies {
cacheService: CacheService;
checkBookingAndDurationLimitsService: CheckBookingAndDurationLimitsService;
prismaClient: PrismaClient;
bookingRepository: BookingRepository;
@@ -1,24 +0,0 @@
- googleChannelExpiration is a string which might cause problems with date/number comparisons like `lt` in prisma, which can possibly cause problems with date comparisons. Though not practical right now
## Responsibilities
- File:`/api/calendar-cache/cron` - Runs every minute and takes care of two things:
1. Watching calendars
- Identifies selectedCalendars that are not watched(identified by `googleChannelId` being null) and watches them
- When feature is enabled, it starts watching all related calendars
- SelectedCalendars with same `externalId` are considered same from CalendarCache perspective
- This is how a newly added SelectedCalendar record gets its googleChannel props set
- CalendarService.watchCalendar ensures that the new subscription is not created unnecessarily, reusing existing SelectedCalendar googleChannel props when possible.
- Identifies calendars that are watched but have their subscription about to expire(identified by `googleChannelExpiration` being less than current tomorrow's date) and watches them again
2. Unwatching calendars
- It takes care of cleaning up when the calendar-cache feature flag is disabled.
- File:`calendar-cache-cleanup`
- Deletes all CalendarCache records that have expired
- File:`googlecalendar/api/webhook`
- Populates CalendarCache records by fetching availability.
## Availability Checking Flow
- CalendarService.getAvailability is called
- It checks if CalendarCache exists for the calendar
- If it does, it fetches availability from CalendarCache
- If it doesn't, it fetches availability from the third party calendar service
- It doesn't populate/update CalendarCache. That is solely the responsibility of webhook
@@ -1,165 +0,0 @@
import type { NextApiRequest } from "next";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { defaultHandler } from "@calcom/lib/server/defaultHandler";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import type { SelectedCalendarEventTypeIds } from "@calcom/types/Calendar";
import { CalendarCache } from "../calendar-cache";
const log = logger.getSubLogger({ prefix: ["CalendarCacheCron"] });
const validateRequest = (req: NextApiRequest) => {
const apiKey = req.headers.authorization || req.query.apiKey;
if (![process.env.CRON_API_KEY, `Bearer ${process.env.CRON_SECRET}`].includes(`${apiKey}`)) {
throw new HttpError({ statusCode: 401, message: "Unauthorized" });
}
};
function logRejected(result: PromiseSettledResult<unknown>) {
if (result.status === "rejected") {
console.error(result.reason);
}
}
function getUniqueCalendarsByExternalId<
T extends {
externalId: string;
eventTypeId: number | null;
credentialId: number | null;
id: string;
}
>(calendars: T[]) {
type ExternalId = string;
return calendars.reduce(
(acc, sc) => {
if (!acc[sc.externalId]) {
acc[sc.externalId] = {
eventTypeIds: [sc.eventTypeId],
credentialId: sc.credentialId,
id: sc.id,
};
} else {
acc[sc.externalId].eventTypeIds.push(sc.eventTypeId);
}
return acc;
},
{} as Record<
ExternalId,
{
eventTypeIds: SelectedCalendarEventTypeIds;
credentialId: number | null;
id: string;
}
>
);
}
const handleCalendarsToUnwatch = async () => {
const calendarsToUnwatch = await SelectedCalendarRepository.getNextBatchToUnwatch(500);
const calendarsWithEventTypeIdsGroupedTogether = getUniqueCalendarsByExternalId(calendarsToUnwatch);
const result = await Promise.allSettled(
Object.entries(calendarsWithEventTypeIdsGroupedTogether).map(
async ([externalId, { eventTypeIds, credentialId, id }]) => {
if (!credentialId) {
// So we don't retry on next cron run
// FIXME: There could actually be multiple calendars with the same externalId and thus we need to technically update error for all of them
await SelectedCalendarRepository.setErrorInUnwatching({
id,
error: "Missing credentialId",
});
log.error("no credentialId for SelectedCalendar: ", id);
return;
}
try {
const cc = await CalendarCache.initFromCredentialId(credentialId);
await cc.unwatchCalendar({ calendarId: externalId, eventTypeIds });
await SelectedCalendarRepository.removeUnwatchingError({ id });
} catch (error) {
let errorMessage = "Unknown error";
if (error instanceof Error) {
errorMessage = error.message;
}
log.error(
`Error unwatching calendar ${externalId}`,
safeStringify({
selectedCalendarId: id,
error: errorMessage,
})
);
await SelectedCalendarRepository.setErrorInUnwatching({
id,
error: `${errorMessage}`,
});
}
}
)
);
log.info(`Processed ${result.length} calendars for unwatching`);
result.forEach(logRejected);
return result;
};
const handleCalendarsToWatch = async () => {
const calendarsToWatch = await SelectedCalendarRepository.getNextBatchToWatch(500);
const calendarsWithEventTypeIdsGroupedTogether = getUniqueCalendarsByExternalId(calendarsToWatch);
const result = await Promise.allSettled(
Object.entries(calendarsWithEventTypeIdsGroupedTogether).map(
async ([externalId, { credentialId, eventTypeIds, id }]) => {
if (!credentialId) {
// So we don't retry on next cron run
await SelectedCalendarRepository.setErrorInWatching({ id, error: "Missing credentialId" });
log.error("no credentialId for SelectedCalendar: ", id);
return;
}
try {
const cc = await CalendarCache.initFromCredentialId(credentialId);
await cc.watchCalendar({ calendarId: externalId, eventTypeIds });
await SelectedCalendarRepository.removeWatchingError({ id });
} catch (error) {
let errorMessage = "Unknown error";
if (error instanceof Error) {
errorMessage = error.message;
}
log.error(
`Error watching calendar ${externalId}`,
safeStringify({
selectedCalendarId: id,
error: errorMessage,
})
);
await SelectedCalendarRepository.setErrorInWatching({
id,
error: `${errorMessage}`,
});
}
}
)
);
log.info(`Processed ${result.length} calendars for watching`);
result.forEach(logRejected);
return result;
};
// This cron is used to activate and renew calendar subscriptions
const handler = defaultResponder(async (request: NextApiRequest) => {
validateRequest(request);
await Promise.allSettled([handleCalendarsToWatch(), handleCalendarsToUnwatch()]);
// TODO: Credentials can be installed on a whole team, check for selected calendars on the team
return {
executedAt: new Date().toISOString(),
};
});
export default defaultHandler({
GET: Promise.resolve({ default: defaultResponder(handler) }),
});
@@ -1,32 +0,0 @@
import type { CalendarCache, Prisma } from "@calcom/prisma/client";
import type { SelectedCalendarEventTypeIds } from "@calcom/types/Calendar";
export type FreeBusyArgs = { timeMin: string; timeMax: string; items: { id: string }[] };
export interface ICalendarCacheRepository {
watchCalendar(args: { calendarId: string; eventTypeIds: SelectedCalendarEventTypeIds }): Promise<any>;
unwatchCalendar(args: { calendarId: string; eventTypeIds: SelectedCalendarEventTypeIds }): Promise<any>;
upsertCachedAvailability({
credentialId,
userId,
args,
value,
}: {
credentialId: number;
userId: number | null;
args: FreeBusyArgs;
value: Prisma.JsonNullValueInput | Prisma.InputJsonValue;
}): Promise<void>;
getCachedAvailability({
credentialId,
userId,
args,
}: {
credentialId: number;
userId: number | null;
args: FreeBusyArgs;
}): Promise<CalendarCache | null>;
getCacheStatusByCredentialIds(
credentialIds: number[]
): Promise<{ credentialId: number; updatedAt: Date | null }[]>;
}
@@ -1,31 +0,0 @@
import logger from "@calcom/lib/logger";
import type { ICalendarCacheRepository } from "./calendar-cache.repository.interface";
const log = logger.getSubLogger({ prefix: ["CalendarCacheRepositoryMock"] });
export class CalendarCacheRepositoryMock implements ICalendarCacheRepository {
async watchCalendar() {
log.info(`Skipping watchCalendar due to calendar-cache being disabled`);
}
async upsertCachedAvailability() {
log.info(`Skipping upsertCachedAvailability due to calendar-cache being disabled`);
}
async getCachedAvailability() {
log.info(`Skipping getCachedAvailability due to calendar-cache being disabled`);
return null;
}
async unwatchCalendar() {
log.info(`Skipping unwatchCalendar due to calendar-cache being disabled`);
}
async deleteManyByCredential() {
log.info(`Skipping deleteManyByCredential due to calendar-cache being disabled`);
}
async getCacheStatusByCredentialIds() {
log.info(`Skipping getCacheStatusByCredentialIds due to calendar-cache being disabled`);
return [];
}
}
@@ -1,9 +0,0 @@
import { z } from "zod";
export const watchCalendarSchema = z.object({
kind: z.literal("api#channel"),
id: z.string(),
resourceId: z.string(),
resourceUri: z.string(),
expiration: z.string(),
});
@@ -1,188 +0,0 @@
import { uniqueBy } from "@calcom/lib/array";
import { isInMemoryDelegationCredential } from "@calcom/lib/delegationCredential";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import type { Calendar, SelectedCalendarEventTypeIds } from "@calcom/types/Calendar";
import type { ICalendarCacheRepository } from "./calendar-cache.repository.interface";
const log = logger.getSubLogger({ prefix: ["CalendarCacheRepository"] });
const MS_PER_DAY = 24 * 60 * 60 * 1000;
const ONE_MONTH_IN_MS = 30 * MS_PER_DAY;
const CACHING_TIME = ONE_MONTH_IN_MS;
function parseKeyForCache(args: FreeBusyArgs): string {
// Ensure that calendarIds are unique
const uniqueItems = uniqueBy(args.items, ["id"]);
const key = JSON.stringify({
timeMin: args.timeMin,
timeMax: args.timeMax,
items: uniqueItems,
});
return key;
}
type FreeBusyArgs = { timeMin: string; timeMax: string; items: { id: string }[] };
/**
* It means that caller can only work with DB Credentials
* In-memory delegation credentials aren't supported here. Delegation User Credentials, that are in DB and have credential.delegationCredential relation can be used though
*/
function assertCalendarHasDbCredential(calendar: Calendar | null) {
if (!calendar?.getCredentialId) {
return;
}
const credentialId = calendar.getCredentialId();
if (credentialId < 0) {
throw new Error(`Received invalid credentialId ${credentialId}`);
}
}
/**
* It means that caller can work with in-memory credential
*/
function declareCanWorkWithInMemoryCredential() {
// No assertion required here, it is for readability who reads the caller's code
}
export class CalendarCacheRepository implements ICalendarCacheRepository {
calendar: Calendar | null;
constructor(calendar: Calendar | null = null) {
this.calendar = calendar;
}
async watchCalendar(args: { calendarId: string; eventTypeIds: SelectedCalendarEventTypeIds }) {
assertCalendarHasDbCredential(this.calendar);
const { calendarId, eventTypeIds } = args;
if (typeof this.calendar?.watchCalendar !== "function") {
log.info(
'[handleWatchCalendar] Skipping watching calendar due to calendar not having "watchCalendar" method'
);
return;
}
await this.calendar?.watchCalendar({ calendarId, eventTypeIds });
}
async unwatchCalendar(args: { calendarId: string; eventTypeIds: SelectedCalendarEventTypeIds }) {
assertCalendarHasDbCredential(this.calendar);
const { calendarId, eventTypeIds } = args;
if (typeof this.calendar?.unwatchCalendar !== "function") {
log.info(
'[unwatchCalendar] Skipping unwatching calendar due to calendar not having "unwatchCalendar" method'
);
return;
}
const response = await this.calendar?.unwatchCalendar({ calendarId, eventTypeIds });
return response;
}
async getCachedAvailability({
credentialId,
userId,
args,
}: {
credentialId: number;
userId: number | null;
args: FreeBusyArgs;
}) {
declareCanWorkWithInMemoryCredential();
log.debug("Getting cached availability", safeStringify({ credentialId, userId, args }));
const key = parseKeyForCache(args);
let cached;
let usedInMemoryDelegationCredential = false;
if (isInMemoryDelegationCredential({ credentialId })) {
usedInMemoryDelegationCredential = true;
if (!userId) {
log.warn("userId is not available when querying cache for in-memory delegation credential");
return null;
}
// We don't have credentialId available when querying the cache, as we use in-memory delegation credentials for this which don't have valid credentialId
// Also, we would prefer to reuse the existing calendar-cache(connected to regular credentials) when enabling delegation credentials, for which we can't use credentialId in querying as that is not in DB
// Security/Privacy wise, it is fine to query solely based on userId as userId and key(which has external email Ids in there) together can be used to uniquely identify the cache
// A user could have multiple third party calendars connected, but they key would still be different for each case in calendar-cache because of the presence of emails in there.
// Sample key: {"timeMin":"2025-04-01T00:00:00.000Z","timeMax":"2025-08-01T00:00:00.000Z","items":[{"id":"[email protected]"}]} <- Notice it has emailId in there for which busytimes are fetched, we could assume that these emailIds would be unique across different calendars like Google/Outlook
cached = await prisma.calendarCache.findFirst({
// We have index on userId and key, so this should be fast
// TODO: Should we consider index on all three - userId, key and expiresAt?
where: {
userId,
key,
expiresAt: { gte: new Date(Date.now()) },
},
orderBy: {
// In case of multiple entries for same key and userId, we prefer the one with highest expiry, which will be the most updated one
// TODO: For better tracking we could also want to use updatedAt directly which doesn't exist yet in CalendarCache table
expiresAt: "desc",
},
});
} else {
cached = await prisma.calendarCache.findUnique({
where: {
credentialId_key: {
credentialId,
key,
},
expiresAt: { gte: new Date(Date.now()) },
},
});
}
log.info(
"Got cached availability",
safeStringify({ key, cached, credentialId, usedInMemoryDelegationCredential })
);
return cached;
}
async upsertCachedAvailability({
credentialId,
userId,
args,
value,
}: {
credentialId: number;
userId: number | null;
args: FreeBusyArgs;
value: Prisma.JsonNullValueInput | Prisma.InputJsonValue;
}) {
assertCalendarHasDbCredential(this.calendar);
const key = parseKeyForCache(args);
await prisma.calendarCache.upsert({
where: {
credentialId_key: {
credentialId,
key,
},
},
update: {
// Ensure that on update userId is also set(It handles the case where userId is not set for legacy records)
userId,
value,
expiresAt: new Date(Date.now() + CACHING_TIME),
},
create: {
value,
credentialId,
userId,
key,
expiresAt: new Date(Date.now() + CACHING_TIME),
},
});
}
async getCacheStatusByCredentialIds(credentialIds: number[]) {
const cacheStatuses = await prisma.calendarCache.groupBy({
by: ["credentialId"],
where: {
credentialId: { in: credentialIds },
},
_max: {
updatedAt: true,
},
});
return cacheStatuses.map((cache) => ({
credentialId: cache.credentialId,
updatedAt: cache._max.updatedAt,
}));
}
}
@@ -1,31 +0,0 @@
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { getCredentialForCalendarCache } from "@calcom/app-store/delegationCredential";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import prisma from "@calcom/prisma";
import type { Calendar } from "@calcom/types/Calendar";
import { CalendarCacheRepository } from "./calendar-cache.repository";
import type { ICalendarCacheRepository } from "./calendar-cache.repository.interface";
import { CalendarCacheRepositoryMock } from "./calendar-cache.repository.mock";
const log = logger.getSubLogger({ prefix: ["CalendarCache"] });
export class CalendarCache {
static async initFromCredentialId(credentialId: number): Promise<ICalendarCacheRepository> {
log.debug("initFromCredentialId", safeStringify({ credentialId }));
const credentialForCalendarCache = await getCredentialForCalendarCache({ credentialId });
const calendarForCalendarCache = await getCalendar(credentialForCalendarCache);
return await CalendarCache.init(calendarForCalendarCache);
}
static async init(calendar: Calendar | null): Promise<ICalendarCacheRepository> {
const featureRepo = new FeaturesRepository(prisma);
const isCalendarCacheEnabledGlobally = await featureRepo.checkIfFeatureIsEnabledGlobally(
"calendar-cache"
);
if (isCalendarCacheEnabledGlobally) return new CalendarCacheRepository(calendar);
return new CalendarCacheRepositoryMock();
}
}
@@ -1,97 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { getTimeMin, getTimeMax } from "./datesForCache";
describe("getTimeMin", () => {
// Tested on multiple dates
vi.setSystemTime("2025-04-24T00:00:13Z");
it("should return start of current month when no date is passed", () => {
const result = getTimeMin();
const expected = new Date();
expected.setUTCDate(1);
expected.setUTCHours(0, 0, 0, 0);
expect(result).toBe(expected.toISOString());
});
it("should return start of month for a given date", () => {
const result = getTimeMin("2025-03-15T10:30:00Z");
expect(result).toMatchInlineSnapshot(`"2025-03-01T00:00:00.000Z"`);
});
it("should handle dates at the start of month", () => {
const result = getTimeMin("2026-03-01T00:00:00Z");
expect(result).toMatchInlineSnapshot(`"2026-03-01T00:00:00.000Z"`);
});
it("should handle DST changes", () => {
const result = getTimeMin("2024-10-27T01:30:00Z");
expect(result).toMatchInlineSnapshot(`"2024-10-01T00:00:00.000Z"`);
});
});
describe("getTimeMax", () => {
it("should return the start of the overnext month when no date is passed", () => {
const result = getTimeMax();
const expected = new Date();
expected.setUTCMonth(expected.getUTCMonth() + 2);
expected.setUTCDate(1);
expected.setUTCHours(0, 0, 0, 0);
expect(result).toBe(expected.toISOString());
});
it("should return the start of overnext month for dates between start of current month and end of next month", () => {
const testDate = "2024-03-15T10:30:00Z";
const result = getTimeMax(testDate);
expect(result).toMatchInlineSnapshot(`"2024-05-01T00:00:00.000Z"`);
});
it("should return end of month for dates beyond overnext month", () => {
const testDate = "2024-05-15T10:30:00Z";
const result = getTimeMax(testDate);
expect(result).toMatchInlineSnapshot(`"2024-07-01T00:00:00.000Z"`);
});
it("should handle dates at the end of month", () => {
const testDate = "2024-03-31T23:59:59Z";
const result = getTimeMax(testDate);
expect(result).toMatchInlineSnapshot(`"2024-05-01T00:00:00.000Z"`);
});
it("should handle October correctly (31 days)", () => {
const testDate = "2024-10-15T10:30:00Z";
const result = getTimeMax(testDate);
expect(result).toMatchInlineSnapshot(`"2024-12-01T00:00:00.000Z"`);
});
it("should handle DST changes", () => {
const testDate = "2024-10-27T01:30:00Z"; // DST change in Europe
const result = getTimeMax(testDate);
expect(result).toMatchInlineSnapshot(`"2024-12-01T00:00:00.000Z"`);
});
it("should handle dates around DST changes in next month", () => {
const testDate = "2024-09-15T10:30:00Z"; // September, next month includes DST change
const result = getTimeMax(testDate);
expect(result).toMatchInlineSnapshot(`"2024-11-01T00:00:00.000Z"`);
});
it("should handle year changes", () => {
const testDate = "2024-12-24T23:59:59Z";
const result = getTimeMax(testDate);
expect(result).toMatchInlineSnapshot(`"2025-02-01T00:00:00.000Z"`);
});
it("should handle next month", () => {
const testDate = "2025-05-01T02:59:59.999Z";
const result = getTimeMax(testDate);
expect(result).toMatchInlineSnapshot(`"2025-06-01T00:00:00.000Z"`);
});
it("should handle special case where timeMax is more than 2 months from now but less than 3 months", () => {
vi.setSystemTime("2025-04-24T00:00:13Z");
const testDate = "2025-06-02T23:59:59.999Z";
const result = getTimeMax(testDate);
expect(result).toMatchInlineSnapshot(`"2025-06-01T00:00:00.000Z"`);
});
});
@@ -1,59 +0,0 @@
/** Expand the start date to the beginning of the current month */
export const getTimeMin = (timeMin?: string) => {
const date = timeMin ? new Date(timeMin) : new Date();
// Set to UTC to avoid timezone issues
const result = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1));
result.setUTCHours(0, 0, 0, 0);
return result.toISOString();
};
/**
* Expand the end date to the start of the overnext month if date
* is between start of current month and end of next month,
* otherwise return start of overnext month from the passed date
* @example
* Today: March 15, 2024 ▼-------------▼ getTimeMax returns May 1st 00:00:00
* Mar Apr May Jun
* ├────────┼────────┼────────┼────────┤
* Current Month █████████| | | |
* Next Month | █████████| | |
**/
export function getTimeMax(timeMax?: string) {
const now = new Date();
const currentMonth = now.getUTCMonth();
const currentYear = now.getUTCFullYear();
// If no date is passed, return start of the month two months from *now*.
if (!timeMax) {
const result = new Date(Date.UTC(currentYear, currentMonth + 2, 1));
result.setUTCHours(0, 0, 0, 0);
return result.toISOString();
}
// If a date is passed, determine the base month/year for calculation.
const date = new Date(timeMax);
const dateMonth = date.getUTCMonth();
const dateYear = date.getUTCFullYear();
let baseYear = currentYear;
let baseMonth = currentMonth;
// Check if date is within the current month or the next two months relative to *now*.
const isWithinCurrentOrNextTwoMonths =
(dateYear === currentYear && dateMonth <= currentMonth + 2) ||
(dateYear === currentYear + 1 &&
((currentMonth === 10 && dateMonth === 0) || (currentMonth === 11 && dateMonth <= 1)));
// If the input date is beyond the next two months relative to *now*,
// use the *input date's* month/year as the base.
if (!isWithinCurrentOrNextTwoMonths) {
baseYear = dateYear;
baseMonth = dateMonth;
}
// Otherwise, the base remains the current year/month.
// Calculate the start of the month two months after the determined base date.
const result = new Date(Date.UTC(baseYear, baseMonth + 2, 1));
result.setUTCHours(0, 0, 0, 0);
return result.toISOString();
}
@@ -1,93 +0,0 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { IFeaturesRepository } from "@calcom/features/flags/features.repository.interface";
import { CacheService } from "./getShouldServeCache";
import { CalendarSubscriptionService } from "@calcom/features/calendar-subscription/lib/CalendarSubscriptionService";
describe("CacheService.getShouldServeCache", () => {
const mockFeaturesRepository: IFeaturesRepository = {
checkIfTeamHasFeature: vi.fn(),
checkIfFeatureIsEnabledGlobally: vi.fn(),
checkIfUserHasFeature: vi.fn(),
};
const cacheService = new CacheService({ featuresRepository: mockFeaturesRepository });
afterEach(() => {
vi.clearAllMocks();
});
describe("when shouldServeCache is explicitly set to boolean", () => {
it("should return true when shouldServeCache is true", async () => {
const result = await cacheService.getShouldServeCache(true, 123);
expect(result).toBe(true);
expect(mockFeaturesRepository.checkIfTeamHasFeature).not.toHaveBeenCalled();
});
it("should return false when shouldServeCache is false", async () => {
const result = await cacheService.getShouldServeCache(false, 123);
expect(result).toBe(false);
expect(mockFeaturesRepository.checkIfTeamHasFeature).not.toHaveBeenCalled();
});
});
describe("when shouldServeCache is undefined", () => {
it("should return false when no teamId is provided", async () => {
const result = await cacheService.getShouldServeCache(undefined, undefined);
expect(result).toBe(false);
expect(mockFeaturesRepository.checkIfTeamHasFeature).not.toHaveBeenCalled();
});
it("should return false when teamId is null", async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = await cacheService.getShouldServeCache(undefined, null as any);
expect(result).toBe(false);
expect(mockFeaturesRepository.checkIfTeamHasFeature).not.toHaveBeenCalled();
});
it("should return false when teamId is 0", async () => {
const result = await cacheService.getShouldServeCache(undefined, 0);
expect(result).toBe(false);
expect(mockFeaturesRepository.checkIfTeamHasFeature).not.toHaveBeenCalled();
});
it("should check feature repository when teamId is provided and return true if feature is enabled", async () => {
vi.mocked(mockFeaturesRepository.checkIfTeamHasFeature).mockResolvedValue(true);
const result = await cacheService.getShouldServeCache(undefined, 123);
expect(result).toBe(true);
expect(mockFeaturesRepository.checkIfTeamHasFeature).toHaveBeenCalledWith(123, CalendarSubscriptionService.CALENDAR_SUBSCRIPTION_CACHE_FEATURE);
});
it("should check feature repository when teamId is provided and return false if feature is disabled", async () => {
vi.mocked(mockFeaturesRepository.checkIfTeamHasFeature).mockResolvedValue(false);
const result = await cacheService.getShouldServeCache(undefined, 456);
expect(result).toBe(false);
expect(mockFeaturesRepository.checkIfTeamHasFeature).toHaveBeenCalledWith(456, CalendarSubscriptionService.CALENDAR_SUBSCRIPTION_CACHE_FEATURE);
});
});
describe("edge cases", () => {
it("should prioritize explicit shouldServeCache over teamId check", async () => {
vi.mocked(mockFeaturesRepository.checkIfTeamHasFeature).mockResolvedValue(true);
const result = await cacheService.getShouldServeCache(false, 123);
expect(result).toBe(false);
expect(mockFeaturesRepository.checkIfTeamHasFeature).not.toHaveBeenCalled();
});
it("should handle positive teamId correctly", async () => {
vi.mocked(mockFeaturesRepository.checkIfTeamHasFeature).mockResolvedValue(true);
const result = await cacheService.getShouldServeCache(undefined, 999);
expect(result).toBe(true);
expect(mockFeaturesRepository.checkIfTeamHasFeature).toHaveBeenCalledWith(999, CalendarSubscriptionService.CALENDAR_SUBSCRIPTION_CACHE_FEATURE);
});
});
});
@@ -1,16 +0,0 @@
import type { IFeaturesRepository } from "@calcom/features/flags/features.repository.interface";
import { CalendarSubscriptionService } from "@calcom/features/calendar-subscription/lib/CalendarSubscriptionService";
export interface ICacheService {
featuresRepository: IFeaturesRepository;
}
export class CacheService {
constructor(private readonly dependencies: ICacheService) {}
async getShouldServeCache(shouldServeCache?: boolean | undefined, teamId?: number) {
if (typeof shouldServeCache === "boolean") return shouldServeCache;
if (!teamId) return false;
return await this.dependencies.featuresRepository.checkIfTeamHasFeature(teamId, CalendarSubscriptionService.CALENDAR_SUBSCRIPTION_CACHE_FEATURE);
}
}
@@ -7,7 +7,6 @@ import { createContainer } from "../di";
import { availableSlotsModule } from "../modules/AvailableSlots";
import { bookingRepositoryModule } from "../modules/Booking";
import { busyTimesModule } from "../modules/BusyTimes";
import { cacheModule } from "../modules/Cache";
import { checkBookingLimitsModule } from "../modules/CheckBookingLimits";
import { eventTypeRepositoryModule } from "../modules/EventType";
import { featuresRepositoryModule } from "../modules/Features";
@@ -35,7 +34,6 @@ container.load(DI_TOKENS.BOOKING_REPOSITORY_MODULE, bookingRepositoryModule);
container.load(DI_TOKENS.EVENT_TYPE_REPOSITORY_MODULE, eventTypeRepositoryModule);
container.load(DI_TOKENS.ROUTING_FORM_RESPONSE_REPOSITORY_MODULE, routingFormResponseRepositoryModule);
container.load(DI_TOKENS.FEATURES_REPOSITORY_MODULE, featuresRepositoryModule);
container.load(DI_TOKENS.CACHE_SERVICE_MODULE, cacheModule);
container.load(DI_TOKENS.CHECK_BOOKING_LIMITS_SERVICE_MODULE, checkBookingLimitsModule);
container.load(DI_TOKENS.AVAILABLE_SLOTS_SERVICE_MODULE, availableSlotsModule);
container.load(DI_TOKENS.GET_USER_AVAILABILITY_SERVICE_MODULE, getUserAvailabilityModule);
-16
View File
@@ -1,16 +0,0 @@
import { DI_TOKENS } from "@calcom/features/di/tokens";
import { prismaModule } from "@calcom/features/di/modules/Prisma";
import type { CacheService } from "../../../features/calendar-cache/lib/getShouldServeCache";
import { createContainer } from "../di";
import { cacheModule } from "../modules/Cache";
import { featuresRepositoryModule } from "../modules/Features";
const container = createContainer();
container.load(DI_TOKENS.PRISMA_MODULE, prismaModule);
container.load(DI_TOKENS.FEATURES_REPOSITORY_MODULE, featuresRepositoryModule);
container.load(DI_TOKENS.CACHE_SERVICE_MODULE, cacheModule);
export function getCacheService() {
return container.get<CacheService>(DI_TOKENS.CACHE_SERVICE);
}
@@ -15,7 +15,6 @@ availableSlotsModule.bind(DI_TOKENS.AVAILABLE_SLOTS_SERVICE).toClass(AvailableSl
eventTypeRepo: DI_TOKENS.EVENT_TYPE_REPOSITORY,
routingFormResponseRepo: DI_TOKENS.ROUTING_FORM_RESPONSE_REPOSITORY,
redisClient: DI_TOKENS.REDIS_CLIENT,
cacheService: DI_TOKENS.CACHE_SERVICE,
checkBookingLimitsService: DI_TOKENS.CHECK_BOOKING_LIMITS_SERVICE,
userAvailabilityService: DI_TOKENS.GET_USER_AVAILABILITY_SERVICE,
busyTimesService: DI_TOKENS.BUSY_TIMES_SERVICE,
-23
View File
@@ -1,23 +0,0 @@
import { CacheService } from "@calcom/features/calendar-cache/lib/getShouldServeCache";
import { createModule, bindModuleToClassOnToken, type ModuleLoader } from "../di";
import { DI_TOKENS } from "../tokens";
import { moduleLoader as featuresRepositoryModuleLoader } from "./Features";
export const cacheModule = createModule();
const token = DI_TOKENS.CACHE_SERVICE;
const moduleToken = DI_TOKENS.CACHE_SERVICE_MODULE;
const loadModule = bindModuleToClassOnToken({
module: cacheModule,
moduleToken,
token,
classs: CacheService,
depsMap: {
featuresRepository: featuresRepositoryModuleLoader,
},
});
export const moduleLoader: ModuleLoader = {
token,
loadModule,
};
-2
View File
@@ -32,8 +32,6 @@ export const DI_TOKENS = {
INSIGHTS_BOOKING_SERVICE_MODULE: Symbol("InsightsBookingServiceModule"),
FEATURES_REPOSITORY: Symbol("FeaturesRepository"),
FEATURES_REPOSITORY_MODULE: Symbol("FeaturesRepositoryModule"),
CACHE_SERVICE: Symbol("CacheService"),
CACHE_SERVICE_MODULE: Symbol("CacheServiceModule"),
CHECK_BOOKING_LIMITS_SERVICE: Symbol("CheckBookingLimitsService"),
CHECK_BOOKING_LIMITS_SERVICE_MODULE: Symbol("CheckBookingLimitsServiceModule"),
CHECK_BOOKING_AND_DURATION_LIMITS_SERVICE: Symbol("CheckBookingAndDurationLimitsService"),