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

feat: c version #306

Merged
merged 2 commits into from
Oct 23, 2024
Merged

feat: c version #306

merged 2 commits into from
Oct 23, 2024

Conversation

ponderingdemocritus
Copy link
Contributor

@ponderingdemocritus ponderingdemocritus commented Oct 22, 2024

Summary by CodeRabbit

  • Chores
    • Updated the repository cloning process in the build script to clone the default branch instead of a specific branch.
  • New Features
    • Introduced new interfaces for game models, enhancing the structure for player, game, item, and galaxy data.
    • Added a schema constant to initialize default values for the game models.
  • Bug Fixes
    • Adjusted logical operators in query conversion to ensure consistent behavior and output.
    • Simplified the handling of hashed keys in entity fetching functions, improving clarity and functionality.
  • Documentation
    • Enhanced comments and documentation throughout the type definitions for better clarity and guidance.

Copy link

coderabbitai bot commented Oct 22, 2024

Walkthrough

The build.sh script in the packages/torii-wasm directory has been updated to modify the repository cloning process. The previous specification of the grpc-update branch has been removed, allowing the script to clone the default branch instead. Other functionalities of the script, including build commands and cleanup operations, remain unchanged. Additionally, several TypeScript files have been updated to introduce new interfaces, modify logical operators, and enhance type definitions, impacting the SDK's query and entity handling capabilities.

Changes

File Path Change Summary
packages/torii-wasm/build.sh Modified to clone the default branch instead of grpc-update.
packages/sdk/src/example/index.ts Added import for torii, defined multiple game-related interfaces, and created a schema constant.
packages/sdk/src/tests/convertQueryToClause.test.ts Updated logical operators from "And" to "Or" in test cases and standardized casing for logical operators.
packages/sdk/src/convertQuerytoClause.ts Changed composite clause operator from "And" to "Or" and updated logical operator casing in the code.
packages/sdk/src/getEntities.ts Simplified handling of dont_include_hashed_keys property in the toriiQuery object.
packages/sdk/src/getEventMessages.ts Changed dont_include_hashed_keys from true to false in the toriiQuery object.
packages/sdk/src/types.ts Updated LogicalOperator type, modified WhereCondition, added BaseQueryType, and renamed QueryType.

Possibly related PRs

  • feat: allow wasm in nodejs #253: The changes in packages/torii-wasm/build.sh related to the build commands for Node.js and web environments are relevant as they enhance the functionality of the build process, which is closely related to the modifications made in the main PR that also involves the build.sh script.
  • fix: types #304: The updates to the getEntities function in packages/sdk/src/getEntities.ts include the addition of the dont_include_hashed_keys parameter, which aligns with the changes made in the main PR regarding the handling of entity fetching and the overall structure of the SDK.
  • fix: constants #305: The modifications to constants in packages/core/src/constants/index.ts may not directly relate to the main PR, but they indicate ongoing changes in the codebase that could affect the overall functionality and integration of the SDK, which is relevant to the context of the main PR.

Poem

In the code where rabbits play,
A branch was changed, hip-hip-hooray!
No more grpc-update to see,
Just the default, wild and free.
With builds that hop and clean with glee,
Let's celebrate this change with tea! 🐇✨


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

@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 (8)
packages/sdk/src/getEventMessages.ts (1)

Based on the git history, I can now provide a final response:

Breaking change confirmed: dont_include_hashed_keys parameter was changed from true to false

The git history shows that this parameter was previously defaulting to true and was changed to false in commit 0b76d37. This is indeed a breaking change as it alters the response structure by including previously excluded data.

Action items needed:

  • Add this change to the SDK's changelog (packages/sdk/CHANGELOG.md)
  • Bump the major version (currently at 1.0.0-alpha.22)
  • Document the migration steps for clients that may be affected by the larger response payloads

The change affects both getEventMessages.ts and getEntities.ts as shown in the ripgrep results, making this a significant API behavior modification.

🔗 Analysis chain

Line range hint 1-89: Flag potential breaking change.

Setting dont_include_hashed_keys to false changes the response structure by including previously excluded data. This could be a breaking change for clients that:

  1. Expect hashed keys to be excluded
  2. Have fixed response parsing logic
  3. Have memory constraints for handling larger payloads

Consider:

  1. Adding this change to the changelog
  2. Bumping the major version if following semver
  3. Adding a migration guide for affected clients

Let me check the changelog and version information for the SDK package where this change is being made.


Let me check the torii-client package to understand if this is actually a breaking change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Look for version and changelog files to ensure breaking changes are documented

# Search for changelog files
fd -i changelog

# Search for version related files
fd -i "version|release" -e json -e md

Length of output: 565


Script:

#!/bin/bash
# Check SDK changelog and package.json for version info
cat packages/sdk/CHANGELOG.md
cat packages/sdk/package.json

# Check if dont_include_hashed_keys is used elsewhere in the codebase
rg "dont_include_hashed_keys" -B 2 -A 2

# Check the torii-client package for the Query interface definition
cat packages/torii-client/src/types.ts

Length of output: 3353


Script:

#!/bin/bash
# Check torii-client package for the Query interface and its usage
fd -t f . packages/torii-client -x cat {}

# Check if this parameter was previously defaulting to true
git log -p packages/sdk/src/getEventMessages.ts

Length of output: 11105

packages/sdk/src/__example__/index.ts (4)

Line range hint 3-40: LGTM! Well-structured type definitions.

The interfaces are well-organized and provide good type safety. The consistent use of fieldOrder across all models helps maintain a predictable structure.

Consider adding JSDoc comments to document the purpose of each interface and their fields, especially since this is an example file that others might learn from.


Line range hint 78-91: Consider using more realistic example URLs.

The placeholder URLs (your-rpc-url, your-torii-url, etc.) could be replaced with example.com URLs or documented format patterns to better guide users.

-           rpcUrl: "your-rpc-url",
-           toriiUrl: "your-torii-url",
-           relayUrl: "your-relay-url",
-           worldAddress: "your-world-address",
+           rpcUrl: "https://rpc.example.com",
+           toriiUrl: "https://torii.example.com",
+           relayUrl: "https://relay.example.com",
+           worldAddress: "0x1234567890abcdef1234567890abcdef12345678",

Line range hint 103-112: Remove or comment out the invalid example.

The invalid example might be confusing as it appears to be executable code. Consider either commenting it out or wrapping it in a @ts-expect-error directive to make it clear this is intentionally wrong.

-    const invalidMessage = {
-        id: "0x123",
-        name: "Alice",
-        score: 100,
-        unknownField: "Invalid",
-    };
-
-    const invalidTypedData = db.generateTypedData(
-        "Player",
-        invalidMessage // TypeScript Error
-    );
+    // Example of incorrect usage that TypeScript will catch:
+    // @ts-expect-error - Demonstrating type safety
+    // const invalidTypedData = db.generateTypedData("Player", {
+    //     id: "0x123",
+    //     name: "Alice",
+    //     score: 100,
+    //     unknownField: "Invalid", // Unknown field will cause type error
+    // });

Line range hint 114-134: Refactor duplicate callback handling logic.

The error handling and data logging logic is duplicated between the subscription and query callbacks. Consider extracting this into a reusable function.

+    // Helper function for handling query responses
+    const handleQueryResponse = (context: string) => (resp: any) => {
+        if (resp.error) {
+            console.error(`Error querying ${context}:`, resp.error.message);
+            return;
+        }
+        if (resp.data) {
+            console.log(`Queried ${context}:`, resp.data.map((a) => a.models));
+        }
+    };
+
     db.subscribeEntityQuery(
         {
             world: {
                 player: {
                     $: {
                         where: {
                             name: { $is: "Alice" },
                             score: { $is: 10 },
                         },
                     },
                 },
             },
         },
-        (resp) => {
-            if (resp.error) {
-                console.error(
-                    "Error querying todos and goals:",
-                    resp.error.message
-                );
-                return;
-            }
-            if (resp.data) {
-                console.log(
-                    "Queried todos and goals:",
-                    resp.data.map((a) => a.models.world)
-                );
-            }
-        }
+        handleQueryResponse("player data")
     );

Also applies to: 135-177

packages/sdk/src/__tests__/convertQueryToClause.test.ts (1)

Line range hint 9-180: Consider adding edge case tests

While the current test coverage is good, consider adding tests for:

  • Empty conditions
  • Invalid operator combinations
  • Boundary value cases

Would you like me to help generate additional test cases for these scenarios?

packages/sdk/src/convertQuerytoClause.ts (1)

Line range hint 1-319: Consider architectural improvements for better maintainability.

The file handles complex query transformations and could benefit from:

  1. Breaking down into smaller, focused modules (e.g., separate files for operators, primitives, and clause builders)
  2. Adding more comprehensive error handling with custom error types
  3. Enhancing documentation with examples for common use cases

Would you like help with restructuring this into smaller, more focused modules?

packages/sdk/src/types.ts (1)

Line range hint 163-178: Document migration path for breaking changes.

The renaming of QueryType to ModelQueryType and the introduction of the new union QueryType improve type clarity. However, these are breaking changes that require migration from existing codebases.

Consider adding a comment or updating documentation to guide users in migrating from the old type structure to the new one. For example:

/**
 * @deprecated Use ModelQueryType for model-specific queries
 * Migration guide:
 * 1. Rename existing QueryType<T> to ModelQueryType<T>
 * 2. Use new QueryType<T> when you need either base or model queries
 */
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2e6a4aa and 0b76d37.

📒 Files selected for processing (6)
  • packages/sdk/src/example/index.ts (1 hunks)
  • packages/sdk/src/tests/convertQueryToClause.test.ts (6 hunks)
  • packages/sdk/src/convertQuerytoClause.ts (3 hunks)
  • packages/sdk/src/getEntities.ts (1 hunks)
  • packages/sdk/src/getEventMessages.ts (1 hunks)
  • packages/sdk/src/types.ts (3 hunks)
🧰 Additional context used
🔇 Additional comments (9)
packages/sdk/src/getEventMessages.ts (1)

52-52: Verify consistent handling of hashed keys across the codebase.

The change to include hashed keys aligns with similar changes in getEntities.ts, but we should verify this behavior is consistent across all query-related functions.

#!/bin/bash
# Description: Search for other instances of dont_include_hashed_keys to ensure consistent configuration
# Expected: All instances should be set to false or removed

# Search for dont_include_hashed_keys usage
rg -A 2 "dont_include_hashed_keys" 

# Search for Query type/interface definition
ast-grep --pattern 'interface Query {
  $$$
  dont_include_hashed_keys?: $_
  $$$
}'

Note: Including hashed keys will increase the response payload size. Consider:

  1. Adding documentation about the memory implications
  2. Implementing response compression if not already in place
  3. Adding pagination best practices to the documentation
packages/sdk/src/getEntities.ts (1)

52-52: Verify the intentional removal of conditional hashed keys behavior.

The change to always include hashed keys (dont_include_hashed_keys: false) removes the previous conditional behavior based on query.entityIds. While this simplifies the logic, it may have implications:

  1. Response payload size will increase as hashed keys are always included
  2. This could affect performance for large result sets
  3. Existing consumers might be impacted if they relied on hashed keys being excluded in certain scenarios

Let's verify the usage patterns in the codebase:

Consider adding a comment in the code or updating the JSDoc to document this behavioral change, particularly noting that hashed keys are always included in the response.

✅ Verification successful

Let me try a different approach to verify the usage and impact of this change.


Based on the search results, I can now provide a conclusive response about the change to dont_include_hashed_keys.

The change to always include hashed keys is consistent with existing usage patterns

The codebase search reveals that:

  1. In packages/state/src/recs/index.ts, all direct calls to client.getEntities() already explicitly set dont_include_hashed_keys: false
  2. The change aligns with the existing behavior across the codebase
  3. No consumers were found that rely on hashed keys being excluded

The modification appears to be a refactoring that standardizes the behavior that was already established in practice, rather than introducing a breaking change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for patterns of consuming code that might be affected by this change
rg -A 5 "getEntities.*dont_include_hashed_keys" --type ts

Length of output: 59


Script:

#!/bin/bash
# Search for all usages of getEntities function
rg -A 10 "getEntities\(" --type ts

# Also check for any tests that might reveal expected behavior
fd "test|spec" -e ts -e js -X rg -l "getEntities"

# Look for the function definition to understand the full context
ast-grep --pattern 'export $_ function getEntities($_) { $$$ }'

Length of output: 14030

packages/sdk/src/__example__/index.ts (1)

Line range hint 42-76: LGTM! Well-structured schema definition.

The schema implementation properly matches the type definitions and provides appropriate default values. The organization into 'world' and 'universe' namespaces provides good separation of concerns.

packages/sdk/src/__tests__/convertQueryToClause.test.ts (2)

7-7: LGTM: Import addition enhances type safety

The addition of SchemaType import aligns with the enhanced type system.


30-30: Verify operator changes match implementation

The operator changes from "And" to "Or" appear consistent across test cases. Let's verify this aligns with the main implementation.

Also applies to: 84-84, 142-142, 113-128

✅ Verification successful

The output shows that the "Or" operator is indeed present in the main implementation file convertQuerytoClause.ts, matching the test cases. However, let me verify the complete context by checking both the implementation and test files for a comprehensive comparison of operator usage.

This will help us confirm that the operator changes in the test cases are fully aligned with the implementation's logic and usage patterns.


Based on the comprehensive output, I can now generate the final response as we have sufficient evidence to verify the operator changes.

Operator changes are correctly implemented and consistent

The operator changes in the test cases are perfectly aligned with the implementation:

  • The main implementation in convertQuerytoClause.ts supports both "Or" and "And" operators in composite clauses
  • The test cases' operator changes to "Or" match the implementation's behavior, particularly in the composite clause construction
  • The nested operator usage in test cases (including the complex nested "Or" operators) is supported by the implementation's composite clause handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify operator changes in convertQueryToClause implementation
# Expected: Should find "Or" operator usage in the main implementation

# Check the main implementation file
rg -A 5 'operator:\s*"Or"' packages/sdk/src/convertQuerytoClause.ts

Length of output: 227


Script:

#!/bin/bash
# Get a broader context of operator usage in both files
echo "=== Implementation file ==="
rg -B 2 -A 2 'operator:' packages/sdk/src/convertQuerytoClause.ts

echo -e "\n=== Test file ==="
rg -B 2 -A 2 'operator:' packages/sdk/src/__tests__/convertQueryToClause.test.ts

Length of output: 4115

packages/sdk/src/convertQuerytoClause.ts (2)

161-162: LGTM: Consistent casing for logical operators.

The update to use title case ("And"/"Or") improves consistency with the Torii client types.


36-37: Verify the impact of changing AND to OR operator.

This change fundamentally alters how multiple clauses are combined, switching from requiring all conditions to match (AND) to allowing any condition to match (OR). This could significantly broaden query results and potentially break existing queries.

Let's verify the impact:

packages/sdk/src/types.ts (2)

158-160: LGTM! Good separation of concerns.

The introduction of BaseQueryType as a foundation for query types is a clean design choice that promotes better type organization.


93-93: Verify compatibility with torii.LogicalOperator.

The change to use torii.LogicalOperator promotes better maintainability. However, let's verify that the imported type matches the expected values.

✅ Verification successful

Let me gather more information about the LogicalOperator type and its implementation.

This will help us understand:

  1. Where the torii types are imported from
  2. Any local definitions of logical operators
  3. The actual implementation in convertQuerytoClause.ts to see how these operators are used

Let me check the actual torii-client package to verify the LogicalOperator type definition.

This will help us:

  1. Find the type definition in the dependency
  2. Verify the package dependency
  3. Check test cases for usage examples

Based on the evidence gathered so far:

  1. The code consistently imports torii from "@dojoengine/torii-client" (a workspace dependency)
  2. The implementation in convertQuerytoClause.ts shows that LogicalOperator is used with only two values: "And" and "Or"
  3. The type is used consistently across the codebase in a type-safe manner
  4. The package.json confirms @dojoengine/torii-client as a workspace dependency

Let me generate the final response:

The usage of torii.LogicalOperator is correctly implemented

The change to use torii.LogicalOperator is safe and well-implemented. The codebase consistently uses only "And" and "Or" operators, which are the standard logical operators supported by the torii client. The implementation in convertQuerytoClause.ts confirms proper type usage and mapping.

The verification is conclusive because:

  1. The implementation shows clear mapping of logical operators
  2. The type is used consistently across the codebase
  3. The dependency is properly managed as a workspace package
  4. There's no evidence of any compatibility issues or mismatched types
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the LogicalOperator type definition in torii-client
# and its usage across the codebase

# Test 1: Find the LogicalOperator type definition
echo "Looking for LogicalOperator definition in torii-client:"
rg -p "type LogicalOperator" 

# Test 2: Find all usages of LogicalOperator
echo "Finding all usages of LogicalOperator:"
rg -p "LogicalOperator"

Length of output: 481


Script:

#!/bin/bash
# Let's find more context about LogicalOperator and its usage

# Find the torii import statement
echo "Finding torii import:"
rg -p "import.*torii.*from"

# Look for any enum or type definitions related to logical operators
echo "Finding logical operator related definitions:"
rg -p "(?i)(type|enum|interface).*logical.*operator" -A 5

# Check the convertQuerytoClause.ts file for more context
echo "Checking convertQuerytoClause.ts implementation:"
cat packages/sdk/src/convertQuerytoClause.ts

Length of output: 13418


Script:

#!/bin/bash
# Let's examine the node_modules for torii-client type definitions
echo "Looking for LogicalOperator in node_modules:"
fd -e d.ts -e ts "index.d.ts" -x grep -l "LogicalOperator"

# Also check package.json to confirm the dependency
echo "Checking package.json for torii-client dependency:"
cat packages/sdk/package.json

# Check if there are any tests using LogicalOperator
echo "Checking tests for LogicalOperator usage:"
rg -p "LogicalOperator.*=.*" packages/sdk/src/__tests__/

Length of output: 2223

Comment on lines +137 to +138
console.log("result", result);

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove debug console.log statement

Debug logging statements should be removed before merging to production.

-        console.log("result", result);
-
📝 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
console.log("result", result);

@@ -299,6 +299,7 @@ function convertToPrimitive(value: any): torii.MemberValue {
* @throws {Error} - If the operator is unsupported.
*/
function convertOperator(operator: string): torii.ComparisonOperator {
console.log(operator);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove or improve debug logging.

The console.log statement appears to be debugging code that was accidentally committed. If logging is needed, consider:

  1. Using a proper logging framework with level control
  2. Adding more context about what's being logged
  3. Moving it to debug/trace level

Remove the debug logging:

-    console.log(operator);

Or improve it with better context:

-    console.log(operator);
+    logger.debug(`Converting query operator: ${operator}`);

Committable suggestion was skipped due to low confidence.

@ponderingdemocritus ponderingdemocritus merged commit e3bb546 into main Oct 23, 2024
3 checks passed
@ponderingdemocritus ponderingdemocritus deleted the c-upgrade branch October 23, 2024 03:17
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