Skip to content

Comments

fix: Faulty logic around shouldServeCache#24465

Merged
emrysal merged 6 commits intomainfrom
fix-shouldServeCache
Oct 15, 2025
Merged

fix: Faulty logic around shouldServeCache#24465
emrysal merged 6 commits intomainfrom
fix-shouldServeCache

Conversation

@joeauyeung
Copy link
Contributor

What does this PR do?

  • Fixes a bug where getShouldServeCache was returning undefined when no teamId was passed
  • Changes a shouldServeCache === false check to !shouldServeCache to handle all falsey values

@keithwillcode keithwillcode added core area: core, team members only enterprise area: enterprise, audit log, organisation, SAML, SSO labels Oct 14, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 14, 2025

Walkthrough

  • packages/app-store/googlecalendar/lib/CalendarService.ts: getFreeBusyResult now uses a falsy check (!shouldServeCache) instead of shouldServeCache === false to decide fetching fresh availability.
  • packages/app-store/googlecalendar/lib/tests/getFreeBusyResult.test.ts: Adds tests verifying that falsy shouldServeCache values (false, undefined, null, 0, "") trigger fetchAvailability and return expected busy data.
  • packages/features/calendar-cache/lib/getShouldServeCache.ts: When shouldServeCache is not a boolean and teamId is not provided, the function now returns false (previously undefined); with teamId, it still delegates to featuresRepository.checkIfTeamHasFeature for "calendar-cache-serve".
  • packages/features/calendar-cache/lib/getShouldServeCache.test.ts: Adds tests covering explicit booleans, undefined/null/0 cases, teamId feature checks, and precedence of explicit shouldServeCache.

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title succinctly describes the core change by indicating a fix to the faulty logic around the shouldServeCache condition, matching the primary purpose of the pull request.
Description Check ✅ Passed The description directly outlines the bug in getShouldServeCache and explains how the condition was updated to handle all falsy values, clearly relating to the actual code changes in the pull request.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-shouldServeCache

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

devin-ai-integration bot added a commit that referenced this pull request Oct 14, 2025
- Add tests for CacheService.getShouldServeCache to verify it returns false when no teamId is provided (instead of undefined)
- Add tests for GoogleCalendarService.getFreeBusyResult to verify the falsey check properly handles undefined, null, 0, empty string, and false values
- All tests verify the fix in PR #24465 which changes undefined return to false and changes === false check to !shouldServeCache

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>
@vercel
Copy link

vercel bot commented Oct 14, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

2 Skipped Deployments
Project Deployment Preview Comments Updated (UTC)
cal Ignored Ignored Oct 15, 2025 10:48am
cal-eu Ignored Ignored Oct 15, 2025 10:48am

- Add tests for CacheService.getShouldServeCache to verify it returns false when no teamId is provided (instead of undefined)
- Add tests for GoogleCalendarService.getFreeBusyResult to verify the falsey check properly handles undefined, null, 0, empty string, and false values
- All tests verify the fix in PR #24465 which changes undefined return to false and changes === false check to !shouldServeCache

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>
@joeauyeung joeauyeung marked this pull request as ready for review October 15, 2025 00:06
@joeauyeung joeauyeung requested a review from a team as a code owner October 15, 2025 00:06
@graphite-app graphite-app bot requested a review from a team October 15, 2025 00:06
@dosubot dosubot bot added the 🐛 bug Something isn't working label Oct 15, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/app-store/googlecalendar/lib/CalendarService.ts (1)

56-56: Consider using named export instead of default export.

The coding guidelines recommend named exports over default exports for better tree-shaking, easier refactoring, and clearer imports.

As per coding guidelines.

Apply this diff to convert to a named export:

-export default class GoogleCalendarService implements Calendar {
+export class GoogleCalendarService implements Calendar {

Then update imports across the codebase from:

import GoogleCalendarService from "./CalendarService";

to:

import { GoogleCalendarService } from "./CalendarService";
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 003aaaa and 1842e17.

📒 Files selected for processing (4)
  • packages/app-store/googlecalendar/lib/CalendarService.ts (1 hunks)
  • packages/app-store/googlecalendar/lib/__tests__/getFreeBusyResult.test.ts (1 hunks)
  • packages/features/calendar-cache/lib/getShouldServeCache.test.ts (1 hunks)
  • packages/features/calendar-cache/lib/getShouldServeCache.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/review.mdc)

**/*.ts: For Prisma queries, only select data you need; never use include, always use select
Ensure the credential.key field is never returned from tRPC endpoints or APIs

Files:

  • packages/features/calendar-cache/lib/getShouldServeCache.test.ts
  • packages/features/calendar-cache/lib/getShouldServeCache.ts
  • packages/app-store/googlecalendar/lib/__tests__/getFreeBusyResult.test.ts
  • packages/app-store/googlecalendar/lib/CalendarService.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/review.mdc)

Flag excessive Day.js use in performance-critical code; prefer native Date or Day.js .utc() in hot paths like loops

Files:

  • packages/features/calendar-cache/lib/getShouldServeCache.test.ts
  • packages/features/calendar-cache/lib/getShouldServeCache.ts
  • packages/app-store/googlecalendar/lib/__tests__/getFreeBusyResult.test.ts
  • packages/app-store/googlecalendar/lib/CalendarService.ts
**/*.{ts,tsx,js,jsx}

⚙️ CodeRabbit configuration file

Flag default exports and encourage named exports. Named exports provide better tree-shaking, easier refactoring, and clearer imports. Exempt main components like pages, layouts, and components that serve as the primary export of a module.

Files:

  • packages/features/calendar-cache/lib/getShouldServeCache.test.ts
  • packages/features/calendar-cache/lib/getShouldServeCache.ts
  • packages/app-store/googlecalendar/lib/__tests__/getFreeBusyResult.test.ts
  • packages/app-store/googlecalendar/lib/CalendarService.ts
**/*Service.ts

📄 CodeRabbit inference engine (.cursor/rules/review.mdc)

Service files must include Service suffix, use PascalCase matching exported class, and avoid generic names (e.g., MembershipService.ts)

Files:

  • packages/app-store/googlecalendar/lib/CalendarService.ts
🧠 Learnings (1)
📚 Learning: 2025-08-05T12:04:29.037Z
Learnt from: din-prajapati
PR: calcom/cal.com#21854
File: packages/app-store/office365calendar/__tests__/unit_tests/SubscriptionManager.test.ts:0-0
Timestamp: 2025-08-05T12:04:29.037Z
Learning: In packages/app-store/office365calendar/lib/CalendarService.ts, the fetcher method in Office365CalendarService class is public, not private. It was specifically changed from private to public in this PR to support proper testing and external access patterns.

Applied to files:

  • packages/app-store/googlecalendar/lib/CalendarService.ts
⏰ Context from checks skipped due to timeout of 180000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Install dependencies / Yarn install & cache
🔇 Additional comments (4)
packages/app-store/googlecalendar/lib/CalendarService.ts (1)

469-469: LGTM: Falsy check correctly handles all non-cache cases.

The change from shouldServeCache === false to !shouldServeCache correctly handles all falsy values (including undefined returned by getShouldServeCache when no teamId is provided). This ensures the cache is properly bypassed when it shouldn't be served.

packages/app-store/googlecalendar/lib/__tests__/getFreeBusyResult.test.ts (1)

1-135: LGTM: Comprehensive test coverage for falsy value handling.

The test suite thoroughly validates that getFreeBusyResult immediately calls fetchAvailability for all falsy shouldServeCache values (false, undefined, null, 0, ""), confirming the fix works as intended.

packages/features/calendar-cache/lib/getShouldServeCache.test.ts (1)

1-90: LGTM: Excellent test coverage for all scenarios.

The test suite comprehensively validates:

  • Explicit boolean values take precedence over teamId checks
  • undefined with no/falsy teamId returns false without repository calls
  • Valid teamId triggers feature flag check via repository
  • Return value matches repository result

This confirms the bug fix and ensures correct behavior across all edge cases.

packages/features/calendar-cache/lib/getShouldServeCache.ts (1)

12-12: Approved: explicit false return for !teamId is correct—tests verify teamId = 0 returns false.

volnei
volnei previously approved these changes Oct 15, 2025
- Fix private credential property access by using type assertion
- Add missing IFeaturesRepository methods to mock

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/app-store/googlecalendar/lib/__tests__/getFreeBusyResult.test.ts (4)

10-34: Optional: Consider a cleaner mock setup pattern.

The current approach of creating an empty object, manually attaching methods, and binding the prototype works but is somewhat unconventional. For better type safety and clarity, consider using a partial mock or creating a minimal test double with the required properties.

Example alternative:

-    calendarService = {} as CalendarService;
-
-    const mockFetchAvailability = vi.fn().mockResolvedValue({
+    const mockFetchAvailability = vi.fn().mockResolvedValue({
       calendars: {
         "test@example.com": {
           busy: [
@@ -25,11 +23,11 @@
         },
       },
     });
 
-    calendarService.fetchAvailability = mockFetchAvailability;
+    calendarService = {
+      fetchAvailability: mockFetchAvailability,
+      credential: { id: 1, userId: 1 },
+      getFreeBusyResult: CalendarService.prototype.getFreeBusyResult,
+    } as CalendarService;
     fetchAvailabilitySpy = mockFetchAvailability;
-
-    calendarService.getFreeBusyResult = CalendarService.prototype.getFreeBusyResult.bind(calendarService);
-    // eslint-disable-next-line @typescript-eslint/no-explicit-any
-    (calendarService as any).credential = { id: 1, userId: 1 };

75-93: Reconsider testing non-boolean falsy values.

Tests for null, 0, and "" as shouldServeCache values require type assertions to bypass TypeScript, indicating these are not part of the actual type contract (likely boolean | undefined). Testing exotic falsy values that cannot occur in production adds maintenance burden without improving coverage.

Consider removing these tests or consolidating them into a single edge-case test if there's a specific runtime scenario where non-boolean values might occur.

Also applies to: 95-113, 115-133


37-133: Reduce test duplication with parameterized tests.

All five test cases follow an identical structure with only the shouldServeCache value varying. Vitest supports test.each for parameterized tests, which would significantly reduce duplication and improve maintainability.

Example refactor:

test.each([
  { value: false, description: "explicitly false" },
  { value: undefined, description: "undefined (falsey)" },
])("should call fetchAvailability immediately when shouldServeCache is $description", async ({ value }) => {
  const args = {
    timeMin: new Date().toISOString(),
    timeMax: new Date().toISOString(),
    items: [{ id: "test@example.com" }],
  };

  const result = await calendarService.getFreeBusyResult(args, value);

  expect(fetchAvailabilitySpy).toHaveBeenCalledWith(args);
  expect(fetchAvailabilitySpy).toHaveBeenCalledTimes(1);
  expect(result.calendars?.["test@example.com"]?.busy).toEqual([
    {
      start: "2023-12-01T20:00:00Z",
      end: "2023-12-01T21:00:00Z",
    },
  ]);
});

39-40: Use fixed timestamps for test reproducibility.

Using new Date().toISOString() generates different timestamps on each test run, which can complicate debugging and make tests less reproducible. Since the specific date values don't affect the test logic, prefer fixed timestamps.

Example:

-    const args = {
-      timeMin: new Date().toISOString(),
-      timeMax: new Date().toISOString(),
+    const args = {
+      timeMin: "2023-12-01T10:00:00Z",
+      timeMax: "2023-12-01T12:00:00Z",
       items: [{ id: "test@example.com" }],
     };

Also applies to: 58-59, 77-78, 97-98, 117-118

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1842e17 and ea4d9fd.

📒 Files selected for processing (2)
  • packages/app-store/googlecalendar/lib/__tests__/getFreeBusyResult.test.ts (1 hunks)
  • packages/features/calendar-cache/lib/getShouldServeCache.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/review.mdc)

**/*.ts: For Prisma queries, only select data you need; never use include, always use select
Ensure the credential.key field is never returned from tRPC endpoints or APIs

Files:

  • packages/app-store/googlecalendar/lib/__tests__/getFreeBusyResult.test.ts
  • packages/features/calendar-cache/lib/getShouldServeCache.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/review.mdc)

Flag excessive Day.js use in performance-critical code; prefer native Date or Day.js .utc() in hot paths like loops

Files:

  • packages/app-store/googlecalendar/lib/__tests__/getFreeBusyResult.test.ts
  • packages/features/calendar-cache/lib/getShouldServeCache.test.ts
**/*.{ts,tsx,js,jsx}

⚙️ CodeRabbit configuration file

Flag default exports and encourage named exports. Named exports provide better tree-shaking, easier refactoring, and clearer imports. Exempt main components like pages, layouts, and components that serve as the primary export of a module.

Files:

  • packages/app-store/googlecalendar/lib/__tests__/getFreeBusyResult.test.ts
  • packages/features/calendar-cache/lib/getShouldServeCache.test.ts
⏰ Context from checks skipped due to timeout of 180000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Production builds / Build Docs
  • GitHub Check: Production builds / Build Web App
  • GitHub Check: Production builds / Build API v2
  • GitHub Check: Tests / Unit
  • GitHub Check: Production builds / Build Atoms
  • GitHub Check: Production builds / Build API v1
  • GitHub Check: Type check / check-types
  • GitHub Check: Linters / lint
🔇 Additional comments (1)
packages/features/calendar-cache/lib/getShouldServeCache.test.ts (1)

1-92: LGTM! Excellent test coverage.

The test suite is comprehensive, well-structured, and properly validates all the key scenarios:

  • Explicit boolean values bypassing feature checks
  • Falsy teamId values (undefined, null, 0) correctly returning false
  • Valid teamId delegation to the feature repository
  • Precedence of explicit shouldServeCache over teamId checks

The tests align perfectly with the PR objectives of handling undefined values and ensuring correct cache-serving logic.

@github-actions
Copy link
Contributor

github-actions bot commented Oct 15, 2025

E2E results are ready!

@emrysal emrysal enabled auto-merge (squash) October 15, 2025 10:55
@emrysal emrysal merged commit 17ab088 into main Oct 15, 2025
39 of 40 checks passed
@emrysal emrysal deleted the fix-shouldServeCache branch October 15, 2025 11:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐛 bug Something isn't working core area: core, team members only enterprise area: enterprise, audit log, organisation, SAML, SSO ready-for-e2e size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants