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

Docker setup in Setup Script #3187

Conversation

VanshikaSabharwal
Copy link
Contributor

@VanshikaSabharwal VanshikaSabharwal commented Jan 6, 2025

What kind of change does this PR introduce?

feature

Issue Number:

Fixes #2446

Previous PR:- #2615

Did you add tests for your changes?

No

Snapshots/Videos:

Screen.Recording.2025-01-06.001224.mp4

If relevant, did you update the documentation?

Summary

Does this PR introduce a breaking change?

Other information

Have you read the contributing guide?

Yes

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced setup process with improved Docker configuration options.
    • Added ability to set a custom port for the application.
    • Introduced more robust environment file management.
  • Improvements

    • Streamlined user interaction during setup.
    • Improved error handling for configuration steps.
    • Added validation for port and API URL inputs.
  • Bug Fixes

    • Resolved potential configuration inconsistencies.
    • Improved handling of environment variable updates.

Copy link
Contributor

coderabbitai bot commented Jan 6, 2025

Walkthrough

The pull request introduces significant enhancements to the setup process for Talawa Admin, focusing on improving Docker configuration, port management, and environment variable handling. The changes involve creating modular functions for different setup tasks, such as Docker option selection, port configuration, and Talawa API URL setup. The implementation emphasizes error handling, user interaction, and flexibility in the installation process, making it more robust and user-friendly.

Changes

File Change Summary
setup.ts Refactored main setup function with improved error handling and modular function calls. Added functions for Docker options, port, and reCAPTCHA setup.
src/setup/askAndSetDockerOption/... New module for handling Docker configuration options with user prompts and environment file updates.
src/setup/askAndUpdatePort/... New module for managing custom port configuration with user interaction and validation.
src/setup/askForDocker/... Added functions for Docker port and Talawa API URL configuration with validation and error handling.
src/setup/updateEnvFile/... Implemented utility function for updating .env file dynamically with error handling.
src/setup/validateRecaptcha/... Introduced validation function for reCAPTCHA with accompanying test suite.

Assessment against linked issues

Objective Addressed Explanation
Make setup script foolproof
Improve script intuitiveness
Simplify installation process
Comprehensive testing
Maintain configuration file integrity

Possibly related PRs

Suggested labels

test

Suggested reviewers

  • palisadoes
  • varshith257
  • DMills27

Poem

🐰 A Setup Script's Tale 🐰
With Docker and ports in sight,
Our rabbit hops through config's might,
Prompts dancing, errors kept at bay,
Talawa Admin finds its way!
Simplicity reigns, setup's delight! 🚀


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

Copy link

github-actions bot commented Jan 6, 2025

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

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 (14)
setup.ts (2)

11-42: Consider clarifying the user prompt for reCAPTCHA.
Users might be unsure where to obtain a valid site key. Training them to visit official reCAPTCHA admin pages or project docs can help.


Line range hint 44-57: Use consistent environment variable naming.
"ALLOW_LOGS" might conflict with or confuse other environment variables. Consider a more descriptive naming convention, such as "TALAWA_ADMIN_LOG_ERRORS."

-    updateEnvFile('ALLOW_LOGS', 'YES');
+    updateEnvFile('TALAWA_ADMIN_LOG_ERRORS', 'YES');
src/setup/askForDocker/askForDocker.ts (2)

5-10: Replace mock implementation with real checks for production.
checkConnection is marked as a mock. In a production setup, consider implementing an actual connectivity check (e.g., health-check endpoint).


32-99: Handle partial 'localhost' matches carefully.
Lines 83-94 replace 'localhost' with 'host.docker.internal'. If 'localhost' appears elsewhere in the URL (e.g., path, querystrings), it might cause unexpected rewriting. Consider stricter URL parsing or user disclaimers.

src/setup/updateEnvFile/updateEnvFile.ts (1)

3-19: Check for potential key collisions or partial matches.
Your regex pattern is mostly robust (^KEY=.*$), but collisions might occur if environment keys share name prefixes. This is unlikely but worth noting in larger codebases.

src/setup/askAndUpdatePort/askAndUpdatePort.ts (1)

5-23: Consider verifying port availability.
This logic ensures the port is in the valid range but doesn’t verify whether it’s free. For improved UX, you may probe the port or warn the user if it’s already occupied.

src/setup/askAndSetDockerOption/askAndSetDockerOption.ts (1)

5-33: Allow customization of Docker container names.
The container name is hard-coded to "talawa-admin." Letting users override it could improve flexibility in multi-container setups.

-    const DOCKER_NAME = 'talawa-admin';
+    const { dockerContainerName } = await inquirer.prompt({
+      type: 'input',
+      name: 'dockerContainerName',
+      message: 'Enter your preferred Docker container name:',
+      default: 'talawa-admin',
+    });
+    const DOCKER_NAME = dockerContainerName;
src/setup/askAndUpdatePort/askForUpdatePort.spec.ts (2)

16-28: Ensure custom port coverage

You're testing a valid port scenario here. It would be beneficial to include an additional assertion to confirm that the function returns or logs a success message indicating the port update was completed. This keeps validations consistent and improves test clarity regarding user-facing feedback.

 it('should update the port when user confirms and provides a valid port', async () => {
   // ...
   await askAndUpdatePort();

+  // Additional assertion for user feedback or returned result
+  // e.g., expect(console.log).toHaveBeenCalledWith('Port updated to 3000');
   expect(updateEnvFile).toHaveBeenCalledWith('PORT', '3000');
 });

43-54: Strengthen negative test coverage

The invalid port test is excellent, but you may want to test more boundary conditions (e.g., exactly 1024 and 65535 in this file) to ensure robust coverage. Although these edge cases exist in another file, duplicating them here ensures this function’s custom port validation is tested end-to-end without relying on askForCustomPort tests alone.

src/setup/askAndSetDockerOption/askAndSetDockerOption.spec.ts (2)

29-39: Validate environment file synergy in Docker scenario

After setting USE_DOCKER and DOCKER_PORT, ensure you validate final .env contents or the returned result. This helps confirm that the flow from user input -> environment variables is integrated properly.

 await askAndSetDockerOption();

 expect(updateEnvFile).toHaveBeenCalledWith('USE_DOCKER', 'YES');
 expect(updateEnvFile).toHaveBeenCalledWith('DOCKER_PORT', 8080);
+// Potentially read the .env content or confirm user feedback:
+// const envContent = fs.readFileSync('.env', 'utf8');
+// expect(envContent).toContain('DOCKER_PORT=8080');

51-60: Distinguish between user cancellation and errors

When askForDocker fails, the test throws "Docker error" to confirm error-handling. Consider differentiating expected user-initiated exit vs genuine errors. If there's a scenario where a user aborts the Docker setup, capturing that distinctly clarifies the user journey in your tests.

src/setup/askForDocker/askForDocker.spec.ts (2)

17-24: Add boundary-checking test for user-provided port

While you test various port values, it's helpful to add a single combined test verifying both numeric input and range in one go. This could reduce duplication, making sure all numeric validations and range checks pass in a consolidated scenario.


26-37: Improve error message clarity

The test's thrown error message is explicit, but consider adding a recommended solution or instructions in the error string (e.g., “Please enter a valid port number...Did you type a letter accidentally?”). This guides users better if they mistakenly enter non-numeric or invalid inputs.

src/setup/updateEnvFile/updateEnvFile.spec.ts (1)

36-48: Optimize read vs append operations

When appending a new key, you first read the existing file content. If the file is large, re-checking content before each key append might be costly. If performance matters for large .env files, consider buffering or caching in future enhancements. For small .env files, this is likely negligible.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c8a1290 and c00d82d.

📒 Files selected for processing (9)
  • setup.ts (2 hunks)
  • src/setup/askAndSetDockerOption/askAndSetDockerOption.spec.ts (1 hunks)
  • src/setup/askAndSetDockerOption/askAndSetDockerOption.ts (1 hunks)
  • src/setup/askAndUpdatePort/askAndUpdatePort.ts (1 hunks)
  • src/setup/askAndUpdatePort/askForUpdatePort.spec.ts (1 hunks)
  • src/setup/askForDocker/askForDocker.spec.ts (1 hunks)
  • src/setup/askForDocker/askForDocker.ts (1 hunks)
  • src/setup/updateEnvFile/updateEnvFile.spec.ts (1 hunks)
  • src/setup/updateEnvFile/updateEnvFile.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test Application
  • GitHub Check: Analyse Code With CodeQL (javascript)
🔇 Additional comments (5)
setup.ts (2)

6-9: Great addition of modular helpers!
Importing these new functions and modules improves the maintainability and clarity of the setup script.


60-85: Confirm test coverage for Docker vs. non-Docker paths.
You have a clear, structured main function with separate branches for Docker and non-Docker usage. However, no tests were added for this logic. Ensure robust coverage is in place to avoid regressions when toggling USE_DOCKER.

src/setup/askForDocker/askForDocker.ts (2)

1-3: Imports look good.
These imports correctly separate concerns and keep the code organized.


11-30: Validate combined usage with Docker environment.
The askForDocker function ensures valid port input. Confirm that the chosen port doesn't conflict with other services.

src/setup/updateEnvFile/updateEnvFile.spec.ts (1)

64-73: Verify file-creation logic further

Currently, the test ensures that appendFileSync is called if the file doesn’t exist. To reinforce reliability, test the scenario where .env is present but empty vs nonexistent. Confirm it correctly handles permissions or partial writes if the file is locked or read-only to ensure robust error handling.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 6, 2025
@rishav-jha-mech rishav-jha-mech added the ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files label Jan 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)
src/setup/validateRecaptcha/validateRecaptcha.spec.ts (1)

Line range hint 10-21: Solid Coverage of Invalid Cases, Consider Testing Empty String or Null

The tests for special characters, incorrect length, and spaces collectively broaden coverage for potential invalid cases. However, it might be beneficial to also test scenarios involving empty string input or null/undefined to ensure the function gracefully handles those edge cases.

Apply the following snippet to add an extra test case:

+  it('should return false for an empty string', () => {
+    const invalidRecaptcha = '';
+    expect(validateRecaptcha(invalidRecaptcha)).toBe(false);
+  });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c00d82d and a049818.

📒 Files selected for processing (1)
  • src/setup/validateRecaptcha/validateRecaptcha.spec.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test Application
🔇 Additional comments (2)
src/setup/validateRecaptcha/validateRecaptcha.spec.ts (2)

1-2: Imports and Testing Framework Setup Look Good

Importing from Vitest is correct, and referencing the local validateRecaptcha module aligns well with best practices for modular testing.


Line range hint 4-9: Comprehensive Positive Case Testing

The test for a valid Recaptcha string is straightforward and confirms that the function returns true as expected. This ensures the core functionality works for the happy path.

@palisadoes palisadoes merged commit 2f68501 into PalisadoesFoundation:develop-postgres Jan 6, 2025
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants