revert: "feat: Populate gCal calendar cache via webhooks (#11928)" (#17675)

This reverts commit d294a74aad.
This commit is contained in:
Keith Williams authored and GitHub committed 2024-11-15 19:28:30 -03:00
1 parent bdf94c7f48
commit 6272c881c8
39 files changed
+240 -952

No files matched your search

@@ -1,62 +0,0 @@
import type { NextRequest } from "next/server";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server/defaultResponder.appDir";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import { CalendarCache } from "../calendar-cache";
const validateRequest = (req: NextRequest) => {
const searchParams = req.nextUrl.searchParams;
const apiKey = searchParams.get("apiKey") || req.headers.get("authorization");
if (!apiKey || ![process.env.CRON_API_KEY, `Bearer ${process.env.CRON_SECRET}`].includes(apiKey)) {
throw new HttpError({ statusCode: 401, message: "Unauthorized" });
}
};
const handleCalendarsToUnwatch = async () => {
const calendarsToUnwatch = await SelectedCalendarRepository.getNextBatchToUnwatch();
const result = await Promise.allSettled(
calendarsToUnwatch.map(async (sc) => {
if (!sc.credentialId) return;
const cc = await CalendarCache.initFromCredentialId(sc.credentialId);
await cc.unwatchCalendar({ calendarId: sc.externalId });
})
);
return result;
};
const handleCalendarsToWatch = async () => {
const calendarsToWatch = await SelectedCalendarRepository.getNextBatchToWatch();
const result = await Promise.allSettled(
calendarsToWatch.map(async (sc) => {
if (!sc.credentialId) return;
const cc = await CalendarCache.initFromCredentialId(sc.credentialId);
await cc.watchCalendar({ calendarId: sc.externalId });
})
);
return result;
};
// This cron is used to activate and renew calendar subcriptions
export const GET = defaultResponder(async (request: NextRequest) => {
validateRequest(request);
const [watchedResult, unwatchedResult] = await Promise.all([
handleCalendarsToWatch(),
handleCalendarsToUnwatch(),
]);
// TODO: Credentials can be installed on a whole team, check for selected calendars on the team
return {
succeededAt: new Date().toISOString(),
watched: {
successful: watchedResult.filter((x) => x.status === "fulfilled").length,
failed: watchedResult.filter((x) => x.status === "rejected").length,
},
unwatched: {
successful: unwatchedResult.filter((x) => x.status === "fulfilled").length,
failed: unwatchedResult.filter((x) => x.status === "rejected").length,
},
};
});
@@ -1,14 +0,0 @@
import type { CalendarCache, Prisma } from "@prisma/client";
export type FreeBusyArgs = { timeMin: string; timeMax: string; items: { id: string }[] };
export interface ICalendarCacheRepository {
watchCalendar(args: { calendarId: string }): Promise<any>;
unwatchCalendar(args: { calendarId: string }): Promise<any>;
upsertCachedAvailability(
credentialId: number,
args: FreeBusyArgs,
value: Prisma.JsonNullValueInput | Prisma.InputJsonValue
): Promise<void>;
getCachedAvailability(credentialId: number, args: FreeBusyArgs): Promise<CalendarCache | null>;
}
@@ -1,22 +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`);
}
}
@@ -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,124 +0,0 @@
import type { Prisma } from "@prisma/client";
import logger from "@calcom/lib/logger";
import prisma from "@calcom/prisma";
import type { Calendar } from "@calcom/types/Calendar";
import type { ICalendarCacheRepository } from "./calendar-cache.repository.interface";
import { watchCalendarSchema } from "./calendar-cache.repository.schema";
const log = logger.getSubLogger({ prefix: ["CalendarCacheRepository"] });
/** Enable or disable the expanded cache. Enabled by default. */
const ENABLE_EXPANDED_CACHE = process.env.ENABLE_EXPANDED_CACHE !== "0";
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);
const key = JSON.stringify({ timeMin, timeMax, items });
return key;
}
/**
* By expanding the cache to whole months, we can save round trips to the third party APIs.
* In this case we already have the data in the database, so we can just return it.
*/
function handleMinMax(min: string, max: string) {
if (!ENABLE_EXPANDED_CACHE) return { timeMin: min, timeMax: max };
return { timeMin: getTimeMin(min), timeMax: getTimeMax(max) };
}
type FreeBusyArgs = { timeMin: string; timeMax: string; items: { id: string }[] };
export class CalendarCacheRepository implements ICalendarCacheRepository {
calendar: Calendar | null;
constructor(calendar: Calendar | null = null) {
this.calendar = calendar;
}
async watchCalendar(args: { calendarId: string }) {
const { calendarId } = args;
if (typeof this.calendar?.watchCalendar !== "function") {
log.info(
'[handleWatchCalendar] Skipping watching calendar due to calendar not having "watchCalendar" method'
);
return;
}
const response = await this.calendar?.watchCalendar({ calendarId });
const parsedResponse = watchCalendarSchema.safeParse(response);
if (!parsedResponse.success) {
log.info(
"[handleWatchCalendar] Received invalid response from calendar.watchCalendar, skipping watching calendar"
);
return;
}
return parsedResponse.data;
}
async unwatchCalendar(args: { calendarId: string }) {
const { calendarId } = args;
if (typeof this.calendar?.unwatchCalendar !== "function") {
log.info(
'[unwatchCalendar] Skipping watching calendar due to calendar not having "watchCalendar" method'
);
return;
}
const response = await this.calendar?.unwatchCalendar({ calendarId });
return response;
}
async getCachedAvailability(credentialId: number, args: FreeBusyArgs) {
const key = parseKeyForCache(args);
log.info("Getting cached availability", key);
const cached = await prisma.calendarCache.findUnique({
where: {
credentialId_key: {
credentialId,
key,
},
expiresAt: { gte: new Date(Date.now()) },
},
});
return cached;
}
async upsertCachedAvailability(
credentialId: number,
args: FreeBusyArgs,
value: Prisma.JsonNullValueInput | Prisma.InputJsonValue
) {
const key = parseKeyForCache(args);
await prisma.calendarCache.upsert({
where: {
credentialId_key: {
credentialId,
key,
},
},
update: {
value,
expiresAt: new Date(Date.now() + CACHING_TIME),
},
create: {
value,
credentialId,
key,
expiresAt: new Date(Date.now() + CACHING_TIME),
},
});
}
}
@@ -1,28 +0,0 @@
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import prisma from "@calcom/prisma";
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
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";
export class CalendarCache {
static async initFromCredentialId(credentialId: number): Promise<ICalendarCacheRepository> {
const credential = await prisma.credential.findUnique({
where: { id: credentialId },
select: credentialForCalendarServiceSelect,
});
const calendar = await getCalendar(credential);
return await CalendarCache.init(calendar);
}
static async init(calendar: Calendar | null): Promise<ICalendarCacheRepository> {
const featureRepo = new FeaturesRepository();
const isCalendarCacheEnabledGlobally = await featureRepo.checkIfFeatureIsEnabledGlobally(
"calendar-cache"
);
if (isCalendarCacheEnabledGlobally) return new CalendarCacheRepository(calendar);
return new CalendarCacheRepositoryMock();
}
}
@@ -28,8 +28,6 @@ const CalendarSwitch = (props: ICalendarSwitchProps) => {
const body = {
integration: type,
externalId: externalId,
// new URLSearchParams does not accept numbers
credentialId: String(credentialId),
};
if (isOn) {
@@ -38,7 +36,7 @@ const CalendarSwitch = (props: ICalendarSwitchProps) => {
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
body: JSON.stringify({ ...body, credentialId }),
});
if (!res.ok) {
@@ -1,7 +1,4 @@
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: string): Promise<boolean>;
checkIfTeamOrUserHasFeature(args: { teamId?: number; userId?: number }, slug: string): Promise<boolean>;
@@ -2,19 +2,9 @@ import { captureException } from "@sentry/nextjs";
import db from "@calcom/prisma";
import type { AppFlags } from "./config";
import type { IFeaturesRepository } from "./features.repository.interface";
import { getFeatureFlag } from "./server/utils";
export class FeaturesRepository implements IFeaturesRepository {
async checkIfFeatureIsEnabledGlobally(slug: keyof AppFlags) {
try {
return await getFeatureFlag(db, slug);
} catch (err) {
captureException(err);
throw err;
}
}
async checkIfTeamHasFeature(teamId: number, slug: string) {
try {
const teamFeature = await db.teamFeatures.findUnique({
+3 -20
View File
@@ -1,26 +1,9 @@
import type { AppFlags } from "@calcom/features/flags/config";
import { trpc } from "@calcom/trpc/react";
const initialData: AppFlags = {
organizations: false,
teams: false,
"calendar-cache": false,
emails: false,
insights: false,
webhooks: false,
workflows: false,
"email-verification": false,
"google-workspace-directory": false,
"disable-signup": false,
attributes: false,
"organizer-request-email-v2": false,
};
if (process.env.NEXT_PUBLIC_IS_E2E) {
initialData.organizations = true;
initialData.teams = true;
}
const initialData: Partial<AppFlags> = process.env.NEXT_PUBLIC_IS_E2E
? { organizations: true, teams: true }
: {};
export function useFlags(): Partial<AppFlags> {
const query = trpc.viewer.features.map.useQuery(undefined, {
initialData,
+2 -8
View File
@@ -2,21 +2,15 @@ import type { PrismaClient } from "@calcom/prisma";
import type { AppFlags } from "../config";
// This is a temporary cache to avoid hitting the database on every lambda invocation
let TEMP_CACHE: AppFlags | null = null;
export async function getFeatureFlagMap(prisma: PrismaClient) {
// If we've already fetched the flags, return them
if (TEMP_CACHE) return TEMP_CACHE;
const flags = await prisma.feature.findMany({
orderBy: { slug: "asc" },
cacheStrategy: { swr: 300, ttl: 300 },
});
TEMP_CACHE = flags.reduce((acc, flag) => {
return flags.reduce((acc, flag) => {
acc[flag.slug as keyof AppFlags] = flag.enabled;
return acc;
}, {} as AppFlags);
return TEMP_CACHE;
}, {} as Partial<AppFlags>);
}
interface CacheEntry {