* 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 <volnei.munhoz@gmail.com> * 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 <volnei.munhoz@gmail.com> * 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 <volnei.munhoz@gmail.com> * 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 <me@alexvanandel.com> * 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 <volnei.munhoz@gmail.com> * 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 <volnei.munhoz@gmail.com> * 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 <volnei.munhoz@gmail.com> * 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 <me@alexvanandel.com> Co-authored-by: Keith Williams <keithwillcode@gmail.com>
100 lines
3.3 KiB
TypeScript
100 lines
3.3 KiB
TypeScript
import type { CalendarSubscriptionEventItem } from "@calcom/features/calendar-subscription/lib/CalendarSubscriptionPort.interface";
|
|
import type { ICalendarCacheEventRepository } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventRepository.interface";
|
|
import logger from "@calcom/lib/logger";
|
|
import type { CalendarCacheEvent, SelectedCalendar } from "@calcom/prisma/client";
|
|
|
|
const log = logger.getSubLogger({ prefix: ["CalendarCacheEventService"] });
|
|
|
|
/**
|
|
* Service to handle calendar cache
|
|
*/
|
|
export class CalendarCacheEventService {
|
|
constructor(
|
|
private deps: {
|
|
calendarCacheEventRepository: ICalendarCacheEventRepository;
|
|
}
|
|
) {}
|
|
|
|
/**
|
|
* Handle calendar events from provider and update the cache
|
|
*
|
|
* @param selectedCalendar
|
|
* @param calendarSubscriptionEvents
|
|
*/
|
|
async handleEvents(
|
|
selectedCalendar: SelectedCalendar,
|
|
calendarSubscriptionEvents: CalendarSubscriptionEventItem[]
|
|
): Promise<void> {
|
|
log.debug("handleEvents", { count: calendarSubscriptionEvents.length });
|
|
const toUpsert: Partial<CalendarCacheEvent>[] = [];
|
|
const toDelete: Pick<CalendarCacheEvent, "externalId" | "selectedCalendarId">[] = [];
|
|
|
|
for (const event of calendarSubscriptionEvents) {
|
|
// not storing free or cancelled events
|
|
if (event.busy && event.status !== "cancelled") {
|
|
toUpsert.push({
|
|
externalId: event.id,
|
|
selectedCalendarId: selectedCalendar.id,
|
|
start: event.start,
|
|
end: event.end,
|
|
summary: event.summary,
|
|
description: event.description,
|
|
location: event.location,
|
|
isAllDay: event.isAllDay,
|
|
timeZone: event.timeZone,
|
|
originalStartTime: event.originalStartDate,
|
|
recurringEventId: event.recurringEventId,
|
|
externalEtag: event.etag || "",
|
|
externalCreatedAt: event.createdAt,
|
|
externalUpdatedAt: event.updatedAt,
|
|
});
|
|
} else {
|
|
toDelete.push({
|
|
selectedCalendarId: selectedCalendar.id,
|
|
externalId: event.id,
|
|
});
|
|
}
|
|
}
|
|
|
|
log.info("handleEvents: applying changes to the database", {
|
|
received: calendarSubscriptionEvents.length,
|
|
toUpsert: toUpsert.length,
|
|
toDelete: toDelete.length,
|
|
});
|
|
await Promise.all([
|
|
this.deps.calendarCacheEventRepository.deleteMany(toDelete),
|
|
this.deps.calendarCacheEventRepository.upsertMany(toUpsert),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Removes all events from the cache
|
|
*
|
|
* @param selectedCalendar calendar to cleanup
|
|
*/
|
|
async cleanupCache(selectedCalendar: SelectedCalendar): Promise<void> {
|
|
log.debug("cleanupCache", { selectedCalendarId: selectedCalendar.id });
|
|
await this.deps.calendarCacheEventRepository.deleteAllBySelectedCalendarId(selectedCalendar.id);
|
|
}
|
|
|
|
/**
|
|
* Removes stale events from the cache
|
|
*/
|
|
async cleanupStaleCache(): Promise<void> {
|
|
log.debug("cleanupStaleCache");
|
|
await this.deps.calendarCacheEventRepository.deleteStale();
|
|
}
|
|
|
|
/**
|
|
* Checks if the app is supported
|
|
*
|
|
* @param type
|
|
* @returns
|
|
*/
|
|
static isCalendarTypeSupported(type: string | null): boolean {
|
|
if (!type) return false;
|
|
// return ["google_calendar", "office365_calendar"].includes(type);
|
|
return ["google_calendar"].includes(type);
|
|
}
|
|
}
|