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

refactor(torii-core): enqueue models & events #2471

Merged
merged 4 commits into from
Sep 24, 2024

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Sep 24, 2024

Summary by CodeRabbit

  • New Features

    • Introduced new query types: EventMessage, RegisterModel, and StoreEvent, enhancing the query handling capabilities.
    • Improved event messaging system with better error handling for database queries.
  • Refactor

    • Streamlined SQL query handling by centralizing parameter management and modifying how events are processed and communicated.

@Larkooo Larkooo marked this pull request as ready for review September 24, 2024 17:28
Copy link

coderabbitai bot commented Sep 24, 2024

Walkthrough

Ohayo, sensei! This pull request introduces changes to the QueryType enum and the QueryQueue implementation in query_queue.rs, adding three new variants: EventMessage(Ty), RegisterModel, and StoreEvent. The sql.rs file is refactored to enhance SQL query handling, including the removal of certain imports and a shift to a new parameter binding approach. Overall, these modifications expand the functionality of the query handling system and streamline interactions with the database.

Changes

Files Change Summary
crates/torii/core/src/query_queue.rs Added new enum variants: EventMessage(Ty), RegisterModel, and StoreEvent. Updated QueryQueue to handle these variants, including error handling for database queries and publishing corresponding broker messages.
crates/torii/core/src/sql.rs Removed chrono::Utc and event-related imports. Refactored SQL query handling to use an arguments vector for parameter binding. Changed how messages are enqueued to the query_queue, removing direct fetching of certain types.

Possibly related PRs

Suggested reviewers

  • glihm: A potential reviewer with relevant expertise for this pull request.

Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4915e74 and 10f4805.

Files selected for processing (1)
  • crates/torii/core/src/sql.rs (4 hunks)
Files skipped from review as they are similar to previous changes (1)
  • crates/torii/core/src/sql.rs

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

@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

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b598b07 and d1990c0.

Files selected for processing (2)
  • crates/torii/core/src/query_queue.rs (2 hunks)
  • crates/torii/core/src/sql.rs (4 hunks)
Additional comments not posted (6)
crates/torii/core/src/query_queue.rs (2)

52-54: Ohayo, sensei! The new QueryType variants look great.

Adding EventMessage(Ty), RegisterModel, and StoreEvent to the QueryType enum appropriately extends the functionality of the query handling system.


150-158: Verify that EventMessageUpdated receives the correct updated_model.

Ohayo, sensei! In the QueryType::EventMessage(entity) variant, event_message.updated_model is set using the provided entity. Please verify that entity contains the correct data and that updated_model is being used as intended in subsequent processing.

You can confirm this by checking where EventMessageUpdated is published and how updated_model is utilized:

crates/torii/core/src/sql.rs (4)

18-19: Ohayo, sensei! The new imports enhance the functionality.

The addition of Argument, DeleteEntityQuery, QueryQueue, and QueryType from query_queue, as well as utc_dt_string_from_timestamp from utils, is appropriate for the refactoring efforts.


174-184: Ohayo, sensei! The arguments vector is correctly constructed for the insert_models query.

The arguments vector now includes all necessary parameters, ensuring proper insertion into the database. The use of utc_dt_string_from_timestamp(block_timestamp) correctly formats the timestamp.


315-324: Ohayo, sensei! The insert_entities query is accurately enqueued with the right arguments.

Enqueuing the insert_entities query with the provided arguments ensures that event messages are stored correctly. The inclusion of QueryType::Other is appropriate here.


502-502: Ohayo, sensei! The use of QueryType::StoreEvent enhances event handling.

Assigning QueryType::StoreEvent to the event storage query improves the clarity and management of different query types within the queue.

Comment on lines 143 to 165
QueryType::RegisterModel => {
let row = query.fetch_one(&mut *tx).await.with_context(|| {
format!("Failed to execute query: {:?}, args: {:?}", statement, arguments)
})?;
let model_registered = ModelRegistered::from_row(&row)?;
self.push_publish(BrokerMessage::ModelRegistered(model_registered));
}
QueryType::EventMessage(entity) => {
let row = query.fetch_one(&mut *tx).await.with_context(|| {
format!("Failed to execute query: {:?}, args: {:?}", statement, arguments)
})?;
let mut event_message = EventMessageUpdated::from_row(&row)?;
event_message.updated_model = Some(entity);
let broker_message = BrokerMessage::EventMessageUpdated(event_message);
self.push_publish(broker_message);
}
QueryType::StoreEvent => {
let row = query.fetch_one(&mut *tx).await.with_context(|| {
format!("Failed to execute query: {:?}, args: {:?}", statement, arguments)
})?;
let event = EventEmitted::from_row(&row)?;
self.push_publish(BrokerMessage::EventEmitted(event));
}
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 refactoring to reduce code duplication in query execution and error handling.

Sensei, the QueryType::RegisterModel, QueryType::EventMessage, and QueryType::StoreEvent variants share similar logic for executing a query, handling errors, fetching a row, and publishing a broker message. Refactoring this repeated code into a helper function would enhance maintainability and reduce redundancy.

Here's how you might implement the refactor:

  1. Create a helper function for executing queries and publishing messages:

    async fn execute_query_and_publish<T, F>(
        &mut self,
        query: sqlx::Query<'_, sqlx::Sqlite, sqlx::SqliteArguments<'_>>,
        tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
        statement: &str,
        arguments: &Vec<Argument>,
        map_row: F,
    ) -> Result<()>
    where
        T: for<'r> sqlx::FromRow<'r, sqlx::sqlite::SqliteRow> + Send,
        F: Fn(T) -> BrokerMessage,
    {
        let row = query.fetch_one(tx).await.with_context(|| {
            format!("Failed to execute query: {:?}, args: {:?}", statement, arguments)
        })?;
        let item = T::from_row(&row)?;
        self.push_publish(map_row(item));
        Ok(())
    }
  2. Use the helper function in each variant:

    QueryType::RegisterModel => {
        self.execute_query_and_publish(
            query,
            &mut tx,
            &statement,
            &arguments,
            |model_registered| BrokerMessage::ModelRegistered(model_registered),
        ).await?;
    }
    QueryType::EventMessage(entity) => {
        self.execute_query_and_publish(
            query,
            &mut tx,
            &statement,
            &arguments,
            move |mut event_message| {
                event_message.updated_model = Some(entity.clone());
                BrokerMessage::EventMessageUpdated(event_message)
            },
        ).await?;
    }
    QueryType::StoreEvent => {
        self.execute_query_and_publish(
            query,
            &mut tx,
            &statement,
            &arguments,
            |event| BrokerMessage::EventEmitted(event),
        ).await?;
    }

This refactor reduces duplication and makes the code more modular and easier to maintain.

Comment on lines 159 to 165
QueryType::StoreEvent => {
let row = query.fetch_one(&mut *tx).await.with_context(|| {
format!("Failed to execute query: {:?}, args: {:?}", statement, arguments)
})?;
let event = EventEmitted::from_row(&row)?;
self.push_publish(BrokerMessage::EventEmitted(event));
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure proper handling when no rows are returned in StoreEvent.

Sensei, in the QueryType::StoreEvent variant, if fetch_one does not find a matching event, it will result in an error. Consider using fetch_optional and handling the case where no event is found to prevent potential runtime errors.

Here is a suggested change to handle this scenario:

 let row = query.fetch_one(&mut *tx).await.with_context(|| {
     format!("Failed to execute query: {:?}, args: {:?}", statement, arguments)
 })?;
 let event = EventEmitted::from_row(&row)?;
 self.push_publish(BrokerMessage::EventEmitted(event));

Apply this diff:

-let row = query.fetch_one(&mut *tx).await.with_context(|| {
+let row = query.fetch_optional(&mut *tx).await.with_context(|| {
     format!("Failed to execute query: {:?}, args: {:?}", statement, arguments)
 })?;
-let event = EventEmitted::from_row(&row)?;
-self.push_publish(BrokerMessage::EventEmitted(event));
+if let Some(row) = row {
+    let event = EventEmitted::from_row(&row)?;
+    self.push_publish(BrokerMessage::EventEmitted(event));
+} else {
+    // Optionally handle the case where no event is found
+    // For example, log a warning or take alternative action
+}

This change ensures that your code gracefully handles situations where the query returns no results.

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
QueryType::StoreEvent => {
let row = query.fetch_one(&mut *tx).await.with_context(|| {
format!("Failed to execute query: {:?}, args: {:?}", statement, arguments)
})?;
let event = EventEmitted::from_row(&row)?;
self.push_publish(BrokerMessage::EventEmitted(event));
}
QueryType::StoreEvent => {
let row = query.fetch_optional(&mut *tx).await.with_context(|| {
format!("Failed to execute query: {:?}, args: {:?}", statement, arguments)
})?;
if let Some(row) = row {
let event = EventEmitted::from_row(&row)?;
self.push_publish(BrokerMessage::EventEmitted(event));
} else {
// Optionally handle the case where no event is found
// For example, log a warning or take alternative action
}
}

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

Outside diff range and nitpick comments (2)
crates/torii/core/src/query_queue.rs (2)

49-51: LGTM! Consider adding documentation for new variants.

Ohayo, sensei! The new variants in the QueryType enum look good and expand the functionality of the query system. To improve clarity and maintainability, consider adding documentation comments for these new variants to explain their purpose and usage.

Here's a suggestion for documenting the new variants:

pub enum QueryType {
    // ... existing variants ...

    /// Represents an event message query with associated type information.
    EventMessage(Ty),
    /// Represents a query to register a new model.
    RegisterModel,
    /// Represents a query to store an event.
    StoreEvent,

    // ... other variants ...
}

138-160: LGTM! Consider refactoring to reduce duplication.

Ohayo, sensei! The new cases for RegisterModel, EventMessage, and StoreEvent are well-implemented and consistent with the new enum variants. The error handling and broker message creation look good.

However, there's some code duplication in the error handling and row fetching logic. Consider refactoring this common pattern into a helper function to improve maintainability and reduce the chance of errors.

Here's a suggestion for a helper function:

async fn fetch_and_publish<T, F>(
    query: sqlx::Query<'_, sqlx::Sqlite>,
    tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
    statement: &str,
    arguments: &[Argument],
    publish_queue: &mut VecDeque<BrokerMessage>,
    transform: F,
) -> Result<()>
where
    T: for<'r> FromRow<'r, sqlx::sqlite::SqliteRow>,
    F: FnOnce(T) -> BrokerMessage,
{
    let row = query.fetch_one(&mut *tx).await.with_context(|| {
        format!("Failed to execute query: {:?}, args: {:?}", statement, arguments)
    })?;
    let item = T::from_row(&row)?;
    publish_queue.push_back(transform(item));
    Ok(())
}

You could then use this helper function in each case:

QueryType::RegisterModel => {
    fetch_and_publish::<ModelRegistered, _>(
        query,
        &mut tx,
        &statement,
        &arguments,
        &mut publish_queue,
        BrokerMessage::ModelRegistered,
    ).await?;
}

This refactoring would make the code more concise and easier to maintain.

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d1990c0 and 9567da0.

Files selected for processing (2)
  • crates/torii/core/src/query_queue.rs (5 hunks)
  • crates/torii/core/src/sql.rs (4 hunks)
Files skipped from review as they are similar to previous changes (1)
  • crates/torii/core/src/sql.rs
Additional comments not posted (4)
crates/torii/core/src/query_queue.rs (4)

57-57: LGTM! Simplified struct definition.

Ohayo, sensei! The removal of the publish_queue field from the QueryQueue struct simplifies its definition. This change looks good, but it's important to ensure that the execute_all method has been updated accordingly to handle publish operations without relying on this field.

To verify that the publish operations are still handled correctly, please check the execute_all method implementation.


71-73: LGTM! Local publish queue introduced.

Ohayo, sensei! The introduction of a local publish_queue variable is a good approach to handle publish operations after removing the field from the struct. This change maintains the functionality while improving the design by localizing the queue to the method where it's used.


97-97: LGTM! Consistent use of local publish queue.

Ohayo, sensei! The direct push to the local publish_queue is consistent with the earlier changes. This modification maintains the functionality while simplifying the code by removing the need for a separate push_publish method.


172-174: LGTM! Consistent use of local publish queue.

Ohayo, sensei! The publish loop at the end of the execute_all method has been updated to use the local publish_queue, which is consistent with the earlier changes. This modification maintains the original functionality while adapting to the new structure of the code.

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

The max length of the queue is still 1000 right? So RAM wise, shouldn't be an issue to have all the messages staged in the RAM before being sent.

Copy link

codecov bot commented Sep 24, 2024

Codecov Report

Attention: Patch coverage is 81.13208% with 10 lines in your changes missing coverage. Please review.

Project coverage is 68.44%. Comparing base (b598b07) to head (10f4805).
Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/core/src/query_queue.rs 56.52% 10 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2471      +/-   ##
==========================================
- Coverage   68.45%   68.44%   -0.02%     
==========================================
  Files         368      368              
  Lines       48162    48185      +23     
==========================================
+ Hits        32971    32980       +9     
- Misses      15191    15205      +14     

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

@Larkooo Larkooo merged commit 8f4bcbb into dojoengine:main Sep 24, 2024
14 of 15 checks passed
Argument::String(event_id.to_string()),
Argument::String(utc_dt_string_from_timestamp(block_timestamp)),
],
QueryType::Other,
Copy link
Collaborator

Choose a reason for hiding this comment

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

think this should be QueryType::EntityMessage

Copy link
Collaborator

Choose a reason for hiding this comment

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

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.

3 participants