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

fix structure owners & transfers #2544

Merged
merged 1 commit into from
Dec 17, 2024
Merged

Conversation

bob0005
Copy link
Collaborator

@bob0005 bob0005 commented Dec 17, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced loading state management in the World Structures Menu, displaying a loading indicator during data fetching.
    • New querying capabilities for handling multiple entity IDs.
  • Bug Fixes

    • Improved logic for filtering and updating player arrivals.
  • Documentation

    • Updated method signatures for clarity.
  • Chores

    • Cleaned up unused code and removed performance logging statements.

Copy link

vercel bot commented Dec 17, 2024

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

Name Status Preview Comments Updated (UTC)
eternum 🔄 Building (Inspect) Visit Preview 💬 Add feedback Dec 17, 2024 0:07am
eternum-docs 🔄 Building (Inspect) Visit Preview 💬 Add feedback Dec 17, 2024 0:07am
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
eternum-landing ⬜️ Ignored (Inspect) Dec 17, 2024 0:07am

Copy link
Contributor

coderabbitai bot commented Dec 17, 2024

Walkthrough

This pull request introduces significant modifications across multiple files in the client-side codebase, focusing on query management, state handling, and loading mechanisms. The changes primarily involve renaming and updating query functions to handle multiple entity IDs, enhancing the flexibility of data retrieval. A new loading state for structures has been added to the world store, and the WorldStructuresMenu component now includes improved loading state management. The modifications aim to improve data synchronization, query performance, and user interface responsiveness.

Changes

File Change Summary
client/src/dojo/queries.ts - Renamed syncBuildingQty to addToSubscriptionTwoKeyModelbyRealmEntityId
- Updated function to handle multiple entity IDs
- Modified query structure with composite "Or" operator
client/src/dojo/setup.ts - Increased debounce time to 1000ms
- Removed performance measurement variables
- Added s0_eternum-EntityOwner model
client/src/hooks/helpers/use-resource-arrivals.tsx - Refactored getArrivalsWithResourceOnPosition return logic
- Enhanced handleArrivalUpdate filtering mechanism
client/src/hooks/store/useWorldLoading.tsx - Added isStructuresLoading state
- Implemented setStructuresLoading method
client/src/ui/layouts/World.tsx - Updated import statements
- Replaced subscription management functions
client/src/ui/modules/world-structures/WorldStructuresMenu.tsx - Added loading state management
- Updated fetchHyperstructureData function signature

Sequence Diagram

sequenceDiagram
    participant Client
    participant QueryManager
    participant DataStore
    Client->>QueryManager: Request multiple entity IDs
    QueryManager->>DataStore: Composite query with "Or" operator
    DataStore-->>QueryManager: Retrieve matching entities
    QueryManager-->>Client: Return entity data
Loading

Possibly related PRs

  • weight fix #2355: Changes in resource management logic related to entity ID tracking

Suggested reviewers

  • edisontim
  • ponderingdemocritus

Poem

🐰 Queries dance, entities leap,
Through code's meadow, secrets we keep
Multiple IDs, a flexible flow
Loading states ebb, performance grows
Rabbit's code hops with glee! 🌈

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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

@mentatbot mentatbot bot left a comment

Choose a reason for hiding this comment

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

The changes look good overall - removing console.logs, adding proper loading states, and consolidating query functions. The error handling could be more robust and there are a few minor optimizations possible, but the core changes are solid. The new loading state management for structures is a good addition but could benefit from timeout handling to prevent stuck states.

Thanks for using MentatBot. Give comments a 👍 or 👎 to help me improve!

...entityID.map((id) => ({
Keys: {
keys: [id, undefined],
pattern_matching: "VariableLen" as PatternMatching,
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling and retry logic for failed entity fetches

Comment on lines +62 to +65
const arrivals = positions.flatMap((position) => {
return Array.from(runQuery([HasValue(Position, { x: position.x, y: position.y }), ...queryFragments]));
});
return arrivals;
Copy link
Contributor

Choose a reason for hiding this comment

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

This intermediate variable assignment is unnecessary. You can return the flatMap result directly.

Suggested change
const arrivals = positions.flatMap((position) => {
return Array.from(runQuery([HasValue(Position, { x: position.x, y: position.y }), ...queryFragments]));
});
return arrivals;
return positions.flatMap((position) => {
return Array.from(runQuery([HasValue(Position, { x: position.x, y: position.y }), ...queryFragments]));
});

isStructuresLoading: boolean,
setStructuresLoading: (loading: boolean) => void,
) => {
if (!isStructuresLoading) {
return;
}

Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding a timeout to prevent infinite loading states

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

🔭 Outside diff range comments (1)
client/src/hooks/helpers/use-resource-arrivals.tsx (1)

Line range hint 98-113: Ensure subscriptions are properly cleaned up

In the useEffect hook starting at line 98, make sure to return a clean-up function that unsubscribes from the query.update$ subscription. This prevents memory leaks and unintended side effects when the component unmounts.

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

44-47: Extract model names to constants or enums

Model names like "s0_eternum-BuildingQuantityv2" are hardcoded strings. Extracting these into constants or an enum would prevent typos, facilitate reuse, and make future changes easier.

client/src/hooks/store/useWorldLoading.tsx (1)

7-10: Align interface properties for readability

The properties in the WorldState interface are not consistently aligned, which affects readability. Align the new properties with the existing ones for better code clarity.

Apply this diff to align the code:

 interface WorldState {
   isWorldLoading: boolean;
   isMarketLoading: boolean;
+  isStructuresLoading: boolean;
   setWorldLoading: (loading: boolean) => void;
   setMarketLoading: (loading: boolean) => void;
+  setStructuresLoading: (loading: boolean) => void;
 }
client/src/hooks/helpers/use-resource-arrivals.tsx (1)

62-65: Simplify function by returning directly

In getArrivalsWithResourceOnPosition, the variable arrivals is assigned but not modified before being returned. You can simplify the function by returning the result directly, improving readability.

Apply this diff:

 const getArrivalsWithResourceOnPosition = useCallback((positions: Position[]) => {
-  const arrivals = positions.flatMap((position) => {
+  return positions.flatMap((position) => {
     return Array.from(runQuery([HasValue(Position, { x: position.x, y: position.y }), ...queryFragments]));
   });
-  return arrivals;
 }, []);
client/src/ui/layouts/World.tsx (1)

150-154: Enhance error handling in subscription management

While the new subscription approach is good, consider improving error handling to ensure graceful degradation if subscriptions fail.

 addToSubscriptionOneKeyModelbyRealmEntityId(
   dojo.network.toriiClient,
   dojo.network.contractComponents as any,
-  [...filteredStructures.map((structure) => structure.entity_id.toString())],
+  [...filteredStructures.map((structure) => structure.entity_id.toString())],
+).catch((error) => {
+  console.error('Failed to subscribe to one-key models:', error);
+  // Consider showing a user-friendly error message
 ),
client/src/ui/modules/world-structures/WorldStructuresMenu.tsx (2)

356-356: Remove console.log statement

Remove debugging console.log statement before merging to production.

-  console.log("Fetching hyperstructure data");

382-387: Extract magic number to a named constant

Consider extracting the timeout value (40_000) to a named constant for better maintainability.

+const ENTITIES_QUERY_TIMEOUT = 40_000;
+
 await getEntities(
   client,
   // ... other params ...
-  40_000,
+  ENTITIES_QUERY_TIMEOUT,
   false,
 ).finally(() => {
   setStructuresLoading(false);
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7e00f41 and 45f2cb7.

📒 Files selected for processing (6)
  • client/src/dojo/queries.ts (3 hunks)
  • client/src/dojo/setup.ts (1 hunks)
  • client/src/hooks/helpers/use-resource-arrivals.tsx (1 hunks)
  • client/src/hooks/store/useWorldLoading.tsx (1 hunks)
  • client/src/ui/layouts/World.tsx (2 hunks)
  • client/src/ui/modules/world-structures/WorldStructuresMenu.tsx (6 hunks)
🔇 Additional comments (7)
client/src/dojo/queries.ts (2)

35-49: Ensure correct usage of undefined in keys

In addToSubscriptionTwoKeyModelbyRealmEntityId, the keys array includes [id, undefined] for each entity ID. Using undefined may lead to unintended behavior in the pattern matching or query results. Verify that this is intentional and aligns with the expected API behavior.


Line range hint 60-78: Refactor duplicate code in subscription functions

Similar to the previous function, addToSubscriptionOneKeyModelbyRealmEntityId also contains duplicated logic. Refactoring this common logic into a shared helper function would improve code quality and maintainability.

client/src/hooks/store/useWorldLoading.tsx (1)

16-19: Verify initial loading state of structures

isStructuresLoading is initialized to true. Confirm that this reflects the actual loading state at initialization. If structures are not loading immediately, consider initializing this value to false to prevent misleading the UI.

client/src/dojo/setup.ts (1)

143-143: Addition of EntityOwner model improves data completeness

Including "s0_eternum-EntityOwner" in the models list enhances the data retrieved during entity synchronization. This allows for ownership information to be readily available in components that rely on it.

client/src/hooks/helpers/use-resource-arrivals.tsx (1)

Line range hint 109-114: Optimize state updates to prevent unnecessary re-renders

The handleArrivalUpdate function updates state for every component update matching the query, which could lead to performance issues due to frequent re-renders. Consider batching state updates or adding conditions to minimize unnecessary updates.

[performance]

client/src/ui/layouts/World.tsx (1)

6-11: LGTM: Import changes align with the new subscription management approach

The new imports suggest a more flexible approach to handling entity subscriptions, supporting the PR's objective of fixing structure owners & transfers.

client/src/ui/modules/world-structures/WorldStructuresMenu.tsx (1)

36-37: LGTM: Improved loading state management

Good addition of loading state management with proper UI feedback for better user experience.

Also applies to: 145-151

Comment on lines +32 to +49
export const addToSubscriptionTwoKeyModelbyRealmEntityId = async <S extends Schema>(
client: ToriiClient,
components: Component<S, Metadata, undefined>[],
entityID: string,
entityID: string[],
) => {
await getEntities(
client,
{
Keys: {
keys: [entityID, undefined],
pattern_matching: "FixedLen" as PatternMatching,
models: ["s0_eternum-BuildingQuantityv2"],
Composite: {
operator: "Or",
clauses: [
...entityID.map((id) => ({
Keys: {
keys: [id, undefined],
pattern_matching: "VariableLen" as PatternMatching,
models: ["s0_eternum-BuildingQuantityv2"],
},
})),
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

Refactor duplicate code in subscription functions

The functions addToSubscriptionTwoKeyModelbyRealmEntityId and addToSubscriptionOneKeyModelbyRealmEntityId share similar logic in constructing composite queries. Consider creating a helper function to reduce code duplication and improve maintainability.

@ponderingdemocritus ponderingdemocritus merged commit a66b1ce into next Dec 17, 2024
9 of 13 checks passed
@bob0005 bob0005 deleted the fix/missing-modles branch December 20, 2024 09:19
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