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: change to new torii queries #2652

Merged
merged 4 commits into from
Jan 23, 2025
Merged

feat: change to new torii queries #2652

merged 4 commits into from
Jan 23, 2025

Conversation

edisontim
Copy link
Collaborator

@edisontim edisontim commented Jan 21, 2025

Summary by CodeRabbit

  • Refactor

    • Replaced subscription-based data retrieval with direct data fetching methods across multiple components.
    • Updated method names and signatures to reflect new data retrieval approach.
    • Centralized model definitions and improved performance logging.
  • Bug Fixes

    • Adjusted key matching and entity retrieval strategies to enhance data synchronization.
  • Chores

    • Removed user message about high loading times from loading screen.
    • Updated import statements and component references.

@edisontim edisontim requested review from aymericdelab and bob0005 and removed request for aymericdelab January 21, 2025 17:37
Copy link

vercel bot commented Jan 21, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
eternum ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 23, 2025 0:20am
eternum-docs ❌ Failed (Inspect) Jan 23, 2025 0:20am
eternum-landing ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 23, 2025 0:20am

Copy link
Contributor

mentatbot bot commented Jan 21, 2025

Hi @edisontim! You need to be added as a user to interact with me. Please ask @ponderingdemocritus to add you on the settings page.

You are receiving this comment because I am set to review all PRs. That is configurable here.

Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

Caution

Review failed

The pull request is closed.

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

client/apps/game/src/dojo/sync.ts

Oops! Something went wrong! :(

ESLint: 9.18.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

Walkthrough

The pull request introduces a comprehensive refactoring of data retrieval mechanisms across multiple files in the game client. The primary focus is shifting from subscription-based methods to direct data fetching techniques. Key changes include renaming functions, modifying query parameters, and updating how entities are retrieved from the Torii network. The modifications span files like debounced-queries.ts, queries.ts, sync.ts, and several UI components, indicating a systematic approach to improving data synchronization and performance.

Changes

File Change Summary
client/apps/game/src/dojo/debounced-queries.ts Renamed subscription functions to get* methods, updated function calls and parameters, introduced new data retrieval functions.
client/apps/game/src/dojo/queries.ts Renamed functions, modified query logic, added new methods like getMarketFromTorii, updated entity retrieval parameters.
client/apps/game/src/dojo/sync.ts Introduced configModels and singleKeyModels, moved configClauses, added performance logging.
client/apps/game/src/ui/components/resources/inventory-resources.tsx Updated function imports, changed component references from dojo.setup.components to dojo.network.contractComponents.
client/apps/game/src/ui/components/trading/resource-arrivals.tsx Replaced addToSubscription with getEntitiesFromTorii.
client/apps/game/src/ui/layouts/world.tsx Removed old subscription methods, added new data retrieval methods.
client/apps/game/src/ui/modules/loading-screen.tsx Removed user message about high loading times.

Possibly related PRs

  • prettier #2636: The changes in this PR involve a refactor of the use-battles and use-armies hooks, which are directly related to the changes in the main PR that also refactors subscription handling and data retrieval methods in the debounced-queries.ts and queries.ts files.
  • ++Refactor use-armies and clean battles #2640: This PR focuses on refactoring the use-armies hook, which aligns with the main PR's changes that also involve significant modifications to how army data is managed and retrieved.
  • feat: change to new torii queries  #2652: The changes in this PR involve a significant refactoring of the subscription handling in the debounced-queries.ts file, which is directly related to the changes made in the main PR regarding the transition from subscription-based methods to direct data retrieval methods.

Poem

🐰 Hop, hop, through the code we go,
Subscriptions fade, new methods grow.
From Torii's realm, data flows free,
Refactored paths of efficiency.
A rabbit's dance of clean design! 🚀


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fef13be and d3ae21d.

📒 Files selected for processing (5)
  • client/apps/game/src/dojo/sync.ts (2 hunks)
  • client/apps/game/src/ui/components/resources/inventory-resources.tsx (4 hunks)
  • client/apps/game/src/ui/components/trading/resource-arrivals.tsx (2 hunks)
  • client/apps/game/src/ui/layouts/world.tsx (4 hunks)
  • client/apps/game/src/ui/modules/loading-screen.tsx (0 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Failed to generate code suggestions for PR

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🔭 Outside diff range comments (1)
client/apps/game/src/dojo/queries.ts (1)

Line range hint 107-149: Optimize asynchronous calls in 'getMarketFromTorii'

In the getMarketFromTorii function, both getEntities calls are awaited individually, and then Promise.all is called on their results, which are no longer promises. This can lead to sequential execution rather than concurrent.

To run these calls concurrently, initiate both without awaiting them immediately and then await them together:

-  const resourcePromise = await getEntities(...);
...
-  const marketPromise = await getEntities(...);
...
-  await Promise.all([resourcePromise, marketPromise]);
+  const resourcePromise = getEntities(...);
...
+  const marketPromise = getEntities(...);
...
+  await Promise.all([resourcePromise, marketPromise]);

This adjustment allows both asynchronous operations to run in parallel, improving performance.

🧹 Nitpick comments (6)
client/apps/game/src/dojo/queries.ts (1)

104-104: Avoid using 'as any' for improved type safety

Casting components to any reduces type safety and may introduce runtime errors. Consider refining the types or updating interfaces to eliminate the need for as any:

await getEntities(client, query, components, [], entityModels, 40_000);

This enhances maintainability and catches potential issues at compile time.

client/apps/game/src/dojo/debounced-queries.ts (2)

Line range hint 15-16: Consider making RequestQueue parameters configurable.

The batchSize and batchDelayMs are hardcoded. Consider making these configurable through the constructor to allow for different queue configurations based on use cases.

 class RequestQueue {
   private queue: Array<() => Promise<void>> = [];
   private processing = false;
-  private batchSize = 3; // Number of concurrent requests
-  private batchDelayMs = 100; // Delay between batches
+  constructor(
+    private readonly batchSize: number = 3,
+    private readonly batchDelayMs: number = 100
+  ) {}

56-65: Standardize debounce delays across functions.

The debounce delays vary between functions (250ms vs 500ms) without clear justification. Consider standardizing these delays or documenting why different delays are necessary.

Consider extracting the delays to named constants:

+const ENTITY_DEBOUNCE_DELAY = 250;
+const MARKET_DEBOUNCE_DELAY = 500;

 export const debouncedTwoKeyEntitiesFromTorii = debounce(
   // ... function implementation
-  250,
+  ENTITY_DEBOUNCE_DELAY,
   { leading: true },
 );

Also applies to: 69-79, 82-91, 95-109, 113-122

client/apps/game/src/ui/components/resources/inventory-resources.tsx (1)

8-9: Enhance error handling and cache management.

The error handling could be improved, and the cache management could be extracted into a reusable utility.

Consider implementing a more robust error handling and cache management:

+const SYNC_RETRY_ATTEMPTS = 3;
+const SYNC_RETRY_DELAY = 1000;
+
+const getCacheKey = (entityId: string) => `${CACHE_KEY}-${entityId}`;
+
+const isValidCache = (cachedTime: string | null) => {
+  if (!cachedTime) return false;
+  return Date.now() - parseInt(cachedTime) < CACHE_DURATION;
+};
+
+const syncResources = async (entityId: string, dojo: any) => {
+  let attempts = 0;
+  while (attempts < SYNC_RETRY_ATTEMPTS) {
     try {
-      console.log("AddToSubscriptionStart - 4");
       await debouncedGetEntitiesFromTorii(
         dojo.network.toriiClient,
         dojo.network.contractComponents as any,
         [entityId.toString()]
       );
+      localStorage.setItem(getCacheKey(entityId), Date.now().toString());
+      return true;
     } catch (error) {
-      console.error("Fetch failed", error);
+      console.error(`Sync attempt ${attempts + 1} failed:`, error);
+      attempts++;
+      if (attempts < SYNC_RETRY_ATTEMPTS) {
+        await new Promise(resolve => setTimeout(resolve, SYNC_RETRY_DELAY));
+      }
     }
+  }
+  return false;
+};

Also applies to: 62-64

client/apps/game/src/dojo/sync.ts (2)

81-116: Enhance performance monitoring.

The performance monitoring could be more structured and reusable.

Consider implementing a performance monitoring utility:

+const measurePerformance = async (name: string, fn: () => Promise<any>) => {
+  const start = performance.now();
+  try {
+    return await fn();
+  } finally {
+    const end = performance.now();
+    console.log(`[composite] ${name}`, end - start);
+  }
+};

-let start = performance.now();
-Promise.all([
+await measurePerformance('big config query', () => Promise.all([
   // ... existing getEntities calls
-]);
-let end = performance.now();
-console.log("[composite] big config query", end - start);
+]));

263-297: Consider organizing model names into categories.

The large arrays of model names could be better organized for maintainability.

Consider organizing the models into logical categories:

+const MODEL_CATEGORIES = {
+  CONFIG: {
+    WORLD: ['s1_eternum-WorldConfig', 's1_eternum-MapConfig'],
+    SEASON: ['s1_eternum-SeasonAddressesConfig', 's1_eternum-SeasonBridgeConfig'],
+    HYPERSTRUCTURE: ['s1_eternum-HyperstructureResourceConfig', 's1_eternum-HyperstructureConfig'],
+    // ... other categories
+  },
+  SINGLE_KEY: {
+    REALM: ['s1_eternum-Realm', 's1_eternum-RealmMaxLevelConfig'],
+    BATTLE: ['s1_eternum-Battle', 's1_eternum-BattleConfig'],
+    // ... other categories
+  }
+};

-const configModels = [ ... ];
-const singleKeyModels = [ ... ];
+const configModels = Object.values(MODEL_CATEGORIES.CONFIG).flat();
+const singleKeyModels = Object.values(MODEL_CATEGORIES.SINGLE_KEY).flat();

Also applies to: 299-319

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e6af898 and bf217d0.

📒 Files selected for processing (8)
  • client/apps/game/src/dojo/debounced-queries.ts (2 hunks)
  • client/apps/game/src/dojo/queries.ts (4 hunks)
  • client/apps/game/src/dojo/sync.ts (2 hunks)
  • client/apps/game/src/ui/components/resources/inventory-resources.tsx (2 hunks)
  • client/apps/game/src/ui/components/trading/resource-arrivals.tsx (2 hunks)
  • client/apps/game/src/ui/layouts/world.tsx (4 hunks)
  • client/apps/game/src/ui/modules/loading-screen.tsx (0 hunks)
  • client/public/resource_addresses/local/resource_addresses.json (0 hunks)
💤 Files with no reviewable changes (2)
  • client/public/resource_addresses/local/resource_addresses.json
  • client/apps/game/src/ui/modules/loading-screen.tsx
🧰 Additional context used
🪛 GitHub Actions: lint
client/apps/game/src/ui/components/trading/resource-arrivals.tsx

[warning] Code formatting does not match Prettier standards. Run Prettier with --write to fix.

🪛 GitHub Actions: knip
client/apps/game/src/ui/components/resources/inventory-resources.tsx

[error] 1-4: Multiple unresolved imports: '@/dojo/debouncedQueries', '@/hooks/context/DojoContext', '@/ui/elements/ResourceCost'

client/apps/game/src/ui/layouts/world.tsx

[error] 1-1: Unresolved import: '@/dojo/debouncedQueries'

client/apps/game/src/dojo/queries.ts

[warning] 9-152: Unused exports: 'getTwoKeyModelbyRealmEntityIdFromTorii', 'getOneKeyModelbyRealmEntityIdFromTorii', 'getMarketFromTorii', 'addDonkeysAndArmiesSubscription'

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Run pr agent on every pull request, respond to user comments
🔇 Additional comments (5)
client/apps/game/src/dojo/queries.ts (5)

Line range hint 9-33: Remove unused exported function 'getTwoKeyModelbyRealmEntityIdFromTorii'

According to the pipeline failure logs, the function getTwoKeyModelbyRealmEntityIdFromTorii is exported but not used anywhere in the codebase. To keep the codebase clean and maintainable, consider removing this function if it's unnecessary or ensure it is being used appropriately.


Line range hint 37-61: Remove unused exported function 'getOneKeyModelbyRealmEntityIdFromTorii'

The function getOneKeyModelbyRealmEntityIdFromTorii is also exported but not used. Please verify its necessity and remove it if it's redundant.


Line range hint 107-149: Remove unused exported function 'getMarketFromTorii'

Per the pipeline failure logs, getMarketFromTorii is exported but not used. Verify if this function is necessary. If not, consider removing it to clean up the codebase.


Line range hint 153-176: Remove unused exported function 'addDonkeysAndArmiesSubscription'

The function addDonkeysAndArmiesSubscription is exported but not utilized. Please check if it's needed and remove it if it's obsolete to reduce unnecessary code.


95-98: Verify usage of 'undefined' in 'keys' array

In the getEntitiesFromTorii function, undefined values are included in the keys array:

keys: [String(position?.x || 0), String(position?.y || 0), undefined, undefined],

Using undefined in the keys array might lead to unexpected behavior. Please confirm if this is intentional and adjust if necessary.

✅ Verification successful

Usage of undefined in keys array is intentional and follows established patterns

The usage of undefined values in the keys array is consistent with the established patterns throughout the codebase, particularly in sync and query operations. This pattern appears in multiple locations with both "FixedLen" and "VariableLen" pattern matching, indicating it's a deliberate design choice for the Torii client implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Find the complete implementation of getEntitiesFromTorii
ast-grep --pattern 'function getEntitiesFromTorii($$$) {
  $$$
}'

# Search for similar patterns with undefined in keys array
rg 'keys:\s*\[.*undefined.*\]' -A 2 -B 2

# Look for PatternMatching type definition
ast-grep --pattern 'type PatternMatching = $$$'

# Search for any comments or documentation about keys pattern
rg -B 3 'keys.*undefined.*undefined'

Length of output: 5532

Comment on lines 2 to 6
debouncedGetDonkeysAndArmiesFromTorii,
debouncedGetEntitiesFromTorii,
debouncedGetMarketFromTorii,
debouncedGetOneKeyEntitiesByRealmEntityIdFromTorii,
} from "@/dojo/debouncedQueries";
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

Fix unresolved import of '@/dojo/debouncedQueries'

The pipeline reports an unresolved import error:

import {
  debouncedGetDonkeysAndArmiesFromTorii,
  debouncedGetEntitiesFromTorii,
  debouncedGetMarketFromTorii,
  debouncedGetOneKeyEntitiesByRealmEntityIdFromTorii,
} from "@/dojo/debouncedQueries";

Please ensure that the module '@/dojo/debouncedQueries' exists and that the import path is correct. Verify the file name and its export statements to resolve this issue.

@@ -46,7 +46,7 @@ export const AllResourceArrivals = memo(
addSubscribedIds(unsubscribedIds);

// Move API call outside of state updates
addToSubscription(dojo.network.toriiClient, dojo.network.contractComponents as any, unsubscribedIds).catch(
getEntitiesFromTorii(dojo.network.toriiClient, dojo.network.contractComponents as any, unsubscribedIds, ["s1_eternum-DetachedResource"]).catch(
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

Fix code formatting to match Prettier standards

The pipeline indicates that the code formatting does not comply with Prettier standards. Please run Prettier with the --write flag to automatically fix formatting issues.

🧰 Tools
🪛 GitHub Actions: lint

[warning] Code formatting does not match Prettier standards. Run Prettier with --write to fix.

Comment on lines 1 to 4
import { debouncedGetEntitiesFromTorii } from "@/dojo/debouncedQueries";
import { useDojo } from "@/hooks/context/DojoContext";
import { useUIStore } from "@/hooks/store/use-ui-store";
import { ResourceCost } from "@/ui/elements/resource-cost";
import { ResourceCost } from "@/ui/elements/ResourceCost";
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

Fix unresolved imports.

The pipeline is failing due to unresolved imports. Ensure the import paths are correct:

  • '@/dojo/debouncedQueries'
  • '@/hooks/context/DojoContext'
  • '@/ui/elements/ResourceCost'
🧰 Tools
🪛 GitHub Actions: knip

[error] 1-4: Multiple unresolved imports: '@/dojo/debouncedQueries', '@/hooks/context/DojoContext', '@/ui/elements/ResourceCost'

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
client/apps/game/src/ui/layouts/world.tsx (2)

154-160: Consider extracting entity types to constants.

The entity type strings are repeated across multiple queries. Consider extracting them to a shared constant to improve maintainability.

+const STRUCTURE_ENTITY_TYPES = [
+  "s1_eternum-BuildingQuantityv2",
+  "s1_eternum-Hyperstructure",
+  "s1_eternum-Resource",
+  "s1_eternum-Building",
+  "s1_eternum-Quest",
+] as const;

148-148: Consider structured performance logging.

The performance monitoring logs are scattered throughout the code. Consider creating a utility function for consistent performance logging:

+const logQueryPerformance = (queryName: string, startTime: number) => {
+  const duration = performance.now() - startTime;
+  console.log(`[composite] ${queryName} query: ${duration.toFixed(2)}ms`);
+};

-let start = performance.now();
-// ... query code ...
-let end = performance.now();
-console.log("[composite] buildings query", end - start);
+const start = performance.now();
+// ... query code ...
+logQueryPerformance("buildings", start);

Also applies to: 165-166, 182-182, 197-198, 200-200, 207-208

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bf217d0 and 57db325.

📒 Files selected for processing (2)
  • client/apps/game/src/ui/components/resources/inventory-resources.tsx (4 hunks)
  • client/apps/game/src/ui/layouts/world.tsx (4 hunks)
🔇 Additional comments (5)
client/apps/game/src/ui/components/resources/inventory-resources.tsx (3)

32-33: LGTM: Component reference updated correctly.

The change from dojo.setup.components to dojo.network.contractComponents aligns with the new architecture.


1-1: Verify import resolution.

The import statement has been updated to use debouncedGetEntitiesFromTorii. Please ensure that the pipeline errors regarding unresolved imports have been addressed.

✅ Verification successful

Import resolution verified successfully

The debouncedGetEntitiesFromTorii function is correctly exported from client/apps/game/src/dojo/debounced-queries.ts and the import path is properly resolved.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the import path exists and is exported correctly
rg -l "export.*debouncedGetEntitiesFromTorii" "src/dojo/"

Length of output: 107


Script:

#!/bin/bash
# Find the dojo directory and debounced-queries file
fd -t d "dojo$"
fd "debounced-queries\.(ts|tsx|js|jsx)$"

# After finding the files, search for the export
rg "export.*debouncedGetEntitiesFromTorii"

Length of output: 335


62-67: Consider impact on real-time updates.

The switch from subscription to direct query might affect real-time data synchronization. Consider implementing a polling mechanism or WebSocket connection if real-time updates are required.

client/apps/game/src/ui/layouts/world.tsx (2)

Line range hint 254-260: LGTM: Robust error handling.

The error handling ensures loading states are properly reset even when errors occur, preventing UI from being stuck in a loading state.


2-5: Verify import resolution.

The new query function imports align with the architectural changes. Please ensure that the pipeline errors regarding unresolved imports have been resolved.

✅ Verification successful

Import resolution verified successfully

All debounced query functions are properly exported from client/apps/game/src/dojo/debounced-queries.ts and are being used successfully across multiple components.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify all new imports exist and are exported correctly
rg -l "export.*\b(debouncedGetDonkeysAndArmiesFromTorii|debouncedGetEntitiesFromTorii|debouncedGetMarketFromTorii|debouncedGetOneKeyEntitiesByRealmEntityIdFromTorii)\b" "src/dojo/"

Length of output: 230


Script:

#!/bin/bash
# Search for the debounced function definitions across the repository
rg -A 2 "export.*\b(debouncedGetDonkeysAndArmiesFromTorii|debouncedGetEntitiesFromTorii|debouncedGetMarketFromTorii|debouncedGetOneKeyEntitiesByRealmEntityIdFromTorii)\b"

# Find any files containing these function names to understand the context
rg "\b(debouncedGetDonkeysAndArmiesFromTorii|debouncedGetEntitiesFromTorii|debouncedGetMarketFromTorii|debouncedGetOneKeyEntitiesByRealmEntityIdFromTorii)\b"

Length of output: 2999

"s1_eternum-LeaderboardRegisterContribution",
"s1_eternum-LeaderboardRegisterShare",
"s1_eternum-CapacityConfigCategory",
"s1_eternum-ResourceCost",
Copy link
Collaborator

Choose a reason for hiding this comment

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

Remove duplicate model

client/apps/game/src/dojo/sync.ts Show resolved Hide resolved
Comment on lines +150 to +153
"s1_eternum-LeaderboardRegisterShare",
"s1_eternum-Epoch",
"s1_eternum-Progress",
"s1_eternum-LeaderboardRegisterContribution",
Copy link
Collaborator

Choose a reason for hiding this comment

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

Leaderboard models already fetched in previous getEntities

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (2)
client/apps/game/src/dojo/sync.ts (2)

104-109: ⚠️ Potential issue

Remove duplicate ResourceCost model.

The "s1_eternum-ResourceCost" model appears twice in the array.

Apply this diff to remove the duplicate:

   "s1_eternum-ResourceCost",
   "s1_eternum-LeaderboardRegisterContribution",
   "s1_eternum-LeaderboardRegisterShare",
-  "s1_eternum-CapacityConfigCategory",
-  "s1_eternum-ResourceCost",
+  "s1_eternum-CapacityConfigCategory"

149-153: ⚠️ Potential issue

Remove redundant leaderboard model fetches.

These leaderboard models are already fetched in the previous getEntities call.

Remove the redundant models:

-      "s1_eternum-LeaderboardRegisterShare",
       "s1_eternum-Epoch",
       "s1_eternum-Progress",
-      "s1_eternum-LeaderboardRegisterContribution",
🧹 Nitpick comments (1)
client/apps/game/src/dojo/sync.ts (1)

81-82: Consider using structured logging for better performance analysis.

The performance logging is helpful but could be improved by using a consistent structured format that would make it easier to analyze query patterns and performance trends.

Consider using an object structure for logging:

-console.log("[composite] big config query", end - start);
+console.log({
+  type: "query_performance",
+  name: "big_config_query",
+  duration_ms: end - start,
+  timestamp: new Date().toISOString()
+});

Also applies to: 115-116, 122-122, 160-161, 164-164, 182-183, 191-191, 222-223

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 57db325 and fef13be.

📒 Files selected for processing (1)
  • client/apps/game/src/dojo/sync.ts (2 hunks)
🔇 Additional comments (2)
client/apps/game/src/dojo/sync.ts (2)

264-320: Well-organized model constants improve maintainability.

Good job organizing the models into separate constants. This improves code maintainability and follows the DRY principle.


97-98: Verify the performance impact of using "VariableLen" pattern matching.

Changing from "FixedLen" to "VariableLen" pattern matching could affect query performance as it allows for more flexible but potentially slower key matching.

Run this script to analyze the query patterns and their performance impact:

✅ Verification successful

Pattern matching change aligns with codebase patterns

The change to "VariableLen" follows established patterns in the codebase, particularly in queries.ts. Performance monitoring is already in place, and the mixed usage of both patterns suggests intentional design choices based on specific query requirements.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Analyze the usage of VariableLen vs FixedLen pattern matching
# and their performance implications

# Search for all pattern matching usages
echo "Pattern Matching Usage Analysis:"
rg -A 2 'pattern_matching:' --type ts

# Search for any performance-related comments or issues
echo -e "\nPerformance Related Context:"
rg -i 'performance|slow|optimization' --type ts

Length of output: 7740

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