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 sync #2469

Merged
merged 2 commits into from
Dec 13, 2024
Merged

fix sync #2469

merged 2 commits into from
Dec 13, 2024

Conversation

aymericdelab
Copy link
Collaborator

@aymericdelab aymericdelab commented Dec 12, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new addMarketSubscription method for subscribing to market data.
    • Enhanced the World component to support market subscriptions alongside existing functionalities.
    • Added a loading indicator in the MarketModal to provide feedback during market data synchronization.
  • Bug Fixes

    • Improved error handling during market data subscription attempts.

Copy link

vercel bot commented Dec 12, 2024

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 Dec 12, 2024 11:32pm
eternum-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 12, 2024 11:32pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
eternum-landing ⬜️ Ignored (Inspect) Visit Preview Dec 12, 2024 11:32pm

Copy link
Contributor

coderabbitai bot commented Dec 12, 2024

Walkthrough

The pull request introduces enhancements to the addToSubscription and addMarketSubscription functions in the client/src/dojo/queries.ts file. The addToSubscription function now conditionally invokes getEntities based on the presence of the position parameter. A new function, addMarketSubscription, is added to facilitate market data subscriptions. Additionally, the World component in client/src/ui/layouts/World.tsx is updated to incorporate the new subscription method within an existing useEffect hook, including error handling for subscription failures. The useWorldStore is also modified to manage a new loading state for market data.

Changes

File Change Summary
client/src/dojo/queries.ts - Enhanced addToSubscription to conditionally call getEntities based on position.
- Added addMarketSubscription function for market data subscriptions.
client/src/ui/layouts/World.tsx - Imported addMarketSubscription and integrated it into useEffect for market data fetching.
- Added error handling for the new subscription logic.
client/src/hooks/store/useWorldLoading.tsx - Added isMarketLoading property to WorldState interface and setMarketLoading method.
- Updated initial state to include isMarketLoading: true.
client/src/ui/components/trading/MarketModal.tsx - Integrated isMarketLoading state to conditionally render a loading indicator.

Possibly related PRs

  • feat: lazy loading components #1841: The MarketModal.tsx component now imports addMarketSubscription, which is directly related to the new addMarketSubscription function introduced in the main PR.
  • [client] spectator mode #2075: This PR modifies the useWorldStore to include a new loading state, isMarketLoading, which is relevant to the changes in the main PR that also involve managing loading states for subscriptions.
  • Refactor deposit resources and entity list components #2243: The changes in DepositResources and EntityList components may not directly relate to the main PR, but they involve similar concepts of managing resources and subscriptions, indicating a broader context of subscription management.
  • feat: add countdown backdrop to client page #2383: The introduction of the CountdownTimer component in the DojoContext.tsx may not directly relate to the main PR, but it enhances user feedback during loading states, which is a theme present in the main PR's changes.
  • hs cost #2443: The modifications in the setup function regarding entity synchronization may not directly relate to the main PR, but they reflect ongoing improvements in how entities are managed, which is relevant to the subscription logic introduced in the main PR.
  • feat: optimise event messages #2455: The optimizations in the TileManager class may not directly relate to the main PR, but they indicate a focus on improving event handling and messaging, which aligns with the overall goal of enhancing functionality in the codebase.

Suggested reviewers

  • ponderingdemocritus

Poem

In the dojo where queries play,
A new subscription joins the fray.
With conditions set, we fetch with care,
Market data dances in the air!
Errors logged, but fears allayed,
In this world, new features are made! 🐇✨


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. (Experiment)
  • @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
Contributor

mentatbot bot commented Dec 12, 2024

You are out of MentatBot reviews. Your usage will refresh December 16 at 08:00 AM.

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

🧹 Outside diff range and nitpick comments (1)
client/src/ui/layouts/World.tsx (1)

143-147: Separate market subscription into its own useEffect

The market subscription logic should be separated from the structure-specific useEffect for several reasons:

  1. Market subscription is independent of structure changes
  2. Current placement causes unnecessary retries on structure changes
  3. Loading state isn't properly handled for market subscription failures

Consider refactoring to:

+ // Separate useEffect for market subscription
+ useEffect(() => {
+   const fetchMarketData = async () => {
+     try {
+       setWorldLoading(true);
+       await addMarketSubscription(dojo.network.toriiClient, dojo.network.contractComponents as any);
+     } catch (error) {
+       console.error("Market fetch failed:", error);
+     } finally {
+       setWorldLoading(false);
+     }
+   };
+
+   fetchMarketData();
+ }, []); // Run once on component mount

  useEffect(() => {
    if (!structureEntityId || subscriptions[structureEntityId.toString()] || structureEntityId === 999999998) {
      return;
    }

    const position = getComponentValue(
      dojo.setup.components.Position,
      getEntityIdFromKeys([BigInt(structureEntityId)]),
    );

    setWorldLoading(true);
    setSubscriptions((prev) => ({ ...prev, [structureEntityId.toString()]: true }));
    const fetch = async () => {
      try {
        await addToSubscription(
          dojo.network.toriiClient,
          dojo.network.contractComponents as any,
          structureEntityId.toString(),
          { x: position?.x || 0, y: position?.y || 0 },
        );
-     } catch (error) {
-       console.error("Fetch failed", error);
-     } finally {
-       setWorldLoading(false);
-     }
-
-     try {
-       await addMarketSubscription(dojo.network.toriiClient, dojo.network.contractComponents as any);
-     } catch (error) {
-       console.error("Fetch failed", error);
-     }
+     } catch (error) {
+       console.error("Structure fetch failed:", error);
+     } finally {
+       setWorldLoading(false);
+     }
    };

    fetch();
  }, [structureEntityId, subscriptions, setWorldLoading, setSubscriptions]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e9ad1ea and 2517810.

📒 Files selected for processing (2)
  • client/src/dojo/queries.ts (2 hunks)
  • client/src/ui/layouts/World.tsx (2 hunks)
🔇 Additional comments (1)
client/src/dojo/queries.ts (1)

69-78: LGTM: Conditional entity fetching based on position

The conditional execution of getEntities based on position presence fixes unnecessary fetches. The implementation correctly handles optional position parameter.

Let's verify the impact of this change:

✅ Verification successful

Let me check the implementation of addToSubscription to understand how it handles the position parameter.


Let me try a different approach to find the implementation.


Let me check the complete implementation of the function to understand how it uses the position parameter.


The conditional entity fetching change is safe and correct

Based on the verification:

  1. The addToSubscription function properly handles the optional position parameter in both its signature and implementation
  2. All calls to addToSubscription found in the codebase pass the position parameter as optional, matching the function's signature
  3. The conditional execution of getEntities is correctly guarded by the position check, preventing unnecessary fetches when position is not provided

The change aligns with the function's design and its usage across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all calls to addToSubscription to ensure they handle optional position correctly
rg -A 3 "addToSubscription\(" 

Length of output: 1709


Script:

#!/bin/bash
# Search for the implementation of addToSubscription
ast-grep --pattern 'export const addToSubscription = async $_'

Length of output: 485


Script:

#!/bin/bash
# Search for the implementation of addToSubscription using ripgrep
rg -A 10 "export const addToSubscription" 

Length of output: 1485


Script:

#!/bin/bash
# Get the complete implementation of addToSubscription
rg -A 20 "export const addToSubscription" client/src/dojo/queries.ts

Length of output: 614

Comment on lines +95 to +98
export const addMarketSubscription = async <S extends Schema>(
client: ToriiClient,
components: Component<S, Metadata, undefined>[],
) => {
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

Add error handling for getEntities failure

The new market subscription function should handle potential failures from getEntities to prevent silent failures.

Consider wrapping the call with try-catch:

 export const addMarketSubscription = async <S extends Schema>(
   client: ToriiClient,
   components: Component<S, Metadata, undefined>[],
 ) => {
+  try {
     await getEntities(
       client,
       {
         Keys: {
           keys: [undefined, undefined],
           pattern_matching: "FixedLen",
           models: ["s0_eternum-DetachedResource"],
         },
       },
       components,
       10_000,
       false,
     );
+  } catch (error) {
+    console.error("Failed to fetch market entities:", error);
+    throw error; // Re-throw to allow caller to handle the error
+  }
 };
📝 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
export const addMarketSubscription = async <S extends Schema>(
client: ToriiClient,
components: Component<S, Metadata, undefined>[],
) => {
export const addMarketSubscription = async <S extends Schema>(
client: ToriiClient,
components: Component<S, Metadata, undefined>[],
) => {
try {
await getEntities(
client,
{
Keys: {
keys: [undefined, undefined],
pattern_matching: "FixedLen",
models: ["s0_eternum-DetachedResource"],
},
},
components,
10_000,
false,
);
} catch (error) {
console.error("Failed to fetch market entities:", error);
throw error; // Re-throw to allow caller to handle the error
}
};

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 and nitpick comments (1)
client/src/ui/components/trading/MarketModal.tsx (1)

207-207: Consider enhancing loading indicator accessibility.

While the implementation is clean and non-intrusive, consider adding ARIA attributes for better accessibility.

Apply this diff to improve accessibility:

-      <div className="market-modal-selector container border mx-auto grid grid-cols-12 bg-dark border-gold/30 h-full row-span-12 rounded-2xl relative">
+      <div className="market-modal-selector container border mx-auto grid grid-cols-12 bg-dark border-gold/30 h-full row-span-12 rounded-2xl relative" role="dialog" aria-label="Market Modal">
       {/* ... existing content ... */}
       {isMarketLoading && (
-        <div className="absolute bottom-4 inset-x-0 z-10 flex justify-center pointer-events-none">
+        <div className="absolute bottom-4 inset-x-0 z-10 flex justify-center pointer-events-none" role="status" aria-live="polite">
           <div className="bg-brown/90 text-sm px-4 py-1 rounded-t-lg border border-gold/30 flex items-center gap-2">
             <div className="w-2 h-2 bg-gold/50 rounded-full animate-pulse" />
-            <span>Syncing market data...</span>
+            <span aria-label="Loading">Syncing market data...</span>
           </div>
         </div>
       )}

Also applies to: 350-357

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2517810 and 7535b93.

📒 Files selected for processing (3)
  • client/src/hooks/store/useWorldLoading.tsx (1 hunks)
  • client/src/ui/components/trading/MarketModal.tsx (4 hunks)
  • client/src/ui/layouts/World.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/src/ui/layouts/World.tsx
🔇 Additional comments (2)
client/src/hooks/store/useWorldLoading.tsx (1)

6-8: LGTM! Loading state management implementation follows best practices.

The implementation:

  • Maintains consistency with existing patterns
  • Properly types the new market loading state
  • Follows Zustand's recommended approach for state updates

Also applies to: 13-15

client/src/ui/components/trading/MarketModal.tsx (1)

18-18: LGTM! Clean integration of market loading state.

The hook usage follows React best practices by:

  • Properly importing the store
  • Using selector pattern for optimal performance

Also applies to: 68-69

Comment on lines +350 to +357
{isMarketLoading && (
<div className="absolute bottom-4 inset-x-0 z-10 flex justify-center pointer-events-none">
<div className="bg-brown/90 text-sm px-4 py-1 rounded-t-lg border border-gold/30 flex items-center gap-2">
<div className="w-2 h-2 bg-gold/50 rounded-full animate-pulse" />
<span>Syncing market data...</span>
</div>
</div>
)}
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

Consider adding error handling for market data sync failures.

The loading indicator provides good feedback during loading, but there's no handling for potential sync failures.

Consider implementing error handling:

 const isMarketLoading = useWorldStore((state) => state.isMarketLoading);
+const [syncError, setSyncError] = useState<string | null>(null);
+
+useEffect(() => {
+  if (syncError) {
+    const timer = setTimeout(() => setSyncError(null), 5000);
+    return () => clearTimeout(timer);
+  }
+}, [syncError]);

 // ... existing JSX ...

       {isMarketLoading && (
         <div className="absolute bottom-4 inset-x-0 z-10 flex justify-center pointer-events-none">
           <div className="bg-brown/90 text-sm px-4 py-1 rounded-t-lg border border-gold/30 flex items-center gap-2">
             <div className="w-2 h-2 bg-gold/50 rounded-full animate-pulse" />
             <span>Syncing market data...</span>
           </div>
         </div>
       )}
+      {syncError && (
+        <div className="absolute bottom-4 inset-x-0 z-10 flex justify-center pointer-events-none">
+          <div className="bg-red-900/90 text-sm px-4 py-1 rounded-t-lg border border-red-500/30 flex items-center gap-2">
+            <span>⚠️ {syncError}</span>
+          </div>
+        </div>
+      )}

Committable suggestion skipped: line range outside the PR's diff.

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