Skip to content
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

chore: Read mail env variables only when needed #37660

Merged
merged 1 commit into from
Nov 23, 2024

Conversation

sharat87
Copy link
Member

@sharat87 sharat87 commented Nov 23, 2024

Loading env variables at import time doesn't work now since we're importing first, and them loading env variables, after having moved to TypeScript.

This PR fixes that in the mailer module.

Automation

/test sanity

🔍 Cypress test results

Caution

If you modify the content in this section, you are likely to disrupt the CI result for your PR.

Communication

Should the DevRel and Marketing teams inform users about this change?

  • Yes
  • No

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling for email configuration by ensuring environment variables are validated before sending emails.
  • Refactor

    • Adjusted the scope of several environment variables to enhance code organization and maintainability.

Copy link
Contributor

coderabbitai bot commented Nov 23, 2024

Walkthrough

The changes in this pull request involve modifying the sendBackupErrorToAdmins function in the mailer.ts file. The environment variable declarations have been moved from the module level to within the function scope, affecting their accessibility and initialization timing. The error handling logic remains unchanged, ensuring that the necessary environment variables are validated before sending emails.

Changes

File Path Change Summary
app/client/packages/rts/src/ctl/mailer.ts Moved declarations of mailEnabled, mailFrom, mailHost, mailPort, mailUser, mailPass, and mailTo from module-level to local scope within sendBackupErrorToAdmins.

Possibly related PRs

Suggested labels

ok-to-test

Suggested reviewers

  • mohanarpit
  • nidhi-nair
  • pratapaprasanna

🌟 In the code where emails fly,
Variables now local, oh my!
From module's reach, they now confine,
Sending errors with a clearer line.
Check those envs, don’t let them stray,
For backups need their mail today! 📧


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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.

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.

@github-actions github-actions bot added the skip-changelog Adding this label to a PR prevents it from being listed in the changelog label Nov 23, 2024
@sharat87 sharat87 marked this pull request as ready for review November 23, 2024 05:38
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

🧹 Outside diff range and nitpick comments (4)
app/client/packages/rts/src/ctl/mailer.ts (4)

7-13: Consider adding type annotations for environment variables

While moving the environment variables into the function scope is good for lazy loading, consider adding proper TypeScript types for better type safety.

-  const mailEnabled = process.env.APPSMITH_MAIL_ENABLED;
-  const mailPort = process.env.APPSMITH_MAIL_PORT;
+  const mailEnabled = process.env.APPSMITH_MAIL_ENABLED as string;
+  const mailPort = parseInt(process.env.APPSMITH_MAIL_PORT ?? '', 10);

Line range hint 17-35: Simplify validation logic and remove redundant check

The validation contains a redundant check for mailEnabled and could be simplified.

    if (
      !mailEnabled ||
      !mailFrom ||
      !mailHost ||
      !mailPort ||
      !mailUser ||
      !mailPass
    ) {
      throw new Error(
        "Failed to send error mail. Email provider is not configured, please refer to https://docs.appsmith.com/setup/instance-configuration/email to configure it.",
      );
    } else if (!mailTo) {
      throw new Error(
        "Failed to send error mail. Admin email(s) not configured, please refer to https://docs.appsmith.com/setup/instance-configuration/disable-user-signup#administrator-emails to configure it.",
      );
-    } else if (!mailEnabled) {
-      throw new Error(
-        "Mail not sent! APPSMITH_MAIL_ENABLED env val is disabled, please refer to https://docs.appsmith.com/setup/instance-configuration/email to enable it.",
-      );
    } else {

Line range hint 55-71: Improve string handling and URL construction

The current implementation uses string concatenation and lacks URL validation.

-      let text =
-        "Appsmith backup did not complete successfully.\n\n " +
-        "Backup timestamp: " +
-        backupTimestamp +
-        "\n\n" +
-        "Last Successful Backup timestamp: " +
-        lastBackupTimestamp;
+      let text = `Appsmith backup did not complete successfully.
+
+Backup timestamp: ${backupTimestamp}
+
+Last Successful Backup timestamp: ${lastBackupTimestamp}`;

       if (domainName) {
+        const protocol = domainName.startsWith('http') ? '' : 'http://';
         text =
-          text +
-          "Link to Appsmith admin settings: " +
-          "http://" +
-          domainName +
-          "/settings/general";
+          `${text}
+Link to Appsmith admin settings: ${protocol}${domainName}/settings/general`;
       }

Line range hint 82-97: Improve email transport configuration

The email transport configuration could be improved with proper types and timeout.

+      const port = typeof mailPort === 'string' ? parseInt(mailPort, 10) : mailPort;
       const transporter = nodemailer.createTransport({
         host: mailHost,
-        port: mailPort,
+        port,
         auth: {
           user: mailUser,
           pass: mailPass,
-        },
+        },
+        pool: true,
+        maxConnections: 1,
+        rateDelta: 20000,
+        rateLimit: 5,
       } as any);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 86d17a6 and 094fc08.

📒 Files selected for processing (1)
  • app/client/packages/rts/src/ctl/mailer.ts (1 hunks)
🔇 Additional comments (1)
app/client/packages/rts/src/ctl/mailer.ts (1)

6-14: Verify the timing of environment variable loading

The changes correctly move environment variable loading to runtime, addressing the original issue. Let's verify there are no other instances of mail-related environment variables being loaded at import time.

✅ Verification successful

Let me verify if these environment variables are accessed at import time by checking if they are used outside of functions.


Environment variables are correctly accessed at runtime

All mail-related environment variables are accessed within the sendBackupErrorToAdmins function and not at import time. The changes successfully address the original concern.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining mail-related environment variable access at import time
rg "process\.env\.APPSMITH_MAIL" --type ts

Length of output: 616


Script:

#!/bin/bash
# Show the full context of mailer.ts to verify if env vars are accessed at import time
cat app/client/packages/rts/src/ctl/mailer.ts

Length of output: 3056

@sharat87 sharat87 merged commit a4d35d2 into release Nov 23, 2024
19 checks passed
@sharat87 sharat87 deleted the chore/ctl-mail-env-vars branch November 23, 2024 11:39
github-actions bot pushed a commit to Zeral-Zhang/appsmith that referenced this pull request Nov 27, 2024
Loading env variables at import time doesn't work now since we're
importing first, and them loading env variables, after having moved to
TypeScript.

This PR fixes that in the mailer module.


## Automation

/test sanity

### 🔍 Cypress test results
<!-- This is an auto-generated comment: Cypress test results  -->
> [!CAUTION]  
> If you modify the content in this section, you are likely to disrupt
the CI result for your PR.

<!-- end of auto-generated comment: Cypress test results  -->


## Communication
Should the DevRel and Marketing teams inform users about this change?
- [ ] Yes
- [x] No


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Bug Fixes**
- Improved error handling for email configuration by ensuring
environment variables are validated before sending emails.

- **Refactor**
- Adjusted the scope of several environment variables to enhance code
organization and maintainability.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
skip-changelog Adding this label to a PR prevents it from being listed in the changelog
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants