fix: Handle calendar-cache with Delegation Credentials
Fixes CAL-5372 # Delegation Credentials with CalendarCache. Following content is a snapshot of the [internal document](https://calendso.slack.com/docs/T08B8KA2BNF/F08L5JYU3V3) **Problem-1 :** CalendarCache needs SelectedCalendar records to work but SelectedCalendar record is only created when a user connects their calendar and then enables some calendar for conflict checking. Because with Delegation, no manual connection is done by any of the members, we need a way to create SelectedCalendar records automatically. **Problem-2** CalendarCache connects to credential(regular credential) which doesn’t exist for Delegation Credential scenario. Also, DelegationCredential is common for all the members(different from Credential which is different for different members) of the organization and we need to identify to which user the CalendarCache belongs. **Solution for both problems** - Create credential records for Delegation Credentials as well - Through Cron(new - we could schedule it every 5mins) - Now create SelectedCalendar records for those Credential records - Through another Cron(new - we could schedule it every 5mins) - Now CalendarCache records will automatically be created for those SelectedCalendar records -existing cron ## Fixed some Delegation Credentials bugs unrelated to calendar-cache - If DestinationCalendar wasn't set(which is possible only with Delegation Credentials), then Google Meet wasn't used as a conferencing app - [Added a test] - If no SelectedCalendar is there but Google Calendar connection exists(possible only with Delegation Credential) then we were not doing conflict checking. It is expected to not do it for Regular Credentials, but for Delegation Credential we must check for conflict in that case too [Added a test] - Earlier if a user has Regular Credential as well as Delegation Credential for the same external id which is the member email(say [email protected]) then availability were retrieved twice because we weren't deduplicating credentials as it wasn't a trivial thing to do. Now that is being done. **Env Variables:** Note this PR doesn't introduce any new env variable. The existing env variable has been added to .env.example. But if this env variable isn't already set, it must be set. `CALCOM_SERVICE_ACCOUNT_ENCRYPTION_KEY={SAME_AS_SET_FOR_V2_API}` **Deployment Plan:** 1. Add Observability for SelectedCalendar when _error_ field is set 2. Follow https://github.com/calcom/cal.com/blob/calendar-cache-dwd-support/apps/web/app/(use-page-wrapper)/settings/(settings-layout)/organizations/delegation-credential/delegation-credential.md#setting-up-delegation-credential-for-google-calendar-api to enable Delegation Credential for i.cal.com 3. Note that to be able to see the option to enable Delegation Credential for an organization, you need to enable `teamFeature` and `feature` for `delegation-credential` ## Automation Tests - Introduced tests for calendar-cache.repository.ts - Tests all methods of the repository - Added more tests for handleNewBooking/delegation-credential flow. - Added test to verify the bug fix when no DestinationCalendar exists and Google Meet should be used still - Added more tests for Google Calendar/CalendarService targeting DelegationCredential - Added more tests for getCalendarsEvents. - To test the new logic of calling getAvailability still if there are no selectedCalendars in case of Delegation Credential - Also introduced tests for `getAvailabitlityWithTimezones` which was an existing function but now has some new changes. - Added tests for deduplication logic in CalendarManager.ts ## How to Test Enable Calendar Cache and Delegation Credential feature for acme org through `features` and `teamFeatures` tables. - Enable Delegation Credential for acme org - Enable atleast 1 calendar for conflict checking for one of the users(say owner1) - Ensure GOOGLE_WEBHOOK_TOKEN is set in .env file - Ensure GOOGLE_WEBHOOK_URL is set to ngrok url of webapp in .env file - Hit cron endpoint `curl http://localhost:3000/api/calendar-cache/cron\?apiKey\={API_KEY}` that would cache the freebusy result for the selected calendars Followup - https://github.com/calcom/cal.com/pull/20698 - https://github.com/calcom/cal.com/pull/18619/files#r2046795643
This commit is contained in:
1 parent
17f1932467
commit
e3bd90c4f2
55 files changed
+3409
-629
No files matched your search
+179
-1
@@ -51,7 +51,7 @@ describe("handleNewBooking", () => {
|
||||
setupAndTeardown();
|
||||
describe("Delegation Credential", () => {
|
||||
test(
|
||||
`should create a successful booking using the delegation credential
|
||||
`should create a successful booking using the delegation credential when User's destination calendar is set toGoogle Calendar
|
||||
1. Should create a booking in the database with reference having Delegation credential
|
||||
2. Should create an event in calendar with Delegation credential
|
||||
3. Should use Google Meet as the location even when not explicitly set.
|
||||
@@ -229,6 +229,184 @@ describe("handleNewBooking", () => {
|
||||
timeout
|
||||
);
|
||||
|
||||
test(
|
||||
`should create a successful booking using the delegation credential event when User/EventType's destination calendar is not set
|
||||
1. Should create a booking in the database with reference having Delegation credential
|
||||
2. Should create an event in calendar with Delegation credential
|
||||
3. Should use Google Meet as the location even when not explicitly set and no destination calendar is set for User/EventType
|
||||
`,
|
||||
async ({ emails }) => {
|
||||
const handleNewBooking = (await import("@calcom/features/bookings/lib/handleNewBooking")).default;
|
||||
|
||||
const org = await createOrganization({
|
||||
name: "Test Org",
|
||||
slug: "testorg",
|
||||
});
|
||||
|
||||
const payloadToMakePartOfOrganization = [
|
||||
{
|
||||
membership: {
|
||||
accepted: true,
|
||||
role: MembershipRole.ADMIN,
|
||||
},
|
||||
team: {
|
||||
id: org.id,
|
||||
name: "Test Org",
|
||||
slug: "testorg",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const booker = getBooker({
|
||||
email: "[email protected]",
|
||||
name: "Booker",
|
||||
});
|
||||
|
||||
const organizer = getOrganizer({
|
||||
name: "Organizer",
|
||||
email: "[email protected]",
|
||||
id: 101,
|
||||
schedules: [TestData.schedules.IstWorkHours],
|
||||
selectedCalendars: [TestData.selectedCalendars.google],
|
||||
// User must be part of organization to be able to use that organization's Delegation credential
|
||||
teams: payloadToMakePartOfOrganization,
|
||||
// No regular credentials provided
|
||||
credentials: [],
|
||||
});
|
||||
|
||||
const delegationCredential = await createDelegationCredential(org.id);
|
||||
const payloadToCreateUserEventTypeForOrganizer = {
|
||||
id: 1,
|
||||
slotInterval: 30,
|
||||
length: 30,
|
||||
users: [
|
||||
{
|
||||
id: organizer.id,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
await createBookingScenario(
|
||||
getScenarioData({
|
||||
webhooks: [
|
||||
{
|
||||
userId: organizer.id,
|
||||
eventTriggers: ["BOOKING_CREATED"],
|
||||
subscriberUrl: "http://my-webhook.example.com",
|
||||
active: true,
|
||||
eventTypeId: 1,
|
||||
appId: null,
|
||||
},
|
||||
],
|
||||
workflows: [
|
||||
{
|
||||
userId: organizer.id,
|
||||
trigger: "NEW_EVENT",
|
||||
action: "EMAIL_HOST",
|
||||
template: "REMINDER",
|
||||
activeOn: [1],
|
||||
},
|
||||
],
|
||||
eventTypes: [payloadToCreateUserEventTypeForOrganizer],
|
||||
organizer,
|
||||
apps: [TestData.apps["daily-video"], TestData.apps["google-calendar"]],
|
||||
})
|
||||
);
|
||||
|
||||
// Mock a Scenario where iCalUID isn't returned by Google Calendar in which case booking UID is used as the ics UID
|
||||
const calendarMock = mockCalendarToHaveNoBusySlots("googlecalendar", {
|
||||
create: {
|
||||
id: "GOOGLE_CALENDAR_EVENT_ID",
|
||||
uid: "MOCK_ID",
|
||||
appSpecificData: {
|
||||
googleCalendar: {
|
||||
hangoutLink: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const mockBookingData = getMockRequestDataForBooking({
|
||||
data: {
|
||||
eventTypeId: 1,
|
||||
responses: {
|
||||
email: booker.email,
|
||||
name: booker.name,
|
||||
location: { optionValue: "", value: BookingLocations.GoogleMeet },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createdBooking = await handleNewBooking({
|
||||
bookingData: mockBookingData,
|
||||
});
|
||||
|
||||
expect(createdBooking.responses).toEqual(
|
||||
expect.objectContaining({
|
||||
email: booker.email,
|
||||
name: booker.name,
|
||||
})
|
||||
);
|
||||
|
||||
expect(createdBooking).toEqual(
|
||||
expect.objectContaining({
|
||||
location: BookingLocations.GoogleMeet,
|
||||
})
|
||||
);
|
||||
|
||||
await expectBookingToBeInDatabase({
|
||||
description: "",
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
uid: createdBooking.uid!,
|
||||
eventTypeId: mockBookingData.eventTypeId,
|
||||
status: BookingStatus.ACCEPTED,
|
||||
references: [
|
||||
{
|
||||
type: appStoreMetadata.googlecalendar.type,
|
||||
uid: "GOOGLE_CALENDAR_EVENT_ID",
|
||||
meetingId: "GOOGLE_CALENDAR_EVENT_ID",
|
||||
meetingPassword: "MOCK_PASSWORD",
|
||||
meetingUrl: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
|
||||
// Verify Delegation credential was used
|
||||
delegationCredentialId: delegationCredential.id,
|
||||
},
|
||||
],
|
||||
iCalUID: createdBooking.iCalUID,
|
||||
});
|
||||
|
||||
expectWorkflowToBeTriggered({ emailsToReceive: [organizer.email], emails });
|
||||
expectSuccessfulCalendarEventCreationInCalendar(calendarMock, {
|
||||
credential: buildDelegationCredential({
|
||||
serviceAccountKey: delegationCredential.serviceAccountKey,
|
||||
}),
|
||||
calendarIdUsingFallbackOfFirstCalendarCredential: TestData.selectedCalendars.google.externalId,
|
||||
// There would be no videoCallUrl in this case as it is not a dedicated conferencing case and hangoutLink is used instead
|
||||
videoCallUrl: null,
|
||||
});
|
||||
|
||||
const iCalUID = expectICalUIDAsString(createdBooking.iCalUID);
|
||||
|
||||
expectSuccessfulBookingCreationEmails({
|
||||
booking: {
|
||||
uid: createdBooking.uid!,
|
||||
},
|
||||
booker,
|
||||
organizer,
|
||||
emails,
|
||||
iCalUID,
|
||||
});
|
||||
|
||||
expectBookingCreatedWebhookToHaveBeenFired({
|
||||
booker,
|
||||
organizer,
|
||||
location: BookingLocations.GoogleMeet,
|
||||
subscriberUrl: "http://my-webhook.example.com",
|
||||
videoCallUrl: "https://GOOGLE_MEET_URL_IN_CALENDAR_EVENT",
|
||||
});
|
||||
},
|
||||
timeout
|
||||
);
|
||||
|
||||
test(
|
||||
`should create a successful booking using the office365 delegation credential with Cal Video as the location
|
||||
1. Should create a booking in the database with reference having Delegation credential
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
## Responsibilities
|
||||
- File:`/api/calendar-cache/cron` - Runs every minute and takes care of two things:
|
||||
1. Watching calendars
|
||||
- Identifies calendars that are not watched(identified by `googleChannelId` being null) and watches them
|
||||
- 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
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { NextApiRequest } from "next";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { defaultHandler } from "@calcom/lib/server/defaultHandler";
|
||||
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
|
||||
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
|
||||
@@ -8,6 +9,8 @@ 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}`)) {
|
||||
@@ -22,7 +25,12 @@ function logRejected(result: PromiseSettledResult<unknown>) {
|
||||
}
|
||||
|
||||
function getUniqueCalendarsByExternalId<
|
||||
T extends { externalId: string; eventTypeId: number | null; credentialId: number | null; id: string }
|
||||
T extends {
|
||||
externalId: string;
|
||||
eventTypeId: number | null;
|
||||
credentialId: number | null;
|
||||
id: string;
|
||||
}
|
||||
>(calendars: T[]) {
|
||||
type ExternalId = string;
|
||||
return calendars.reduce(
|
||||
@@ -57,12 +65,27 @@ const handleCalendarsToUnwatch = async () => {
|
||||
async ([externalId, { eventTypeIds, credentialId, id }]) => {
|
||||
if (!credentialId) {
|
||||
// So we don't retry on next cron run
|
||||
await SelectedCalendarRepository.updateById(id, { error: "Missing credentialId" });
|
||||
console.log("no credentialId for SelecedCalendar: ", id);
|
||||
|
||||
// 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.updateById(id, {
|
||||
error: "Missing credentialId",
|
||||
});
|
||||
log.error("no credentialId for SelectedCalendar: ", id);
|
||||
return;
|
||||
}
|
||||
const cc = await CalendarCache.initFromCredentialId(credentialId);
|
||||
await cc.unwatchCalendar({ calendarId: externalId, eventTypeIds });
|
||||
|
||||
try {
|
||||
const cc = await CalendarCache.initFromCredentialId(credentialId);
|
||||
await cc.unwatchCalendar({ calendarId: externalId, eventTypeIds });
|
||||
} catch (error) {
|
||||
let errorMessage = "Unknown error";
|
||||
if (error instanceof Error) {
|
||||
errorMessage = error.message;
|
||||
}
|
||||
await SelectedCalendarRepository.updateById(id, {
|
||||
error: `Error unwatching calendar: ${errorMessage}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
)
|
||||
);
|
||||
@@ -79,12 +102,25 @@ const handleCalendarsToWatch = async () => {
|
||||
async ([externalId, { credentialId, eventTypeIds, id }]) => {
|
||||
if (!credentialId) {
|
||||
// So we don't retry on next cron run
|
||||
await SelectedCalendarRepository.updateById(id, { error: "Missing credentialId" });
|
||||
console.log("no credentialId for SelecedCalendar: ", id);
|
||||
await SelectedCalendarRepository.updateById(id, {
|
||||
error: "Missing credentialId",
|
||||
});
|
||||
log.error("no credentialId for SelectedCalendar: ", id);
|
||||
return;
|
||||
}
|
||||
const cc = await CalendarCache.initFromCredentialId(credentialId);
|
||||
await cc.watchCalendar({ calendarId: externalId, eventTypeIds });
|
||||
|
||||
try {
|
||||
const cc = await CalendarCache.initFromCredentialId(credentialId);
|
||||
await cc.watchCalendar({ calendarId: externalId, eventTypeIds });
|
||||
} catch (error) {
|
||||
let errorMessage = "Unknown error";
|
||||
if (error instanceof Error) {
|
||||
errorMessage = error.message;
|
||||
}
|
||||
await SelectedCalendarRepository.updateById(id, {
|
||||
error: `Error watching calendar: ${errorMessage}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
@@ -7,10 +7,24 @@ export type FreeBusyArgs = { timeMin: string; timeMax: string; items: { id: stri
|
||||
export interface ICalendarCacheRepository {
|
||||
watchCalendar(args: { calendarId: string; eventTypeIds: SelectedCalendarEventTypeIds }): Promise<any>;
|
||||
unwatchCalendar(args: { calendarId: string; eventTypeIds: SelectedCalendarEventTypeIds }): Promise<any>;
|
||||
upsertCachedAvailability(
|
||||
credentialId: number,
|
||||
args: FreeBusyArgs,
|
||||
value: Prisma.JsonNullValueInput | Prisma.InputJsonValue
|
||||
): Promise<void>;
|
||||
getCachedAvailability(credentialId: number, args: FreeBusyArgs): Promise<CalendarCache | null>;
|
||||
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>;
|
||||
}
|
||||
@@ -19,4 +19,8 @@ export class CalendarCacheRepositoryMock implements ICalendarCacheRepository {
|
||||
async unwatchCalendar() {
|
||||
log.info(`Skipping unwatchCalendar due to calendar-cache being disabled`);
|
||||
}
|
||||
|
||||
async deleteManyByCredential() {
|
||||
log.info(`Skipping deleteManyByCredential due to calendar-cache being disabled`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import prismock from "../../../tests/libs/__mocks__/prisma";
|
||||
|
||||
import { describe, expect, it, beforeEach, vi } from "vitest";
|
||||
|
||||
import type { Calendar } from "@calcom/types/Calendar";
|
||||
|
||||
import { CalendarCacheRepository } from "./calendar-cache.repository";
|
||||
|
||||
vi.mock("./lib/datesForCache", () => ({
|
||||
getTimeMin: vi.fn().mockImplementation((timeMin) => timeMin),
|
||||
getTimeMax: vi.fn().mockImplementation((timeMax) => timeMax),
|
||||
}));
|
||||
|
||||
describe("CalendarCacheRepository", () => {
|
||||
let mockCalendar: Calendar;
|
||||
|
||||
beforeEach(() => {
|
||||
// Clear the database before each test
|
||||
prismock.calendarCache.deleteMany();
|
||||
|
||||
// Setup mock calendar
|
||||
mockCalendar = {
|
||||
watchCalendar: vi.fn(),
|
||||
unwatchCalendar: vi.fn(),
|
||||
} as unknown as Calendar;
|
||||
});
|
||||
|
||||
// It needs to consider parseKeyForCache being called
|
||||
// eslint-disable-next-line playwright/no-skipped-test
|
||||
describe("getCachedAvailability", () => {
|
||||
it("should return cached availability data", async () => {
|
||||
const repository = new CalendarCacheRepository();
|
||||
const args = {
|
||||
timeMin: "2023-01-01T00:00:00Z",
|
||||
timeMax: "2023-01-02T00:00:00Z",
|
||||
items: [{ id: "calendar-1" }],
|
||||
};
|
||||
|
||||
const testData = {
|
||||
credentialId: 1,
|
||||
userId: 1,
|
||||
key: JSON.stringify({
|
||||
timeMin: args.timeMin,
|
||||
timeMax: args.timeMax,
|
||||
items: args.items,
|
||||
}),
|
||||
value: { busy: [] },
|
||||
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
||||
};
|
||||
|
||||
await prismock.calendarCache.create({ data: testData });
|
||||
|
||||
const result = await repository.getCachedAvailability({
|
||||
credentialId: 1,
|
||||
userId: 1,
|
||||
args,
|
||||
});
|
||||
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
key: testData.key,
|
||||
value: testData.value,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should return cached availability data even if credentialId is -1", async () => {
|
||||
const repository = new CalendarCacheRepository();
|
||||
const args = {
|
||||
timeMin: "2023-01-01T00:00:00Z",
|
||||
timeMax: "2023-01-02T00:00:00Z",
|
||||
items: [{ id: "calendar-1" }],
|
||||
};
|
||||
|
||||
const testData = {
|
||||
credentialId: -1,
|
||||
userId: 1,
|
||||
key: JSON.stringify({
|
||||
timeMin: args.timeMin,
|
||||
timeMax: args.timeMax,
|
||||
items: args.items,
|
||||
}),
|
||||
value: { busy: [] },
|
||||
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
||||
};
|
||||
|
||||
await prismock.calendarCache.create({ data: testData });
|
||||
|
||||
const resultWithWrongUserId = await repository.getCachedAvailability({
|
||||
credentialId: -1,
|
||||
userId: 2,
|
||||
args,
|
||||
});
|
||||
|
||||
expect(resultWithWrongUserId).toBeNull();
|
||||
const resultWithCorrectUserId = await repository.getCachedAvailability({
|
||||
credentialId: -1,
|
||||
userId: 1,
|
||||
args,
|
||||
});
|
||||
|
||||
expect(resultWithCorrectUserId).toEqual(
|
||||
expect.objectContaining({
|
||||
key: testData.key,
|
||||
value: testData.value,
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("upsertCachedAvailability(mocks min and max time fns)", () => {
|
||||
it("should create new cache entry when none exists", async () => {
|
||||
const repository = new CalendarCacheRepository();
|
||||
const args = {
|
||||
timeMin: "2023-01-01T00:00:00Z",
|
||||
timeMax: "2023-01-02T00:00:00Z",
|
||||
items: [{ id: "calendar-1" }],
|
||||
};
|
||||
const value = { busy: [] };
|
||||
|
||||
await repository.upsertCachedAvailability({
|
||||
credentialId: 1,
|
||||
userId: 1,
|
||||
args,
|
||||
value,
|
||||
});
|
||||
|
||||
const result = await prismock.calendarCache.findFirst({
|
||||
where: {
|
||||
credentialId: 1,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
credentialId: 1,
|
||||
value,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should update existing cache entry", async () => {
|
||||
const repository = new CalendarCacheRepository();
|
||||
const args = {
|
||||
timeMin: "2023-01-01T00:00:00Z",
|
||||
timeMax: "2023-01-02T00:00:00Z",
|
||||
items: [{ id: "calendar-1" }],
|
||||
};
|
||||
|
||||
const key = JSON.stringify({
|
||||
timeMin: args.timeMin,
|
||||
timeMax: args.timeMax,
|
||||
items: args.items,
|
||||
});
|
||||
|
||||
// Create initial cache entry
|
||||
const initialData = {
|
||||
credentialId: 1,
|
||||
key,
|
||||
value: { busy: [] },
|
||||
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
||||
};
|
||||
await prismock.calendarCache.create({ data: initialData });
|
||||
|
||||
// Update with new value
|
||||
const newValue = { busy: [{ start: "2023-01-01T10:00:00Z", end: "2023-01-01T11:00:00Z" }] };
|
||||
await repository.upsertCachedAvailability({
|
||||
credentialId: 1,
|
||||
userId: 1,
|
||||
args,
|
||||
value: newValue,
|
||||
});
|
||||
|
||||
const result = await prismock.calendarCache.findFirst({
|
||||
where: {
|
||||
credentialId: 1,
|
||||
key,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
credentialId: 1,
|
||||
key,
|
||||
value: newValue,
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
|
||||
import { uniqueBy } from "@calcom/lib/array";
|
||||
import { isInMemoryDelegationCredential } from "@calcom/lib/delegationCredential/clientAndServer";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import prisma from "@calcom/prisma";
|
||||
@@ -27,12 +28,33 @@ function parseKeyForCache(args: FreeBusyArgs): string {
|
||||
|
||||
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(
|
||||
@@ -44,6 +66,7 @@ export class CalendarCacheRepository implements ICalendarCacheRepository {
|
||||
}
|
||||
|
||||
async unwatchCalendar(args: { calendarId: string; eventTypeIds: SelectedCalendarEventTypeIds }) {
|
||||
assertCalendarHasDbCredential(this.calendar);
|
||||
const { calendarId, eventTypeIds } = args;
|
||||
if (typeof this.calendar?.unwatchCalendar !== "function") {
|
||||
log.info(
|
||||
@@ -55,25 +78,64 @@ export class CalendarCacheRepository implements ICalendarCacheRepository {
|
||||
return response;
|
||||
}
|
||||
|
||||
async getCachedAvailability(credentialId: number, args: FreeBusyArgs) {
|
||||
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);
|
||||
const cached = await prisma.calendarCache.findUnique({
|
||||
where: {
|
||||
credentialId_key: {
|
||||
credentialId,
|
||||
let cached;
|
||||
if (isInMemoryDelegationCredential({ credentialId })) {
|
||||
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()) },
|
||||
},
|
||||
expiresAt: { gte: new Date(Date.now()) },
|
||||
},
|
||||
});
|
||||
});
|
||||
} 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 }));
|
||||
return cached;
|
||||
}
|
||||
async upsertCachedAvailability(
|
||||
credentialId: number,
|
||||
args: FreeBusyArgs,
|
||||
value: Prisma.JsonNullValueInput | Prisma.InputJsonValue
|
||||
) {
|
||||
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: {
|
||||
@@ -89,6 +151,7 @@ export class CalendarCacheRepository implements ICalendarCacheRepository {
|
||||
create: {
|
||||
value,
|
||||
credentialId,
|
||||
userId,
|
||||
key,
|
||||
expiresAt: new Date(Date.now() + CACHING_TIME),
|
||||
},
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
|
||||
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
|
||||
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
|
||||
import { getCredentialForCalendarCache } from "@calcom/lib/delegationCredential/server";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
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> {
|
||||
const credential = await CredentialRepository.findCredentialForCalendarServiceById({
|
||||
id: credentialId,
|
||||
});
|
||||
const calendar = await getCalendar(credential);
|
||||
return await CalendarCache.init(calendar);
|
||||
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();
|
||||
|
||||
Reference in new issue
Block a user