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

Change logic for Sitemap CronJob #1912

Open
wants to merge 2 commits into
base: staging
Choose a base branch
from
Open

Conversation

kkatusic
Copy link
Collaborator

@kkatusic kkatusic commented Jan 21, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced sitemap generation process with more comprehensive data collection.
    • Added ability to fetch and include projects, users, and QF rounds in sitemap.
    • Improved logging and error handling for sitemap generation.
  • Chores

    • Updated environment variable configuration for frontend URL retrieval.

@kkatusic kkatusic self-assigned this Jan 21, 2025
Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

Walkthrough

The pull request modifies the functionality of the cron job responsible for generating a sitemap on the frontend. It introduces new asynchronous functions to fetch projects, users, and qfRounds from the database, replacing a previous generic request. The job now uses a POST request instead of GET, sending a detailed payload of collected data. Additionally, it retrieves the frontend URL from environment variables and includes enhanced logging for better observability.

Changes

File Change Summary
src/services/cronJobs/generateSitemapOnFrontend.ts - Added FRONTEND_URL constant from environment variables
- Implemented fetchProjects(), fetchUsers(), and fetchQFRounds() async functions
- Modified sitemap generation to use POST request with collected data
- Added logging for frontend URL

Possibly related PRs

  • Feat/Cron job for sitemap generating on FE #1900: This PR introduces a new cron job for generating a sitemap on the frontend, which is directly related to the changes made in the main PR regarding the functionality of the sitemap generation.
  • Fix/Sitemap env variables #1910: This PR fixes the syntax for interpolating environment variables in the runGenerateSitemapOnFrontend function, which is relevant to the changes in the main PR that also involve this function.
  • fix missing prefix for url #1911: This PR adds the https:// prefix to the FRONTEND_URL in the runGenerateSitemapOnFrontend function, which is directly related to the changes made in the main PR regarding the same function.

Suggested reviewers

  • CarlosQ96

Poem

🐰 In the garden of code, a sitemap blooms,
Fetching projects and users, dispelling the glooms.
With a POST request, the data takes flight,
Logging the URL, shining so bright.
Cron jobs dance, in digital delight! 🌐

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

🧹 Nitpick comments (5)
src/services/cronJobs/generateSitemapOnFrontend.ts (5)

4-4: Use consistent terminology in comments.

Consider updating "qfRounds" to "QF rounds" for clarity and consistency.


44-47: Validate FRONTEND_URL to ensure it's a valid URL.

Even if FRONTEND_URL is defined, it might not be a valid URL. Consider adding validation to ensure frontendUrl is correctly formed before making the request.

You can enhance the validation as follows:

          const frontendUrl = FRONTEND_URL.startsWith('http')
            ? FRONTEND_URL.trim()
            : `https://${FRONTEND_URL.trim()}`;

+         try {
+           new URL(frontendUrl);
+         } catch (e) {
+           logger.error('Invalid FRONTEND_URL:', frontendUrl);
+           return;
+         }

34-36: Handle empty data arrays gracefully when fetching data.

If any of the fetchProjects, fetchUsers, or fetchQFRounds functions return empty arrays due to errors, the POST request still proceeds. Consider adding checks to handle empty data arrays and log warnings or adjust the request accordingly.

Example:

          const projects = await fetchProjects();
          const users = await fetchUsers();
          const qfRounds = await fetchQFRounds();

+         if (projects.length === 0 && users.length === 0 && qfRounds.length === 0) {
+           logger.warn('No data fetched for sitemap generation. Skipping request.');
+           return;
+         }

32-32: Avoid logging environment variables directly.

Logging process.env.FRONTEND_URL may expose sensitive information in your logs. Consider logging the FRONTEND_URL variable instead, which you've already assigned and possibly sanitized.

Apply this diff:

-        logger.debug('FRONTEND_URL:', process.env.FRONTEND_URL);
+        logger.debug('FRONTEND_URL:', FRONTEND_URL);

48-54: Ensure error handling covers failed POST requests.

While the code is wrapped in a try-catch block, consider handling specific HTTP errors or adding retry logic if the POST request fails due to transient network issues.

Optionally, you can enhance error handling as follows:

          const response = await axios.post(
            `${frontendUrl}/api/generate-sitemap`,
            {
              projects,
              users,
              qfRounds,
            },
            {
              headers: {
                Authorization: `Bearer ${process.env.SITEMAP_CRON_SECRET}`,
              },
+             timeout: 5000, // Set a timeout for the request
            },
          );

And handle specific error cases:

        } catch (error) {
+         if (error.response) {
+           // The request was made and the server responded with a status code outside of the 2xx range
+           logger.error('Sitemap generation failed with status:', error.response.status);
+         } else if (error.request) {
+           // The request was made but no response was received
+           logger.error('No response received for sitemap generation request:', error.message);
+         } else {
+           // Something happened in setting up the request that triggered an Error
+           logger.error('Error in sitemap generation request setup:', error.message);
+         }
          logger.error('runGenerateSitemapOnFrontend() error:', error.message);
        }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7bbfcdf and 8e8f471.

📒 Files selected for processing (1)
  • src/services/cronJobs/generateSitemapOnFrontend.ts (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (2)
src/services/cronJobs/generateSitemapOnFrontend.ts (2)

71-74: Data fetching for projects is implemented correctly.

The fetchProjects function correctly retrieves active projects with the required fields.


98-100: Data fetching for QF rounds is implemented correctly.

The fetchQFRounds function appropriately retrieves QF round data needed for the sitemap.

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

♻️ Duplicate comments (1)
src/services/cronJobs/generateSitemapOnFrontend.ts (1)

84-95: ⚠️ Potential issue

Review PII exposure in user data fetching.

The function selects sensitive user information (firstName, lastName, walletAddress) which may have privacy implications.

Consider limiting the data to only what's necessary for the sitemap:

     const users = await User.createQueryBuilder('user')
-      .select(['user.firstName', 'user.lastName', 'user.walletAddress'])
+      .select(['user.slug', 'user.username'])
       .getMany();
🧹 Nitpick comments (2)
src/services/cronJobs/generateSitemapOnFrontend.ts (2)

49-55: Enhance error handling for data fetching.

While the code properly sends the data via POST request, consider adding validation for the fetched data before making the request. If all fetch operations fail, you might want to skip the request entirely.

+      if (!projects.length && !users.length && !qfRounds.length) {
+        logger.error('No data fetched for sitemap generation');
+        return;
+      }
+
       const response = await axios.post(

97-108: Consider adding pagination for large datasets.

While the current implementation works, fetching all records at once might cause memory issues as the dataset grows. Consider implementing pagination or limiting the number of records fetched.

   try {
     const qfRounds = await QfRound.createQueryBuilder('qf_round')
       .select(['qf_round.slug', 'qf_round.name', 'qf_round.description'])
+      .take(1000) // Add a reasonable limit
       .getMany();
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8e8f471 and e33a3ea.

📒 Files selected for processing (1)
  • src/services/cronJobs/generateSitemapOnFrontend.ts (4 hunks)
🔇 Additional comments (4)
src/services/cronJobs/generateSitemapOnFrontend.ts (4)

14-16: LGTM! Imports are properly organized.

The new entity imports are necessary for the data fetching functionality.


34-39: LGTM! Early return for missing FRONTEND_URL.

The validation logic properly checks for undefined or empty FRONTEND_URL and returns early, preventing invalid requests.


45-47: LGTM! Proper URL formatting.

The code ensures the URL has the correct format by adding 'https://' if not already present.


70-82: LGTM! Project fetching is well implemented.

The function properly filters for active projects and selects only the necessary fields for sitemap generation.

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.

1 participant