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

Optimze fetch functions #212

Merged
merged 10 commits into from
Jul 9, 2024
Merged

Optimze fetch functions #212

merged 10 commits into from
Jul 9, 2024

Conversation

Behzad-rabiei
Copy link
Member

@Behzad-rabiei Behzad-rabiei commented Jul 9, 2024

Summary by CodeRabbit

  • New Features

    • Added the ability to retrieve the latest guild member data based on specified filter criteria.
    • Introduced fetching of all users who reacted to a message with a specific emoji.
  • Enhancements

    • Improved channel, member, and role fetching processes for better performance and logging.
    • Enhanced metadata update logic for platform data during fetch operations.
    • Updated Discord bot initialization process for better clarity and functionality.
  • Bug Fixes

    • Improved error logging for RnDAO guild command deletions.

Copy link

coderabbitai bot commented Jul 9, 2024

Walkthrough

Recent changes were made across multiple files to enhance and optimize the codebase. Key updates include the addition of a function to retrieve the oldest guild member, refined fetching logic for channels and members, improved reaction handling for messages, and concurrent data fetching for members, channels, and roles. Additionally, logging was adjusted for better clarity, and initialization routines were consolidated for the Discord bot.

Changes

File Change Summary
src/database/services/guildMember.service.ts Added getLatestGuildMember function to fetch the oldest guild member based on filter criteria.
src/functions/fetchChannels.ts, src/functions/fetchRoles.ts Refactored fetching and processing logic, removed unnecessary function pushChannelsToArray, improved logging.
src/functions/fetchMembers.ts Introduced chunk-based member fetching, added constants, refined function signatures, and logging.
src/functions/fetchMessages.ts Modified to better handle reactions and users fetching, adding fetchAllUsersForReaction function.
src/functions/guildExtraction.ts Consolidated logic into a single function, removing individual calls to fetch data and enhancing logging.
src/index.ts Reorganized function calls within app() for better initialization flow and modified a logging message.
src/rabbitmq/events/fetchEvent.ts Updated to fetch members, channels, and roles concurrently after metadata updates.
src/rabbitmq/events/fetchMembersEvent.ts Enhanced to set a flag before concurrent data fetching, improving robustness and clarity of the process.
src/scripts/deleteRnDAOGuildCommands.ts Replaced console.log with logger.error for error handling during command deletion.
src/services/core.service.ts Updated DiscordBotManager to include additional GatewayIntentBits and Partials for enhanced functionality.

Sequence Diagram(s)

sequenceDiagram
    participant Platform
    participant BotManager
    participant FetchEvent
    participant GuildMemberService

    Note right of Platform: Initial State

    Platform->>FetchEvent: Trigger Data Fetch
    FetchEvent->>BotManager: Initialize Fetching

    par Concurrent Data Fetch
        FetchEvent->>GuildMemberService: Fetch Members
        FetchEvent->>BotManager: Fetch Channels
        FetchEvent->>BotManager: Fetch Roles
    end

    FetchEvent->>Platform: Update Metadata

    Note right of Platform: Final State
Loading

Poem

🐇 In code we find harmony, a digital delight,
Fetching data by chunks, both day and night.
Channels and members, reactions galore,
Guilds refreshed, optimizations soar.
With logs and intents, our bot takes flight,
Oh, what a wondrous code update sight!


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

@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 (6)
src/functions/guildExtraction.ts (2)

16-16: Add clarity to the log message.

The log message could be more descriptive to indicate the start of the guild extraction process.

- logger.info({ guild_id: platform.metadata?.id }, 'Guild extraction for guild is running');
+ logger.info({ guild_id: platform.metadata?.id }, `Guild extraction for guild ${platform.metadata?.id} is starting`);

27-27: Add clarity to the log message.

The log message could be more descriptive to indicate the end of the guild extraction process.

- logger.info({ guild_id: platform.metadata?.id }, 'Guild extraction for guild is done');
+ logger.info({ guild_id: platform.metadata?.id }, `Guild extraction for guild ${platform.metadata?.id} is completed`);
src/index.ts (1)

37-37: Improve fatal error log message.

The log message could be more descriptive to indicate the failure reason.

- logger.fatal({ error }, 'Failed To start the application!!');
+ logger.fatal({ error }, 'Failed to start the application due to an error');
src/functions/fetchRoles.ts (3)

21-21: Add clarity to the log message.

The log message could be more descriptive to indicate the missing bot access.

- logger.info({ guild_id: platform.metadata?.id }, 'Bot access missing');
+ logger.info({ guild_id: platform.metadata?.id }, `Bot access to guild ${platform.metadata?.id} is missing`);

25-25: Add clarity to the log message.

The log message could be more descriptive to indicate the start of role fetching.

- logger.info({ guild_id: platform.metadata?.id }, 'Fetching roles');
+ logger.info({ guild_id: platform.metadata?.id }, `Fetching roles for guild ${platform.metadata?.id}`);

29-29: Add clarity to the log message.

The log message could be more descriptive to indicate the successful storage of roles.

- logger.info({ guild_id: platform.metadata?.id }, 'Roles stored successfully');
+ logger.info({ guild_id: platform.metadata?.id }, `Roles for guild ${platform.metadata?.id} stored successfully`);
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between acafc4c and 0219dcd.

Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
Files selected for processing (11)
  • src/database/services/guildMember.service.ts (2 hunks)
  • src/functions/fetchChannels.ts (3 hunks)
  • src/functions/fetchMembers.ts (2 hunks)
  • src/functions/fetchMessages.ts (2 hunks)
  • src/functions/fetchRoles.ts (3 hunks)
  • src/functions/guildExtraction.ts (2 hunks)
  • src/index.ts (1 hunks)
  • src/rabbitmq/events/fetchEvent.ts (1 hunks)
  • src/rabbitmq/events/fetchMembersEvent.ts (1 hunks)
  • src/scripts/deleteRnDAOGuildCommands.ts (1 hunks)
  • src/services/core.service.ts (3 hunks)
Files skipped from review due to trivial changes (1)
  • src/scripts/deleteRnDAOGuildCommands.ts
Additional comments not posted (19)
src/index.ts (1)

21-25: Ensure correct initialization sequence.

The reordering of these function calls appears logical, but verify that the new sequence does not introduce any dependency issues.

src/functions/fetchRoles.ts (1)

19-19: Avoid potential data inconsistency.

Ensure that the rolesToStore array is only populated if the bot has access to the guild.

src/services/core.service.ts (3)

1-1: Ensure necessary imports.

Verify that the additional GatewayIntentBits and Partials are required for the application's functionality.


17-19: Avoid redundant intents.

The GatewayIntentBits.DirectMessages appears twice in the intents array.

- GatewayIntentBits.DirectMessages,

Likely invalid or redundant comment.


36-38: Avoid redundant intents.

The GatewayIntentBits.DirectMessages appears twice in the intents array.

- GatewayIntentBits.DirectMessages,

Likely invalid or redundant comment.

src/functions/fetchChannels.ts (3)

27-28: Verify channel type filtering logic.

Ensure that the filtering logic correctly identifies the needed channel types (0, 2, 4). Consider adding a comment to explain the channel types for better readability.


30-31: Mapping operation looks good.

The mapping operation using channelService.getNeededDateFromChannel is a good refactor. Ensure that all required channel data is correctly extracted and stored.


32-32: Good error handling.

The error handling with logging is well-implemented. Ensure that the error messages provide enough context for debugging.

src/rabbitmq/events/fetchMembersEvent.ts (3)

17-17: Ensure correct metadata flag update before fetching.

The metadata flag isFetchingIntialData is set to true before fetching. Ensure that this update is correctly reflected in the platform metadata.


18-22: Concurrent fetching looks good.

The use of Promise.all for concurrent fetching is a good optimization. Ensure that each fetch function (fetchMembers, fetchChannels, fetchRoles) handles errors properly to avoid unhandled promise rejections.


23-23: Ensure correct metadata flag update after fetching.

The metadata flag isFetchingIntialData is set to false after fetching. Ensure that this update is correctly reflected in the platform metadata.

src/rabbitmq/events/fetchEvent.ts (3)

26-26: Ensure correct metadata flag update before fetching.

The metadata flag isFetchingIntialData is set to true before fetching. Ensure that this update is correctly reflected in the platform metadata.


27-31: Concurrent fetching looks good.

The use of Promise.all for concurrent fetching is a good optimization. Ensure that each fetch function (fetchMembers, fetchChannels, fetchRoles) handles errors properly to avoid unhandled promise rejections.


32-32: Ensure correct metadata flag update after fetching.

The metadata flag isFetchingIntialData is set to false after fetching. Ensure that this update is correctly reflected in the platform metadata.

src/functions/fetchMembers.ts (3)

37-39: Mapping and storing members looks good.

The mapping operation using guildMemberService.getNeededDateFromGuildMember and storing members with createGuildMembers is a good approach. Ensure that all required member data is correctly extracted and stored.


54-57: Ensure correct handling of platform parameter.

The platform parameter is correctly passed to the function. Ensure that all necessary platform metadata is used within the function.


66-68: Fetching members logic looks good.

The fetching logic using fetchMembersInChunks is well-implemented. Ensure that all members are correctly fetched and stored.

src/functions/fetchMessages.ts (2)

34-64: Ensure proper handling of custom emojis and improve error handling.

The function appears to handle custom emojis correctly. However, ensure that all potential errors are logged appropriately.


69-112: Ensure proper handling of pagination and improve error handling.

The function handles pagination correctly. However, ensure that all potential errors are logged appropriately.

Comment on lines +207 to +217
/**
* Retrieves the oldest guildMember object from the database.
* @param {Connection} connection - Mongoose connection object for the database.
* @param {object} filter - An object specifying the filter criteria to match the desired rawInfo entry.
* @returns {Promise<IRawInfo | null>} - A promise that resolves to the oldest rawInfo object for the channel, or null if not found.
*/
async function getLatestGuildMember(connection: Connection, filter: object): Promise<IGuildMember | null> {
return await connection.models.GuildMember.findOne(filter).sort({
_id: -1,
});
}
Copy link

Choose a reason for hiding this comment

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

Add error handling for getLatestGuildMember.

The function should handle potential errors that might occur during the database query.

async function getLatestGuildMember(connection: Connection, filter: object): Promise<IGuildMember | null> {
  try {
    return await connection.models.GuildMember.findOne(filter).sort({
      _id: -1,
    });
  } catch (error) {
    logger.error({ database: connection.name, filter, error }, 'Failed to get latest guild member');
    return null;
  }
}
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
/**
* Retrieves the oldest guildMember object from the database.
* @param {Connection} connection - Mongoose connection object for the database.
* @param {object} filter - An object specifying the filter criteria to match the desired rawInfo entry.
* @returns {Promise<IRawInfo | null>} - A promise that resolves to the oldest rawInfo object for the channel, or null if not found.
*/
async function getLatestGuildMember(connection: Connection, filter: object): Promise<IGuildMember | null> {
return await connection.models.GuildMember.findOne(filter).sort({
_id: -1,
});
}
/**
* Retrieves the oldest guildMember object from the database.
* @param {Connection} connection - Mongoose connection object for the database.
* @param {object} filter - An object specifying the filter criteria to match the desired rawInfo entry.
* @returns {Promise<IRawInfo | null>} - A promise that resolves to the oldest rawInfo object for the channel, or null if not found.
*/
async function getLatestGuildMember(connection: Connection, filter: object): Promise<IGuildMember | null> {
try {
return await connection.models.GuildMember.findOne(filter).sort({
_id: -1,
});
} catch (error) {
logger.error({ database: connection.name, filter, error }, 'Failed to get latest guild member');
return null;
}
}

Comment on lines +22 to +26
// TODO: fetch after latest stored guild member
// const latestGuildMember = await guildMemberService.getLatestGuildMember(connection,{})
// if(latestGuildMember !== null){
// lastMemberId=latestGuildMember.discordId;
// }
Copy link

Choose a reason for hiding this comment

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

Address the TODO comment.

The TODO comment indicates that the function should fetch members after the latest stored guild member. Implement this logic to avoid fetching duplicate members.

Do you want me to implement this logic or open a GitHub issue to track this task?

@cyri113 cyri113 merged commit 93d6bfb into main Jul 9, 2024
13 checks passed
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