* refactor: replace shouldServeCache with mode parameter for calendar cache control Replace the boolean shouldServeCache parameter with a new CalendarFetchMode type that can have values 'slots', 'overlay', and 'booking'. This provides better control over when to serve cache vs relay on calendar providers. - 'slots' mode: Check feature flags and use cache when available (for getting actual calendar availability) - 'overlay' mode: Don't use cache (for overlay calendar availability) - 'booking' mode: Don't use cache (for booking confirmation) - undefined: Same as 'slots' for backwards compatibility The cache decision logic is now centralized in getCalendar.ts based on the mode parameter. Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * fix: update CalendarService.test.ts to use mode parameter Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * refactor: use shared GetAvailabilityParams type across all calendar services - Import GetAvailabilityParams and GetAvailabilityWithTimeZonesParams from @calcom/types/Calendar - Replace inline type definitions with shared types in all calendar service implementations - Update BaseCalendarService, CalendarCacheWrapper, and CalendarTelemetryWrapper - Ensures consistent typing and follows DRY principles Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * fix: add missing IntegrationCalendar import and update mock getAvailability signature - Add IntegrationCalendar back to sendgrid CalendarService imports - Update bookingScenario mock getAvailability to use typed params object - Add listCalendars method to mock Calendar object Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * fix: update test files to use typed params object for getAvailability methods - Update CalendarCacheWrapper.test.ts to call getAvailability/getAvailabilityWithTimeZones with params object - Update getCalendarsEvents.test.ts toHaveBeenCalledWith assertions to expect params object - All 32 tests now pass Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * refactor: consolidate to single GetAvailabilityParams type for both getAvailability methods - Remove GetAvailabilityWithTimeZonesParams, use GetAvailabilityParams for both methods - Add mode parameter to getAvailabilityWithTimeZones calls - Update wrapper classes to pass mode through to underlying calendar - Update test files to include mode in getAvailabilityWithTimeZones calls and assertions Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * refactor: use EventBusyDate with optional timeZone for getAvailabilityWithTimeZones - Add optional timeZone field to EventBusyDate type - Update getAvailabilityWithTimeZones return type to use EventBusyDate[] - Update Google Calendar service and wrapper classes to use the new type Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * fix: type errors and remove unused calendar watching methods - Fix type errors in CalendarCacheWrapper.ts (convert null to undefined for timeZone) - Fix type errors in getCalendarsEvents.ts (ensure timeZone is always present) - Remove unused watchCalendar/unwatchCalendar from Calendar interface - Remove unused startWatchingCalendarsInGoogle/stopWatchingCalendarsInGoogle from GoogleCalendarService - Remove unused imports (uuid, uniqueBy, GOOGLE_WEBHOOK_URL, ONE_MONTH_IN_MS) Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * fix: remove watchCalendar/unwatchCalendar from CalendarTelemetryWrapper Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * refactor: remove verbose JSDoc param comments from wrapper classes Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * refactor: make mode parameter required in getCalendar Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * fix: add required mode parameter to all getCalendar callers Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * fix: provide default mode value in getBusyCalendarTimes Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * fix: add mode parameter to remaining getCalendar callers Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * fix: add mode parameter to vital and wipemycalother reschedule Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * fix: add mode parameter to credential-sync API endpoint Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * refactor: add 'none' mode to CalendarFetchMode and use as default Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * test: add mode parameter to getCalendarsEvents test calls Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com> * Update packages/app-store/delegationCredential.ts Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
246 lines
9.1 KiB
TypeScript
246 lines
9.1 KiB
TypeScript
import type { ICalendarCacheEventRepository } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventRepository.interface";
|
|
import logger from "@calcom/lib/logger";
|
|
import { withSpan } from "@calcom/lib/sentryWrapper";
|
|
import type {
|
|
Calendar,
|
|
CalendarEvent,
|
|
CalendarServiceEvent,
|
|
EventBusyDate,
|
|
GetAvailabilityParams,
|
|
IntegrationCalendar,
|
|
NewCalendarEventType,
|
|
} from "@calcom/types/Calendar";
|
|
|
|
const log = logger.getSubLogger({ prefix: ["CachedCalendarWrapper"] });
|
|
|
|
/**
|
|
* A wrapper to load cache from database and cache it.
|
|
*
|
|
* @see Calendar
|
|
*/
|
|
export class CalendarCacheWrapper implements Calendar {
|
|
constructor(
|
|
private deps: {
|
|
originalCalendar: Calendar;
|
|
calendarCacheEventRepository: ICalendarCacheEventRepository;
|
|
}
|
|
) {}
|
|
|
|
getCredentialId?(): number {
|
|
return this.deps.originalCalendar.getCredentialId ? this.deps.originalCalendar.getCredentialId() : -1;
|
|
}
|
|
|
|
createEvent(
|
|
event: CalendarServiceEvent,
|
|
credentialId: number,
|
|
externalCalendarId?: string
|
|
): Promise<NewCalendarEventType> {
|
|
return this.deps.originalCalendar.createEvent(event, credentialId, externalCalendarId);
|
|
}
|
|
|
|
updateEvent(
|
|
uid: string,
|
|
event: CalendarServiceEvent,
|
|
externalCalendarId?: string | null
|
|
): Promise<NewCalendarEventType | NewCalendarEventType[]> {
|
|
return this.deps.originalCalendar.updateEvent(uid, event, externalCalendarId);
|
|
}
|
|
|
|
deleteEvent(uid: string, event: CalendarEvent, externalCalendarId?: string | null): Promise<unknown> {
|
|
return this.deps.originalCalendar.deleteEvent(uid, event, externalCalendarId);
|
|
}
|
|
|
|
/**
|
|
* Retrieves availability combining cache and live sources.
|
|
*
|
|
* - Calendars **with** both `syncToken` and `syncSubscribedAt` → fetched from cache.
|
|
* - Calendars **without** one of them → fetched directly from the original calendar.
|
|
* - Results are merged into a single array.
|
|
*/
|
|
async getAvailability(params: GetAvailabilityParams): Promise<EventBusyDate[]> {
|
|
const { dateFrom, dateTo, selectedCalendars } = params;
|
|
return withSpan(
|
|
{
|
|
name: "CalendarCacheWrapper.getAvailability",
|
|
op: "calendar.cache.internal.getAvailability",
|
|
attributes: {
|
|
calendarCount: selectedCalendars?.length ?? 0,
|
|
},
|
|
},
|
|
async (span) => {
|
|
log.debug("getAvailability (mixed cache + original)", {
|
|
dateFrom,
|
|
dateTo,
|
|
calendarIds: selectedCalendars.map((c) => c.id),
|
|
calendarCount: selectedCalendars.length,
|
|
});
|
|
|
|
if (!selectedCalendars?.length) return [];
|
|
|
|
const withSync = selectedCalendars.filter((c) => c.syncToken && c.syncSubscribedAt);
|
|
const withoutSync = selectedCalendars.filter((c) => !c.syncToken || !c.syncSubscribedAt);
|
|
|
|
const results: EventBusyDate[] = [];
|
|
|
|
// Fetch from cache for synced calendars
|
|
if (withSync.length) {
|
|
const cacheStartTime = performance.now();
|
|
const ids = withSync.map((c) => c.id).filter((id): id is string => Boolean(id));
|
|
const cached = await this.deps.calendarCacheEventRepository.findAllBySelectedCalendarIdsBetween(
|
|
ids,
|
|
new Date(dateFrom),
|
|
new Date(dateTo)
|
|
);
|
|
const cacheDurationMs = performance.now() - cacheStartTime;
|
|
results.push(
|
|
...cached.map((event) => ({
|
|
...event,
|
|
timeZone: event.timeZone ?? undefined,
|
|
}))
|
|
);
|
|
|
|
span.setAttribute("cachedCalendarCount", withSync.length);
|
|
span.setAttribute("cacheFetchDurationMs", cacheDurationMs);
|
|
span.setAttribute("cachedEventsCount", cached.length);
|
|
log.info("Calendar cache fetch completed", {
|
|
cachedCalendarCount: withSync.length,
|
|
cacheFetchDurationMs: cacheDurationMs,
|
|
cachedEventsCount: cached.length,
|
|
});
|
|
}
|
|
|
|
// Fetch from original calendar for unsynced ones
|
|
if (withoutSync.length) {
|
|
const originalStartTime = performance.now();
|
|
const original = await this.deps.originalCalendar.getAvailability({
|
|
dateFrom,
|
|
dateTo,
|
|
selectedCalendars: withoutSync,
|
|
mode: params.mode,
|
|
fallbackToPrimary: params.fallbackToPrimary,
|
|
});
|
|
const originalDurationMs = performance.now() - originalStartTime;
|
|
results.push(...original);
|
|
|
|
span.setAttribute("originalCalendarCount", withoutSync.length);
|
|
span.setAttribute("originalFetchDurationMs", originalDurationMs);
|
|
span.setAttribute("originalEventsCount", original.length);
|
|
log.info("Original calendar fetch completed", {
|
|
originalCalendarCount: withoutSync.length,
|
|
originalFetchDurationMs: originalDurationMs,
|
|
originalEventsCount: original.length,
|
|
});
|
|
}
|
|
|
|
span.setAttribute("cacheUsed", withSync.length > 0);
|
|
span.setAttribute("totalEventsCount", results.length);
|
|
|
|
return results;
|
|
}
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Retrieves availability with time zones, combining cache and live data.
|
|
*
|
|
* - Calendars **with** both `syncToken` and `syncSubscribedAt` → fetched from cache.
|
|
* - Calendars **without** one of them → fetched directly from the original calendar.
|
|
* - Results are merged into a single array with `{ start, end, timeZone }` format.
|
|
*/
|
|
async getAvailabilityWithTimeZones(params: GetAvailabilityParams): Promise<EventBusyDate[]> {
|
|
const { dateFrom, dateTo, selectedCalendars } = params;
|
|
return withSpan(
|
|
{
|
|
name: "CalendarCacheWrapper.getAvailabilityWithTimeZones",
|
|
op: "calendar.cache.internal.getAvailabilityWithTimeZones",
|
|
attributes: {
|
|
calendarCount: selectedCalendars?.length ?? 0,
|
|
},
|
|
},
|
|
async (span) => {
|
|
log.debug("getAvailabilityWithTimeZones (mixed cache + original)", {
|
|
dateFrom,
|
|
dateTo,
|
|
calendarIds: selectedCalendars.map((c) => c.id),
|
|
calendarCount: selectedCalendars.length,
|
|
});
|
|
|
|
if (!selectedCalendars?.length) return [];
|
|
|
|
const withSync = selectedCalendars.filter((c) => c.syncToken && c.syncSubscribedAt);
|
|
const withoutSync = selectedCalendars.filter((c) => !c.syncToken || !c.syncSubscribedAt);
|
|
|
|
const results: EventBusyDate[] = [];
|
|
|
|
// Fetch from cache for synced calendars
|
|
if (withSync.length) {
|
|
const cacheStartTime = performance.now();
|
|
const ids = withSync.map((c) => c.id).filter((id): id is string => Boolean(id));
|
|
const cached = await this.deps.calendarCacheEventRepository.findAllBySelectedCalendarIdsBetween(
|
|
ids,
|
|
new Date(dateFrom),
|
|
new Date(dateTo)
|
|
);
|
|
const cacheDurationMs = performance.now() - cacheStartTime;
|
|
results.push(
|
|
...cached.map(({ start, end, timeZone }) => ({
|
|
start,
|
|
end,
|
|
timeZone: timeZone || "UTC",
|
|
}))
|
|
);
|
|
|
|
span.setAttribute("cachedCalendarCount", withSync.length);
|
|
span.setAttribute("cacheFetchDurationMs", cacheDurationMs);
|
|
span.setAttribute("cachedEventsCount", cached.length);
|
|
log.info("Calendar cache fetch with timezones completed", {
|
|
cachedCalendarCount: withSync.length,
|
|
cacheFetchDurationMs: cacheDurationMs,
|
|
cachedEventsCount: cached.length,
|
|
});
|
|
}
|
|
|
|
// Fetch from original calendar for unsynced ones
|
|
if (withoutSync.length) {
|
|
const originalStartTime = performance.now();
|
|
const original = await this.deps.originalCalendar.getAvailabilityWithTimeZones?.({
|
|
dateFrom,
|
|
dateTo,
|
|
selectedCalendars: withoutSync,
|
|
mode: params.mode,
|
|
fallbackToPrimary: params.fallbackToPrimary,
|
|
});
|
|
const originalDurationMs = performance.now() - originalStartTime;
|
|
if (original?.length) results.push(...original);
|
|
|
|
span.setAttribute("originalCalendarCount", withoutSync.length);
|
|
span.setAttribute("originalFetchDurationMs", originalDurationMs);
|
|
span.setAttribute("originalEventsCount", original?.length ?? 0);
|
|
log.info("Original calendar fetch with timezones completed", {
|
|
originalCalendarCount: withoutSync.length,
|
|
originalFetchDurationMs: originalDurationMs,
|
|
originalEventsCount: original?.length ?? 0,
|
|
});
|
|
}
|
|
|
|
span.setAttribute("cacheUsed", withSync.length > 0);
|
|
span.setAttribute("totalEventsCount", results.length);
|
|
|
|
return results;
|
|
}
|
|
);
|
|
}
|
|
|
|
fetchAvailabilityAndSetCache?(selectedCalendars: IntegrationCalendar[]): Promise<unknown> {
|
|
return this.deps.originalCalendar.fetchAvailabilityAndSetCache?.(selectedCalendars) || Promise.resolve();
|
|
}
|
|
|
|
listCalendars(event?: CalendarEvent): Promise<IntegrationCalendar[]> {
|
|
return this.deps.originalCalendar.listCalendars(event);
|
|
}
|
|
|
|
testDelegationCredentialSetup?(): Promise<boolean> {
|
|
return this.deps.originalCalendar.testDelegationCredentialSetup?.() || Promise.resolve(false);
|
|
}
|
|
}
|