Files
cal.diy/packages/features/calendar-subscription/lib/cache/CalendarCacheWrapper.ts
T
4571215794 feat(calendar-subscription): add telemetry metrics for cache performance and webhook calls (#26501)
* feat(calendar-subscription): add telemetry metrics for cache performance and webhook calls

- Add Sentry span telemetry to CalendarCacheWrapper.getAvailability() and getAvailabilityWithTimeZones() to measure:
  - Cache fetch duration (cacheFetchDurationMs)
  - Original calendar fetch duration (originalFetchDurationMs)
  - Number of calendars from cache vs original source
  - Number of events from each source
  - Whether cache was used (cacheUsed)

- Add Sentry span telemetry to CalendarSubscriptionService.processWebhook() to track:
  - Provider (google_calendar, office365_calendar)
  - Success/failure status
  - Processing duration (durationMs)
  - Error messages on failure
  - Channel ID and selected calendar ID

- Create telemetry module with types, sentry-span, and no-op-span implementations

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* refactor(calendar-subscription): move telemetry to @calcom/lib for reusability

- Add withSpan helper to @calcom/lib/sentryWrapper for reusable telemetry
- Update CalendarCacheWrapper to use withSpan from @calcom/lib
- Update CalendarTelemetryWrapper to use withSpan from @calcom/lib
- Update CalendarSubscriptionService to use withSpan from @calcom/lib
- Remove old telemetry module from calendar-subscription feature
- Add telemetry tracking when cache is disabled for performance comparison

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* fix(calendar-subscription): only apply telemetry wrapper when Sentry is configured

- Fix unit test failures by checking if Sentry is configured before wrapping
- Remove ESLint inline rules from getCalendar.ts

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* refactor(calendar-subscription): move CalendarTelemetryWrapper to telemetry directory

- Move CalendarTelemetryWrapper from cache/ to telemetry/ directory
- Update import path in getCalendar.ts

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* feat(telemetry): add console fallback when Sentry is not configured

- Add console logging fallback in development mode when Sentry is not configured
- Create isTelemetryEnabled() helper to check if telemetry should be enabled
- Update getCalendar.ts to use isTelemetryEnabled() helper
- Logs span name, operation, duration, and attributes to console via @calcom/lib/logger

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* refactor(calendar-subscription): wrap all calendars with CalendarTelemetryWrapper

- CalendarTelemetryWrapper now wraps ALL cache-supported calendars with cacheEnabled parameter
- CalendarCacheWrapper keeps cache-specific metrics with distinct op (calendar.cache.internal.*)
- CalendarTelemetryWrapper uses canonical op (calendar.getAvailability) for consistent querying
- Nested spans: outer telemetry wrapper measures end-to-end, inner cache wrapper measures cache internals

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-01-07 11:27:40 +00:00

263 lines
9.7 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,
IntegrationCalendar,
NewCalendarEventType,
SelectedCalendarEventTypeIds,
} 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.
*
* @param dateFrom - Start date (ISO string)
* @param dateTo - End date (ISO string)
* @param selectedCalendars - List of calendars to retrieve availability from
* @returns Combined array of busy date ranges
*/
async getAvailability(
dateFrom: string,
dateTo: string,
selectedCalendars: IntegrationCalendar[]
): Promise<EventBusyDate[]> {
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);
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, withoutSync);
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.
*
* @param dateFrom - Start date (ISO string)
* @param dateTo - End date (ISO string)
* @param selectedCalendars - List of calendars to retrieve availability from
* @returns Combined array of time-zone-aware availability ranges
*/
async getAvailabilityWithTimeZones(
dateFrom: string,
dateTo: string,
selectedCalendars: IntegrationCalendar[]
): Promise<{ start: Date | string; end: Date | string; timeZone: string }[]> {
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: { start: Date | string; end: Date | string; timeZone: string }[] = [];
// 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,
withoutSync
);
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);
}
watchCalendar?(options: {
calendarId: string;
eventTypeIds: SelectedCalendarEventTypeIds;
}): Promise<unknown> {
return this.deps.originalCalendar.watchCalendar?.(options) || Promise.resolve();
}
unwatchCalendar?(options: {
calendarId: string;
eventTypeIds: SelectedCalendarEventTypeIds;
}): Promise<void> {
return this.deps.originalCalendar.unwatchCalendar?.(options) || Promise.resolve();
}
}