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

Fixed bugs to ensure proper flow of prompts and remove repetitive prompts #2845

Open
wants to merge 11 commits into
base: develop
Choose a base branch
from

Conversation

Aad1tya27
Copy link

@Aad1tya27 Aad1tya27 commented Jan 10, 2025

What kind of change does this PR introduce?
Bug in setup.ts

Issue Number:

Fixes #2829

Snapshots/Videos:
image

If relevant, did you update the documentation?
No

Does this PR introduce a breaking change?
Yeah, there was a breaking change related to __dirname, which was caused due CommonJS to ES.

Checklist

CodeRabbit AI Review

  • I have reviewed and addressed all critical issues flagged by CodeRabbit AI
  • I have implemented or provided justification for each non-critical suggestion
  • I have documented my reasoning in the PR comments where CodeRabbit AI suggestions were not implemented

Test Coverage

  • I have written tests for all new changes/features
  • I have verified that test coverage meets or exceeds 95%
  • I have run the test suite locally and all tests pass

Other information

Have you read the contributing guide?

Summary by CodeRabbit

  • Chores
    • Improved setup process error handling and logging.
    • Refined data management logic for MongoDB database.
    • Updated import and path resolution mechanisms.
    • Streamlined sample data import workflow.
    • Enhanced setup confirmation messaging.
  • Tests
    • Introduced a new test suite for validating the transaction log path input functionality.

Copy link

coderabbitai bot commented Jan 10, 2025

Walkthrough

The pull request modifies the setup.ts file to enhance the setup process for the Talawa API, focusing on imports, error handling, logging, and data management. Key changes include updating import statements for better path resolution, improving error handling by throwing descriptive messages, refining the logic for data management, and simplifying user prompts. Additionally, new tests for the askForTransactionLogPath function have been introduced to ensure correct handling of user input.

Changes

File Change Summary
setup.ts - Updated imports to include dirname and fileURLToPath
- Improved error handling in wipeExistingData and checkDb functions
- Modified transaction log path resolution
- Simplified data management and import logic
- Refined prompt messages for data importation
- Moved final setup confirmation message to the end of the main function
- Exported function signatures for transactionLogPath, askForTransactionLogPath, and getDockerComposeCommand
tests/setup/transactionLog.spec.ts - Introduced a test suite for askForTransactionLogPath with two test cases for valid and invalid paths

Assessment against linked issues

Objective Addressed Explanation
Data importation flow improvement [#2829]
Remove Docker-specific prompts when not using Docker [#2829] Requires further verification of complete Docker prompt removal
Clarify data importation questions [#2829]

Possibly related PRs

Suggested reviewers

  • palisadoes
  • SiddheshKukade
  • adithyanotfound

Poem

🐰 In the realm of setup's grand design,
Code dances, imports now align!
Errors caught with gentle care,
Data flows without a snare,
Talawa's path now clear and fine! 🚀

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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

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

@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 (3)
setup.ts (3)

226-226: Enhance error handling consistency.

While the error handling improvements are good, consider adding more specific error information to help with troubleshooting.

-    throw new Error("Could not connect to database to check for data");
+    const error = err instanceof Error ? err.message : String(err);
+    throw new Error(`Failed to connect to database: ${error}`);

Also applies to: 242-254


Line range hint 1276-1323: Consider extracting MongoDB connection retry logic.

The MongoDB connection retry logic could be extracted into a separate function for better maintainability.

+async function waitForMongoDB(url: string, maxRetries: number = 30): Promise<void> {
+  let isConnected = false;
+  let retryCount = 0;
+  while (!isConnected) {
+    if (retryCount >= maxRetries) {
+      throw new Error(`Timed out waiting for MongoDB to be ready after ${maxRetries} seconds`);
+    }
+    try {
+      const client = new MongoClient(url);
+      await client.connect();
+      await client.db().command({ ping: 1 });
+      client.close();
+      isConnected = true;
+      console.log("MongoDB is ready!");
+    } catch (err) {
+      const error = err instanceof Error ? err.message : String(err);
+      console.log(
+        `Waiting for MongoDB to be ready... Retry ${retryCount + 1}/${maxRetries}. Details: ${error}`
+      );
+      await new Promise((resolve) => setTimeout(resolve, 1000));
+      retryCount++;
+    }
+  }
+}

1332-1335: Enhance setup completion message.

Consider providing more specific information about what was successfully set up.

-    "\nCongratulations! Talawa API has been successfully setup! 🥂🎉",
+    "\nCongratulations! Talawa API has been successfully set up! 🥂🎉\n" +
+    "- Database configuration: ✅\n" +
+    `- Default data imported: ✅\n` +
+    `- Sample data imported: ${shouldImportSampleData ? "✅" : "❌"}\n` +
+    "- Docker containers: " + (isDockerInstallation ? "✅" : "❌"),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 25207c5 and 067fdb2.

📒 Files selected for processing (1)
  • setup.ts (13 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Check for linting, formatting, and type errors
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (3)
setup.ts (3)

5-5: Import changes align with ES modules transition.

The addition of dirname and fileURLToPath imports properly handles path resolution in ES modules, addressing the breaking change mentioned in the PR objectives.

Also applies to: 34-34


145-149: Improved log path resolution and file management.

The changes correctly handle path resolution for ES modules and improve log file management by:

  • Using dirname(fileURLToPath(import.meta.url)) for proper path resolution
  • Creating logs directory if it doesn't exist

Also applies to: 159-159


Line range hint 1233-1275: Improved data import flow and user prompts.

The changes provide clearer prompts and better separation between default and sample data import operations.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 10, 2025
@palisadoes palisadoes added the ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files label Jan 10, 2025
Copy link
Contributor

@palisadoes palisadoes left a comment

Choose a reason for hiding this comment

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

  1. Remember to add tests.
  2. We can't have this again

@Aad1tya27
Copy link
Author

  1. Remember to add tests.
  2. We can't have this again

Yes I'm writing tests now.

Copy link

@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 comments (1)
setup.ts (1)

Line range hint 1233-1275: Add error handling for data import operations.

The database setup flow has been improved, but consider adding:

  1. Error handling for failed data imports
  2. Rollback mechanism for partial import failures
  3. Progress indicators for long-running operations
       if (shouldOverwriteData) {
         await wipeExistingData(process.env.MONGO_DB_URL);
-        await importDefaultData();
+        try {
+          console.log("Importing default data...");
+          await importDefaultData();
+          console.log("Default data imported successfully.");
+        } catch (error) {
+          console.error("Failed to import default data:", error);
+          const { shouldRetry } = await inquirer.prompt({
+            type: "confirm",
+            name: "shouldRetry",
+            message: "Would you like to retry importing default data?",
+            default: true,
+          });
+          if (shouldRetry) {
+            await importDefaultData();
+          } else {
+            throw new Error("Setup cannot continue without default data");
+          }
+        }
🧹 Nitpick comments (5)
tests/setup/transactionLog.spec.ts (2)

6-16: Update test documentation to match the actual test cases.

The documentation comments describe test cases for askForSuperAdminEmail and superAdmin functions, but this file is testing the askForTransactionLogPath function. Please update the documentation to reflect the actual test cases in this file.


33-45: Consider adding assertions for prompt calls and error handling.

While the test effectively verifies the retry behavior, consider adding assertions to:

  1. Verify that inquirer.prompt was called exactly twice
  2. Verify error messages shown to users match expected values

Example enhancement:

 const result = await askForTransactionLogPath();
 expect(result).toEqual(testPath);
+expect(inquirer.prompt).toHaveBeenCalledTimes(2);
+expect(console.error).toHaveBeenCalledWith(
+  "Invalid path or file does not exist. Please enter a valid file path."
+);
setup.ts (3)

Line range hint 172-202: Enhance user feedback in the prompt.

Consider the following improvements:

  1. The default path shown in the prompt message should match the actual default path used in transactionLogPath
  2. Error messages could be more specific about permission issues
       {
         type: "input",
         name: "logPath",
         message: "Enter absolute path of log file:",
-        default: null,
+        default: path.join(process.cwd(), "logs", "transaction.log"),
       },

     if (logPath && fs.existsSync(logPath)) {
       try {
         fs.accessSync(logPath, fs.constants.R_OK | fs.constants.W_OK);
         isValidPath = true;
       } catch {
         console.error(
-          "The file is not readable/writable. Please enter a valid file path.",
+          `The file exists but ${!fs.accessSync(logPath, fs.constants.R_OK) ? "is not readable" : "is not writable"}. Please ensure you have proper permissions.`,
         );
       }

Line range hint 1276-1331: Enhance Docker setup reliability.

Consider the following improvements:

  1. Move timeout values to constants
  2. Add health checks for Redis and MinIO services
  3. Add retry mechanism for Docker compose failures
+const MONGODB_READY_TIMEOUT_SECONDS = 30;
+const MONGODB_CHECK_INTERVAL_MS = 1000;
+
     if (shouldStartDockerContainers) {
       console.log("Starting docker container...");
       try {
         await runDockerComposeWithLogs();
         console.log("Docker containers have been built successfully!");
-        // Wait for mongoDB to be ready
-        console.log("Waiting for mongoDB to be ready...");
+        // Wait for services to be ready
+        console.log("Waiting for services to be ready...");
         let isConnected = false;
-        const maxRetries = 30; // 30 seconds timeout
+        const maxRetries = MONGODB_READY_TIMEOUT_SECONDS;
         let retryCount = 0;
+
+        // Check MongoDB readiness
         while (!isConnected) {
           if (retryCount >= maxRetries) {
             throw new Error(
-              "Timed out waiting for MongoDB to be ready after 30 seconds",
+              `Timed out waiting for MongoDB to be ready after ${MONGODB_READY_TIMEOUT_SECONDS} seconds`,
             );
           }
           try {
             const client = new MongoClient(process.env.MONGO_DB_URL as string);
             await client.connect();
             await client.db().command({ ping: 1 });
             client.close();
             isConnected = true;
             console.log("MongoDB is ready!");
           } catch (err) {
             const error = err instanceof Error ? err.message : String(err);
             console.log(
               `Waiting for MongoDB to be ready... Retry ${retryCount + 1}/${maxRetries}. Details: ${error}`,
             );
-            await new Promise((resolve) => setTimeout(resolve, 1000));
+            await new Promise((resolve) => setTimeout(resolve, MONGODB_CHECK_INTERVAL_MS));
             retryCount++;
           }
         }
+
+        // Check Redis readiness
+        console.log("Checking Redis connection...");
+        await checkRedisConnection(`redis://${process.env.REDIS_HOST}:${process.env.REDIS_PORT}`);
+        console.log("Redis is ready!");
+
+        // Check MinIO readiness
+        console.log("Checking MinIO connection...");
+        // Add MinIO health check here
+        console.log("MinIO is ready!");

1332-1335: Enhance the success message with setup details.

Consider adding more information to help users get started:

-  console.log(
-    "\nCongratulations! Talawa API has been successfully setup! 🥂🎉",
-  );
+  console.log(`
+    \nCongratulations! Talawa API has been successfully setup! 🥂🎉
+    
+    Your setup details:
+    - API running on port: ${process.env.SERVER_PORT}
+    - MongoDB URL: ${process.env.MONGO_DB_URL}
+    - Redis host: ${process.env.REDIS_HOST}
+    - MinIO endpoint: ${process.env.MINIO_ENDPOINT}
+    
+    To start the server, run: npm start
+    For more information, visit: https://github.com/PalisadoesFoundation/talawa-api
+  `);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 067fdb2 and 9de22b4.

📒 Files selected for processing (2)
  • setup.ts (15 hunks)
  • tests/setup/transactionLog.spec.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Check for linting, formatting, and type errors
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (2)
tests/setup/transactionLog.spec.ts (1)

22-31: LGTM! Well-structured test case.

The test effectively covers the success scenario with proper mocking of dependencies and validation of the result.

setup.ts (1)

Line range hint 143-171: LGTM! Proper ES modules path resolution implementation.

The function correctly handles the transition from CommonJS to ES modules by using fileURLToPath and dirname for path resolution while maintaining the existing functionality.

Copy link

codecov bot commented Jan 11, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 97.72%. Comparing base (25207c5) to head (9de22b4).

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #2845   +/-   ##
========================================
  Coverage    97.72%   97.72%           
========================================
  Files          364      364           
  Lines        18569    18569           
  Branches      2682     2682           
========================================
  Hits         18147    18147           
  Misses         417      417           
  Partials         5        5           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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.

2 participants