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

Hotfix automatic model score sync #1849

Merged
merged 3 commits into from
Oct 1, 2024

Conversation

CarlosQ96
Copy link
Collaborator

@CarlosQ96 CarlosQ96 commented Oct 1, 2024

Remerging this Pr

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new cron job to periodically update user model scores based on donations.
    • Added functionality to identify users without a model score in the current QF round.
    • New test scripts to validate the functionality of user score updates and retrieval.
  • Bug Fixes

    • Enhanced error handling and logging during cron job execution.
  • Documentation

    • Updated test cases to ensure comprehensive coverage of new functionalities.

Copy link
Contributor

coderabbitai bot commented Oct 1, 2024

Walkthrough

The changes encompass the addition of new functionalities and tests related to user model score synchronization in the giveth-graphql-api project. A new cron job has been introduced to periodically update user scores based on their donation activity. Corresponding test cases have been created to ensure the correctness of these functionalities, alongside updates to existing repository methods to support the new logic.

Changes

File Change Summary
package.json Added a new test script test:syncUsersModelScore to run tests for user score synchronization.
src/repositories/qfRoundRepository.ts Introduced a new function findUsersWithoutMBDScoreInActiveAround to identify users without scores in the active QF round and added a constant for configuration.
src/repositories/qfRoundRepository.test.ts Added a test case for findUsersWithoutMBDScoreInActiveAround to validate its functionality.
src/server/bootstrap.ts Integrated a new cron job function runCheckPendingUserModelScoreCronjob for managing user score synchronization based on an environment variable.
src/services/cronJobs/syncUsersModelScore.test.ts Created a test suite for updateUsersWithoutMBDScoreInRound to validate user score updates during active rounds.
src/services/cronJobs/syncUsersModelScore.ts Added cron job functionality with runCheckPendingUserModelScoreCronjob and updateUsersWithoutMBDScoreInRound for user score updates.
src/workers/userMBDScoreSyncWorker.ts Introduced a worker module with an asynchronous function syncUserScore for concurrent score synchronization.

Possibly related PRs

  • add user mbdscore sync workers and cronjob #1838: The main PR adds a new test script for syncUsersModelScore, which is directly related to the changes in this retrieved PR that also introduces a test script for the same functionality.
  • Feature new qf scoring model #1634: This PR introduces new functions in qfRoundRepository.ts that handle user model scores, which is relevant to the main PR's focus on user score synchronization.
  • Master to develop #1758: This PR modifies package.json and includes changes to qfRoundRepository.ts, which is relevant as it deals with user scores and the repository structure that the main PR interacts with.

Suggested reviewers

  • mohammadranjbarz
  • RamRamez

🐰 In the land of code, where bunnies play,
New scripts and functions hop in today.
With scores to sync and tests so bright,
Our project shines, a true delight!
So let’s all cheer, with a joyful thump,
For every change, we proudly jump! 🎉


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.

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

🧹 Outside diff range and nitpick comments (13)
src/workers/userMBDScoreSyncWorker.ts (1)

1-9: Update the file name in the comment

The comment on line 1 refers to "workers/auth.js", which doesn't match the actual file name "src/workers/userMBDScoreSyncWorker.ts". Please update the comment to reflect the correct file name.

Other than that, the import statements and type definitions look good. The use of custom types enhances type safety and code readability.

src/services/cronJobs/syncUsersModelScore.test.ts (4)

22-37: LGTM: Test setup is comprehensive.

The test setup is thorough, creating necessary QfRound and project data.

Consider extracting the QfRound creation into a separate helper function for better reusability across tests:

function createActiveQfRound() {
  const qfRound = QfRound.create({
    isActive: true,
    name: 'test',
    allocatedFund: 100,
    minimumPassportScore: 8,
    slug: new Date().getTime().toString(),
    beginDate: new Date(),
    endDate: moment().add(10, 'days').toDate(),
  });
  return qfRound.save();
}

38-60: LGTM: User and donation creation look good.

The creation of users and donations is well-structured and appropriate for the test case.

Consider creating a helper function to reduce code duplication when saving donations:

function saveDonationForUser(user, project, qfRound) {
  return saveDonationDirectlyToDb(
    {
      ...createDonationData(),
      segmentNotified: false,
      qfRoundId: qfRound.id,
      status: 'verified',
    },
    user.id,
    project.id,
  );
}

This would allow you to simplify the donation creation for both users:

await saveDonationForUser(user, project, qfRound);
await saveDonationForUser(user2, project, qfRound);

62-84: LGTM with suggestions: Function execution and assertions are good, but can be improved.

The test executes the main function and checks the results correctly. However, there are a few ways to make the test more robust:

  1. Add assertions to check the initial state:
const initialUser1Score = await UserQfRoundModelScore.findOne({ where: { userId: user.id, qfRoundId: qfRound.id } });
const initialUser2Score = await UserQfRoundModelScore.findOne({ where: { userId: user2.id, qfRoundId: qfRound.id } });
assert.isNull(initialUser1Score, 'User 1 should not have a score initially');
assert.isNull(initialUser2Score, 'User 2 should not have a score initially');
  1. Use more specific assertions:
assert.isNotNull(user1ModelScore, 'User 1 should have a model score');
assert.isNotNull(user2ModelScore, 'User 2 should have a model score');
assert.strictEqual(user1ModelScore?.score, 1, 'User 1 score should be 1');
assert.strictEqual(user2ModelScore?.score, 1, 'User 2 score should be 1');
  1. Consider adding a test for a user without donations to ensure they don't get a score:
const userWithoutDonation = await saveUserDirectlyToDb(generateRandomEtheriumAddress());
const userWithoutDonationScore = await UserQfRoundModelScore.findOne({ where: { userId: userWithoutDonation.id, qfRoundId: qfRound.id } });
assert.isNull(userWithoutDonationScore, 'User without donation should not have a score');

These changes will make the test more comprehensive and robust.


1-85: Good test coverage, but consider adding more test cases.

The test file provides good coverage for the happy path of the updateUsersWithoutMBDScoreInRound function. However, to ensure comprehensive testing, consider adding the following test cases:

  1. Test with an inactive round to ensure scores are not updated.

  2. Test with users who have already received scores to check if the function handles updates correctly.

  3. Test with edge cases such as:

    • Users with multiple donations in the same round
    • Rounds with no donations
    • Users with donations in multiple rounds
  4. Test error handling scenarios, such as database connection issues or invalid data.

Adding these test cases will significantly improve the robustness of your test suite and help catch potential edge case bugs.

src/repositories/qfRoundRepository.ts (1)

18-20: LGTM! Consider using SCREAMING_SNAKE_CASE for the constant name.

The addition of the qfRoundUsersMissedMBDScore constant is a good practice for configuration management. It allows for easy adjustment of the value without code changes.

Consider using SCREAMING_SNAKE_CASE for the constant name to adhere to common TypeScript naming conventions for global constants:

const QF_ROUND_USERS_MISSED_MBD_SCORE = Number(
  process.env.QF_ROUND_USERS_MISSED_SCORE || 0
);
src/repositories/qfRoundRepository.test.ts (1)

50-98: LGTM with suggestions: New test case added, consider additional scenarios.

The new test case for findUsersWithoutMBDScoreInActiveAround is well-structured and covers the main functionality. However, consider adding the following test scenarios to improve coverage:

  1. Test with users who have MBD scores to ensure they're not returned.
  2. Test with donations in inactive rounds to ensure those users aren't returned.
  3. Test with unverified donations to ensure those users aren't returned.
  4. Test with an empty database to ensure an empty array is returned.
  5. Test with multiple active rounds to ensure users from all active rounds are returned.

Would you like me to provide example implementations for these additional test scenarios?

src/server/bootstrap.ts (1)

370-374: LGTM: New cron job correctly integrated with feature toggle.

The conditional execution of runCheckPendingUserModelScoreCronjob() is properly implemented using the SYNC_USERS_MBD_SCORE_ACTIVE environment variable. This follows the existing pattern for feature toggles in the codebase.

Consider updating the comment to be more specific:

- // If we need to deactivate the process use the env var NO MORE
+ // To activate/deactivate the user model score sync process, use the SYNC_USERS_MBD_SCORE_ACTIVE env var

This change would make the purpose of the environment variable clearer.

package.json (1)

138-138: LGTM! Consider adding this script to a test group.

The new test script for syncUsersModelScore looks good and follows the established pattern for other test scripts in this project. It correctly sets the NODE_ENV to "test" and includes the pre-test script.

Consider grouping this new test script with other related cron job tests if there are any. This could improve organization and make it easier to run related tests together. For example, you could create a new script that runs all cron job related tests:

"test:cronJobs": "npm run test:syncProjectsRequiredForListing && npm run test:backupDonationImport && npm run test:syncUsersModelScore && npm run test:notifyDonationsWithSegment && npm run test:checkProjectVerificationStatus"

This suggestion is optional and depends on your team's preferences for organizing test scripts.

src/services/cronJobs/syncUsersModelScore.ts (4)

6-8: Typo in imported function name

The function name findUsersWithoutMBDScoreInActiveAround may contain a typo. If the intended name is findUsersWithoutMBDScoreInActiveRound, please correct it in the import statement for clarity.


34-34: Typo in function name findUsersWithoutMBDScoreInActiveAround

The function name findUsersWithoutMBDScoreInActiveAround may contain a typo. If the correct name is findUsersWithoutMBDScoreInActiveRound, consider renaming it for consistency.


58-60: Log the caught exceptions for better debugging

In the catch block, the exception is caught but not logged. Logging the exception details can aid in troubleshooting. Consider modifying the log statement to include the error information:

- logger.info(`User with Id ${userId} did not sync MBD score this batch`);
+ logger.error(`Failed to sync MBD score for user with Id ${userId}:`, e);

47-47: Unnecessary optional chaining on user.walletAddress

Since the user object is verified to exist in the previous line (if (!user) continue;), the optional chaining operator ?. on user.walletAddress is unnecessary. Consider removing it to simplify the code:

- userWallet: user?.walletAddress,
+ userWallet: user.walletAddress,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ecf4e19 and e8d3b25.

📒 Files selected for processing (7)
  • package.json (1 hunks)
  • src/repositories/qfRoundRepository.test.ts (3 hunks)
  • src/repositories/qfRoundRepository.ts (2 hunks)
  • src/server/bootstrap.ts (2 hunks)
  • src/services/cronJobs/syncUsersModelScore.test.ts (1 hunks)
  • src/services/cronJobs/syncUsersModelScore.ts (1 hunks)
  • src/workers/userMBDScoreSyncWorker.ts (1 hunks)
🔇 Additional comments (7)
src/workers/userMBDScoreSyncWorker.ts (1)

17-17: LGTM: Worker correctly exposed

The worker object is properly exposed using the expose function from the 'threads' library. This allows the worker to be used in a multi-threaded environment.

src/services/cronJobs/syncUsersModelScore.test.ts (1)

1-21: LGTM: Imports and test structure look good.

The imports, describe block, and function declaration are well-structured and appropriate for the test file.

src/repositories/qfRoundRepository.test.ts (3)

20-20: LGTM: Import statement added correctly.

The new function findUsersWithoutMBDScoreInActiveAround is imported correctly from the qfRoundRepository file.


31-34: LGTM: New describe block added correctly.

The new describe block for 'findUsersWithoutMBDScoreInActiveAround test cases' is correctly placed and follows the existing naming convention.


Line range hint 1-98: Overall assessment: Good addition with room for improvement.

The new test case for findUsersWithoutMBDScoreInActiveAround is a valuable addition to the test suite. It's well-structured and consistent with the existing codebase. However, to ensure robust testing of this functionality, consider adding more test scenarios as suggested in the previous comment.

Additionally, ensure that the findUsersWithoutMBDScoreInActiveAround function in the main repository file (qfRoundRepository.ts) is implemented correctly to match this test case.

To verify the implementation of findUsersWithoutMBDScoreInActiveAround, please run the following script:

✅ Verification successful

Verification Successful: findUsersWithoutMBDScoreInActiveAround is correctly implemented as an exported constant.

The function findUsersWithoutMBDScoreInActiveAround exists in qfRoundRepository.ts and is defined as an exported constant using an arrow function (export const). This confirms that the implementation aligns with the test case provided in the review comment.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of findUsersWithoutMBDScoreInActiveAround

# Test: Check if the function is implemented in qfRoundRepository.ts
rg --type typescript -A 10 'export async function findUsersWithoutMBDScoreInActiveAround' src/repositories/qfRoundRepository.ts

# Test: Check if the function queries for active QfRounds
rg --type typescript 'isActive: true' src/repositories/qfRoundRepository.ts

# Test: Check if the function filters users without MBD scores
rg --type typescript 'mdbScore' src/repositories/qfRoundRepository.ts

Length of output: 382


Script:

#!/bin/bash
# Description: Verify the implementation of findUsersWithoutMBDScoreInActiveAround with corrected type alias

# Test: Check if the function is implemented in qfRoundRepository.ts
rg --type ts -A 10 'export async function findUsersWithoutMBDScoreInActiveAround' src/repositories/qfRoundRepository.ts

# Test: Check if the function queries for active QfRounds
rg --type ts 'isActive: true' src/repositories/qfRoundRepository.ts

# Test: Check if the function filters users without MBD scores
rg --type ts 'mdbScore' src/repositories/qfRoundRepository.ts

Length of output: 253


Script:

#!/bin/bash
# Description: Comprehensive verification of findUsersWithoutMBDScoreInActiveAround implementation

# Test: Search for any function named findUsersWithoutMBDScoreInActiveAround using ast-grep
ast-grep --lang typescript --pattern 'function findUsersWithoutMBDScoreInActiveAround($_)' src/repositories/qfRoundRepository.ts

# Test: Search for the function name without export or async using rg
rg 'findUsersWithoutMBDScoreInActiveAround' src/repositories/qfRoundRepository.ts

# Test: Search for class methods named findUsersWithoutMBDScoreInActiveAround using ast-grep
ast-grep --lang typescript --pattern 'class $_ { $$$ findUsersWithoutMBDScoreInActiveAround($_) { $$$ } $$$ }' src/repositories/qfRoundRepository.ts

Length of output: 436

src/server/bootstrap.ts (2)

72-72: LGTM: New cron job import added correctly.

The import statement for runCheckPendingUserModelScoreCronjob is correctly placed and follows the existing pattern for importing cron job functions.


72-72: Summary: New user model score sync cron job successfully integrated.

The changes in this PR successfully integrate a new cron job for syncing user model scores. The implementation follows existing patterns in the codebase, making use of a feature toggle through an environment variable. The changes are minimal and well-contained, with no apparent negative impact on existing functionality.

Key points:

  1. New import added for the cron job function.
  2. Conditional execution based on the SYNC_USERS_MBD_SCORE_ACTIVE environment variable.
  3. Proper integration into the initializeCronJobs function.

These changes align well with the PR objective of implementing a "Hotfix automatic model score sync".

Also applies to: 370-374

Comment on lines +11 to +15
const worker: UserMBDScoreSyncWorker = {
async syncUserScore(args: { userWallet: string }) {
return await getGitcoinAdapter().getUserAnalysisScore(args.userWallet);
},
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding error handling and data transformation

The syncUserScore function looks good in terms of simplicity, but there are a couple of improvements to consider:

  1. Error Handling: Add try-catch block to handle potential errors from the getUserAnalysisScore call. This will make the worker more robust and easier to debug.

  2. Data Transformation: Consider if the raw output from getUserAnalysisScore is exactly what you want to return, or if any transformation is needed.

Here's a suggested implementation:

async syncUserScore(args: { userWallet: string }) {
  try {
    const score = await getGitcoinAdapter().getUserAnalysisScore(args.userWallet);
    // Add any necessary data transformation here
    return score;
  } catch (error) {
    console.error(`Error syncing score for wallet ${args.userWallet}:`, error);
    throw error; // or handle it as appropriate for your use case
  }
}

Comment on lines +1 to +17
// workers/auth.js
import { expose } from 'threads/worker';
import { WorkerModule } from 'threads/dist/types/worker';
import { getGitcoinAdapter } from '../adapters/adaptersFactory';

type UsersMBDScoreSyncWorkerFunctions = 'syncUserScore';

export type UserMBDScoreSyncWorker =
WorkerModule<UsersMBDScoreSyncWorkerFunctions>;

const worker: UserMBDScoreSyncWorker = {
async syncUserScore(args: { userWallet: string }) {
return await getGitcoinAdapter().getUserAnalysisScore(args.userWallet);
},
};

expose(worker);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Overall good implementation with minor suggestions

The implementation of the UserMBDScoreSyncWorker is concise, focused, and makes good use of TypeScript and the 'threads' library. Here's a summary of the review:

  1. The file name in the comment needs to be updated (addressed in a previous comment).
  2. Error handling has been suggested for the syncUserScore function.
  3. The worker is correctly exposed for use in a multi-threaded environment.

One additional suggestion:

  1. Consider adding input validation for the userWallet parameter. For example:
async syncUserScore(args: { userWallet: string }) {
  if (!args.userWallet || typeof args.userWallet !== 'string') {
    throw new Error('Invalid userWallet provided');
  }
  // ... rest of the function
}

This will ensure that the function always receives a valid input before proceeding with the API call.

Comment on lines +179 to +202
export const findUsersWithoutMBDScoreInActiveAround = async (): Promise<
number[]
> => {
const activeQfRoundId =
(await findActiveQfRound())?.id || qfRoundUsersMissedMBDScore;

if (!activeQfRoundId || activeQfRoundId === 0) return [];

const usersMissingMDBScore = await QfRound.query(
`
SELECT DISTINCT d."userId"
FROM public.donation d
LEFT JOIN user_qf_round_model_score uqrms ON d."userId" = uqrms."userId" AND uqrms."qfRoundId" = $1
WHERE d."qfRoundId" = $1
AND d.status = 'verified'
AND uqrms.id IS NULL
AND d."userId" IS NOT NULL
ORDER BY d."userId";
`,
[activeQfRoundId],
);

return usersMissingMDBScore.map(user => user.userId);
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Good implementation. Consider using parameterized queries and adding error handling.

The findUsersWithoutMBDScoreInActiveAround function effectively retrieves users without an MBD score in the active QF round. However, there are a few areas for improvement:

  1. Security: Use parameterized queries instead of string interpolation to prevent SQL injection vulnerabilities.
  2. Error Handling: Add try-catch block to handle potential database errors.
  3. Logging: Consider adding logging for important operations and error cases.

Here's a suggested improvement:

export const findUsersWithoutMBDScoreInActiveAround = async (): Promise<number[]> => {
  try {
    const activeQfRound = await findActiveQfRound();
    const activeQfRoundId = activeQfRound?.id ?? QF_ROUND_USERS_MISSED_MBD_SCORE;

    if (!activeQfRoundId || activeQfRoundId === 0) {
      logger.info('No active QF round found');
      return [];
    }

    const usersMissingMDBScore = await QfRound.query(
      `
      SELECT DISTINCT d."userId"
      FROM public.donation d
      LEFT JOIN user_qf_round_model_score uqrms ON d."userId" = uqrms."userId" AND uqrms."qfRoundId" = $1
      WHERE d."qfRoundId" = $1
        AND d.status = $2
        AND uqrms.id IS NULL
        AND d."userId" IS NOT NULL
      ORDER BY d."userId";
      `,
      [activeQfRoundId, 'verified']
    );

    return usersMissingMDBScore.map(user => user.userId);
  } catch (error) {
    logger.error('Error finding users without MBD score', { error });
    throw error;
  }
};

This version improves security by using parameterized queries, adds error handling, and includes logging for important operations.

Comment on lines +370 to +374
// If we need to deactivate the process use the env var NO MORE
if (process.env.SYNC_USERS_MBD_SCORE_ACTIVE === 'true') {
runCheckPendingUserModelScoreCronjob();
}

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

LGTM: New cron job well-integrated into the initialization process.

The runCheckPendingUserModelScoreCronjob() is correctly integrated into the initializeCronJobs function. Its placement and conditional execution are consistent with other cron jobs in the file.

Consider adding a log statement to indicate when this cron job is activated, similar to the logging done for other cron jobs (e.g., the givPower cron jobs). This would improve observability:

 if (process.env.SYNC_USERS_MBD_SCORE_ACTIVE === 'true') {
+  logger.debug('Running user model score sync cron job');
   runCheckPendingUserModelScoreCronjob();
 }
📝 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
// If we need to deactivate the process use the env var NO MORE
if (process.env.SYNC_USERS_MBD_SCORE_ACTIVE === 'true') {
runCheckPendingUserModelScoreCronjob();
}
// If we need to deactivate the process use the env var NO MORE
if (process.env.SYNC_USERS_MBD_SCORE_ACTIVE === 'true') {
logger.debug('Running user model score sync cron job');
runCheckPendingUserModelScoreCronjob();
}

Comment on lines +13 to +14
(config.get('MAKE_UNREVIEWED_PROJECT_LISTED_CRONJOB_EXPRESSION') as string) ||
'0 0 * * * *';
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect configuration key used for cron job schedule

The configuration key 'MAKE_UNREVIEWED_PROJECT_LISTED_CRONJOB_EXPRESSION' seems unrelated to syncing user model scores. Consider defining a new configuration key specific to this cron job, such as 'SYNC_USERS_MODEL_SCORE_CRONJOB_EXPRESSION'.


const cronJobTime =
(config.get('MAKE_UNREVIEWED_PROJECT_LISTED_CRONJOB_EXPRESSION') as string) ||
'0 0 * * * *';
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Cron job default schedule may be incorrect

The default cron expression '0 0 * * * *' schedules the job to run at the top of every hour. If the intended default schedule is to run every minute, consider changing it to '*/1 * * * *'.

Comment on lines +36 to +37
(await findActiveQfRound())?.id || qfRoundUsersMissedMBDScore;
if (!activeQfRoundId || activeQfRoundId === 0) return;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential issue with activeQfRoundId assignment and default value

If findActiveQfRound() returns null or undefined, activeQfRoundId is assigned qfRoundUsersMissedMBDScore, which defaults to 0. However, since the subsequent check returns if activeQfRoundId is 0, the default value doesn't have any effect. Consider handling the absence of an active QF round more explicitly or updating the default value to a meaningful fallback.

Comment on lines +62 to +63
await Thread.terminate(worker);
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure worker thread is terminated even if an exception occurs

If an exception is thrown before reaching await Thread.terminate(worker);, the worker thread may not be terminated properly. Consider using a try...finally block to ensure the worker is terminated regardless of errors:

-export const updateUsersWithoutMBDScoreInRound = async () => {
+export const updateUsersWithoutMBDScoreInRound = async () => {
+  try {
     const worker = await spawn(
       new Worker('../../workers/userMBDScoreSyncWorker'),
     );
     // ...existing code...
   } finally {
     await Thread.terminate(worker);
   }
 };

Committable suggestion was skipped due to low confidence.

@CarlosQ96 CarlosQ96 merged commit de13f3c into staging Oct 1, 2024
9 checks passed
@CarlosQ96 CarlosQ96 deleted the hotfix_automatic_model_score_sync branch October 1, 2024 17:36
CarlosQ96 added a commit that referenced this pull request Oct 3, 2024
* fix: remove memo for project verification managing funds

* fix: remove memo for project verification managing funds

* add projectId and qfRoundId to qf data export

* fix: getDraftDonationById bug (toWalletMemo can be null)

* fix: add memo for stellar project address uniqueness

* fix: add memo for manage address validation

* fix: add duplicate address error message for stellar

* fix: linter error

* add index for project stellar address

* eslint error

* fix: case when owner donate to his own peoject (Stellar chain)

* fix: add calculateGivbackFactor to Stellar cron job

* onlyEndaement option added to donationResolvers to get only endaoment projects

* chore: implementing coderabbitai suggestion to remove string literal

* feat: register secondary donation

* running migration to set project banners appropriately for endaoment … (#1778)

* running migration to set project banners appropriately for endaoment projects

* chore: correcting tab spaces for syntax

* fix: linter errors

* Modify add banner to endaoment projects migration (#1791)

related to #1600

* Fix lint errors

* Fix running tests

* Fix projectResolver test cases

* Fix donationResolver test cases

* skip should renew the expiration date of the draft donation test case

---------

Co-authored-by: Hrithik Sampson <hrithiksampson@Hrithiks-MacBook-Air.local>
Co-authored-by: mohammadranjbarz <mranjbar.z2993@gmail.com>

* improve adminjs to import qfround matching and better filters

* fix eslint

* fix: remove adding secondary donation logic

* fix minor form issues

* order middleware in bootstrap file

* test: add test cases to fetch only Endaoment projects

* chore: change the second Project to first Project

* chore: change the second Project to first Project

* chore: change the second Project to first Project

* chore: change the second user to new user since it is interfering with the pre-existing test cases

* delete previous_round_rank when deleting a project (#1809)

* Implement  allocatedGivbacks function (#1808)

* WIP Implement  allocatedGivbacks function

related to Giveth/giveth-dapps-v2#4678 Giveth/giveth-dapps-v2#4679

* allocatedGivbacks() endpoint implemented and works

related to Giveth/giveth-dapps-v2#4678 Giveth/giveth-dapps-v2#4679

* Fix allocatedGivbacksQuery test cases

* migration: project banners for endaoment projects need to have the correct banners

* chore: underscore before unused variable in add_endaoment_project_banners

* Use Gnosis giv token for getting price of GIV

* Use superfluid mock adapter for test cases

* Use superfluid adapter on test env again

* Feat/separate givback verfied (#1770)

* add isGivbackEligible field

* add AddIsGivbackEligibleColumnToProject1637168932304

* add UpdateIsGivbackEligibleForVerifiedProjects1637168932305 migration

* add migration to rename isProjectVerified to isProjectGivbackEligible

* change isProjectVerified tp isProjectGivbackEligible

* update octant donation

* add approve project

* treat project.verified and project.isGivbackEligible equally on sorting

* remove reset verification status on verify

* check isGivbackEligible on create ProjectVerificationForm

* add ProjectInstantPowerViewV3 migration

* use verifiedOrIsGivbackEligibleCondition

* Use different materialized view for givback factor

related to #1770

* Fix build error

* Fix build error

* Fix project query for isGivbackEligible and verified

* Fix add base token migration

* Fix eslint errors

* Fix add base token migration

* Fix add base token migration

* Fix add base token migration

* Fix donation test cases related to isGivbackEligible

* Fix build error

---------

Co-authored-by: Mohammad Ranjbar Z <mranjbar.z2993@gmail.com>

* Fix test cases related to isProjectVerified

* add isImported And categories to project tab

* fix isProjectGivbackEligible Migration in wrong folder

* add chaintype and solana networks to tokenTab

* update branch

* add environment and energy image mapping

* add categories to show and edit forms in adminjs for projects

* fix eslint

* add best match sort option

* update addSearchQuery to prioritize the title

* Add Stellar to QFRound

* run linter

* remove eager from project categories in entity

* Add isGivbackEligible filter

* Hotfix automatic model score sync (#1849)

* add user mbdscore sync workers and cronjob

* add active env var for syncing score

* add tests to the user sync worker and cronjob

* prevent duplicate tokens being added in adminJS

* Ensure correct emails are sent for project status changes related to decentralized verification

* fix test

* fix test cases

* fix test cases

---------

Co-authored-by: Meriem-BM <barhoumi.meriem1@gmail.com>
Co-authored-by: Carlos <carlos.quintero096@gmail.com>
Co-authored-by: HrithikSampson <hrithikedwardsampson@gmail.com>
Co-authored-by: HrithikSampson <56023811+HrithikSampson@users.noreply.github.com>
Co-authored-by: Hrithik Sampson <hrithiksampson@Hrithiks-MacBook-Air.local>
Co-authored-by: CarlosQ96 <92376054+CarlosQ96@users.noreply.github.com>
Co-authored-by: Cherik <Pourcheriki@gmail.com>
Co-authored-by: Ramin <raminramazanpour@gmail.com>
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