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: Reduce RTS calls in the updateLayout flow #37127

Merged
merged 47 commits into from
Nov 29, 2024
Merged

Conversation

rishabhrathod01
Copy link
Contributor

@rishabhrathod01 rishabhrathod01 commented Oct 29, 2024

Description

In this PR, we update the code to send all the bindings to RTS together instead of calling it for each property binding. It was observed that the calls were earlier around 40k for the test application.

This change leads to optimisation of performance for

  • updateLayout call ( when updating anything in the DSL )
  • query/API action update
  • JS action update

Fixes #37055

Tests on DP

Deploy-Preview-URL: https://ce-37127.dp.appsmith.com/

  • Multiple widgets with the same bindings impacting the sequence of onPageLoadActions
  • onPageLoadActions update as expected when
    • DSL is updated
    • Query is updated
    • JS Object is updated

EE PR - https://github.com/appsmithorg/appsmith-ee/pull/5642

Automation

/ok-to-test tags="@tag.All"

🔍 Cypress test results

Tip

🟢 🟢 🟢 All cypress tests have passed! 🎉 🎉 🎉
Workflow run: https://github.com/appsmithorg/appsmith/actions/runs/12082854290
Commit: 07b68d4
Cypress dashboard.
Tags: @tag.All
Spec:


Fri, 29 Nov 2024 11:44:31 UTC

Communication

Should the DevRel and Marketing teams inform users about this change?

  • Yes
  • No

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced retrieval of possible entity references and their relationships with a new method.
    • Added new test cases to validate action execution on page load and dynamic binding handling.
  • Bug Fixes

    • Improved error handling and validation for executable references.
    • Enhanced assertions to ensure correct execution of layout actions.
  • Tests

    • Added a test to validate layout actions with multiple widgets referencing the same action.
    • Refactored existing tests for better readability and maintainability.
    • Expanded test coverage for layout updates and dynamic binding scenarios.

Copy link
Contributor

coderabbitai bot commented Oct 29, 2024

Walkthrough

The changes involve the removal of a constant from the OnLoadSpanCE class and significant modifications to the OnLoadExecutablesUtilCEImpl class, including the addition of a new private method and updates to existing method signatures for improved entity reference handling. New test methods are introduced in both the ActionCollectionServiceTest and LayoutServiceTest classes to validate layout actions and dynamic bindings. These changes collectively enhance the management of entity references during page load execution.

Changes

File Change Summary
app/server/appsmith-interfaces/src/main/java/com/appsmith/external/constants/spans/ce/OnLoadSpanCE.java Removed public static final String constant: EXECUTABLE_IN_CREATOR_CONTEXT.
app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java Added private method getPossibleEntityReferencesMap, updated signatures for getPossibleEntityReferences and getPossibleEntityParentsMap, refactored addDirectlyReferencedExecutablesToGraph, and improved error handling and documentation.
app/server/appsmith-server/src/test/java/com/appsmith/server/services/ActionCollectionServiceTest.java Added new test method testLayoutOnLoadActions_withTwoWidgetsAndSameBinding and several private helper methods. Refactored existing tests for clarity.
app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutServiceTest.java Added new test methods to validate layout updates and dynamic bindings, enhanced error handling, and refactored existing tests.

Assessment against linked issues

Objective Addressed Explanation
Resolve the delay due to RTS for the updateLayout (#37055) The changes do not directly address the RTS delay issue.

Possibly related PRs

  • chore: added instrumentation for js object update #36999: This PR adds instrumentation for JavaScript object updates, which is directly related to the removal of the EXECUTABLE_IN_CREATOR_CONTEXT constant in the main PR, as both involve the management of executable contexts.
  • chore: Add spans attributes for no of lines and action count #37001: This PR introduces span attributes for counting lines and actions, which aligns with the changes in the main PR that affect constants related to executable contexts, indicating a focus on tracking and managing executable references.
  • chore: removed unwanted metrics #37052: This PR removes unwanted metrics, including constants related to entity references, which connects to the main PR's removal of the EXECUTABLE_IN_CREATOR_CONTEXT constant, both reflecting a cleanup of unnecessary elements in the codebase.
  • fix: skipped unnecessary code for js object updates #37125: This PR further refines the logic for JavaScript object updates, which is relevant to the main PR's changes in the OnLoadSpanCE class, as both address the handling of executable contexts and their associated constants.
  • chore: perf optimisation for js action creation phase 1 #37391: This PR optimizes the action creation process for JavaScript actions, which relates to the main PR's focus on constants that manage executable contexts, indicating a broader effort to streamline the handling of actions and their contexts.

Suggested labels

JS Objects, Javascript Product

Suggested reviewers

  • sneha122
  • nidhi-nair
  • NilanshBansal

🎉 In code we trust, with constants anew,
Entity references grow, as we pursue.
Methods refined, with tests that align,
In the realm of Java, our code will shine!
Let's celebrate progress, with joy in our heart,
For every small change is a brand new start! 🎈


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.

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.

@rishabhrathod01 rishabhrathod01 changed the title Chore/rts-metrics chore: Add RTS metrics Oct 29, 2024
@github-actions github-actions bot added the skip-changelog Adding this label to a PR prevents it from being listed in the changelog label Oct 29, 2024
Copy link

Failed server tests

  • com.appsmith.server.refactors.ce.RefactoringServiceCETest#testRefactorWidgetName_forDefaultWidgetsInList_updatesBothWidgetsAndTemplateReferences

- After this change we reduce the RTS calls from 2*N to 2 where N is the no of bindings in the layout.
Copy link

Failed server tests

  • com.appsmith.server.services.LayoutActionServiceTest#OnLoadActionsWhenActionDependentOnActionViaWidget

@github-actions github-actions bot added Integrations Pod General Issues related to the Integrations Pod that don't fit into other tags. Integrations Pod Integrations Product Issues related to a specific integration Query & JS Pod Issues related to the query & JS Pod Task A simple Todo labels Oct 30, 2024
@rishabhrathod01 rishabhrathod01 added the ok-to-test Required label for CI label Oct 30, 2024
Copy link

Failed server tests

  • com.appsmith.server.services.LayoutActionServiceTest#OnLoadActionsWhenActionDependentOnActionViaWidget

Copy link

Failed server tests

  • com.appsmith.server.services.ce.ActionServiceCE_Test#invalidCreateActionNullName

Copy link

github-actions bot commented Nov 1, 2024

Failed server tests

  • com.appsmith.server.services.LayoutServiceTest#getActionsExecuteOnLoadWithAstLogic

Copy link

github-actions bot commented Nov 1, 2024

Failed server tests

  • com.appsmith.server.services.LayoutServiceTest#getActionsExecuteOnLoadWithAstLogic

1 similar comment
Copy link

github-actions bot commented Nov 1, 2024

Failed server tests

  • com.appsmith.server.services.LayoutServiceTest#getActionsExecuteOnLoadWithAstLogic

@rishabhrathod01 rishabhrathod01 changed the title chore: Add RTS metrics fix: Reduce RTS calls in the updateLayout flow Nov 1, 2024
@github-actions github-actions bot added Bug Something isn't working and removed skip-changelog Adding this label to a PR prevents it from being listed in the changelog labels Nov 1, 2024
Copy link

github-actions bot commented Nov 1, 2024

Failed server tests

  • com.appsmith.server.services.LayoutServiceTest#getActionsExecuteOnLoadWithAstLogic

Copy link

Failed server tests

  • com.appsmith.server.services.LayoutServiceTest#getActionsExecuteOnLoadWithAstLogic

1 similar comment
Copy link

Failed server tests

  • com.appsmith.server.services.LayoutServiceTest#getActionsExecuteOnLoadWithAstLogic

Copy link

Failed server tests

  • com.appsmith.server.services.LayoutServiceTest#getActionsExecuteOnLoadWithAstLogic

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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ae70aa5 and bdd2e7f.

📒 Files selected for processing (1)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java (5 hunks)
🔇 Additional comments (3)
app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java (3)

669-669: LGTM: Parameter type change aligns with batching optimization

The change from Set<String> to List<String> supports the PR's objective to optimize RTS calls by enabling batched processing.


702-738: LGTM: Improved reactive stream handling with batched processing

The changes effectively optimize the processing of widget bindings while maintaining proper reactive stream handling.


1201-1201: LGTM: Consistent parameter type change

The change to use List instead of Set is consistent with the overall optimization strategy.

Copy link

Failed server tests

  • com.appsmith.server.services.ce.ActionServiceCE_Test#findByIdAndBranchName_forGitConnectedAction_getBranchedAction

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 (3)
app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java (2)

598-612: Replace array index tracking with more robust solution

Using array index for tracking widget paths is error-prone and makes the code harder to maintain. Consider using a more explicit mapping structure.

-Map<Number, String> indexToWidgetPathMap = new HashMap<>();
-int bindingStartIndexInAllBindings = 0;
+List<Tuple2<String, List<String>>> widgetPathBindings = new ArrayList<>();
 for (Map.Entry<String, Set<String>> entry : widgetDynamicBindingsMap.entrySet()) {
     String widgetPath = entry.getKey();
     Set<String> bindings = entry.getValue();
-    allBindings.addAll(bindings);
-    int numberOfBindingsInPath = bindings.size();
-    for (int i = bindingStartIndexInAllBindings;
-            i < bindingStartIndexInAllBindings + numberOfBindingsInPath;
-            i++) {
-        indexToWidgetPathMap.put(i, widgetPath);
-    }
-    bindingStartIndexInAllBindings = bindingStartIndexInAllBindings + numberOfBindingsInPath;
+    widgetPathBindings.add(Tuples.of(widgetPath, new ArrayList<>(bindings)));
+    allBindings.addAll(bindings);
 }

669-673: Add parameter validation for getPossibleEntityParentsMap

The method accepts a List parameter but lacks null/empty validation.

 private Mono<Map<String, Set<EntityDependencyNode>>> getPossibleEntityParentsMap(
         List<String> bindings, int types, int evalVersion) {
+    if (bindings == null || bindings.isEmpty()) {
+        return Mono.just(new HashMap<>());
+    }
     Flux<Tuple2<String, Set<String>>> findingToReferencesFlux =
             astService.getPossibleReferencesFromDynamicBinding(bindings, evalVersion);
     return MustacheHelper.getPossibleEntityParentsMap(findingToReferencesFlux, types);
app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutServiceTest.java (1)

939-1001: Refactor repetitive mock setups in tests

Consider refactoring the repeated Mockito.when() calls for astService.getPossibleReferencesFromDynamicBinding into a helper method to improve readability and maintainability.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bdd2e7f and 98b7eb5.

📒 Files selected for processing (2)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java (5 hunks)
  • app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutServiceTest.java (2 hunks)
🔇 Additional comments (2)
app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java (1)

1201-1201: LGTM: Minor optimization to avoid intermediate collection

The change to use ArrayList constructor is a good optimization to avoid creating an intermediate collection.

app/server/appsmith-server/src/test/java/com/appsmith/server/services/LayoutServiceTest.java (1)

527-536: Verify proper formatting of embedded JavaScript code

Ensure that the embedded JavaScript function within the string is correctly formatted and escaped to avoid runtime errors during execution.

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)
app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java (1)

702-735: Add error handling and documentation for reactive chain

The reactive transformation chain lacks error handling for potential failures in entity reference processing. Consider:

  1. Adding .onErrorResume() handlers for graceful error recovery
  2. Documenting the purpose of each transformation step
  3. Adding logging for debugging complex scenarios
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 98b7eb5 and 191e96f.

📒 Files selected for processing (1)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java (5 hunks)
🔇 Additional comments (2)
app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java (2)

1201-1201: LGTM: Consistent with method signature change

The conversion to ArrayList is correctly implemented and maintains consistency with the updated method signature.


669-673: Consider performance implications of Set to List change

The change from Set<String> to List<String> could allow duplicate bindings to be processed. For large collections, this might impact performance. Consider adding a deduplication step or documenting why duplicates are acceptable.

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

🧹 Outside diff range and nitpick comments (2)
app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java (2)

669-671: Method signature change needs documentation

The method signature has been changed from Set<String> to List<String> for the bindings parameter, but lacks documentation explaining the reason for this change.

Add Javadoc to explain the change:

+/**
+ * @param bindings List of bindings to analyze (changed from Set to List to maintain order)
+ * @param types The types of EntityDependencyNode references to look for
+ * @param evalVersion Version used for AST parsing
+ * @return Map of bindings to their possible entity parents
+ */
private Mono<Map<String, Set<EntityDependencyNode>>> getPossibleEntityParentsMap(

586-657: New method implements batch processing of bindings

The implementation correctly handles batch processing of bindings to reduce RTS calls, aligning with the PR objectives.

Consider adding metrics/monitoring to track:

  1. Average batch size
  2. Processing time per batch
  3. Success/failure rates
    This will help validate the performance improvements.
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 191e96f and d1b3791.

📒 Files selected for processing (1)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java (6 hunks)
🔇 Additional comments (2)
app/server/appsmith-server/src/main/java/com/appsmith/server/onload/internal/OnLoadExecutablesUtilCEImpl.java (2)

1221-1221: Parameter type change matches method signature

The change from Set<String> to ArrayList<>(widgetBindingEntries.getValue()) aligns with the updated method signature.


Line range hint 702-755: Verify widget dependency handling

The changes to handle widget dependencies look correct, but we should verify the edge cases.

✅ Verification successful

Widget dependency handling implementation is robust and properly integrated

The implementation correctly:

  • Creates widget dependency nodes with proper entity reference type
  • Handles widget-to-executable relationships via dependency edges
  • Maintains widget bindings in a thread-safe manner using computeIfAbsent
  • Properly processes widget paths and dynamic bindings
  • Has error boundaries in the layout service implementation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential edge cases in widget dependency handling
rg -A 2 "widgetDependencyNode.*EntityDependencyNode" 

# Check for any existing error handling patterns
rg -B 2 -A 2 "catch.*EntityDependencyNode"

Length of output: 99


Script:

#!/bin/bash
# Let's search for the EntityDependencyNode class definition and its usage patterns
ast-grep --pattern 'class EntityDependencyNode {
  $$$
}'

# Search for widget dependency handling patterns
rg -B 2 -A 2 "EntityReferenceType.WIDGET"

# Search for any error handling related to widget dependencies
rg -B 2 -A 2 "widgetDynamicBindingsMap"

# Look for related test cases
fd -e java -e ts -e js --exec rg -l "widgetDependencyNode|EntityDependencyNode"

Length of output: 19996

@rishabhrathod01
Copy link
Contributor Author

./build-deploy-preview skip-tests=true

@rishabhrathod01
Copy link
Contributor Author

/build-deploy-preview skip-tests=true

Copy link

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/12078659951.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 37127.
recreate: .

Copy link

Deploy-Preview-URL: https://ce-37127.dp.appsmith.com

Copy link

Failed server tests

  • com.appsmith.server.services.LayoutActionServiceTest#OnLoadActionsWhenActionDependentOnWidgetButNotPageLoadCandidate

@sneha122 sneha122 self-requested a review November 29, 2024 10:56
@rishabhrathod01 rishabhrathod01 merged commit e8cb73d into release Nov 29, 2024
82 checks passed
@rishabhrathod01 rishabhrathod01 deleted the chore/rts-metrics branch November 29, 2024 11:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Something isn't working Integrations Pod General Issues related to the Integrations Pod that don't fit into other tags. Integrations Pod Integrations Product Issues related to a specific integration ok-to-test Required label for CI Query & JS Pod Issues related to the query & JS Pod Task A simple Todo
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Task]: Resolve the delay due to RTS for the updateLayout
3 participants