This commit is contained in:
1 parent
50df22928b
commit
7c0ee9f186
38 files changed
+920
-240
No files matched your search
@@ -0,0 +1,65 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
|
||||
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
|
||||
|
||||
import { CalendarCache } from "../calendar-cache";
|
||||
|
||||
const validateRequest = (req: NextApiRequest) => {
|
||||
const apiKey = String(req.query.apiKey) || req.headers.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
|
||||
const handler = defaultResponder(async (request: NextApiRequest) => {
|
||||
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,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export default defaultHandler({
|
||||
GET: Promise.resolve({ default: defaultResponder(handler) }),
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
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>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
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(),
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
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),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user