Skip to content

fix: resolve circular dependency in getUserAvailability by extracting getPeriodStartDatesBetween utility #22913

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged

Conversation

zomars
Copy link
Member

@zomars zomars commented Aug 6, 2025

fix: resolve circular dependency in getUserAvailability by extracting getPeriodStartDatesBetween utility

Summary

This PR fixes a circular dependency issue that was causing ReferenceError: Cannot access 'getUserAvailabilityModule' before initialization during fast refresh in development mode.

The Problem:
A circular dependency chain existed between:

  1. packages/lib/di/containers/get-user-availability.ts → imports getUserAvailabilityModule
  2. packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts → imports getUserAvailabilityService
  3. packages/lib/getUserAvailability.ts → imports getBusyTimesFromLimits

This caused module initialization order issues during fast refresh, breaking the development experience.

The Solution:

  • Extracted getPeriodStartDatesBetween into a standalone utility function at packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • Updated getBusyTimesFromLimits.ts to import the utility directly instead of calling through the service
  • Modified UserAvailabilityService to delegate to the utility function, preserving the existing API
  • Breaks the circular dependency chain while maintaining all existing functionality

Review & Testing Checklist for Human

  • Test fast refresh functionality - Make changes to files in the affected modules and verify the ReferenceError: Cannot access 'getUserAvailabilityModule' before initialization no longer occurs
  • Verify availability calculations work correctly - Test booking flows, availability checks, and interval limits to ensure no functional regressions
  • Test edge cases - Verify timezone handling, period calculations, and boundary conditions work the same as before
  • Run full test suite - Ensure no existing tests are broken by the refactoring
  • Check for new circular dependencies - Verify the solution didn't introduce new circular dependency issues elsewhere

Recommended Test Plan:

  1. Start development server with yarn dev
  2. Make changes to files in packages/lib/getUserAvailability.ts and packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
  3. Verify fast refresh works without errors
  4. Test booking creation with various interval limits (daily, weekly, monthly)
  5. Test availability queries across different timezones
  6. Verify existing booking limit functionality still works

Diagram

%%{ init : { "theme" : "default" }}%%
graph TD
    Container["packages/lib/di/containers/<br/>get-user-availability.ts"]:::context
    GetUserAvail["packages/lib/<br/>getUserAvailability.ts"]:::minor-edit
    GetBusyTimes["packages/lib/intervalLimits/server/<br/>getBusyTimesFromLimits.ts"]:::minor-edit
    NewUtil["packages/lib/intervalLimits/utils/<br/>getPeriodStartDatesBetween.ts"]:::major-edit
    
    Container -->|"loads module"| GetUserAvail
    GetBusyTimes -.->|"OLD: imported service<br/>(caused circular dep)"| Container
    GetBusyTimes -->|"NEW: imports utility<br/>(breaks circular dep)"| NewUtil
    GetUserAvail -->|"delegates to"| NewUtil
    GetUserAvail -.->|"OLD: imported by<br/>getBusyTimesFromLimits"| GetBusyTimes
    
    subgraph Legend
        L1["Major Edit"]:::major-edit
        L2["Minor Edit"]:::minor-edit  
        L3["Context/No Edit"]:::context
    end

    classDef major-edit fill:#90EE90
    classDef minor-edit fill:#87CEEB
    classDef context fill:#FFFFFF
Loading

Notes

  • The extracted utility function maintains the same signature and behavior as the original method
  • All existing functionality is preserved through delegation in the UserAvailabilityService
  • TypeScript compilation passes and the development server runs without circular dependency errors
  • The solution follows the existing codebase patterns for utility functions and maintains the withReporting wrapper

Session Details:

… getPeriodStartDatesBetween utility

- Extract getPeriodStartDatesBetween into standalone utility function
- Remove dependency on getUserAvailabilityService from getBusyTimesFromLimits.ts
- Update UserAvailabilityService to delegate to utility function
- Breaks circular dependency chain while preserving all existing functionality
- Fixes ReferenceError during fast refresh in development mode

Co-Authored-By: zomars@cal.com <zomars@me.com>
Copy link
Contributor

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR that start with 'DevinAI'.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment and CI monitoring

Copy link
Contributor

coderabbitai bot commented Aug 6, 2025

Walkthrough

The changes refactor how the calculation of period start dates between two dates is handled across the codebase. The internal method for generating these dates within the UserAvailabilityService class has been removed and replaced by a call to a new shared utility function, getPeriodStartDatesBetween, now located in a dedicated utility module. This utility function is also adopted in other modules, replacing previous calls to the class method. The new utility function is implemented with an internal helper and is wrapped with Sentry error reporting. No changes were made to the signatures of public methods, except for the relocation of logic. Additionally, the dependency version of @calcom/platform-libraries was updated in one API package.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b15294c and 65cbff5.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (1)
  • apps/api/v2/package.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/api/v2/package.json
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Install dependencies / Yarn install & cache
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch devin/1754453316-fix-circular-dependency-get-user-availability

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@keithwillcode keithwillcode added core area: core, team members only foundation labels Aug 6, 2025
Copy link
Member Author

@zomars zomars left a comment

Choose a reason for hiding this comment

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

cc @calcom/foundation this is causing issues with local development

@zomars zomars marked this pull request as ready for review August 6, 2025 04:36
@zomars zomars requested a review from a team as a code owner August 6, 2025 04:36
@zomars zomars enabled auto-merge (squash) August 6, 2025 04:36
@dosubot dosubot bot added the 💻 refactor label Aug 6, 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/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)

7-22: Consider optimizing Day.js usage in the loop for performance.

The while loop creates new Day.js objects on each iteration (line 19: startDate.add(1, period)), which could impact performance in hot paths. Per coding guidelines, excessive Day.js use should be flagged in performance-critical code.

However, given the complexity of timezone-aware period calculations and the need for .startOf(), .endOf(), and .add() operations, the current Day.js approach may be necessary for correctness.

Consider profiling this function if it becomes a bottleneck, especially for large date ranges or frequent calls.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5d0dc3f and b15294c.

📒 Files selected for processing (3)
  • packages/lib/getUserAvailability.ts (2 hunks)
  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (3 hunks)
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.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/lib/intervalLimits/server/getBusyTimesFromLimits.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/getUserAvailability.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/lib/intervalLimits/server/getBusyTimesFromLimits.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/getUserAvailability.ts
🧠 Learnings (5)
📓 Common learnings
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.
📚 Learning: in packages/app-store/office365calendar/lib/calendarservice.ts, the fetcher method in office365calen...
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/lib/intervalLimits/server/getBusyTimesFromLimits.ts
  • packages/lib/getUserAvailability.ts
📚 Learning: applies to **/*.{ts,tsx} : flag excessive day.js use in performance-critical code; prefer native dat...
Learnt from: CR
PR: calcom/cal.com#0
File: .cursor/rules/review.mdc:0-0
Timestamp: 2025-07-28T11:50:23.946Z
Learning: Applies to **/*.{ts,tsx} : Flag excessive Day.js use in performance-critical code; prefer native Date or Day.js `.utc()` in hot paths like loops

Applied to files:

  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
  • packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts
  • packages/lib/getUserAvailability.ts
📚 Learning: the office365calendar webhook handler in packages/app-store/office365calendar/api/webhook.ts is spec...
Learnt from: vijayraghav-io
PR: calcom/cal.com#21072
File: packages/app-store/office365calendar/api/webhook.ts:120-123
Timestamp: 2025-07-18T17:57:16.395Z
Learning: The office365calendar webhook handler in packages/app-store/office365calendar/api/webhook.ts is specifically designed for Office365 calendar integration, not as a generic webhook handler. Therefore, it's safe to assume that fetchAvailabilityAndSetCache method will be implemented in the Office365CalendarService, making explicit validation checks unnecessary.

Applied to files:

  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
📚 Learning: in the insightsbookingservice (packages/lib/server/service/insightsbooking.ts), the constructor stor...
Learnt from: eunjae-lee
PR: calcom/cal.com#22702
File: packages/lib/server/service/insightsBooking.ts:120-124
Timestamp: 2025-07-24T08:39:06.185Z
Learning: In the InsightsBookingService (packages/lib/server/service/insightsBooking.ts), the constructor stores null for invalid options or filters but this is handled safely through null checks in buildFilterConditions() and buildAuthorizationConditions() methods. The service uses defensive programming to return safe fallback conditions (null or NOTHING_CONDITION) rather than throwing errors on invalid inputs.

Applied to files:

  • packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts
🧬 Code Graph Analysis (1)
packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (1)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)
  • getPeriodStartDatesBetween (24-24)
🔇 Additional comments (6)
packages/lib/intervalLimits/utils/getPeriodStartDatesBetween.ts (1)

24-24: LGTM! Proper error reporting integration.

The utility function is correctly wrapped with Sentry error reporting, maintaining consistency with the existing codebase patterns.

packages/lib/intervalLimits/server/getBusyTimesFromLimits.ts (3)

6-6: LGTM! Proper import of the new utility.

The import correctly references the extracted utility function, which will break the circular dependency.


108-108: LGTM! Service dependency successfully removed.

The direct call to getPeriodStartDatesBetween utility replaces the previous dependency on userAvailabilityService.getPeriodStartDatesBetween, effectively breaking the circular dependency while maintaining the same functionality.


170-170: LGTM! Consistent replacement in duration limits function.

The utility function is used consistently across both booking limits and duration limits functions, ensuring uniform behavior.

packages/lib/getUserAvailability.ts (2)

40-40: LGTM! Proper import with alias to avoid naming conflicts.

The import uses a clear alias getPeriodStartDatesBetweenUtil to distinguish from the class method, preventing any naming confusion.


599-603: LGTM! Clean delegation preserves existing API.

The public method now properly delegates to the shared utility while maintaining:

  • The same method signature and parameter types
  • Sentry error reporting wrapper consistency
  • Backward compatibility for existing callers

This completes the circular dependency resolution by having the service use the shared utility instead of maintaining its own implementation.

Copy link
Contributor

github-actions bot commented Aug 6, 2025

E2E results are ready!

Copy link

vercel bot commented Aug 6, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
cal ⬜️ Ignored (Inspect) Aug 6, 2025 5:44am
cal-eu ⬜️ Ignored (Inspect) Aug 6, 2025 5:44am

@ThyMinimalDev ThyMinimalDev requested a review from a team as a code owner August 6, 2025 05:44
@zomars zomars merged commit badd0de into main Aug 6, 2025
36 of 37 checks passed
@zomars zomars deleted the devin/1754453316-fix-circular-dependency-get-user-availability branch August 6, 2025 06:10
Pallava-Joshi pushed a commit to Pallava-Joshi/cal.com that referenced this pull request Aug 8, 2025
… getPeriodStartDatesBetween utility (calcom#22913)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants