feat: Calendar Cache and Sync (#23876)

* feat: calendar cache and sync - wip

* Add env.example

* refactor on CalendarCacheEventService

* remove test console.log

* Fix type checks errors

* chore: remove pt comment

* add route.ts

* chore: fix tests

* Improve cache impl

* chore: update recurring event id

* chore: small improvements

* calendar cache improvements

* Fix remove dynamic imports

* Add cleanup stale cache

* Fix tests

* add event update

* type fixes

* feat: add comprehensive tests for new calendar subscription API routes

- Add tests for /api/cron/calendar-subscriptions-cleanup route (9 tests)
- Add tests for /api/cron/calendar-subscriptions route (10 tests)
- Add tests for /api/webhooks/calendar-subscription/[provider] route (11 tests)
- Add missing feature flags for calendar-subscription-cache and calendar-subscription-sync
- All 30 tests pass with comprehensive coverage of authentication, feature flags, error handling, and service instantiation

Tests cover:
- Authentication scenarios (API key validation, Bearer tokens, query parameters)
- Feature flag combinations (cache/sync enabled/disabled states)
- Success and error handling (including non-Error exceptions)
- Service instantiation with proper dependency injection
- Provider validation for webhook endpoints

Co-Authored-By: Volnei Munhoz <[email protected]>

* feat: add comprehensive tests for calendar subscription services, repositories, and adapters

- Add unit tests for CalendarSubscriptionService with subscription, webhook, and event processing
- Add unit tests for CalendarCacheEventService with cache operations and cleanup
- Add unit tests for CalendarSyncService with Cal.com event filtering and booking operations
- Add unit tests for CalendarCacheEventRepository with CRUD operations
- Add unit tests for SelectedCalendarRepository with calendar selection management
- Add unit tests for GoogleCalendarSubscriptionAdapter with subscription and event fetching
- Add unit tests for Office365CalendarSubscriptionAdapter with placeholder implementation
- Add unit tests for AdaptersFactory with provider management and adapter creation
- Fix lint issues by removing explicit 'any' type casting and unused variables
- All tests follow Cal.com conventions using Vitest framework with proper mocking

Co-Authored-By: Volnei Munhoz <[email protected]>

* fix: improve calendar-subscriptions-cleanup test performance by adding missing mocks

- Add comprehensive mocks for defaultResponderForAppDir, logger, performance monitoring, and Sentry
- Fix slow test execution (933ms -> <100ms) caused by missing dependency mocks
- Ensure consistent test performance across different environments

Co-Authored-By: Volnei Munhoz <[email protected]>

* Fix tests

* Fix tests

* type fix

* Fix coderabbit comments

* Fix types

* Fix test

* Update apps/web/app/api/cron/calendar-subscriptions/route.ts

Co-authored-by: Alex van Andel <[email protected]>

* Fixes by first review

* feat: add database migrations for calendar cache and sync fields

- Add CalendarCacheEventStatus enum with confirmed, tentative, cancelled values
- Add new fields to SelectedCalendar: channelId, channelKind, channelResourceId, channelResourceUri, channelExpiration, syncSubscribedAt, syncToken, syncedAt, syncErrorAt, syncErrorCount
- Create CalendarCacheEvent table with foreign key to SelectedCalendar
- Add necessary indexes and constraints for performance and data integrity

Fixes database schema issues causing e2e test failures with 'column does not exist' errors.

Co-Authored-By: Volnei Munhoz <[email protected]>

* only google-calendar for now

* docs: add Calendar Cache and Sync feature documentation

- Add comprehensive feature overview and motivation
- Document feature flags with SQL examples
- Include SQL examples for enabling features for users and teams
- Reference technical documentation files

Addresses PR #23876 documentation requirements

Co-Authored-By: Volnei Munhoz <[email protected]>

* docs: update calendar subscription README with comprehensive documentation

- Undo incorrect changes to main README.md
- Update packages/features/calendar-subscription/README.md with:
  - Feature overview and motivation
  - Environment variables section
  - Complete feature flags documentation with SQL examples
  - SQL examples for enabling features for users and teams
  - Detailed architecture documentation

Addresses PR #23876 documentation requirements

Co-Authored-By: Volnei Munhoz <[email protected]>

* fix docs

* Fix test to available calendars

* Fix test to available calendars

* add migration and sync boilerplate

* fix typo

* remove double log

* sync boilerplate

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Alex van Andel <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
This commit is contained in:
authored and GitHub committed 2025-09-29 14:26:14 +00:00
1 parent 855a02091f
commit e6b2116a2b
42 files changed
+4723 -42

No files matched your search

@@ -0,0 +1,62 @@
import type { Prisma, SelectedCalendar } from "@calcom/prisma/client";
export interface ISelectedCalendarRepository {
/**
* Find selected calendar by id with credentials
*
* @param id
*/
findByIdWithCredentials(id: string): Promise<SelectedCalendar | null>;
/**
* Find selected calendar by channel id
*
* @param channelId
*/
findByChannelId(channelId: string): Promise<SelectedCalendar | null>;
/**
* Find next batch of selected calendars
* Will check if syncSubscribedAt is null or channelExpiration is greater than current date
*
* @param take the number of calendars to take
* @param integrations the list of integrations
*/
findNextSubscriptionBatch({
take,
integrations,
}: {
take: number;
integrations?: string[];
}): Promise<SelectedCalendar[]>;
/**
* Update status of sync for selected calendar
*
* @param id
* @param data
*/
updateSyncStatus(
id: string,
data: Pick<
Prisma.SelectedCalendarUpdateInput,
"syncToken" | "syncedAt" | "syncErrorAt" | "syncErrorCount"
>
): Promise<SelectedCalendar>;
/**
* Update subscription status for selected calendar
*/
updateSubscription(
id: string,
data: Pick<
Prisma.SelectedCalendarUpdateInput,
| "channelId"
| "channelResourceId"
| "channelResourceUri"
| "channelKind"
| "channelExpiration"
| "syncSubscribedAt"
>
): Promise<SelectedCalendar>;
}
@@ -0,0 +1,83 @@
import type { ISelectedCalendarRepository } from "@calcom/lib/server/repository/SelectedCalendarRepository.interface";
import type { PrismaClient } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
export class SelectedCalendarRepository implements ISelectedCalendarRepository {
constructor(private prismaClient: PrismaClient) {}
async findByIdWithCredentials(id: string) {
return this.prismaClient.selectedCalendar.findUnique({
where: { id },
include: {
credential: {
select: {
delegationCredential: true,
},
},
},
});
}
async findByChannelId(channelId: string) {
return this.prismaClient.selectedCalendar.findFirst({ where: { channelId } });
}
async findNextSubscriptionBatch({ take, integrations }: { take: number; integrations: string[] }) {
return this.prismaClient.selectedCalendar.findMany({
where: {
integration: { in: integrations },
OR: [{ syncSubscribedAt: null }, { channelExpiration: { lte: new Date() } }],
// initially we will run subscription only for teams that have
// the feature flags enabled and it should be removed later
user: {
teams: {
some: {
team: {
features: {
some: {
OR: [
{ featureId: "calendar-subscription-cache" },
{ featureId: "calendar-subscription-sync" },
],
},
},
},
},
},
},
},
take,
});
}
async updateSyncStatus(
id: string,
data: Pick<
Prisma.SelectedCalendarUpdateInput,
"syncToken" | "syncedAt" | "syncErrorAt" | "syncErrorCount"
>
) {
return this.prismaClient.selectedCalendar.update({
where: { id },
data,
});
}
async updateSubscription(
id: string,
data: Pick<
Prisma.SelectedCalendarUpdateInput,
| "channelId"
| "channelResourceId"
| "channelResourceUri"
| "channelKind"
| "channelExpiration"
| "syncSubscribedAt"
>
) {
return this.prismaClient.selectedCalendar.update({
where: { id },
data,
});
}
}
@@ -0,0 +1,315 @@
import { describe, test, expect, vi, beforeEach } from "vitest";
import type { PrismaClient } from "@calcom/prisma";
import type { Prisma, SelectedCalendar } from "@calcom/prisma/client";
import { SelectedCalendarRepository } from "../SelectedCalendarRepository";
const mockPrismaClient = {
selectedCalendar: {
findUnique: vi.fn(),
findFirst: vi.fn(),
findMany: vi.fn(),
update: vi.fn(),
},
} as unknown as PrismaClient;
const mockSelectedCalendar: SelectedCalendar = {
id: "test-calendar-id",
userId: 1,
credentialId: 1,
integration: "google_calendar",
externalId: "[email protected]",
eventTypeId: null,
delegationCredentialId: null,
domainWideDelegationCredentialId: null,
googleChannelId: null,
googleChannelKind: null,
googleChannelResourceId: null,
googleChannelResourceUri: null,
googleChannelExpiration: null,
error: null,
lastErrorAt: null,
watchAttempts: 0,
maxAttempts: 3,
unwatchAttempts: 0,
createdAt: new Date(),
updatedAt: new Date(),
channelId: "test-channel-id",
channelKind: "web_hook",
channelResourceId: "test-resource-id",
channelResourceUri: "test-resource-uri",
channelExpiration: new Date(Date.now() + 86400000),
syncSubscribedAt: new Date(),
syncToken: "test-sync-token",
syncedAt: new Date(),
syncErrorAt: null,
syncErrorCount: 0,
};
describe("SelectedCalendarRepository", () => {
let repository: SelectedCalendarRepository;
beforeEach(() => {
repository = new SelectedCalendarRepository(mockPrismaClient);
vi.clearAllMocks();
});
describe("findByIdWithCredentials", () => {
test("should find selected calendar by id with credential delegation", async () => {
const mockCalendarWithCredential = {
...mockSelectedCalendar,
credential: {
delegationCredential: {
id: "delegation-id",
key: { client_email: "[email protected]" },
},
},
};
vi.mocked(mockPrismaClient.selectedCalendar.findUnique).mockResolvedValue(mockCalendarWithCredential);
const result = await repository.findByIdWithCredentials("test-calendar-id");
expect(mockPrismaClient.selectedCalendar.findUnique).toHaveBeenCalledWith({
where: { id: "test-calendar-id" },
include: {
credential: {
select: {
delegationCredential: true,
},
},
},
});
expect(result).toEqual(mockCalendarWithCredential);
});
test("should return null when calendar not found", async () => {
vi.mocked(mockPrismaClient.selectedCalendar.findUnique).mockResolvedValue(null);
const result = await repository.findByIdWithCredentials("non-existent-id");
expect(result).toBeNull();
});
});
describe("findByChannelId", () => {
test("should find selected calendar by channel id", async () => {
vi.mocked(mockPrismaClient.selectedCalendar.findFirst).mockResolvedValue(mockSelectedCalendar);
const result = await repository.findByChannelId("test-channel-id");
expect(mockPrismaClient.selectedCalendar.findFirst).toHaveBeenCalledWith({
where: { channelId: "test-channel-id" },
});
expect(result).toEqual(mockSelectedCalendar);
});
test("should return null when calendar not found", async () => {
vi.mocked(mockPrismaClient.selectedCalendar.findFirst).mockResolvedValue(null);
const result = await repository.findByChannelId("non-existent-channel-id");
expect(result).toBeNull();
});
});
describe("findNextSubscriptionBatch", () => {
test("should find next batch of calendars for subscription", async () => {
const mockCalendars = [mockSelectedCalendar];
vi.mocked(mockPrismaClient.selectedCalendar.findMany).mockResolvedValue(mockCalendars);
const result = await repository.findNextSubscriptionBatch({
take: 10,
integrations: ["google_calendar", "office365_calendar"],
});
expect(mockPrismaClient.selectedCalendar.findMany).toHaveBeenCalledWith({
where: {
integration: { in: ["google_calendar", "office365_calendar"] },
OR: [{ syncSubscribedAt: null }, { channelExpiration: { lte: expect.any(Date) } }],
user: {
teams: {
some: {
team: {
features: {
some: {
OR: [
{ featureId: "calendar-subscription-cache" },
{ featureId: "calendar-subscription-sync" },
],
},
},
},
},
},
},
},
take: 10,
});
expect(result).toEqual(mockCalendars);
});
test("should handle empty integrations array", async () => {
const mockCalendars = [mockSelectedCalendar];
vi.mocked(mockPrismaClient.selectedCalendar.findMany).mockResolvedValue(mockCalendars);
const result = await repository.findNextSubscriptionBatch({
take: 5,
integrations: [],
});
expect(mockPrismaClient.selectedCalendar.findMany).toHaveBeenCalledWith({
where: {
integration: { in: [] },
OR: [{ syncSubscribedAt: null }, { channelExpiration: { lte: expect.any(Date) } }],
user: {
teams: {
some: {
team: {
features: {
some: {
OR: [
{ featureId: "calendar-subscription-cache" },
{ featureId: "calendar-subscription-sync" },
],
},
},
},
},
},
},
},
take: 5,
});
expect(result).toEqual(mockCalendars);
});
});
describe("updateSyncStatus", () => {
test("should update sync status", async () => {
const updateData: Pick<
Prisma.SelectedCalendarUpdateInput,
"syncToken" | "syncedAt" | "syncErrorAt" | "syncErrorCount"
> = {
syncToken: "new-sync-token",
syncedAt: new Date(),
syncErrorAt: null,
syncErrorCount: 0,
};
const updatedCalendar = {
...mockSelectedCalendar,
...updateData,
};
vi.mocked(mockPrismaClient.selectedCalendar.update).mockResolvedValue(updatedCalendar);
const result = await repository.updateSyncStatus("test-calendar-id", updateData);
expect(mockPrismaClient.selectedCalendar.update).toHaveBeenCalledWith({
where: { id: "test-calendar-id" },
data: updateData,
});
expect(result).toEqual(updatedCalendar);
});
test("should update sync error status", async () => {
const updateData: Pick<
Prisma.SelectedCalendarUpdateInput,
"syncToken" | "syncedAt" | "syncErrorAt" | "syncErrorCount"
> = {
syncErrorAt: new Date(),
syncErrorCount: 1,
};
const updatedCalendar = {
...mockSelectedCalendar,
...updateData,
};
vi.mocked(mockPrismaClient.selectedCalendar.update).mockResolvedValue(updatedCalendar);
const result = await repository.updateSyncStatus("test-calendar-id", updateData);
expect(mockPrismaClient.selectedCalendar.update).toHaveBeenCalledWith({
where: { id: "test-calendar-id" },
data: updateData,
});
expect(result).toEqual(updatedCalendar);
});
});
describe("updateSubscription", () => {
test("should update subscription status", async () => {
const updateData: Pick<
Prisma.SelectedCalendarUpdateInput,
| "channelId"
| "channelResourceId"
| "channelResourceUri"
| "channelKind"
| "channelExpiration"
| "syncSubscribedAt"
> = {
channelId: "new-channel-id",
channelResourceId: "new-resource-id",
channelResourceUri: "new-resource-uri",
channelKind: "web_hook",
channelExpiration: new Date(Date.now() + 86400000),
syncSubscribedAt: new Date(),
};
const updatedCalendar = {
...mockSelectedCalendar,
...updateData,
};
vi.mocked(mockPrismaClient.selectedCalendar.update).mockResolvedValue(updatedCalendar);
const result = await repository.updateSubscription("test-calendar-id", updateData);
expect(mockPrismaClient.selectedCalendar.update).toHaveBeenCalledWith({
where: { id: "test-calendar-id" },
data: updateData,
});
expect(result).toEqual(updatedCalendar);
});
test("should unsubscribe by setting syncSubscribedAt to null", async () => {
const updateData: Pick<
Prisma.SelectedCalendarUpdateInput,
| "channelId"
| "channelResourceId"
| "channelResourceUri"
| "channelKind"
| "channelExpiration"
| "syncSubscribedAt"
> = {
syncSubscribedAt: null,
};
const updatedCalendar = {
...mockSelectedCalendar,
syncSubscribedAt: null,
};
vi.mocked(mockPrismaClient.selectedCalendar.update).mockResolvedValue(updatedCalendar);
const result = await repository.updateSubscription("test-calendar-id", updateData);
expect(mockPrismaClient.selectedCalendar.update).toHaveBeenCalledWith({
where: { id: "test-calendar-id" },
data: updateData,
});
expect(result).toEqual(updatedCalendar);
});
});
});
+11 -8
View File
@@ -387,6 +387,17 @@ export class BookingRepository {
});
}
async findBookingByUidWithEventType({ bookingUid }: { bookingUid: string }) {
return await this.prismaClient.booking.findUnique({
where: {
uid: bookingUid,
},
include: {
eventType: true,
},
});
}
async findByIdIncludeUserAndAttendees(bookingId: number) {
return await this.prismaClient.booking.findUnique({
where: {
@@ -725,13 +736,9 @@ export class BookingRepository {
},
},
},
// eslint-disable-next-line @calcom/eslint/no-prisma-include-true
destinationCalendar: true,
// eslint-disable-next-line @calcom/eslint/no-prisma-include-true
payment: true,
// eslint-disable-next-line @calcom/eslint/no-prisma-include-true
references: true,
// eslint-disable-next-line @calcom/eslint/no-prisma-include-true
workflowReminders: true,
},
});
@@ -873,13 +880,9 @@ export class BookingRepository {
status: filterForUnconfirmed ? BookingStatus.PENDING : BookingStatus.ACCEPTED,
},
include: {
// eslint-disable-next-line @calcom/eslint/no-prisma-include-true
attendees: true,
// eslint-disable-next-line @calcom/eslint/no-prisma-include-true
references: true,
// eslint-disable-next-line @calcom/eslint/no-prisma-include-true
user: true,
// eslint-disable-next-line @calcom/eslint/no-prisma-include-true
payment: true,
},
});