perf: (googlecalendar): batch freebusy calls by delegation credential (#24332)
* perf(googlecalendar): batch freebusy calls by delegation credential - Group selectedCalendars by delegationCredentialId before making API calls - Make one batched freebusy query per delegation credential group - Reduces total API calls while respecting credential boundaries - Maintains existing caching behavior per group - Updated both getAvailability and getAvailabilityWithTimeZones methods - Added groupCalendarsByDelegationCredential helper method - Handles edge case when no calendars provided but fallbackToPrimary is true - Fixed linting issue: replaced hasOwnProperty with 'in' operator Co-Authored-By: Volnei Munhoz <[email protected]> * test(googlecalendar): add test for delegation credential batching - Verify calendars are grouped by delegationCredentialId - Ensure exactly 3 API calls made for 3 delegation credential groups - Confirm all busy times from different groups are properly returned - Fix type-safety issues by replacing 'as any' with proper type constraints - Fix ESLint warnings: unused variables and any types in mock functions Co-Authored-By: Volnei Munhoz <[email protected]> * fix(googlecalendar): ensure fallback logic works with empty calendar groups - Handle empty calendar groups by ensuring at least one iteration - Add test for chunking groups larger than 50 calendars - Verify all delegation credential batching logic works correctly Co-Authored-By: Volnei Munhoz <[email protected]> * fix: fix remaining type errors from merge conflict resolution - Changed getCacheOrFetchAvailability to getFreeBusyData in getAvailabilityWithTimeZones - Removed orphaned merge conflict marker in test file Co-Authored-By: Volnei Munhoz <[email protected]> * fix: reset test file to original PR version and update method name - Reset CalendarService.test.ts to original PR version (0e9eb9e97a) - Updated getCacheOrFetchAvailability to getFreeBusyData to match main branch Co-Authored-By: Volnei Munhoz <[email protected]> * fix: reset test file to main branch version The original PR's test file had tests for caching features that have been removed from main. Reset to main's version to fix type errors. Co-Authored-By: Volnei Munhoz <[email protected]> * test(googlecalendar): add tests for delegation credential batching logic Co-Authored-By: Volnei Munhoz <[email protected]> * Revamp devin's implementation * Remove comsoles.log * fix(tests): update delegation credential batching tests to match reimplementation - Remove tests for private methods that no longer exist (groupCalendarsByDelegationCredential, chunkArray) - Update getAvailability test to verify calendar fetching without expecting multiple API calls per delegation credential - Keep existing tests for fallback to primary calendar and non-google calendar handling Co-Authored-By: Volnei Munhoz <[email protected]> * Remove dead code * improve documentation * docs: add README explaining Google Calendar availability batching feature Co-Authored-By: Volnei Munhoz <[email protected]> * docs: translate README to English Co-Authored-By: Volnei Munhoz <[email protected]> * docs: move README to calendar-batch package with comprehensive documentation - Remove README from googlecalendar lib (wrong location) - Add comprehensive README to packages/features/calendar-batch/ - Document CalendarBatchService and CalendarBatchWrapper - Explain how getCalendar() integrates with batching - Include architecture, data model, and performance considerations Co-Authored-By: Volnei Munhoz <[email protected]> * fix: address cubic-dev-ai review comments - Remove misleading comment from getCalendar.ts cache block - Fix typo 'optmization' -> 'optimization' in comment - Add comprehensive tests for CalendarBatchWrapper batching behavior - Test separate calls for calendars without delegationCredentialId - Test batching calendars with same delegationCredentialId - Test chunking into groups of 50 for API limits - Test mixed calendars handling - Test fallbackToPrimary with empty array - Test result flattening from batched calls - Test pass-through methods delegation Co-Authored-By: Volnei Munhoz <[email protected]> * fix: add shouldServeCache param to CalendarBatchWrapper and verify batching call count - Fix CalendarBatchWrapper.getAvailability signature to match Calendar interface (add shouldServeCache param) - Update CalendarBatchWrapper tests to pass shouldServeCache parameter - Add integration test in CalendarService.test.ts that verifies CalendarBatchWrapper makes separate API calls for different delegationCredentialIds (call count assertion) - This fixes the getCalendarsEvents test failures caused by signature mismatch Co-Authored-By: Volnei Munhoz <[email protected]> * Improve CalendarBatchImplementation * test: add shouldServeCache forwarding and order-independent batching verification tests Co-Authored-By: Volnei Munhoz <[email protected]> * test: make CalendarBatchWrapper tests order-independent Refactored tests to avoid relying on Promise.all execution order: - 'should make separate calls for calendars without delegationCredentialId' now uses set comparison instead of toHaveBeenNthCalledWith - 'should batch calendars with the same delegationCredentialId together' now finds calls by delegation credential instead of call order This addresses Sean's review comment about potential flakiness due to Promise.all not guaranteeing execution order of parallel promises. Co-Authored-By: Volnei Munhoz <[email protected]> * Remove hardcoded ID * test: add comprehensive tests for resolveCalendarServeStrategy Co-Authored-By: [email protected] <[email protected]> * feat: use Promise.allSettled for partial failure handling in CalendarBatchWrapper - Changed Promise.all to Promise.allSettled in getAvailability and getAvailabilityWithTimeZones - Returns partial results when some batches fail instead of failing entirely - Logs warnings for failed batches with error details - Added tests for partial failure scenarios Co-Authored-By: [email protected] <[email protected]> * test: add comprehensive tests for getAvailabilityWithTimeZones - Added batching behavior tests (separate calls, batching by delegationCredentialId, chunking) - Added partial failure handling tests (partial results, all fail, no throw) - Added edge case test for underlying calendar not implementing the method - Total: 24 tests now covering both getAvailability and getAvailabilityWithTimeZones Co-Authored-By: [email protected] <[email protected]> * fix: add required serviceAccountKey fields to delegatedTo mock objects Co-Authored-By: [email protected] <[email protected]> * fix: add missing client_id and private_key to serviceAccountKey mock Co-Authored-By: [email protected] <[email protected]> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: [email protected] <[email protected]>
This commit is contained in:
8 files changed
+1699
-87
No files matched your search
@@ -0,0 +1,408 @@
|
||||
import { describe, test, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
import type { Calendar } from "@calcom/types/Calendar";
|
||||
import type { CredentialForCalendarService } from "@calcom/types/Credential";
|
||||
|
||||
// Type for test results that may include wrapper markers
|
||||
interface TestCalendarResult extends Calendar {
|
||||
__isCacheWrapper?: boolean;
|
||||
__isBatchWrapper?: boolean;
|
||||
}
|
||||
|
||||
// Type for mock delegation credential - matches CredentialForCalendarService.delegatedTo
|
||||
interface MockDelegationCredential {
|
||||
id?: string;
|
||||
serviceAccountKey: {
|
||||
client_email?: string;
|
||||
tenant_id?: string;
|
||||
client_id: string;
|
||||
private_key: string;
|
||||
};
|
||||
}
|
||||
|
||||
// Type for mock features repository
|
||||
interface MockFeaturesRepository {
|
||||
checkIfFeatureIsEnabledGlobally: ReturnType<typeof vi.fn>;
|
||||
checkIfUserHasFeatureNonHierarchical: ReturnType<typeof vi.fn>;
|
||||
}
|
||||
|
||||
// Mock the dependencies before importing the module under test
|
||||
vi.mock("@calcom/prisma", () => ({
|
||||
prisma: {},
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/flags/features.repository", () => ({
|
||||
FeaturesRepository: vi.fn().mockImplementation(() => ({
|
||||
checkIfFeatureIsEnabledGlobally: vi.fn().mockResolvedValue(false),
|
||||
checkIfUserHasFeatureNonHierarchical: vi.fn().mockResolvedValue(false),
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/calendar-subscription/lib/CalendarSubscriptionService", () => ({
|
||||
CalendarSubscriptionService: {
|
||||
CALENDAR_SUBSCRIPTION_CACHE_FEATURE: "calendar-subscription-cache",
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventRepository", () => ({
|
||||
CalendarCacheEventRepository: vi.fn().mockImplementation(() => ({})),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventService", () => ({
|
||||
CalendarCacheEventService: {
|
||||
isCalendarTypeSupported: vi.fn().mockReturnValue(false),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/calendar-subscription/lib/cache/CalendarCacheWrapper", () => ({
|
||||
CalendarCacheWrapper: vi.fn().mockImplementation(({ originalCalendar }) => ({
|
||||
...originalCalendar,
|
||||
__isCacheWrapper: true,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/calendar-batch/lib/CalendarBatchService", () => ({
|
||||
CalendarBatchService: {
|
||||
isSupported: vi.fn().mockReturnValue(false),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/features/calendar-batch/lib/CalendarBatchWrapper", () => ({
|
||||
CalendarBatchWrapper: vi.fn().mockImplementation(({ originalCalendar }) => ({
|
||||
...originalCalendar,
|
||||
__isBatchWrapper: true,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/logger", () => ({
|
||||
default: {
|
||||
getSubLogger: () => ({
|
||||
warn: vi.fn(),
|
||||
info: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock the CalendarServiceMap
|
||||
vi.mock("../../calendar.services.generated", () => ({
|
||||
CalendarServiceMap: {
|
||||
googlecalendar: Promise.resolve({
|
||||
default: vi.fn().mockImplementation(() => createMockCalendar()),
|
||||
}),
|
||||
office365calendar: Promise.resolve({
|
||||
default: vi.fn().mockImplementation(() => createMockCalendar()),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
// Import after mocks are set up
|
||||
import { CalendarCacheEventService } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventService";
|
||||
import { CalendarBatchService } from "@calcom/features/calendar-batch/lib/CalendarBatchService";
|
||||
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
|
||||
import { CalendarCacheWrapper } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheWrapper";
|
||||
import { CalendarBatchWrapper } from "@calcom/features/calendar-batch/lib/CalendarBatchWrapper";
|
||||
|
||||
import { getCalendar } from "../getCalendar";
|
||||
|
||||
function createMockCalendar(): Calendar {
|
||||
return {
|
||||
getAvailability: vi.fn().mockResolvedValue([]),
|
||||
createEvent: vi.fn(),
|
||||
updateEvent: vi.fn(),
|
||||
deleteEvent: vi.fn(),
|
||||
listCalendars: vi.fn().mockResolvedValue([]),
|
||||
} as unknown as Calendar;
|
||||
}
|
||||
|
||||
function createMockCredential(
|
||||
overrides: Partial<CredentialForCalendarService> & { delegatedTo?: MockDelegationCredential | null } = {}
|
||||
): CredentialForCalendarService {
|
||||
return {
|
||||
id: 1,
|
||||
type: "google_calendar",
|
||||
key: { access_token: "test-token" },
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
appId: "google-calendar",
|
||||
invalid: false,
|
||||
delegatedTo: null,
|
||||
...overrides,
|
||||
} as CredentialForCalendarService;
|
||||
}
|
||||
|
||||
describe("getCalendar", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("resolveCalendarServeStrategy", () => {
|
||||
test("should return CalendarCacheWrapper when cache is supported and enabled", async () => {
|
||||
const mockCredential = createMockCredential({ type: "google_calendar" });
|
||||
|
||||
// Enable cache support
|
||||
vi.mocked(CalendarCacheEventService.isCalendarTypeSupported).mockReturnValue(true);
|
||||
vi.mocked(CalendarBatchService.isSupported).mockReturnValue(false);
|
||||
|
||||
const result = (await getCalendar(mockCredential, true)) as TestCalendarResult;
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result.__isCacheWrapper).toBe(true);
|
||||
expect(CalendarCacheWrapper).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should return CalendarBatchWrapper when cache is not supported but batch is supported", async () => {
|
||||
const mockCredential = createMockCredential({
|
||||
type: "google_calendar",
|
||||
delegatedTo: {
|
||||
id: "delegation-1",
|
||||
serviceAccountKey: { client_id: "test-client-id", private_key: "test-private-key" },
|
||||
},
|
||||
});
|
||||
|
||||
// Disable cache, enable batch
|
||||
vi.mocked(CalendarCacheEventService.isCalendarTypeSupported).mockReturnValue(false);
|
||||
vi.mocked(CalendarBatchService.isSupported).mockReturnValue(true);
|
||||
|
||||
const result = (await getCalendar(mockCredential, false)) as TestCalendarResult;
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result.__isBatchWrapper).toBe(true);
|
||||
expect(CalendarBatchWrapper).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should return CalendarBatchWrapper when cache is supported but explicitly disabled", async () => {
|
||||
const mockCredential = createMockCredential({
|
||||
type: "google_calendar",
|
||||
delegatedTo: {
|
||||
id: "delegation-1",
|
||||
serviceAccountKey: { client_id: "test-client-id", private_key: "test-private-key" },
|
||||
},
|
||||
});
|
||||
|
||||
// Cache supported but disabled via shouldServeCache=false, batch enabled
|
||||
vi.mocked(CalendarCacheEventService.isCalendarTypeSupported).mockReturnValue(true);
|
||||
vi.mocked(CalendarBatchService.isSupported).mockReturnValue(true);
|
||||
|
||||
const result = (await getCalendar(mockCredential, false)) as TestCalendarResult;
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result.__isBatchWrapper).toBe(true);
|
||||
expect(CalendarBatchWrapper).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should return original calendar when neither cache nor batch is supported", async () => {
|
||||
const mockCredential = createMockCredential({ type: "google_calendar" });
|
||||
|
||||
// Disable both cache and batch
|
||||
vi.mocked(CalendarCacheEventService.isCalendarTypeSupported).mockReturnValue(false);
|
||||
vi.mocked(CalendarBatchService.isSupported).mockReturnValue(false);
|
||||
|
||||
const result = (await getCalendar(mockCredential, false)) as TestCalendarResult;
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result.__isCacheWrapper).toBeUndefined();
|
||||
expect(result.__isBatchWrapper).toBeUndefined();
|
||||
});
|
||||
|
||||
test("should prioritize cache wrapper over batch wrapper when both are supported", async () => {
|
||||
const mockCredential = createMockCredential({
|
||||
type: "google_calendar",
|
||||
delegatedTo: {
|
||||
id: "delegation-1",
|
||||
serviceAccountKey: { client_id: "test-client-id", private_key: "test-private-key" },
|
||||
},
|
||||
});
|
||||
|
||||
// Enable both cache and batch
|
||||
vi.mocked(CalendarCacheEventService.isCalendarTypeSupported).mockReturnValue(true);
|
||||
vi.mocked(CalendarBatchService.isSupported).mockReturnValue(true);
|
||||
|
||||
const result = (await getCalendar(mockCredential, true)) as TestCalendarResult;
|
||||
|
||||
expect(result).toBeDefined();
|
||||
// Cache should take precedence
|
||||
expect(result.__isCacheWrapper).toBe(true);
|
||||
expect(result.__isBatchWrapper).toBeUndefined();
|
||||
});
|
||||
|
||||
test("should determine shouldServeCache from feature flags when not provided", async () => {
|
||||
const mockCredential = createMockCredential({ type: "google_calendar" });
|
||||
|
||||
// Mock FeaturesRepository to return true for both checks
|
||||
const mockFeaturesRepository: MockFeaturesRepository = {
|
||||
checkIfFeatureIsEnabledGlobally: vi.fn().mockResolvedValue(true),
|
||||
checkIfUserHasFeatureNonHierarchical: vi.fn().mockResolvedValue(true),
|
||||
};
|
||||
vi.mocked(FeaturesRepository).mockImplementation(
|
||||
() => mockFeaturesRepository as unknown as InstanceType<typeof FeaturesRepository>
|
||||
);
|
||||
|
||||
// Enable cache support
|
||||
vi.mocked(CalendarCacheEventService.isCalendarTypeSupported).mockReturnValue(true);
|
||||
vi.mocked(CalendarBatchService.isSupported).mockReturnValue(false);
|
||||
|
||||
// Call without shouldServeCache parameter
|
||||
const result = await getCalendar(mockCredential);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(mockFeaturesRepository.checkIfFeatureIsEnabledGlobally).toHaveBeenCalled();
|
||||
expect(mockFeaturesRepository.checkIfUserHasFeatureNonHierarchical).toHaveBeenCalledWith(
|
||||
mockCredential.userId,
|
||||
"calendar-subscription-cache"
|
||||
);
|
||||
});
|
||||
|
||||
test("should not use cache when feature flag is disabled globally", async () => {
|
||||
const mockCredential = createMockCredential({ type: "google_calendar" });
|
||||
|
||||
// Mock FeaturesRepository to return false for global check
|
||||
const mockFeaturesRepository: MockFeaturesRepository = {
|
||||
checkIfFeatureIsEnabledGlobally: vi.fn().mockResolvedValue(false),
|
||||
checkIfUserHasFeatureNonHierarchical: vi.fn().mockResolvedValue(true),
|
||||
};
|
||||
vi.mocked(FeaturesRepository).mockImplementation(
|
||||
() => mockFeaturesRepository as unknown as InstanceType<typeof FeaturesRepository>
|
||||
);
|
||||
|
||||
// Enable cache support at service level
|
||||
vi.mocked(CalendarCacheEventService.isCalendarTypeSupported).mockReturnValue(true);
|
||||
vi.mocked(CalendarBatchService.isSupported).mockReturnValue(false);
|
||||
|
||||
// Call without shouldServeCache parameter
|
||||
const result = (await getCalendar(mockCredential)) as TestCalendarResult;
|
||||
|
||||
expect(result).toBeDefined();
|
||||
// Should not be cache wrapper because feature flag is disabled
|
||||
expect(result.__isCacheWrapper).toBeUndefined();
|
||||
});
|
||||
|
||||
test("should not use cache when user does not have feature enabled", async () => {
|
||||
const mockCredential = createMockCredential({ type: "google_calendar" });
|
||||
|
||||
// Mock FeaturesRepository to return true globally but false for user
|
||||
const mockFeaturesRepository: MockFeaturesRepository = {
|
||||
checkIfFeatureIsEnabledGlobally: vi.fn().mockResolvedValue(true),
|
||||
checkIfUserHasFeatureNonHierarchical: vi.fn().mockResolvedValue(false),
|
||||
};
|
||||
vi.mocked(FeaturesRepository).mockImplementation(
|
||||
() => mockFeaturesRepository as unknown as InstanceType<typeof FeaturesRepository>
|
||||
);
|
||||
|
||||
// Enable cache support at service level
|
||||
vi.mocked(CalendarCacheEventService.isCalendarTypeSupported).mockReturnValue(true);
|
||||
vi.mocked(CalendarBatchService.isSupported).mockReturnValue(false);
|
||||
|
||||
// Call without shouldServeCache parameter
|
||||
const result = (await getCalendar(mockCredential)) as TestCalendarResult;
|
||||
|
||||
expect(result).toBeDefined();
|
||||
// Should not be cache wrapper because user doesn't have feature
|
||||
expect(result.__isCacheWrapper).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("CalendarBatchService.isSupported integration", () => {
|
||||
test("should use batch wrapper for google_calendar with delegatedTo credential", async () => {
|
||||
const mockCredential = createMockCredential({
|
||||
type: "google_calendar",
|
||||
delegatedTo: {
|
||||
id: "delegation-credential-id",
|
||||
serviceAccountKey: {
|
||||
client_email: "[email protected]",
|
||||
client_id: "test-client-id",
|
||||
private_key: "test-private-key",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Disable cache, enable batch
|
||||
vi.mocked(CalendarCacheEventService.isCalendarTypeSupported).mockReturnValue(false);
|
||||
vi.mocked(CalendarBatchService.isSupported).mockReturnValue(true);
|
||||
|
||||
const result = (await getCalendar(mockCredential, false)) as TestCalendarResult;
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result.__isBatchWrapper).toBe(true);
|
||||
expect(CalendarBatchService.isSupported).toHaveBeenCalledWith(mockCredential);
|
||||
});
|
||||
|
||||
test("should not use batch wrapper for google_calendar without delegatedTo credential", async () => {
|
||||
const mockCredential = createMockCredential({
|
||||
type: "google_calendar",
|
||||
delegatedTo: null,
|
||||
});
|
||||
|
||||
// Disable cache, batch will return false for non-delegated
|
||||
vi.mocked(CalendarCacheEventService.isCalendarTypeSupported).mockReturnValue(false);
|
||||
vi.mocked(CalendarBatchService.isSupported).mockReturnValue(false);
|
||||
|
||||
const result = (await getCalendar(mockCredential, false)) as TestCalendarResult;
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result.__isBatchWrapper).toBeUndefined();
|
||||
});
|
||||
|
||||
test("should not use batch wrapper for non-google calendar types", async () => {
|
||||
const mockCredential = createMockCredential({
|
||||
type: "office365_calendar",
|
||||
delegatedTo: {
|
||||
id: "delegation-1",
|
||||
serviceAccountKey: { client_id: "test-client-id", private_key: "test-private-key" },
|
||||
},
|
||||
});
|
||||
|
||||
// Disable cache, batch returns false for non-google
|
||||
vi.mocked(CalendarCacheEventService.isCalendarTypeSupported).mockReturnValue(false);
|
||||
vi.mocked(CalendarBatchService.isSupported).mockReturnValue(false);
|
||||
|
||||
const result = (await getCalendar(mockCredential, false)) as TestCalendarResult;
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result.__isBatchWrapper).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("edge cases", () => {
|
||||
test("should return null when credential is null", async () => {
|
||||
const result = await getCalendar(null);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
test("should return null when credential.key is missing", async () => {
|
||||
const mockCredential = createMockCredential();
|
||||
Object.assign(mockCredential, { key: null });
|
||||
|
||||
const result = await getCalendar(mockCredential);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
test("should handle _other_calendar suffix in credential type", async () => {
|
||||
const mockCredential = createMockCredential({
|
||||
type: "google_calendar_other_calendar",
|
||||
});
|
||||
|
||||
vi.mocked(CalendarCacheEventService.isCalendarTypeSupported).mockReturnValue(false);
|
||||
vi.mocked(CalendarBatchService.isSupported).mockReturnValue(false);
|
||||
|
||||
const result = await getCalendar(mockCredential, false);
|
||||
|
||||
// Should still work by stripping the suffix
|
||||
expect(result).toBeDefined();
|
||||
});
|
||||
|
||||
test("should handle _crm suffix in credential type", async () => {
|
||||
const mockCredential = createMockCredential({
|
||||
type: "google_calendar_crm",
|
||||
});
|
||||
|
||||
vi.mocked(CalendarCacheEventService.isCalendarTypeSupported).mockReturnValue(false);
|
||||
vi.mocked(CalendarBatchService.isSupported).mockReturnValue(false);
|
||||
|
||||
const result = await getCalendar(mockCredential, false);
|
||||
|
||||
// Should still work by stripping the suffix
|
||||
expect(result).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
import { CalendarBatchService } from "@calcom/features/calendar-batch/lib/CalendarBatchService";
|
||||
import { CalendarBatchWrapper } from "@calcom/features/calendar-batch/lib/CalendarBatchWrapper";
|
||||
import { CalendarSubscriptionService } from "@calcom/features/calendar-subscription/lib/CalendarSubscriptionService";
|
||||
import { CalendarCacheEventRepository } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventRepository";
|
||||
import { CalendarCacheEventService } from "@calcom/features/calendar-subscription/lib/cache/CalendarCacheEventService";
|
||||
@@ -42,6 +44,20 @@ export const getCalendar = async (
|
||||
log.warn(`calendar of type ${calendarType} is not implemented`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line
|
||||
const originalCalendar = new CalendarService(credential as any);
|
||||
return resolveCalendarServeStrategy(originalCalendar, credential, shouldServeCache);
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve best calendar strategy for current calendar and credential
|
||||
*/
|
||||
const resolveCalendarServeStrategy = async (
|
||||
originalCalendar: Calendar,
|
||||
credential: CredentialForCalendarService,
|
||||
shouldServeCache?: boolean
|
||||
): Promise<Calendar> => {
|
||||
// if shouldServeCache is not supplied, determine on the fly.
|
||||
if (typeof shouldServeCache === "undefined") {
|
||||
const featuresRepository = new FeaturesRepository(prisma);
|
||||
@@ -58,20 +74,26 @@ export const getCalendar = async (
|
||||
);
|
||||
shouldServeCache = isCalendarSubscriptionCacheEnabled && isCalendarSubscriptionCacheEnabledForUser;
|
||||
}
|
||||
if (CalendarCacheEventService.isCalendarTypeSupported(calendarType) && shouldServeCache) {
|
||||
log.info(`Calendar Cache is enabled, using CalendarCacheService for credential ${credential.id}`);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const originalCalendar = new CalendarService(credential as any);
|
||||
if (originalCalendar) {
|
||||
// return cacheable calendar
|
||||
const calendarCacheEventRepository = new CalendarCacheEventRepository(prisma);
|
||||
return new CalendarCacheWrapper({
|
||||
originalCalendar,
|
||||
calendarCacheEventRepository,
|
||||
});
|
||||
}
|
||||
if (CalendarCacheEventService.isCalendarTypeSupported(credential.type) && shouldServeCache) {
|
||||
log.info("Calendar Cache is enabled, using CalendarCacheService for credential", {
|
||||
credentialId: credential.id,
|
||||
});
|
||||
const calendarCacheEventRepository = new CalendarCacheEventRepository(prisma);
|
||||
return new CalendarCacheWrapper({
|
||||
originalCalendar: originalCalendar as unknown as Calendar,
|
||||
calendarCacheEventRepository,
|
||||
});
|
||||
} else if (CalendarBatchService.isSupported(credential)) {
|
||||
// If calendar cache isn't supported, we try calendar batch as the second layer of optimization
|
||||
log.info("Calendar Batch is supported, using CalendarBatchService for credential", {
|
||||
credentialId: credential.id,
|
||||
});
|
||||
return new CalendarBatchWrapper({ originalCalendar: originalCalendar as unknown as Calendar });
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return new CalendarService(credential as any);
|
||||
// Ended up returning unoptimized original calendar
|
||||
log.info("Calendar Cache and Batch aren't supported, serving regular calendar for credential", {
|
||||
credentialId: credential.id,
|
||||
});
|
||||
return originalCalendar;
|
||||
};
|
||||
@@ -2,11 +2,9 @@
|
||||
import type { calendar_v3 } from "@googleapis/calendar";
|
||||
import type { GaxiosResponse } from "googleapis-common";
|
||||
import { RRule } from "rrule";
|
||||
import { v4 as uuid } from "uuid";
|
||||
|
||||
import { MeetLocationType } from "@calcom/app-store/constants";
|
||||
import { getLocation, getRichDescription } from "@calcom/lib/CalEventParser";
|
||||
import { uniqueBy } from "@calcom/lib/array";
|
||||
import { ORGANIZER_EMAIL_EXEMPT_DOMAINS } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
@@ -34,12 +32,6 @@ interface GoogleCalError extends Error {
|
||||
code?: number;
|
||||
}
|
||||
|
||||
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
||||
const ONE_MONTH_IN_MS = 30 * MS_PER_DAY;
|
||||
|
||||
const GOOGLE_WEBHOOK_URL_BASE = process.env.GOOGLE_WEBHOOK_URL || process.env.NEXT_PUBLIC_WEBAPP_URL;
|
||||
const GOOGLE_WEBHOOK_URL = `${GOOGLE_WEBHOOK_URL_BASE}/api/integrations/googlecalendar/webhook`;
|
||||
|
||||
const isGaxiosResponse = (error: unknown): error is GaxiosResponse<calendar_v3.Schema$Event> =>
|
||||
typeof error === "object" && !!error && Object.prototype.hasOwnProperty.call(error, "config");
|
||||
|
||||
@@ -120,50 +112,6 @@ export default class GoogleCalendarService implements Calendar {
|
||||
return attendees;
|
||||
};
|
||||
|
||||
private async stopWatchingCalendarsInGoogle(
|
||||
channels: { googleChannelResourceId: string | null; googleChannelId: string | null }[]
|
||||
) {
|
||||
const calendar = await this.authedCalendar();
|
||||
logger.debug(`Unsubscribing from calendars ${channels.map((c) => c.googleChannelId).join(", ")}`);
|
||||
const uniqueChannels = uniqueBy(channels, ["googleChannelId", "googleChannelResourceId"]);
|
||||
await Promise.allSettled(
|
||||
uniqueChannels.map(({ googleChannelResourceId, googleChannelId }) =>
|
||||
calendar.channels
|
||||
.stop({
|
||||
requestBody: {
|
||||
resourceId: googleChannelResourceId,
|
||||
id: googleChannelId,
|
||||
},
|
||||
})
|
||||
.catch((err) => {
|
||||
console.warn(JSON.stringify(err));
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private async startWatchingCalendarsInGoogle({ calendarId }: { calendarId: string }) {
|
||||
const calendar = await this.authedCalendar();
|
||||
logger.debug(`Subscribing to calendar ${calendarId}`, safeStringify({ GOOGLE_WEBHOOK_URL }));
|
||||
|
||||
const res = await calendar.events.watch({
|
||||
// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword.
|
||||
calendarId,
|
||||
requestBody: {
|
||||
// A UUID or similar unique string that identifies this channel.
|
||||
id: uuid(),
|
||||
type: "web_hook",
|
||||
address: GOOGLE_WEBHOOK_URL,
|
||||
token: process.env.GOOGLE_WEBHOOK_TOKEN,
|
||||
params: {
|
||||
// The time-to-live in seconds for the notification channel. Default is 604800 seconds.
|
||||
ttl: `${Math.round(ONE_MONTH_IN_MS / 1000)}`,
|
||||
},
|
||||
},
|
||||
});
|
||||
return res.data;
|
||||
}
|
||||
|
||||
async createEvent(
|
||||
calEvent: CalendarServiceEvent,
|
||||
credentialId: number,
|
||||
@@ -452,9 +400,7 @@ export default class GoogleCalendarService implements Calendar {
|
||||
return apiResponse.json;
|
||||
}
|
||||
|
||||
async getFreeBusyResult(
|
||||
args: FreeBusyArgs,
|
||||
): Promise<calendar_v3.Schema$FreeBusyResponse> {
|
||||
async getFreeBusyResult(args: FreeBusyArgs): Promise<calendar_v3.Schema$FreeBusyResponse> {
|
||||
return await this.fetchAvailability(args);
|
||||
}
|
||||
|
||||
@@ -471,9 +417,7 @@ export default class GoogleCalendarService implements Calendar {
|
||||
return validCals[0];
|
||||
}
|
||||
|
||||
async getFreeBusyData(
|
||||
args: FreeBusyArgs,
|
||||
): Promise<(EventBusyDate & { id: string })[] | null> {
|
||||
async getFreeBusyData(args: FreeBusyArgs): Promise<(EventBusyDate & { id: string })[] | null> {
|
||||
const freeBusyResult = await this.getFreeBusyResult(args);
|
||||
if (!freeBusyResult.calendars) return null;
|
||||
|
||||
@@ -604,11 +548,12 @@ export default class GoogleCalendarService implements Calendar {
|
||||
|
||||
/**
|
||||
* Fetches availability data using the cache-or-fetch pattern
|
||||
*
|
||||
*/
|
||||
private async fetchAvailabilityData(
|
||||
calendarIds: string[],
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
dateTo: string
|
||||
): Promise<EventBusyDate[]> {
|
||||
// More efficient date difference calculation using native Date objects
|
||||
// Use Math.floor to match dayjs diff behavior (truncates, doesn't round up)
|
||||
@@ -619,13 +564,11 @@ export default class GoogleCalendarService implements Calendar {
|
||||
|
||||
// Google API only allows a date range of 90 days for /freebusy
|
||||
if (diff <= 90) {
|
||||
const freeBusyData = await this.getFreeBusyData(
|
||||
{
|
||||
timeMin: dateFrom,
|
||||
timeMax: dateTo,
|
||||
items: calendarIds.map((id) => ({ id })),
|
||||
}
|
||||
);
|
||||
const freeBusyData = await this.getFreeBusyData({
|
||||
timeMin: dateFrom,
|
||||
timeMax: dateTo,
|
||||
items: calendarIds.map((id) => ({ id })),
|
||||
});
|
||||
|
||||
if (!freeBusyData) throw new Error("No response from google calendar");
|
||||
return freeBusyData.map((freeBusy) => ({ start: freeBusy.start, end: freeBusy.end }));
|
||||
@@ -647,13 +590,11 @@ export default class GoogleCalendarService implements Calendar {
|
||||
currentEndTime = originalEndTime;
|
||||
}
|
||||
|
||||
const chunkData = await this.getFreeBusyData(
|
||||
{
|
||||
timeMin: new Date(currentStartTime).toISOString(),
|
||||
timeMax: new Date(currentEndTime).toISOString(),
|
||||
items: calendarIds.map((id) => ({ id })),
|
||||
}
|
||||
);
|
||||
const chunkData = await this.getFreeBusyData({
|
||||
timeMin: new Date(currentStartTime).toISOString(),
|
||||
timeMax: new Date(currentEndTime).toISOString(),
|
||||
items: calendarIds.map((id) => ({ id })),
|
||||
});
|
||||
|
||||
if (chunkData) {
|
||||
busyData.push(...chunkData.map((freeBusy) => ({ start: freeBusy.start, end: freeBusy.end })));
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
import oAuthManagerMock, {
|
||||
defaultMockOAuthManager,
|
||||
setFullMockOAuthManagerRequest,
|
||||
@@ -671,3 +673,197 @@ describe("createEvent", () => {
|
||||
log.info("createEvent recurring event test passed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Delegation Credential Batching", () => {
|
||||
test("getAvailability should fetch availability for selected calendars", async () => {
|
||||
const calendarService = new CalendarService(mockCredential);
|
||||
setFullMockOAuthManagerRequest();
|
||||
|
||||
const mockedBusyTimes = [
|
||||
{ start: "2024-01-01T10:00:00Z", end: "2024-01-01T11:00:00Z" },
|
||||
{ start: "2024-01-02T14:00:00Z", end: "2024-01-02T15:00:00Z" },
|
||||
];
|
||||
|
||||
calendarListMock.mockImplementation(() => {
|
||||
return {
|
||||
data: {
|
||||
items: [
|
||||
{ id: "[email protected]" },
|
||||
{ id: "[email protected]" },
|
||||
],
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
freebusyQueryMock.mockImplementation(() => {
|
||||
return {
|
||||
data: {
|
||||
calendars: {
|
||||
"[email protected]": { busy: [mockedBusyTimes[0]] },
|
||||
"[email protected]": { busy: [mockedBusyTimes[1]] },
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const selectedCalendars = [
|
||||
{
|
||||
externalId: "[email protected]",
|
||||
integration: "google_calendar",
|
||||
delegationCredentialId: "delegation-1",
|
||||
},
|
||||
{
|
||||
externalId: "[email protected]",
|
||||
integration: "google_calendar",
|
||||
delegationCredentialId: "delegation-2",
|
||||
},
|
||||
];
|
||||
|
||||
const availability = await calendarService.getAvailability(
|
||||
"2024-01-01",
|
||||
"2024-01-31",
|
||||
selectedCalendars,
|
||||
false
|
||||
);
|
||||
|
||||
// CalendarService makes a single API call with all calendars
|
||||
// Batching by delegationCredentialId is handled by CalendarBatchWrapper
|
||||
expect(freebusyQueryMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Should return combined results from all calendars
|
||||
expect(availability).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("CalendarBatchWrapper should make separate API calls for different delegationCredentialIds", async () => {
|
||||
// Import CalendarBatchWrapper for integration test
|
||||
const { CalendarBatchWrapper } = await import("@calcom/features/calendar-batch/lib/CalendarBatchWrapper");
|
||||
|
||||
const calendarService = new CalendarService(mockCredential);
|
||||
const wrapper = new CalendarBatchWrapper({ originalCalendar: calendarService });
|
||||
setFullMockOAuthManagerRequest();
|
||||
|
||||
const mockedBusyTimes1 = [{ start: "2024-01-01T10:00:00Z", end: "2024-01-01T11:00:00Z" }];
|
||||
const mockedBusyTimes2 = [{ start: "2024-01-02T14:00:00Z", end: "2024-01-02T15:00:00Z" }];
|
||||
|
||||
calendarListMock.mockImplementation(() => {
|
||||
return {
|
||||
data: {
|
||||
items: [
|
||||
{ id: "[email protected]" },
|
||||
{ id: "[email protected]" },
|
||||
],
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
let callCount = 0;
|
||||
freebusyQueryMock.mockImplementation(() => {
|
||||
callCount++;
|
||||
const busyTimes = callCount === 1 ? mockedBusyTimes1 : mockedBusyTimes2;
|
||||
return {
|
||||
data: {
|
||||
calendars: {
|
||||
"[email protected]": { busy: busyTimes },
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const selectedCalendars = [
|
||||
{
|
||||
externalId: "[email protected]",
|
||||
integration: "google_calendar",
|
||||
delegationCredentialId: "delegation-1",
|
||||
},
|
||||
{
|
||||
externalId: "[email protected]",
|
||||
integration: "google_calendar",
|
||||
delegationCredentialId: "delegation-2",
|
||||
},
|
||||
];
|
||||
|
||||
const availability = await wrapper.getAvailability(
|
||||
"2024-01-01",
|
||||
"2024-01-31",
|
||||
selectedCalendars,
|
||||
undefined,
|
||||
false
|
||||
);
|
||||
|
||||
// CalendarBatchWrapper should make 2 API calls (one per delegation credential group)
|
||||
expect(freebusyQueryMock).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Should return combined results from both groups
|
||||
expect(availability).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("getAvailability should fallback to primary calendar when no calendars selected and fallbackToPrimary is true", async () => {
|
||||
const calendarService = new CalendarService(mockCredential);
|
||||
setFullMockOAuthManagerRequest();
|
||||
|
||||
const mockedBusyTimes = [
|
||||
{ start: "2024-01-01T10:00:00Z", end: "2024-01-01T11:00:00Z" },
|
||||
];
|
||||
|
||||
calendarListMock.mockImplementation(() => {
|
||||
return {
|
||||
data: {
|
||||
items: [
|
||||
{ id: "[email protected]", primary: true },
|
||||
{ id: "[email protected]" },
|
||||
],
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
freebusyQueryMock.mockImplementation(() => {
|
||||
return {
|
||||
data: {
|
||||
calendars: {
|
||||
"[email protected]": { busy: mockedBusyTimes },
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// Empty selected calendars with fallbackToPrimary = true
|
||||
const availability = await calendarService.getAvailability(
|
||||
"2024-01-01",
|
||||
"2024-01-31",
|
||||
[],
|
||||
true
|
||||
);
|
||||
|
||||
// Should have called FreeBusy API
|
||||
expect(freebusyQueryMock).toHaveBeenCalled();
|
||||
|
||||
// Should return busy times from primary calendar
|
||||
expect(availability).toEqual(mockedBusyTimes);
|
||||
});
|
||||
|
||||
test("getAvailability should return empty array when only non-google calendars are selected", async () => {
|
||||
const calendarService = new CalendarService(mockCredential);
|
||||
setFullMockOAuthManagerRequest();
|
||||
|
||||
const selectedCalendars = [
|
||||
{
|
||||
externalId: "[email protected]",
|
||||
integration: "office365_calendar",
|
||||
delegationCredentialId: null,
|
||||
},
|
||||
];
|
||||
|
||||
const availability = await calendarService.getAvailability(
|
||||
"2024-01-01",
|
||||
"2024-01-31",
|
||||
selectedCalendars,
|
||||
false
|
||||
);
|
||||
|
||||
// Should return empty array since no google calendars
|
||||
expect(availability).toEqual([]);
|
||||
|
||||
// Should not have called FreeBusy API
|
||||
expect(freebusyQueryMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user