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(ui): Improve project import synchronization and error handling #995

Merged
merged 2 commits into from
Mar 7, 2025

Conversation

kasugamirai
Copy link
Member

@kasugamirai kasugamirai commented Mar 7, 2025

Overview

What I've done

What I haven't done

How I tested

Screenshot

Which point I want you to review particularly

Memo

Summary by CodeRabbit

  • Refactor
    • Improved the asynchronous process to apply project updates reliably after a successful connection.
    • Streamlined error messaging to provide clearer guidance if a project import fails.
    • Optimized callback management to enhance the overall stability of the project import functionality.

@kasugamirai kasugamirai requested a review from KaWaite as a code owner March 7, 2025 08:34
Copy link
Contributor

coderabbitai bot commented Mar 7, 2025

Walkthrough

The changes involve restructuring the asynchronous handling within the project import hook. The update to the Y.Doc instance is now executed within a transaction triggered by the successful synchronization of the WebSocket connection. The redundant asynchronous wrapper for setting up the WebSocket provider has been removed, and the error message has been clarified. Additionally, the order of dependencies in the handleProjectFileUpload callback has been adjusted.

Changes

File Path Change Summary
ui/src/hooks/useProjectImport.ts - Moved Y.Doc update inside a transaction triggered by the WebSocket "sync" event.
- Removed redundant asynchronous setup wrapper.
- Updated error message text.
- Adjusted dependency order in handleProjectFileUpload callback.

Sequence Diagram(s)

sequenceDiagram
    participant IH as ImportHandler
    participant WP as WebSocketProvider
    participant YD as Y.Doc
    IH->>WP: Initialize connection
    WP->>IH: Emit "sync" event
    IH->>YD: Begin transaction and apply update
    YD-->>IH: Acknowledge update
Loading

Suggested reviewers

  • KaWaite
  • pyshx

Poem

I'm a rabbit in the code, so spry,
Hopping through changes with a joyful sigh.
Sync events bloom, transactions rock,
Error messages now clearly talk.
Leaping high for each neat new tweak, oh my! 🐇✨


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e803b56 and 639c2f7.

📒 Files selected for processing (1)
  • ui/src/hooks/useProjectImport.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • ui/src/hooks/useProjectImport.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Collect information
  • GitHub Check: Redirect rules - reearth-flow
  • GitHub Check: Header rules - reearth-flow
  • GitHub Check: Pages changed - reearth-flow

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

Documentation and Community

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

Copy link

netlify bot commented Mar 7, 2025

Deploy Preview for reearth-flow ready!

Name Link
🔨 Latest commit 639c2f7
🔍 Latest deploy log https://app.netlify.com/sites/reearth-flow/deploys/67cab07d7822b90008c8f93c
😎 Deploy Preview https://deploy-preview-995--reearth-flow.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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

🧹 Nitpick comments (2)
ui/src/hooks/useProjectImport.ts (2)

80-94: Good use of Promise to handle sync event.

The introduction of a Promise to manage the WebSocket synchronization event is a good approach for handling the asynchronous nature of the sync process. However, consider adding a timeout mechanism to prevent potential deadlocks if the sync event never fires.

-          await new Promise<void>((resolve) => {
+          await Promise.race([
+            new Promise<void>((resolve) => {
+              yWebSocketProvider.once("sync", () => {
+                yDoc.transact(() => {
+                  Y.applyUpdate(yDoc, yDocBinary);
+                });
+
+                const yWorkflows = yDoc.getArray<YWorkflow>("workflows");
+                if (!yWorkflows.length) {
+                  console.warn("Imported project has no workflows");
+                }
+
+                setIsProjectImporting(false);
+                resolve();
+              });
+            }),
+            new Promise<void>((_, reject) => {
+              setTimeout(() => reject(new Error("Sync timeout")), 30000); // 30 seconds timeout
+            }),
+          ]);

96-99: Enhance error handling with user feedback.

The error handling only logs to the console and resets the loading state. Consider providing user feedback about the error.

try {
  // ...
} catch (error) {
  console.error("Failed to import project:", error);
+  // Add user feedback here, e.g., notification
+  // if you have a notification system, you might use it like:
+  // notifyError(t("Failed to import project"), error);
  setIsProjectImporting(false);
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2cf660e and e803b56.

📒 Files selected for processing (1)
  • ui/src/hooks/useProjectImport.ts (1 hunks)
🔇 Additional comments (3)
ui/src/hooks/useProjectImport.ts (3)

82-84: Excellent use of transaction for atomic updates.

Wrapping the Y.applyUpdate call in a transaction is a good practice. YJS transactions ensure that all updates within the transaction are applied atomically, which prevents inconsistent states and improves performance by batching updates.


101-101: Dependency array ordering change is correct.

The reordering of dependencies in the useCallback hook doesn't affect functionality as long as all dependencies are included.


108-108: Good addition of fileInputRef to return object.

Adding fileInputRef to the return object makes sense if there's a need to access this ref from outside the hook, allowing more flexible usage by consumers.

Comment on lines 67 to 95
const yDoc = new Y.Doc();
Y.applyUpdate(yDoc, yDocBinary);

const { websocket } = config();

if (websocket && projectMeta) {
(async () => {
const token = await getAccessToken();

const yWebSocketProvider = new WebsocketProvider(
websocket,
`${project.id}:${DEFAULT_ENTRY_GRAPH_ID}`,
yDoc,
{ params: { token } },
);

const token = await getAccessToken();

const yWebSocketProvider = new WebsocketProvider(
websocket,
`${project.id}:${DEFAULT_ENTRY_GRAPH_ID}`,
yDoc,
{ params: { token } },
);

await new Promise<void>((resolve) => {
yWebSocketProvider.once("sync", () => {
yDoc.transact(() => {
Y.applyUpdate(yDoc, yDocBinary);
});

const yWorkflows = yDoc.getArray<YWorkflow>("workflows");
if (!yWorkflows.length) {
console.warn("Imported project has no workflows");
}

setIsProjectImporting(false);
resolve();
});
})();
});
}
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

Missing WebSocket provider cleanup.

The WebSocket provider is created but never cleaned up, which could lead to memory leaks if the component using this hook unmounts before the sync is complete.

Consider adding a cleanup function using a useEffect hook at the component level:

useEffect(() => {
  let yWebSocketProvider: WebsocketProvider | undefined;
  
  // Assign the provider to this variable when creating it
  
  return () => {
    // Clean up WebSocket provider if it exists
    if (yWebSocketProvider) {
      yWebSocketProvider.disconnect();
    }
  };
}, []);

Alternatively, you could return a cleanup function from the hook itself that consumers can call when unmounting.

@kasugamirai kasugamirai enabled auto-merge (squash) March 7, 2025 08:43
@kasugamirai kasugamirai merged commit 718dae6 into main Mar 7, 2025
23 checks passed
@kasugamirai kasugamirai deleted the fix/project-import branch March 7, 2025 13:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants