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

fix/be/server-index-cleanup #1057

Merged
merged 1 commit into from
Oct 25, 2024
Merged

fix/be/server-index-cleanup #1057

merged 1 commit into from
Oct 25, 2024

Conversation

ajhollid
Copy link
Collaborator

This PR cleans up the main server file

  • Remove unused endpoints
  • Add a disconnet method for mongoDB to properly disconnect on shutdown
  • Move DB connection from configs folder to index.js
    • Delete configs directory, it is not needed

Copy link

coderabbitai bot commented Oct 24, 2024

Walkthrough

The changes involve the removal of the connectDbAndRunServer function from Server/configs/db.js, which previously handled database connections and server startup. In Server/db/mongo/MongoDB.js, logging functionality is enhanced, and a new disconnect method is introduced for managing database disconnections. The Server/index.js file is updated to establish a database connection directly and includes new service dependencies. Additionally, the cleanup process is modified to ensure proper disconnection from the database during shutdown.

Changes

File Path Change Summary
Server/configs/db.js Method removed: connectDbAndRunServer
Server/db/mongo/MongoDB.js Method added: disconnect; logging updated to use logger instead of console.log
Server/index.js Constant added: const PORT = 5000; updated database connection logic; removed email route; added call to await db.disconnect()

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • marcelluscaio

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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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

@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 (2)
Server/index.js (2)

Line range hint 68-76: Mom's spaghetti moment: Let's decouple these services!

Adding services directly to the request object creates tight coupling. Consider using a dependency injection container to manage these services more effectively.

Consider using a DI container like awilix:

import { createContainer, asClass, asValue } from 'awilix';

const container = createContainer();
container.register({
  db: asValue(db),
  jobQueue: asValue(jobQueue),
  emailService: asValue(emailService),
  settingsService: asValue(settingsService)
});

app.use((req, res, next) => {
  req.container = container;
  next();
});

158-161: There's vomit on his sweater: Let's clean up this error handling!

The error logging could be more informative by including additional context and stack traces.

Enhance the error logging:

 logger.error(error.message, {
   service: SERVICE_NAME,
+  stack: error.stack,
+  timestamp: new Date().toISOString(),
+  startupPhase: 'initialization'
 });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 07a918b and 0649002.

📒 Files selected for processing (3)
  • Server/configs/db.js (0 hunks)
  • Server/db/mongo/MongoDB.js (3 hunks)
  • Server/index.js (5 hunks)
💤 Files with no reviewable changes (1)
  • Server/configs/db.js
🔇 Additional comments (3)
Server/index.js (1)

142-142: ⚠️ Potential issue

Arms are heavy: Let's make the cleanup more steady!

The cleanup process needs improvement:

  1. Replace console.log with logger
  2. Add timeout for graceful shutdown

Here's how to enhance it:

-console.log("Already cleaning up");
+logger.info("Cleanup already in progress", { service: SERVICE_NAME });
-console.log("Shutting down gracefully");
+logger.info("Initiating graceful shutdown", { service: SERVICE_NAME });

+const SHUTDOWN_TIMEOUT = 10000; // 10 seconds
+const shutdownTimer = setTimeout(() => {
+  logger.error("Forced shutdown due to timeout", { service: SERVICE_NAME });
+  process.exit(1);
+}, SHUTDOWN_TIMEOUT);

 await jobQueue.obliterate();
 await db.disconnect();
+clearTimeout(shutdownTimer);
-console.log("Finished cleanup");
+logger.info("Cleanup completed successfully", { service: SERVICE_NAME });

Likely invalid or redundant comment.

Server/db/mongo/MongoDB.js (2)

4-5: Yo, these logging improvements are straight fire! 🔥

The addition of structured logging and the SERVICE_NAME constant brings better observability to the MongoDB operations. This is a solid improvement over console.log statements.


169-169: Clean export addition, no cap! 💯

The disconnect method is properly exported, maintaining consistency with the existing export structure.

@@ -51,31 +50,11 @@ const __dirname = path.dirname(__filename);
const openApiSpec = JSON.parse(
fs.readFileSync(path.join(__dirname, "openapi.json"), "utf8")
);

const PORT = 5000;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Yo dawg, let's make that PORT configurable!

Instead of hardcoding the port number, we should make it configurable through environment variables. This makes the app more flexible across different environments.

Here's a better way to handle it:

-const PORT = 5000;
+const PORT = process.env.PORT || 5000;
📝 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 PORT = 5000;
const PORT = process.env.PORT || 5000;

Comment on lines +107 to +110
await db.connect();
app.listen(PORT, () => {
console.log(`server started on port:${PORT}`);
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Knees weak: Server startup sequence needs strengthening!

Two issues here:

  1. Using console.log instead of the logger utility
  2. Server starts before all services are initialized (emailService, networkService, etc.)

Fix the logging and sequence:

 await db.connect();
-app.listen(PORT, () => {
-  console.log(`server started on port:${PORT}`);
-});
 const settingsService = new SettingsService(AppSettings);
 await settingsService.loadSettings();
 // ... other service initialization ...
+app.listen(PORT, () => {
+  logger.info(`Server started on port:${PORT}`, { service: SERVICE_NAME });
+});

Committable suggestion was skipped due to low confidence.

@@ -17,14 +19,30 @@ const connect = async () => {
appSettings = new AppSettings({});
await appSettings.save();
}

console.log("Connected to MongoDB");
logger.info("Connected to MongoDB", { service: SERVICE_NAME, method: "connect" });
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Yo dawg, we need to beef up this error handling! 💪

While the structured logging is dope, we could make this even better:

  1. Add connection string validation
  2. Include more error context in the logs

Here's how we can level up this code:

 const connect = async () => {
 	try {
 		const connectionString =
 			process.env.DB_CONNECTION_STRING || "mongodb://localhost:27017/uptime_db";
+		if (!connectionString.startsWith('mongodb://') && !connectionString.startsWith('mongodb+srv://')) {
+			throw new Error('Invalid MongoDB connection string');
+		}
 		await mongoose.connect(connectionString);
 		// If there are no AppSettings, create one
 		let appSettings = await AppSettings.find();
 		if (appSettings.length === 0) {
 			appSettings = new AppSettings({});
 			await appSettings.save();
 		}
 		logger.info("Connected to MongoDB", { service: SERVICE_NAME, method: "connect" });
 	} catch (error) {
 		logger.error("failed to connect to MongoDB", {
 			service: SERVICE_NAME,
 			method: "connect",
+			error: error.message,
+			stack: error.stack
 		});
 		throw error;
 	}
 };

Also applies to: 24-27

Comment on lines +32 to +44
const disconnect = async () => {
try {
logger.info("Disconnecting from MongoDB", { service: SERVICE_NAME });
await mongoose.disconnect();
logger.info("Disconnected from MongoDB", { service: SERVICE_NAME });
return;
} catch (error) {
logger.error("failed to disconnect from MongoDB", {
service: SERVICE_NAME,
errorMsg: error.message,
});
}
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Mom's spaghetti moment: Let's make this disconnect method bulletproof! 🍝

The disconnect method is looking clean, but we could make it even more robust with a few tweaks:

  1. Return success/failure status
  2. Add timeout handling

Here's the improved version:

 const disconnect = async () => {
 	try {
 		logger.info("Disconnecting from MongoDB", { service: SERVICE_NAME });
-		await mongoose.disconnect();
+		await Promise.race([
+			mongoose.disconnect(),
+			new Promise((_, reject) => 
+				setTimeout(() => reject(new Error('Disconnect timeout')), 5000)
+			)
+		]);
 		logger.info("Disconnected from MongoDB", { service: SERVICE_NAME });
-		return;
+		return true;
 	} catch (error) {
 		logger.error("failed to disconnect from MongoDB", {
 			service: SERVICE_NAME,
 			errorMsg: error.message,
+			stack: error.stack
 		});
+		return false;
 	}
 };
📝 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 disconnect = async () => {
try {
logger.info("Disconnecting from MongoDB", { service: SERVICE_NAME });
await mongoose.disconnect();
logger.info("Disconnected from MongoDB", { service: SERVICE_NAME });
return;
} catch (error) {
logger.error("failed to disconnect from MongoDB", {
service: SERVICE_NAME,
errorMsg: error.message,
});
}
};
const disconnect = async () => {
try {
logger.info("Disconnecting from MongoDB", { service: SERVICE_NAME });
await Promise.race([
mongoose.disconnect(),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Disconnect timeout')), 5000)
)
]);
logger.info("Disconnected from MongoDB", { service: SERVICE_NAME });
return true;
} catch (error) {
logger.error("failed to disconnect from MongoDB", {
service: SERVICE_NAME,
errorMsg: error.message,
stack: error.stack
});
return false;
}
};

@ajhollid ajhollid merged commit c196317 into develop Oct 25, 2024
3 checks passed
@ajhollid ajhollid deleted the fix/be/server-index-cleanup branch October 25, 2024 01:28
This was referenced Oct 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants