Skip to content

fix: refactor i18n loadTranslations and set timeout to 3s #22878

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
merged 13 commits into from
Aug 4, 2025

Conversation

hbjORbj
Copy link
Contributor

@hbjORbj hbjORbj commented Aug 4, 2025

What does this PR do?

  • Add validations for locale and ns, and fallback to Engllish and common namespace
  • Add 3s max timeout as well (fetch gets aborted if not completed within 3s)

Mandatory Tasks (DO NOT REMOVE)

  • I have self-reviewed the code (A decent size PR without self-review might be rejected).
  • N/A - I have updated the developer docs in /docs if this PR makes changes that would require a documentation change. If N/A, write N/A here and check the checkbox.
  • I confirm automated tests are in place that prove my fix is effective or that my feature works.

How should this be tested?

  • Please use the latest Vercel preview and test please 🙏.

@graphite-app graphite-app bot requested a review from a team August 4, 2025 02:21
Copy link
Contributor

coderabbitai bot commented Aug 4, 2025

Walkthrough

This change updates the mock implementation of the getTranslation function from the @calcom/lib/server/i18n module across multiple test files to be asynchronous, accepting locale and namespace parameters and returning a translation function with these properties attached. Additionally, the production implementation of loadTranslations in packages/lib/server/i18n.ts is refactored to remove fallback logic, validate locales and namespaces, utilize a new fetchWithTimeout utility, and improve error handling. The new fetchWithTimeout function is introduced to perform HTTP fetch requests with a timeout. No changes are made to exported or public entity declarations except for the addition of fetchWithTimeout.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 05b6913 and 322d731.

📒 Files selected for processing (1)
  • packages/lib/server/i18n.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/lib/server/i18n.ts
⏰ 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). (2)
  • GitHub Check: required
  • GitHub Check: Codacy Static Code Analysis
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/i18n-fix-refactor

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.
    • @coderabbitai modularize this function.
  • 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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.

@hbjORbj hbjORbj changed the title fix: i18n fix refactor fix: refactor i18n loadTranslations and set timeout to 3s Aug 4, 2025
@hbjORbj hbjORbj marked this pull request as draft August 4, 2025 02:22
@keithwillcode keithwillcode added core area: core, team members only foundation labels Aug 4, 2025
@dosubot dosubot bot added automated-tests area: unit tests, e2e tests, playwright i18n area: i18n, translations labels Aug 4, 2025
Copy link

graphite-app bot commented Aug 4, 2025

Graphite Automations

"Add consumer team as reviewer" took an action on this PR • (08/04/25)

1 reviewer was added to this PR based on Keith Williams's automation.

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/fetchWithTimeout.ts (1)

1-13: LGTM! Clean timeout implementation with minor enhancement opportunities.

The fetchWithTimeout utility correctly implements timeout functionality using AbortController. The finally block ensures timeout cleanup.

Consider these enhancements:

-export async function fetchWithTimeout(url: string, options: RequestInit = {}, timeoutMs: number) {
+export async function fetchWithTimeout(url: string, options: RequestInit = {}, timeoutMs: number = 5000) {
+  if (timeoutMs <= 0) {
+    throw new Error('Timeout must be positive');
+  }
+  
   const controller = new AbortController();
   const timeout = setTimeout(() => controller.abort(), timeoutMs);
   try {
     const response = await fetch(url, {
       ...options,
       signal: controller.signal,
     });
     return response;
+  } catch (error) {
+    if (error instanceof Error && error.name === 'AbortError') {
+      throw new Error(`Request timed out after ${timeoutMs}ms`);
+    }
+    throw error;
   } finally {
     clearTimeout(timeout);
   }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b7e11dc and 05b6913.

📒 Files selected for processing (9)
  • apps/web/test/lib/handleChildrenEventTypes.test.ts (1 hunks)
  • packages/features/ee/billing/credit-service.test.ts (1 hunks)
  • packages/features/ee/organizations/lib/server/createOrganizationFromOnboarding.test.ts (1 hunks)
  • packages/features/ee/workflows/lib/reminders/reminderScheduler.test.ts (1 hunks)
  • packages/features/ee/workflows/lib/test/compareReminderBodyToTemplate.test.ts (2 hunks)
  • packages/lib/fetchWithTimeout.ts (1 hunks)
  • packages/lib/server/i18n.ts (1 hunks)
  • packages/lib/server/repository/user.test.ts (1 hunks)
  • packages/lib/server/service/userCreationService.test.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/features/ee/workflows/lib/reminders/reminderScheduler.test.ts
  • packages/features/ee/organizations/lib/server/createOrganizationFromOnboarding.test.ts
  • packages/features/ee/billing/credit-service.test.ts
  • packages/features/ee/workflows/lib/test/compareReminderBodyToTemplate.test.ts
  • packages/lib/server/repository/user.test.ts
  • packages/lib/fetchWithTimeout.ts
  • packages/lib/server/i18n.ts
  • apps/web/test/lib/handleChildrenEventTypes.test.ts
  • packages/lib/server/service/userCreationService.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/features/ee/workflows/lib/reminders/reminderScheduler.test.ts
  • packages/features/ee/organizations/lib/server/createOrganizationFromOnboarding.test.ts
  • packages/features/ee/billing/credit-service.test.ts
  • packages/features/ee/workflows/lib/test/compareReminderBodyToTemplate.test.ts
  • packages/lib/server/repository/user.test.ts
  • packages/lib/fetchWithTimeout.ts
  • packages/lib/server/i18n.ts
  • apps/web/test/lib/handleChildrenEventTypes.test.ts
  • packages/lib/server/service/userCreationService.test.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: CR
PR: calcom/cal.com#0
File: .cursor/rules/review.mdc:0-0
Timestamp: 2025-07-28T11:50:23.946Z
Learning: For large pull requests (>500 lines changed or >10 files touched), advise splitting into smaller, focused PRs by feature, layer, dependency chain, or file/module
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 **/*.tsx : Always use `t()` for text localization in frontend code; direct text embedding should trigger a warning
Learnt from: bandhan-majumder
PR: calcom/cal.com#22359
File: packages/lib/server/locales/en/common.json:1336-1339
Timestamp: 2025-07-14T16:31:45.233Z
Learning: When making localization changes for new features, it's often safer to add new strings rather than modify existing ones to avoid breaking existing functionality that depends on the original strings. This approach allows for feature-specific customization while maintaining backward compatibility.
📚 Learning: applies to **/*.tsx : always use `t()` for text localization in frontend code; direct text embedding...
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 **/*.tsx : Always use `t()` for text localization in frontend code; direct text embedding should trigger a warning

Applied to files:

  • packages/features/ee/workflows/lib/reminders/reminderScheduler.test.ts
  • packages/features/ee/workflows/lib/test/compareReminderBodyToTemplate.test.ts
  • packages/lib/server/repository/user.test.ts
  • packages/lib/server/i18n.ts
  • apps/web/test/lib/handleChildrenEventTypes.test.ts
  • packages/lib/server/service/userCreationService.test.ts
📚 Learning: when making localization changes for new features, it's often safer to add new strings rather than m...
Learnt from: bandhan-majumder
PR: calcom/cal.com#22359
File: packages/lib/server/locales/en/common.json:1336-1339
Timestamp: 2025-07-14T16:31:45.233Z
Learning: When making localization changes for new features, it's often safer to add new strings rather than modify existing ones to avoid breaking existing functionality that depends on the original strings. This approach allows for feature-specific customization while maintaining backward compatibility.

Applied to files:

  • packages/lib/server/i18n.ts
🧬 Code Graph Analysis (1)
packages/lib/server/i18n.ts (3)
packages/config/next-i18next.config.d.ts (1)
  • i18n (2-5)
packages/lib/constants.ts (1)
  • WEBAPP_URL (12-18)
packages/lib/fetchWithTimeout.ts (1)
  • fetchWithTimeout (1-13)
⏰ 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: Detect changes
🔇 Additional comments (12)
packages/features/ee/billing/credit-service.test.ts (1)

28-37: LGTM! Consistent i18n mock implementation.

The async getTranslation mock properly simulates the real i18n behavior by returning a translation function with attached locale and namespace properties. This standardizes testing across the codebase.

packages/features/ee/organizations/lib/server/createOrganizationFromOnboarding.test.ts (1)

46-55: LGTM! Consistent i18n mock pattern.

The i18n mock follows the same async pattern established across other test files, ensuring consistent behavior when testing organization creation workflows that depend on translations.

packages/features/ee/workflows/lib/reminders/reminderScheduler.test.ts (1)

20-29: LGTM! Standardized i18n mock for workflow testing.

The async getTranslation mock maintains consistency with the established pattern, enabling proper testing of reminder scheduling workflows without translation dependency.

packages/features/ee/workflows/lib/test/compareReminderBodyToTemplate.test.ts (2)

2-2: LGTM! Added vi import for mocking.

The import update correctly adds vi to support the new i18n mock implementation.


13-22: LGTM! Consistent async i18n mock for template testing.

The i18n mock maintains the established async pattern and supports the actual getTranslation calls used in the template comparison tests (lines 89, 106, 122, 136, 152).

packages/lib/server/repository/user.test.ts (1)

12-16: LGTM! Mock implementation correctly simulates async behavior.

The updated mock properly reflects the new asynchronous signature of getTranslation with locale and namespace parameters, while maintaining the test behavior of returning keys unchanged. The addition of locale and namespace properties on the returned function aligns with the production implementation structure.

apps/web/test/lib/handleChildrenEventTypes.test.ts (1)

29-34: LGTM! Consistent mock implementation across test files.

The mock update maintains consistency with other test files in the codebase, properly simulating the new async getTranslation function signature while preserving test functionality.

packages/lib/server/service/userCreationService.test.ts (1)

14-18: LGTM! Consistent mock implementation maintained.

The mock implementation follows the same pattern as other test files in this refactor, ensuring consistency across the test suite.

packages/lib/server/i18n.ts (4)

3-3: LGTM! Improved imports and constants.

The new imports enhance the implementation:

  • i18n config enables proper locale validation
  • fetchWithTimeout adds timeout capability for reliability
  • logger provides better error handling than console methods
  • SUPPORTED_NAMESPACES constant improves maintainability

Also applies to: 6-7, 11-11


19-22: LGTM! Enhanced input validation.

The locale and namespace validation logic is well-implemented:

  • Handles zh → zh-CN mapping consistently
  • Validates against supported locales with fallback to "en"
  • Validates namespaces with fallback to "common"

29-36: LGTM! Improved network reliability with timeout.

The use of fetchWithTimeout with a 3-second timeout enhances reliability by preventing hanging requests. The cache policy appropriately differs between production and development environments.


38-46: No runtime errors from empty fallback translations
After inspecting loadTranslations and getTranslation, returning {} on fetch failure simply initializes i18next with an empty resource object. The getFixedT function still returns a valid translator and will fall back to returning the key (rather than throwing). There are no code paths that directly index into the raw translations object, so this change won’t cause runtime exceptions—at worst, untranslated keys will surface in the UI.

Copy link

vercel bot commented Aug 4, 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 4, 2025 4:50am
cal-eu ⬜️ Ignored (Inspect) Aug 4, 2025 4:50am

@hbjORbj hbjORbj marked this pull request as ready for review August 4, 2025 02:40
@hbjORbj hbjORbj requested a review from emrysal August 4, 2025 02:40
@dosubot dosubot bot added the 💻 refactor label Aug 4, 2025
Comment on lines +3 to +4
/* eslint-disable @typescript-eslint/no-var-requires */
const { i18n } = require("@calcom/config/next-i18next.config");
Copy link
Contributor Author

@hbjORbj hbjORbj Aug 4, 2025

Choose a reason for hiding this comment

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

@emrysal

  • If we use ESModule syntax here, packages/platform/libraries build starts failing.
  • We already do this same pattern already apparently here and here
  • Not 100% convinced why not using CommonJS syntax breaks platform/libraries build though, do you know why?

Copy link
Contributor

github-actions bot commented Aug 4, 2025

E2E results are ready!

Copy link
Contributor

@emrysal emrysal left a comment

Choose a reason for hiding this comment

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

lgtm 👍 (attempt #2 😎)

@emrysal emrysal merged commit 4061bfb into main Aug 4, 2025
40 checks passed
@emrysal emrysal deleted the fix/i18n-fix-refactor branch August 4, 2025 09:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automated-tests area: unit tests, e2e tests, playwright core area: core, team members only foundation i18n area: i18n, translations ready-for-e2e 💻 refactor
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants