Revert "perf: (googlecalendar): batch freebusy calls by delegation credential (#24331)"

This reverts commit 253c33df33.
This commit is contained in:
Alex van Andel committed 2025-12-24 00:35:18 +00:00
1 parent 5322d9640b
commit 7f59a1f058
8 files changed
+87 -1699

No files matched your search

-137
View File
@@ -1,137 +0,0 @@
# Calendar Batch Feature
## Overview
The Calendar Batch feature optimizes Google Calendar availability queries by intelligently batching FreeBusy API calls based on delegation credentials. This reduces the number of API calls while respecting Google's API limits.
## Architecture
### Components
#### 1. CalendarBatchService
Location: `lib/CalendarBatchService.ts`
A simple utility class that determines which calendar types support batching optimization.
```typescript
class CalendarBatchService {
static isCalendarTypeSupported(type: string | null): boolean
}
```
Currently, only `google_calendar` is supported. This gate is used by `getCalendar()` to decide whether to wrap the calendar service with batching capabilities.
#### 2. CalendarBatchWrapper
Location: `lib/CalendarBatchWrapper.ts`
A decorator that wraps the original calendar service and optimizes availability queries. It implements the `Calendar` interface, passing through most methods directly to the underlying calendar while intercepting `getAvailability()` and `getAvailabilityWithTimeZones()` for optimization.
**Key Constants:**
- `CALENDAR_BATCH_MAX_SIZE = 50`: Google Calendar FreeBusy API limit for items per request
**Key Methods:**
##### `splitCalendars(selectedCalendars)`
Divides calendars into two groups based on their credential type:
1. **ownCredentials**: Calendars WITHOUT `delegationCredentialId`
- These are processed one-by-one because each may represent a different OAuth token
- Conservative approach to avoid mixing credentials
2. **delegatedCredentials**: Calendars WITH `delegationCredentialId`
- Grouped by their `delegationCredentialId`
- Calendars in the same group share the same delegated credential and can be safely batched together
##### `partition(items, size)`
Splits an array into chunks of the specified size (50 for Google API compliance).
##### `getAvailability(dateFrom, dateTo, selectedCalendars, fallbackToPrimary)`
The main optimization method:
1. Splits calendars using `splitCalendars()`
2. Creates parallel tasks:
- One task per own credential calendar (processed individually)
- For delegated credentials: groups by `delegationCredentialId`, partitions each group into batches of 50, creates one task per batch
3. Executes all tasks in parallel with `Promise.all()`
4. Flattens and returns combined results
**Edge Case:** If no calendars are provided, a single call is made with an empty array to honor `fallbackToPrimary`.
### Integration with getCalendar
Location: `packages/app-store/_utils/getCalendar.ts`
The `getCalendar()` factory function decides which wrapper to use:
```
Decision Flow:
1. Create original calendar service from CalendarServiceMap
2. Check if CalendarCacheWrapper should be used (feature flag based)
- If yes, return CalendarCacheWrapper (cache takes precedence)
3. Check if CalendarBatchService.isCalendarTypeSupported(calendarType)
- If yes, return CalendarBatchWrapper
4. Otherwise, return unoptimized original calendar
```
**Important:** Cache wrapper takes precedence over batch wrapper. If calendar caching is enabled for a user, batching is not applied.
## How It Works with Google Calendar
### Two Levels of Chunking
The system has two independent chunking mechanisms:
1. **CalendarBatchWrapper (this feature)**: Chunks calendars into groups of 50 per API call based on delegation credentials
2. **GoogleCalendarService.fetchAvailabilityData()**: Chunks time periods into 90-day windows (Google FreeBusy API limitation)
This means a single `getAvailability()` call can result in multiple Google API calls:
- Multiple calls for different credential groups (batch wrapper)
- Multiple calls for long date ranges > 90 days (Google service)
### Example Flow
For a user with:
- 2 personal calendars (no delegation)
- 75 delegated calendars under delegation credential "A"
- 30 delegated calendars under delegation credential "B"
The batch wrapper creates:
- 2 tasks for personal calendars (one each)
- 2 tasks for delegation "A" (50 + 25 calendars)
- 1 task for delegation "B" (30 calendars)
Total: 5 parallel API calls instead of 107 sequential calls.
## Data Model
### IntegrationCalendar
The `IntegrationCalendar` interface extends `SelectedCalendar` from Prisma and includes:
- `externalId`: The calendar's external identifier
- `credentialId`: Reference to the Credential used
- `delegationCredentialId`: Reference to a DelegationCredential (if using domain-wide delegation)
### DelegationCredential
A `DelegationCredential` represents a shared credential that allows accessing multiple users' calendars within an organization (e.g., Google Workspace domain-wide delegation). Calendars sharing the same `delegationCredentialId` can be batched together because they use the same authentication context.
## Performance Considerations
1. **Parallel Execution**: All batched tasks run in parallel via `Promise.all()`
2. **Conservative Batching**: Own credentials are never batched together to avoid potential token mixing issues
3. **Respects API Limits**: Never exceeds 50 calendars per FreeBusy request
4. **Pass-through for Non-Availability Methods**: `createEvent`, `updateEvent`, `deleteEvent`, and other methods are not batched - they pass directly to the underlying calendar service
## Supported Calendar Types
Currently only `google_calendar` supports batching. To add support for other calendar types, update `CalendarBatchService.isCalendarTypeSupported()`.
@@ -1,27 +0,0 @@
import logger from "@calcom/lib/logger";
/**
* Utility class for Calendar Batch Service
* Should serve as provide customizable config per calendar type
*/
import type { CredentialForCalendarService } from "@calcom/types/Credential";
const log = logger.getSubLogger({ prefix: ["CalendarBatchService"] });
export class CalendarBatchService {
static isSupported(credential: CredentialForCalendarService): boolean {
// only supports google calendar for now
if (credential.type !== "google_calendar") {
log.info("Only Google Calendar is supported");
return false;
}
// only supports delegated credentials
if (!credential.delegatedTo) {
log.info("Only Delegated Credential is supported");
return false;
}
return true;
}
}
@@ -1,300 +0,0 @@
import logger from "@calcom/lib/logger";
import {
Calendar,
CalendarEvent,
CalendarServiceEvent,
EventBusyDate,
IntegrationCalendar,
NewCalendarEventType,
SelectedCalendarEventTypeIds,
} from "@calcom/types/Calendar";
const log = logger.getSubLogger({ prefix: ["CalendarBatchWrapper"] });
type DelegatedGroups = Record<string, IntegrationCalendar[]>;
/**
* CalendarBatchWrapper wraps original calendar to process availability in
* batches instead of individual calls.
*/
export class CalendarBatchWrapper implements Calendar {
static CALENDAR_BATCH_MAX_SIZE = 50;
constructor(
private deps: {
originalCalendar: Calendar;
}
) {}
/**
* Splits selected calendars into two independent credential flows.
*
* - ownCredentials:
* Calendars without delegationCredentialId.
* Each one may represent a different underlying token,
* so they must be processed one-by-one.
*
* - delegatedCredentials:
* Calendars grouped by delegationCredentialId.
* Calendars in the same group share the same delegated credential
* and can be safely batched.
*/
private splitCalendars(selectedCalendars: IntegrationCalendar[]) {
const ownCredentials: IntegrationCalendar[] = [];
const delegatedCredentials: DelegatedGroups = {};
for (const selectedCalendar of selectedCalendars) {
const delegationCredentialId = selectedCalendar.delegationCredentialId;
if (!delegationCredentialId) {
ownCredentials.push(selectedCalendar);
continue;
}
if (!delegatedCredentials[delegationCredentialId]) {
delegatedCredentials[delegationCredentialId] = [];
}
delegatedCredentials[delegationCredentialId].push(selectedCalendar);
}
return { ownCredentials, delegatedCredentials };
}
/**
* Partitions items into fixed-size batches.
* Google Calendar freebusy enforces a hard limit of CalendarBatchWrapper.CALENDAR_BATCH_MAX_SIZE
*/
private partition<T>(items: T[], size: number): T[][] {
const result: T[][] = [];
for (let i = 0; i < items.length; i += size) {
result.push(items.slice(i, i + size));
}
return result;
}
getCredentialId?(): number {
return 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);
}
async getAvailability(
dateFrom: string,
dateTo: string,
selectedCalendars: IntegrationCalendar[],
shouldServeCache?: boolean,
fallbackToPrimary?: boolean
): Promise<EventBusyDate[]> {
const { ownCredentials, delegatedCredentials } = this.splitCalendars(selectedCalendars);
log.info("Loading free/busy from Google Calendar", {
ownCredentials: ownCredentials.length,
delegatedCredentials: Object.values(delegatedCredentials).reduce(
(sum, calendars) => sum + calendars.length,
0
),
});
const tasks: Promise<EventBusyDate[]>[] = [];
/**
* Own credentials are processed one-by-one because we cannot
* safely assume they share the same underlying token.
*/
for (let i = 0; i < ownCredentials.length; i++) {
const selectedCalendar = ownCredentials[i];
tasks.push(
this.deps.originalCalendar.getAvailability(
dateFrom,
dateTo,
[selectedCalendar],
shouldServeCache,
fallbackToPrimary
)
);
}
/**
* Delegated credentials are grouped by delegationCredentialId.
* Each group can be batched up to the Google API limit.
*/
const delegationIds = Object.keys(delegatedCredentials);
for (let i = 0; i < delegationIds.length; i++) {
const delegationCredentialId = delegationIds[i];
const delegationCredentialCalendars = delegatedCredentials[delegationCredentialId];
const partition = this.partition(
delegationCredentialCalendars,
CalendarBatchWrapper.CALENDAR_BATCH_MAX_SIZE
);
for (let j = 0; j < partition.length; j++) {
tasks.push(
this.deps.originalCalendar.getAvailability(
dateFrom,
dateTo,
partition[j],
shouldServeCache,
fallbackToPrimary
)
);
}
}
/**
* When no calendars are provided, perform a single call
* so fallbackToPrimary can be honored.
*/
if (tasks.length === 0) {
tasks.push(
this.deps.originalCalendar.getAvailability(dateFrom, dateTo, [], shouldServeCache, fallbackToPrimary)
);
}
const results = await Promise.allSettled(tasks);
// Log any failed batches but continue with successful ones
const failedResults = results.filter(
(result): result is PromiseRejectedResult => result.status === "rejected"
);
if (failedResults.length > 0) {
log.warn("Some calendar availability batches failed", {
failedCount: failedResults.length,
totalCount: results.length,
errors: failedResults.map((r) => r.reason),
});
}
// Return only successful results
const successfulResults = results
.filter((result): result is PromiseFulfilledResult<EventBusyDate[]> => result.status === "fulfilled")
.map((result) => result.value);
return successfulResults.flat();
}
async getAvailabilityWithTimeZones(
dateFrom: string,
dateTo: string,
selectedCalendars: IntegrationCalendar[],
fallbackToPrimary?: boolean
): Promise<{ start: Date | string; end: Date | string; timeZone: string }[]> {
const { ownCredentials, delegatedCredentials } = this.splitCalendars(selectedCalendars);
const tasks: Promise<{ start: Date | string; end: Date | string; timeZone: string }[]>[] = [];
const calendar = this.deps.originalCalendar;
/**
* Timezone-aware availability is optional.
* If not implemented by the underlying calendar, fail fast.
*/
if (!calendar.getAvailabilityWithTimeZones) {
log.warn("getAvailabilityWithTimeZones is not implemented on underlying calendar");
return [];
}
/**
* Own credentials are processed one-by-one for the same reason
* as in getAvailability.
*/
for (let i = 0; i < ownCredentials.length; i++) {
const selectedCalendar = ownCredentials[i];
tasks.push(
calendar.getAvailabilityWithTimeZones(dateFrom, dateTo, [selectedCalendar], fallbackToPrimary)
);
}
/**
* Delegated credentials are processed in isolated batches.
*/
const delegationIds = Object.keys(delegatedCredentials);
for (let i = 0; i < delegationIds.length; i++) {
const delegationCredentialId = delegationIds[i];
const delegationCredentialCalendars = delegatedCredentials[delegationCredentialId];
const partition = this.partition(
delegationCredentialCalendars,
CalendarBatchWrapper.CALENDAR_BATCH_MAX_SIZE
);
for (let j = 0; j < partition.length; j++) {
tasks.push(calendar.getAvailabilityWithTimeZones(dateFrom, dateTo, partition[j], fallbackToPrimary));
}
}
/**
* Ensures fallbackToPrimary is honored even when
* no calendars were explicitly selected.
*/
if (tasks.length === 0) {
tasks.push(calendar.getAvailabilityWithTimeZones(dateFrom, dateTo, [], fallbackToPrimary));
}
const results = await Promise.allSettled(tasks);
// Log any failed batches but continue with successful ones
const failedResults = results.filter(
(result): result is PromiseRejectedResult => result.status === "rejected"
);
if (failedResults.length > 0) {
log.warn("Some calendar availability with timezones batches failed", {
failedCount: failedResults.length,
totalCount: results.length,
errors: failedResults.map((r) => r.reason),
});
}
// Return only successful results
type AvailabilityWithTimeZone = { start: Date | string; end: Date | string; timeZone: string };
const successfulResults = results
.filter(
(result): result is PromiseFulfilledResult<AvailabilityWithTimeZone[]> => result.status === "fulfilled"
)
.map((result) => result.value);
return successfulResults.flat();
}
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();
}
}
@@ -1,581 +0,0 @@
import { describe, test, expect, vi, beforeEach } from "vitest";
import type { Calendar, CalendarEvent, CalendarServiceEvent, EventBusyDate, IntegrationCalendar } from "@calcom/types/Calendar";
import { CalendarBatchWrapper } from "../CalendarBatchWrapper";
describe("CalendarBatchWrapper", () => {
let mockOriginalCalendar: Calendar;
let getAvailabilityMock: ReturnType<typeof vi.fn>;
let getAvailabilityWithTimeZonesMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
getAvailabilityMock = vi.fn().mockResolvedValue([]);
getAvailabilityWithTimeZonesMock = vi.fn().mockResolvedValue([]);
mockOriginalCalendar = {
getAvailability: getAvailabilityMock,
getAvailabilityWithTimeZones: getAvailabilityWithTimeZonesMock,
createEvent: vi.fn(),
updateEvent: vi.fn(),
deleteEvent: vi.fn(),
listCalendars: vi.fn().mockResolvedValue([]),
} as unknown as Calendar;
});
describe("getAvailability batching behavior", () => {
test("should make separate calls for calendars without delegationCredentialId", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar" },
{ externalId: "[email protected]", integration: "google_calendar" },
{ externalId: "[email protected]", integration: "google_calendar" },
];
getAvailabilityMock.mockResolvedValue([{ start: "2024-01-01T10:00:00Z", end: "2024-01-01T11:00:00Z" }]);
await wrapper.getAvailability("2024-01-01", "2024-01-31", selectedCalendars, undefined, false);
// Each calendar without delegationCredentialId should be processed separately
expect(getAvailabilityMock).toHaveBeenCalledTimes(3);
// Verify each call has exactly one calendar (order-independent)
const allCalls = getAvailabilityMock.mock.calls as [
string,
string,
IntegrationCalendar[],
boolean | undefined,
boolean
][];
const calendarIdsFromCalls = allCalls.map((call) => {
expect(call[0]).toBe("2024-01-01");
expect(call[1]).toBe("2024-01-31");
expect(call[2]).toHaveLength(1);
expect(call[3]).toBe(undefined);
expect(call[4]).toBe(false);
return call[2][0].externalId;
});
// Verify all expected calendars were called (as a set, order doesn't matter)
expect(new Set(calendarIdsFromCalls)).toEqual(
new Set(["[email protected]", "[email protected]", "[email protected]"])
);
});
test("should batch calendars with the same delegationCredentialId together", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-2" },
];
await wrapper.getAvailability("2024-01-01", "2024-01-31", selectedCalendars, undefined, false);
// Should make 2 calls: one for delegation-1 (batched), one for delegation-2
expect(getAvailabilityMock).toHaveBeenCalledTimes(2);
// Verify calls in an order-independent way
const allCalls = getAvailabilityMock.mock.calls as [
string,
string,
IntegrationCalendar[],
boolean | undefined,
boolean
][];
// Find the call for delegation-1 (should have 2 calendars batched)
const delegation1Call = allCalls.find(
(call) => call[2].length === 2 && call[2][0].delegationCredentialId === "delegation-1"
);
expect(delegation1Call).toBeDefined();
expect(delegation1Call![0]).toBe("2024-01-01");
expect(delegation1Call![1]).toBe("2024-01-31");
const delegation1Ids = new Set(delegation1Call![2].map((c) => c.externalId));
expect(delegation1Ids).toEqual(new Set(["[email protected]", "[email protected]"]));
expect(delegation1Call![3]).toBe(undefined);
expect(delegation1Call![4]).toBe(false);
// Find the call for delegation-2 (should have 1 calendar)
const delegation2Call = allCalls.find(
(call) => call[2].length === 1 && call[2][0].delegationCredentialId === "delegation-2"
);
expect(delegation2Call).toBeDefined();
expect(delegation2Call![0]).toBe("2024-01-01");
expect(delegation2Call![1]).toBe("2024-01-31");
expect(delegation2Call![2][0].externalId).toBe("[email protected]");
expect(delegation2Call![3]).toBe(undefined);
expect(delegation2Call![4]).toBe(false);
});
test("should chunk delegated calendars into groups of 50 for API limits", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
// Create 120 calendars with the same delegationCredentialId
const selectedCalendars: IntegrationCalendar[] = Array.from({ length: 120 }, (_, i) => ({
externalId: `cal${i}@test.com`,
integration: "google_calendar",
delegationCredentialId: "delegation-1",
}));
await wrapper.getAvailability("2024-01-01", "2024-01-31", selectedCalendars, undefined, false);
// Should make 3 calls: 50 + 50 + 20
expect(getAvailabilityMock).toHaveBeenCalledTimes(3);
// First chunk should have 50 calendars
const firstCallCalendars = getAvailabilityMock.mock.calls[0][2];
expect(firstCallCalendars).toHaveLength(50);
// Second chunk should have 50 calendars
const secondCallCalendars = getAvailabilityMock.mock.calls[1][2];
expect(secondCallCalendars).toHaveLength(50);
// Third chunk should have 20 calendars
const thirdCallCalendars = getAvailabilityMock.mock.calls[2][2];
expect(thirdCallCalendars).toHaveLength(20);
});
test("should handle mixed calendars with and without delegationCredentialId", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
{ externalId: "[email protected]", integration: "google_calendar" },
];
await wrapper.getAvailability("2024-01-01", "2024-01-31", selectedCalendars, undefined, false);
// Should make 3 calls: 2 for own credentials (one each), 1 for delegation-1 (batched)
expect(getAvailabilityMock).toHaveBeenCalledTimes(3);
});
test("should make a single call with empty array when no calendars provided to honor fallbackToPrimary", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
await wrapper.getAvailability("2024-01-01", "2024-01-31", [], undefined, true);
// Should make exactly 1 call with empty array so fallbackToPrimary can be honored
expect(getAvailabilityMock).toHaveBeenCalledTimes(1);
expect(getAvailabilityMock).toHaveBeenCalledWith("2024-01-01", "2024-01-31", [], undefined, true);
});
test("should flatten and combine results from all batched calls", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-2" },
];
const busyTimes1: EventBusyDate[] = [{ start: new Date("2024-01-01T10:00:00Z"), end: new Date("2024-01-01T11:00:00Z") }];
const busyTimes2: EventBusyDate[] = [{ start: new Date("2024-01-02T14:00:00Z"), end: new Date("2024-01-02T15:00:00Z") }];
getAvailabilityMock
.mockResolvedValueOnce(busyTimes1)
.mockResolvedValueOnce(busyTimes2);
const result = await wrapper.getAvailability("2024-01-01", "2024-01-31", selectedCalendars, undefined, false);
// Should return combined results from both calls
expect(result).toHaveLength(2);
expect(result).toEqual([...busyTimes1, ...busyTimes2]);
});
test("should forward shouldServeCache parameter to original calendar", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
];
// Test with shouldServeCache = true
await wrapper.getAvailability("2024-01-01", "2024-01-31", selectedCalendars, true, false);
expect(getAvailabilityMock).toHaveBeenLastCalledWith(
"2024-01-01",
"2024-01-31",
selectedCalendars,
true,
false
);
getAvailabilityMock.mockClear();
// Test with shouldServeCache = false
await wrapper.getAvailability("2024-01-01", "2024-01-31", selectedCalendars, false, true);
expect(getAvailabilityMock).toHaveBeenLastCalledWith(
"2024-01-01",
"2024-01-31",
selectedCalendars,
false,
true
);
});
test("should correctly group calendars by delegationCredentialId (order-independent verification)", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-2" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
{ externalId: "[email protected]", integration: "google_calendar" },
];
await wrapper.getAvailability("2024-01-01", "2024-01-31", selectedCalendars, undefined, false);
// Should make 4 calls: 2 for own credentials (one each), 1 for delegation-1 (batched), 1 for delegation-2
expect(getAvailabilityMock).toHaveBeenCalledTimes(4);
// Collect all calendars from all calls
const allCallCalendars = getAvailabilityMock.mock.calls.map(
(call: [string, string, IntegrationCalendar[], boolean | undefined, boolean | undefined]) => call[2]
);
// Verify own credentials are processed one-by-one (each call has exactly 1 calendar without delegationCredentialId)
const ownCredentialCalls = allCallCalendars.filter(
(cals: IntegrationCalendar[]) => cals.length === 1 && !cals[0].delegationCredentialId
);
expect(ownCredentialCalls).toHaveLength(2);
const ownCalendarIds = ownCredentialCalls.flat().map((c: IntegrationCalendar) => c.externalId);
expect(ownCalendarIds).toContain("[email protected]");
expect(ownCalendarIds).toContain("[email protected]");
// Verify delegation-1 calendars are batched together
const delegation1Call = allCallCalendars.find(
(cals: IntegrationCalendar[]) => cals.length > 0 && cals[0].delegationCredentialId === "delegation-1"
);
expect(delegation1Call).toBeDefined();
expect(delegation1Call).toHaveLength(2);
const delegation1Ids = delegation1Call!.map((c: IntegrationCalendar) => c.externalId);
expect(delegation1Ids).toContain("[email protected]");
expect(delegation1Ids).toContain("[email protected]");
// Verify delegation-2 calendar is in its own call
const delegation2Call = allCallCalendars.find(
(cals: IntegrationCalendar[]) => cals.length > 0 && cals[0].delegationCredentialId === "delegation-2"
);
expect(delegation2Call).toBeDefined();
expect(delegation2Call).toHaveLength(1);
expect(delegation2Call![0].externalId).toBe("[email protected]");
// Verify total union equals expected calendars
const allCalendarIds = allCallCalendars.flat().map((c: IntegrationCalendar) => c.externalId);
expect(allCalendarIds).toHaveLength(5);
expect(new Set(allCalendarIds)).toEqual(new Set(selectedCalendars.map((c) => c.externalId)));
});
});
describe("partial failure handling", () => {
test("should return partial results when some batches fail", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-2" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-3" },
];
const successfulBusyTimes: EventBusyDate[] = [
{ start: new Date("2024-01-01T10:00:00Z"), end: new Date("2024-01-01T11:00:00Z") },
];
// First call succeeds, second fails, third succeeds
getAvailabilityMock
.mockResolvedValueOnce(successfulBusyTimes)
.mockRejectedValueOnce(new Error("API rate limit exceeded"))
.mockResolvedValueOnce(successfulBusyTimes);
const result = await wrapper.getAvailability("2024-01-01", "2024-01-31", selectedCalendars, undefined, false);
// Should return results from successful batches only (2 successful calls)
expect(result).toHaveLength(2);
expect(getAvailabilityMock).toHaveBeenCalledTimes(3);
});
test("should return empty array when all batches fail", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-2" },
];
// All calls fail
getAvailabilityMock
.mockRejectedValueOnce(new Error("Network error"))
.mockRejectedValueOnce(new Error("API error"));
const result = await wrapper.getAvailability("2024-01-01", "2024-01-31", selectedCalendars, undefined, false);
// Should return empty array when all batches fail
expect(result).toHaveLength(0);
expect(getAvailabilityMock).toHaveBeenCalledTimes(2);
});
test("should not throw when some batches fail", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar" },
{ externalId: "[email protected]", integration: "google_calendar" },
];
// First call fails, second succeeds
getAvailabilityMock
.mockRejectedValueOnce(new Error("Permission denied"))
.mockResolvedValueOnce([{ start: new Date("2024-01-01T10:00:00Z"), end: new Date("2024-01-01T11:00:00Z") }]);
// Should not throw, should return partial results
await expect(
wrapper.getAvailability("2024-01-01", "2024-01-31", selectedCalendars, undefined, false)
).resolves.not.toThrow();
const result = await wrapper.getAvailability("2024-01-01", "2024-01-31", selectedCalendars, undefined, false);
expect(result).toBeDefined();
});
});
describe("pass-through methods", () => {
test("createEvent should delegate to original calendar", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const mockEvent = { title: "Test Event" } as unknown as CalendarServiceEvent;
await wrapper.createEvent(mockEvent, 1, "[email protected]");
expect(mockOriginalCalendar.createEvent).toHaveBeenCalledWith(mockEvent, 1, "[email protected]");
});
test("updateEvent should delegate to original calendar", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const mockEvent = { title: "Updated Event" } as unknown as CalendarServiceEvent;
await wrapper.updateEvent("event-uid", mockEvent, "[email protected]");
expect(mockOriginalCalendar.updateEvent).toHaveBeenCalledWith("event-uid", mockEvent, "[email protected]");
});
test("deleteEvent should delegate to original calendar", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const mockEvent = { title: "Event to Delete" } as unknown as CalendarEvent;
await wrapper.deleteEvent("event-uid", mockEvent, "[email protected]");
expect(mockOriginalCalendar.deleteEvent).toHaveBeenCalledWith("event-uid", mockEvent, "[email protected]");
});
test("listCalendars should delegate to original calendar", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
await wrapper.listCalendars();
expect(mockOriginalCalendar.listCalendars).toHaveBeenCalled();
});
});
describe("getAvailabilityWithTimeZones batching behavior", () => {
test("should make separate calls for calendars without delegationCredentialId", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar" },
{ externalId: "[email protected]", integration: "google_calendar" },
];
await wrapper.getAvailabilityWithTimeZones("2024-01-01", "2024-01-31", selectedCalendars, false);
// Each calendar without delegationCredentialId should be processed separately
expect(getAvailabilityWithTimeZonesMock).toHaveBeenCalledTimes(2);
});
test("should batch calendars with the same delegationCredentialId together", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-2" },
];
await wrapper.getAvailabilityWithTimeZones("2024-01-01", "2024-01-31", selectedCalendars, false);
// Should make 2 calls: one for delegation-1 (batched), one for delegation-2
expect(getAvailabilityWithTimeZonesMock).toHaveBeenCalledTimes(2);
// Verify calls in an order-independent way
const allCalls = getAvailabilityWithTimeZonesMock.mock.calls as [
string,
string,
IntegrationCalendar[],
boolean
][];
// Find the call for delegation-1 (should have 2 calendars batched)
const delegation1Call = allCalls.find(
(call) => call[2].length === 2 && call[2][0].delegationCredentialId === "delegation-1"
);
expect(delegation1Call).toBeDefined();
const delegation1Ids = new Set(delegation1Call![2].map((c) => c.externalId));
expect(delegation1Ids).toEqual(new Set(["[email protected]", "[email protected]"]));
// Find the call for delegation-2 (should have 1 calendar)
const delegation2Call = allCalls.find(
(call) => call[2].length === 1 && call[2][0].delegationCredentialId === "delegation-2"
);
expect(delegation2Call).toBeDefined();
expect(delegation2Call![2][0].externalId).toBe("[email protected]");
});
test("should chunk delegated calendars into groups of 50 for API limits", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
// Create 120 calendars with the same delegationCredentialId
const selectedCalendars: IntegrationCalendar[] = Array.from({ length: 120 }, (_, i) => ({
externalId: `cal${i}@test.com`,
integration: "google_calendar",
delegationCredentialId: "delegation-1",
}));
await wrapper.getAvailabilityWithTimeZones("2024-01-01", "2024-01-31", selectedCalendars, false);
// Should make 3 calls: 50 + 50 + 20
expect(getAvailabilityWithTimeZonesMock).toHaveBeenCalledTimes(3);
});
test("should make a single call with empty array when no calendars provided to honor fallbackToPrimary", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
await wrapper.getAvailabilityWithTimeZones("2024-01-01", "2024-01-31", [], true);
// Should make exactly 1 call with empty array so fallbackToPrimary can be honored
expect(getAvailabilityWithTimeZonesMock).toHaveBeenCalledTimes(1);
expect(getAvailabilityWithTimeZonesMock).toHaveBeenCalledWith("2024-01-01", "2024-01-31", [], true);
});
test("should flatten and combine results from all batched calls", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-2" },
];
type AvailabilityWithTimeZone = { start: Date | string; end: Date | string; timeZone: string };
const busyTimes1: AvailabilityWithTimeZone[] = [
{ start: new Date("2024-01-01T10:00:00Z"), end: new Date("2024-01-01T11:00:00Z"), timeZone: "America/New_York" },
];
const busyTimes2: AvailabilityWithTimeZone[] = [
{ start: new Date("2024-01-02T14:00:00Z"), end: new Date("2024-01-02T15:00:00Z"), timeZone: "Europe/London" },
];
getAvailabilityWithTimeZonesMock
.mockResolvedValueOnce(busyTimes1)
.mockResolvedValueOnce(busyTimes2);
const result = await wrapper.getAvailabilityWithTimeZones("2024-01-01", "2024-01-31", selectedCalendars, false);
// Should return combined results from both calls
expect(result).toHaveLength(2);
expect(result).toEqual([...busyTimes1, ...busyTimes2]);
});
test("should return empty array when underlying calendar does not implement getAvailabilityWithTimeZones", async () => {
const calendarWithoutMethod = {
getAvailability: getAvailabilityMock,
createEvent: vi.fn(),
updateEvent: vi.fn(),
deleteEvent: vi.fn(),
listCalendars: vi.fn().mockResolvedValue([]),
} as unknown as Calendar;
const wrapper = new CalendarBatchWrapper({ originalCalendar: calendarWithoutMethod });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar" },
];
const result = await wrapper.getAvailabilityWithTimeZones("2024-01-01", "2024-01-31", selectedCalendars, false);
expect(result).toEqual([]);
});
});
describe("getAvailabilityWithTimeZones partial failure handling", () => {
test("should return partial results when some batches fail", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-2" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-3" },
];
type AvailabilityWithTimeZone = { start: Date | string; end: Date | string; timeZone: string };
const successfulBusyTimes: AvailabilityWithTimeZone[] = [
{ start: new Date("2024-01-01T10:00:00Z"), end: new Date("2024-01-01T11:00:00Z"), timeZone: "UTC" },
];
// First call succeeds, second fails, third succeeds
getAvailabilityWithTimeZonesMock
.mockResolvedValueOnce(successfulBusyTimes)
.mockRejectedValueOnce(new Error("API rate limit exceeded"))
.mockResolvedValueOnce(successfulBusyTimes);
const result = await wrapper.getAvailabilityWithTimeZones("2024-01-01", "2024-01-31", selectedCalendars, false);
// Should return results from successful batches only (2 successful calls)
expect(result).toHaveLength(2);
expect(getAvailabilityWithTimeZonesMock).toHaveBeenCalledTimes(3);
});
test("should return empty array when all batches fail", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-1" },
{ externalId: "[email protected]", integration: "google_calendar", delegationCredentialId: "delegation-2" },
];
// All calls fail
getAvailabilityWithTimeZonesMock
.mockRejectedValueOnce(new Error("Network error"))
.mockRejectedValueOnce(new Error("API error"));
const result = await wrapper.getAvailabilityWithTimeZones("2024-01-01", "2024-01-31", selectedCalendars, false);
// Should return empty array when all batches fail
expect(result).toHaveLength(0);
expect(getAvailabilityWithTimeZonesMock).toHaveBeenCalledTimes(2);
});
test("should not throw when some batches fail", async () => {
const wrapper = new CalendarBatchWrapper({ originalCalendar: mockOriginalCalendar });
const selectedCalendars: IntegrationCalendar[] = [
{ externalId: "[email protected]", integration: "google_calendar" },
{ externalId: "[email protected]", integration: "google_calendar" },
];
type AvailabilityWithTimeZone = { start: Date | string; end: Date | string; timeZone: string };
const successResult: AvailabilityWithTimeZone[] = [
{ start: new Date("2024-01-01T10:00:00Z"), end: new Date("2024-01-01T11:00:00Z"), timeZone: "UTC" },
];
// First call fails, second succeeds
getAvailabilityWithTimeZonesMock
.mockRejectedValueOnce(new Error("Permission denied"))
.mockResolvedValueOnce(successResult);
// Should not throw, should return partial results
const result = await wrapper.getAvailabilityWithTimeZones("2024-01-01", "2024-01-31", selectedCalendars, false);
expect(result).toHaveLength(1);
expect(result[0].timeZone).toBe("UTC");
});
});
});