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

Updating the setup script to handle sample data import for Docker #2691

Closed
wants to merge 25 commits into from

Conversation

Suyash878
Copy link

@Suyash878 Suyash878 commented Nov 18, 2024

What kind of change does this PR introduce?

Bug Fix

Issue Number:

Fixes #2270

Did you add tests for your changes?

No

Snapshots/Videos:

image

If relevant, did you update the documentation?

Not sure

Summary

The setup script will now prompt the user when it starts the process for sample data import provided the user is using Docker.

Does this PR introduce a breaking change?

No

Other information

This PR was supposed to be made against the develop-postgres branch but since it is currently under work, and unavailability of the setup script there I am currently raising the PR against the develop branch.
My changes may get introduced to the develop-postgres branch as a seperate issue later on.

Have you read the contributing guide?

Yes

Summary by CodeRabbit

  • New Features

    • Introduced a function for managing Docker container execution with real-time logging.
    • Added prompts for starting Docker containers and importing sample data during setup.
    • New environment variable DOCKER added for enhanced configuration options.
  • Bug Fixes

    • Improved error handling for Docker container startup and sample data import processes.
    • Enhanced logic to ensure MongoDB is ready before proceeding with data imports.

Copy link

coderabbitai bot commented Nov 18, 2024

Walkthrough

The pull request introduces enhancements to the setup.ts file and the .env.sample file, focusing on improving the setup process for Docker installations. A new function, runDockerComposeWithLogs, is added to facilitate Docker container management and logging. The main function is updated to prompt users for Docker-related actions, including importing sample data. Additionally, a new environment variable DOCKER is introduced in the .env.sample file to capture user input regarding Docker usage.

Changes

File Change Summary
setup.ts - Added async function runDockerComposeWithLogs() for Docker container management.
- Updated async function main() to include Docker prompts and improved error handling.
.env.sample - Added new environment variable DOCKER= to capture Docker usage response.

Assessment against linked issues

Objective Addressed Explanation
Prompt user for data import if Docker is running (#2270)
Store previous Docker-related answers (#2270) Previous answers are not stored in the changes.
Provide appropriate error messaging for non-Docker imports (#2270) Unclear if error handling covers non-Docker imports.
Ensure sample data is imported correctly when using Docker (#2270)

Possibly related PRs

  • Fixed setup script #2512: This PR modifies the setup.ts file to enhance user prompts within the main function, which is directly related to the changes made in the main PR that also updates the main function for Docker handling.

Suggested reviewers

  • palisadoes

🐇 In the land of code where rabbits roam,
A Docker setup finds its home.
With logs and prompts, we hop along,
Sample data imports, where we belong!
So let’s cheer for changes, big and small,
Together we’ll build, together we’ll install! 🌟


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.

Copy link

github-actions bot commented Nov 18, 2024

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: 1

🧹 Outside diff range and nitpick comments (1)
setup.ts (1)

1187-1213: Consider adding validation for npm command availability.

The script assumes npm run import:sample-data is available. Add validation to ensure the command exists.

Consider:

  1. Validating package.json for the script definition
  2. Checking if npm is available in PATH
  3. Adding fallback mechanisms if the command fails
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a6e7ac9 and 30adcd8.

📒 Files selected for processing (2)
  • entrypoint.sh (1 hunks)
  • setup.ts (1 hunks)
🧰 Additional context used
🪛 Shellcheck
entrypoint.sh

[error] 2-2: Remove leading spaces before the shebang.

(SC1114)


[error] 2-2: The shebang must be on the first line. Delete blanks and move comments.

(SC1128)

🔇 Additional comments (1)
setup.ts (1)

1187-1213: Verify Docker environment detection.

The Docker installation check relies solely on user input. Consider adding automated detection.

setup.ts Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
setup.ts Fixed Show fixed Hide fixed
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: 2

🧹 Outside diff range and nitpick comments (1)
setup.ts (1)

1187-1223: Consider refactoring Docker sample data import into a separate function.

The implementation would be more maintainable if moved to a dedicated async function.

+async function importDockerSampleData(): Promise<void> {
+  console.log("Starting the sample data import for docker now...");
+
+  const entryPointScript = `#!/bin/bash
+npm run import:sample-data
+`;
+
+  const scriptPath = path.join(os.tmpdir(), `entrypoint-${Date.now()}.sh`);
+  
+  try {
+    // Create script with proper permissions
+    fs.writeFileSync(scriptPath, entryPointScript, { mode: 0o755 });
+    
+    await new Promise<void>((resolve, reject) => {
+      exec(scriptPath, { timeout: 60000 }, (error, stdout, stderr) => {
+        // Clean up script file
+        try {
+          fs.unlinkSync(scriptPath);
+        } catch (cleanupError) {
+          console.warn("Failed to cleanup script file:", cleanupError);
+        }
+        
+        if (error) {
+          console.error("Error importing sample data:");
+          console.error(`Exit code: ${error.code}`);
+          console.error(`Error message: ${error.message}`);
+          reject(error);
+          return;
+        }
+        
+        if (stderr) {
+          console.warn("Sample data import warnings:");
+          console.warn(stderr.trim());
+        }
+        
+        if (stdout) {
+          console.log("Sample data import output:");
+          console.log(stdout.trim());
+        }
+        console.log("Sample data import complete.");
+        resolve();
+      });
+    });
+  } catch (err) {
+    console.error("Failed to setup sample data import:", err);
+    if (fs.existsSync(scriptPath)) {
+      try {
+        fs.unlinkSync(scriptPath);
+      } catch (cleanupError) {
+        console.warn("Failed to cleanup script file:", cleanupError);
+      }
+    }
+    throw err;
+  }
+}

 if (isDockerInstallation) {
-  console.log("Starting the sample data import for docker now...");
-  ...
+  await importDockerSampleData();
 }
🧰 Tools
🪛 GitHub Check: CodeQL

[warning] 1201-1201: Shell command built from environment values
This shell command depends on an uncontrolled absolute path.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 30adcd8 and eab9d94.

📒 Files selected for processing (1)
  • setup.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Check: CodeQL
setup.ts

[warning] 1201-1201: Shell command built from environment values
This shell command depends on an uncontrolled absolute path.

setup.ts Outdated Show resolved Hide resolved
setup.ts Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 1

🧹 Outside diff range and nitpick comments (1)
setup.ts (1)

1184-1234: Implementation looks good with minor formatting suggestion.

The Docker sample data import implementation follows security best practices:

  • Uses secure temporary directory
  • Includes comprehensive error handling
  • Ensures proper cleanup of temporary files
  • Sets appropriate file permissions
  • Has execution timeout

Consider improving the script content formatting for better readability.

 const entryPointScript = `#!/bin/bash
-npm run import:sample-data
+
+# Import sample data for Docker environment
+npm run import:sample-data
+
`;
🧰 Tools
🪛 Biome

[error] 1197-1197: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1199-1199: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1199-1201: Illegal use of an import declaration not at the top level

move this declaration to the top level

(parse)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between eab9d94 and 41c9aac.

📒 Files selected for processing (1)
  • setup.ts (1 hunks)
🧰 Additional context used
🪛 Biome
setup.ts

[error] 1197-1197: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1199-1199: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1199-1201: Illegal use of an import declaration not at the top level

move this declaration to the top level

(parse)

setup.ts Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 1

🧹 Outside diff range and nitpick comments (1)
setup.ts (1)

1184-1186: Improve code organization and remove redundant comment.

The success message should be moved after the Docker check to avoid confusion, and the redundant comment can be removed.

 console.log("\nCongratulations! Talawa API has been successfully setup! 🥂🎉");

-/* Performing the sample data import for docker */

 if (isDockerInstallation) {
+  console.log("\nCongratulations! Talawa API has been successfully setup! 🥂🎉");
   console.log("Starting the sample data import for docker now...");
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 41c9aac and 6144664.

📒 Files selected for processing (1)
  • setup.ts (1 hunks)
🧰 Additional context used
🪛 Biome
setup.ts

[error] 1215-1215: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1215-1215: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1215-1215: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1216-1216: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1216-1216: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1216-1216: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1215-1215: Unexpected label.

Only loops should be labeled.
The use of labels for other statements is suspicious and unfamiliar.

(lint/suspicious/noConfusingLabels)


[error] 1216-1216: Unexpected label.

Only loops should be labeled.
The use of labels for other statements is suspicious and unfamiliar.

(lint/suspicious/noConfusingLabels)


[error] 1215-1216: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)


[error] 1216-1217: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

🔇 Additional comments (1)
setup.ts (1)

1187-1237: LGTM! Implementation follows security best practices.

The Docker sample data import implementation demonstrates several good practices:

  • Uses secure temporary directory with os.tmpdir()
  • Includes comprehensive error handling
  • Ensures cleanup of temporary files
  • Sets appropriate file permissions (0o755)
  • Has execution timeout (60s)
🧰 Tools
🪛 Biome

[error] 1215-1215: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1215-1215: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1215-1215: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1216-1216: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1216-1216: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1216-1216: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 1215-1215: Unexpected label.

Only loops should be labeled.
The use of labels for other statements is suspicious and unfamiliar.

(lint/suspicious/noConfusingLabels)


[error] 1216-1216: Unexpected label.

Only loops should be labeled.
The use of labels for other statements is suspicious and unfamiliar.

(lint/suspicious/noConfusingLabels)


[error] 1215-1216: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)


[error] 1216-1217: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

setup.ts Outdated Show resolved Hide resolved
@varshith257
Copy link
Member

varshith257 commented Nov 18, 2024

@Suyash878 Isn't sample data is imported into docker mango container?

@Suyash878
Copy link
Author

Yes, sample data would be imported to the docker mongo container, totally depends on the mongodb url in the environment variables.

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 19, 2024
@palisadoes
Copy link
Contributor

Please fix the failing tests

@Suyash878
Copy link
Author

Suyash878 commented Nov 21, 2024

The base branch check is failing since it is not targeted to the postgres branch.
I cannot target the PR to postgres since postres does not have a setup script yet, And the other "sensitive file have been changed" is failing since I made a change to the setup script.
The testing application check is something I think others are also facing and is something that needs fixing, Although I could be wrong I posted on slack as well.

Copy link

codecov bot commented Nov 22, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 97.74%. Comparing base (740ca31) to head (6ff5257).

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #2691   +/-   ##
========================================
  Coverage    97.74%   97.74%           
========================================
  Files          358      358           
  Lines        18114    18114           
  Branches      2601     2601           
========================================
  Hits         17706    17706           
  Misses         404      404           
  Partials         4        4           

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

@palisadoes palisadoes added the ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files label Nov 23, 2024
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. Your solution won't work in a Window environment.
  2. There are no tests written for your work.
  3. Does your change match the pattern for other setup script prompts?

setup.ts Outdated Show resolved Hide resolved
entrypoint.sh Outdated Show resolved Hide resolved
@Suyash878
Copy link
Author

Sure I will look into the changes.

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: 4

🧹 Outside diff range and nitpick comments (4)
.env.sample (3)

24-26: Improve the documentation for the DOCKER environment variable.

The comments should be more specific about the expected values and usage. Consider enhancing the documentation:

-# This environment variable is for storing user's response to whether they are 
-# docker to setup or not.
+# This environment variable indicates whether Docker is being used for the setup.
+# Possible values: true/false
+# Example: DOCKER=true

24-27: Consider grouping infrastructure-related environment variables together.

The DOCKER variable would be better placed near other infrastructure or setup-related configurations. Consider moving it closer to the database configuration section since they're related to the deployment setup.


24-27: Consider adding more Docker-related configuration options.

Given that this PR focuses on Docker integration, consider adding more Docker-related environment variables that might be needed for a complete setup:

 # This environment variable indicates whether Docker is being used for the setup.
 # Possible values: true/false
 DOCKER=
+
+# Docker-specific configurations
+# DOCKER_COMPOSE_FILE=docker-compose.yml
+# DOCKER_API_VERSION=
+# DOCKER_HOST=
+# DOCKER_NETWORK=

This would provide more flexibility and control over the Docker setup process.

setup.ts (1)

950-950: Simplify boolean expression.

The ternary operator for the default value can be simplified.

-    default: process.env.MONGO ? false : true,
+    default: !process.env.MONGO,
🧰 Tools
🪛 Biome (1.9.4)

[error] 950-951: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0146c7f and 270e7fa.

📒 Files selected for processing (2)
  • .env.sample (1 hunks)
  • setup.ts (4 hunks)
🧰 Additional context used
🪛 eslint
setup.ts

[error] 9-9: 'child_process' imported multiple times.

(import/no-duplicates)

🪛 GitHub Check: Check for linting, formatting, and type errors
setup.ts

[failure] 9-9:
'child_process' imported multiple times

🪛 Biome (1.9.4)
setup.ts

[error] 950-951: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

.env.sample Outdated Show resolved Hide resolved
setup.ts Outdated Show resolved Hide resolved
setup.ts Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@palisadoes
Copy link
Contributor

Please fix the failing tests

@Suyash878
Copy link
Author

The testing Application test is failing due to a bug I think, I've come across this a bunch of times and its something that needs fixing.

@palisadoes
Copy link
Contributor

The mongodb connection timed out. I'm rerunning the tests.

@palisadoes
Copy link
Contributor

  1. It appears none of the past recent PRs that were merged into this branch failed. Please verify this to see whether we merged any PRs with failing tests.
  2. If not, you'll need to review your changes to setup.ts to see how it may be impacting the outcome.

@Suyash878
Copy link
Author

For me it shows this as the failed test:
image

@Suyash878
Copy link
Author

I will look into it.

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: 2

🧹 Outside diff range and nitpick comments (4)
setup.ts (4)

8-8: Consolidate child_process imports.

Combine the imports from 'child_process' into a single import statement for better code organization.

-import { exec, spawn } from "child_process";
+import { exec, spawn, type ExecException } from "child_process";

489-510: Add timeout and cleanup handling for Docker operations.

The Docker compose operation could potentially hang indefinitely. Consider adding:

  1. A timeout mechanism
  2. Cleanup handling for failed operations
 return new Promise((resolve, reject) => {
+  const timeout = setTimeout(() => {
+    dockerCompose.kill();
+    reject(new Error('Docker compose operation timed out after 5 minutes'));
+  }, 300000);
+
   const dockerCompose = spawn(
     process.platform === "win32" ? "docker-compose.exe" : "docker-compose",
     ["-f", "docker-compose.dev.yaml", "up", "--build", "-d"],
     { stdio: "inherit" },
   );

   dockerCompose.on("error", (error) => {
+    clearTimeout(timeout);
     console.error("Error running docker-compose:", error);
     reject(error);
   });

   dockerCompose.on("close", (code) => {
+    clearTimeout(timeout);
     if (code === 0) {
       console.log("Docker Compose completed successfully.");
       resolve();
     } else {
+      // Attempt cleanup on failure
+      const cleanup = spawn(
+        process.platform === "win32" ? "docker-compose.exe" : "docker-compose",
+        ["-f", "docker-compose.dev.yaml", "down"],
+        { stdio: "inherit" }
+      );
       reject(new Error(`Docker Compose exited with code ${code}`));
     }
   });
 });

967-967: Simplify the default value expression.

The ternary operation with boolean literals can be simplified.

-    default: process.env.MONGO ? false : true,
+    default: !process.env.MONGO,
🧰 Tools
🪛 Biome (1.9.4)

[error] 967-968: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)


1264-1267: Improve error handling in MongoDB connection check.

The error variable is unused, and the error handling could be more informative.

-          } catch (err) {
+          } catch (error) {
+            if (error instanceof Error) {
+              console.log(`MongoDB connection attempt failed: ${error.message}. Retrying in 1 second...`);
+            }
             await new Promise((resolve) => setTimeout(resolve, 1000));
           }
🧰 Tools
🪛 eslint

[error] 1264-1264: 'err' is defined but never used.

(@typescript-eslint/no-unused-vars)

🪛 GitHub Check: Check for linting, formatting, and type errors

[failure] 1264-1264:
'err' is defined but never used

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ee6b384 and 9b96d01.

📒 Files selected for processing (1)
  • setup.ts (4 hunks)
🧰 Additional context used
🪛 GitHub Check: Check for linting, formatting, and type errors
setup.ts

[warning] 485-485:
Unexpected any. Specify a different type


[failure] 1264-1264:
'err' is defined but never used

🪛 Biome (1.9.4)
setup.ts

[error] 967-968: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

🪛 eslint
setup.ts

[error] 1264-1264: 'err' is defined but never used.

(@typescript-eslint/no-unused-vars)

setup.ts Outdated
: reject(new Error("Docker daemon not running")),
);
});
} catch (error:any) {
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use a more specific type for error handling.

Instead of using any, use unknown or Error type for better type safety.

-catch (error: any) {
+catch (error: unknown) {
   if (error instanceof Error) {
     throw new Error(`Docker daemon is not running. Please start Docker and try again. Details: ${error.message}`);
   }
   throw new Error('Docker daemon is not running. Please start Docker and try again.');
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (error:any) {
} catch (error: unknown) {
if (error instanceof Error) {
throw new Error(`Docker daemon is not running. Please start Docker and try again. Details: ${error.message}`);
}
throw new Error('Docker daemon is not running. Please start Docker and try again.');
🧰 Tools
🪛 GitHub Check: Check for linting, formatting, and type errors

[warning] 485-485:
Unexpected any. Specify a different type

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: 2

🧹 Outside diff range and nitpick comments (3)
setup.ts (3)

469-512: Add timeout handling for Docker operations.

The Docker compose operation could potentially hang indefinitely. Consider adding a timeout mechanism.

 return new Promise((resolve, reject) => {
+  const timeout = setTimeout(() => {
+    dockerCompose.kill();
+    reject(new Error('Docker compose operation timed out after 5 minutes'));
+  }, 300000);
+
   const dockerCompose = spawn(
     process.platform === "win32" ? "docker-compose.exe" : "docker-compose",
     ["-f", "docker-compose.dev.yaml", "up", "--build", "-d"],
     { stdio: "inherit" }
   );

   dockerCompose.on("error", (error) => {
+    clearTimeout(timeout);
     console.error("Error running docker-compose:", error);
     reject(error);
   });

   dockerCompose.on("close", (code) => {
+    clearTimeout(timeout);
     if (code === 0) {
       console.log("Docker Compose completed successfully.");
       resolve();
     } else {
       reject(new Error(`Docker Compose exited with code ${code}`));
     }
   });
 });
🧰 Tools
🪛 GitHub Check: Check for linting, formatting, and type errors

[warning] 485-485:
Unexpected any. Specify a different type


969-969: Simplify the default value logic.

The ternary expression for the default value can be simplified.

-    default: process.env.MONGO ? false : true,
+    default: !process.env.MONGO,
🧰 Tools
🪛 Biome (1.9.4)

[error] 969-970: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)


1267-1270: Improve error message formatting.

The error message concatenation can be improved for better readability.

-            console.log(
-              "Waiting for MongoDB to be ready... Retrying in 1 second, Details:" +
-                err,
-            );
+            console.log(
+              `Waiting for MongoDB to be ready... Retrying in 1 second. Details: ${err}`
+            );
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9b96d01 and 3c10f42.

📒 Files selected for processing (1)
  • setup.ts (4 hunks)
🧰 Additional context used
🪛 GitHub Check: Check for linting, formatting, and type errors
setup.ts

[warning] 485-485:
Unexpected any. Specify a different type

🪛 Biome (1.9.4)
setup.ts

[error] 969-970: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

🔇 Additional comments (1)
setup.ts (1)

8-8: LGTM! Good import consolidation.

Combining the imports from 'child_process' into a single statement improves code organization.

setup.ts Outdated Show resolved Hide resolved
setup.ts Outdated Show resolved Hide resolved
@Suyash878
Copy link
Author

Suyash878 and others added 3 commits December 5, 2024 00:12
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 2

🧹 Outside diff range and nitpick comments (3)
setup.ts (3)

485-489: Improve error message formatting.

The error message concatenation could be improved for better readability and error details preservation.

-    throw new Error(
-      `Docker daemon is not running. Please start Docker and try again. Details: ${error}`,
-    );
+    if (error instanceof Error) {
+      throw new Error(
+        `Docker daemon is not running. Please start Docker and try again. Details: ${error.message}`
+      );
+    }
+    throw new Error('Docker daemon is not running. Please start Docker and try again.');

969-969: Simplify boolean expression.

The ternary operator for boolean values can be simplified.

-    default: process.env.MONGO ? false : true,
+    default: !process.env.MONGO,
🧰 Tools
🪛 Biome (1.9.4)

[error] 969-970: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)


1278-1280: Improve error handling in Docker container startup.

The error handling could be more informative and consistent with the rest of the codebase.

-      } catch (err) {
-        console.log("Some error occurred: " + err);
+      } catch (err) {
+        const error = err instanceof Error ? err.message : String(err);
+        console.error(`Failed to start Docker containers: ${error}`);
+        throw err;
       }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3c10f42 and 4b71e18.

📒 Files selected for processing (1)
  • setup.ts (4 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
setup.ts

[error] 969-970: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

setup.ts Outdated Show resolved Hide resolved
setup.ts Outdated Show resolved Hide resolved
@Suyash878
Copy link
Author

I made another PR just today, and the "Testing Application" test is failing there as well, and they are both failing due to similar reasons.
You can refer to the failed test for that issue here:

@palisadoes
Copy link
Contributor

@Suyash878 Please fix the test so that this PR passes.

This PR was supposed to have fixed the issue:

@palisadoes
Copy link
Contributor

@VanshikaSabharwal You have been working on Docker in Talawa Admin

Can you provide any immediate assistance? This has reached a level of urgency. If so please open a PR against this issue as an emergency override of our policy.

@VanshikaSabharwal
Copy link

Yes @palisadoes i am doing it

@palisadoes
Copy link
Contributor

Please make code rabbit approve your changes

@VanshikaSabharwal
Copy link

@Suyash878 To approve code by code rabbit you have to make necessary changes recommended by code rabbit in you codebase and resolve each conversation

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 1

🧹 Outside diff range and nitpick comments (2)
setup.ts (2)

976-976: Simplify the boolean expression.

The ternary operator with boolean literals can be simplified.

-    default: process.env.MONGO ? false : true,
+    default: !process.env.MONGO,
🧰 Tools
🪛 Biome (1.9.4)

[error] 976-977: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)


1292-1293: Improve error logging.

The error concatenation could be improved with template literals and proper error type handling.

-        console.log("Some error occurred: " + err);
+        const errorMessage = err instanceof Error ? err.message : String(err);
+        console.error(`Failed to start Docker containers: ${errorMessage}`);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4b71e18 and 94bbaa5.

📒 Files selected for processing (1)
  • setup.ts (4 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
setup.ts

[error] 976-977: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

🔇 Additional comments (3)
setup.ts (3)

8-8: LGTM! Clean import consolidation.

Good practice to consolidate multiple imports from the same module into a single import statement.


469-519: LGTM! Well-implemented Docker compose function.

The function includes several good practices:

  • Cross-platform support
  • Timeout handling
  • Proper error handling
  • Clear logging

1263-1286: LGTM! Well-implemented MongoDB connection retry logic.

The implementation includes several good practices:

  • Maximum retry limit
  • Clear error messages
  • Proper connection testing with ping
  • Appropriate delay between retries

setup.ts Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 2

🧹 Outside diff range and nitpick comments (1)
setup.ts (1)

977-977: Simplify the boolean expression.

The ternary operator for a boolean result can be simplified.

-    default: process.env.MONGO ? false : true,
+    default: !process.env.MONGO,
🧰 Tools
🪛 Biome (1.9.4)

[error] 977-978: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 94bbaa5 and d706bbd.

📒 Files selected for processing (1)
  • setup.ts (4 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
setup.ts

[error] 977-978: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

🔇 Additional comments (3)
setup.ts (3)

8-8: LGTM! Import statement is correctly placed.

The import of exec and spawn from 'child_process' is appropriate for the Docker-related functionality added.


469-520: Well-structured Docker setup function with good practices!

The function includes:

  • Cross-platform support for Windows/Unix
  • Proper error handling with type narrowing
  • Timeout mechanism to prevent hanging
  • Clear error messages

1264-1287: Well-implemented MongoDB readiness check!

The implementation includes:

  • Proper timeout handling (30 seconds)
  • Retry counter
  • Clear error messages with retry status
  • Type-safe error handling

Comment on lines +498 to +502
const dockerCompose = spawn(
process.platform === "win32" ? "docker-compose.exe" : "docker-compose",
["-f", "docker-compose.dev.yaml", "up", "--build", "-d"],
{ stdio: "inherit" },
);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using path.join for Docker compose file path.

For better cross-platform compatibility and to prevent path traversal attacks, use path.join for the Docker compose file path.

-      ["-f", "docker-compose.dev.yaml", "up", "--build", "-d"],
+      ["-f", path.join(process.cwd(), "docker-compose.dev.yaml"), "up", "--build", "-d"],
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const dockerCompose = spawn(
process.platform === "win32" ? "docker-compose.exe" : "docker-compose",
["-f", "docker-compose.dev.yaml", "up", "--build", "-d"],
{ stdio: "inherit" },
);
const dockerCompose = spawn(
process.platform === "win32" ? "docker-compose.exe" : "docker-compose",
["-f", path.join(process.cwd(), "docker-compose.dev.yaml"), "up", "--build", "-d"],
{ stdio: "inherit" },
);

Comment on lines +1292 to +1294
} catch (err) {
console.log("Some error occurred: " + err);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling in catch block.

The error handling could be more informative and type-safe.

-        console.log("Some error occurred: " + err);
+        const errorMessage = err instanceof Error ? err.message : String(err);
+        console.error(`Failed to start Docker containers: ${errorMessage}`);
+        throw err;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (err) {
console.log("Some error occurred: " + err);
}
} catch (err) {
const errorMessage = err instanceof Error ? err.message : String(err);
console.error(`Failed to start Docker containers: ${errorMessage}`);
throw err;
}

@Suyash878
Copy link
Author

@palisadoes Shall I create a separate issue for the tests regarding these changes? Considering it would be a cleaner approach that way and since this discussion thread has already been quite cluttered with the main changes themselves.

@palisadoes
Copy link
Contributor

We cannot merge into the code base if there are errors. I'll close this until you figure out the solution. However we need this fixed urgently, so I'll open the creation of PRs for this issue to others. @VanshikaSabharwal had volunteered to fix it for example.

@palisadoes palisadoes closed this Dec 9, 2024
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.

4 participants