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

chore: fetch remote reference in local #38009

Merged
merged 5 commits into from
Dec 9, 2024
Merged

Conversation

sondermanish
Copy link
Contributor

@sondermanish sondermanish commented Dec 6, 2024

Description

  • Added fetch remote CGS Impl

Fixes #

Warning

If no issue exists, please create an issue first, and check with the maintainers if the issue is valid.

Automation

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

🔍 Cypress test results

Tip

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


Mon, 09 Dec 2024 20:08:50 UTC

Communication

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

  • Yes
  • No

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced new methods for fetching remote changes in various Git services, enhancing synchronization capabilities.
    • Added new fields for internal metadata management.
    • Implemented user session management improvements for better handling of user-related data.
    • Added analytics tracking for unit execution time to improve performance insights.
  • Bug Fixes

    • Enhanced error handling in new fetch methods to ensure robustness.

@sondermanish sondermanish requested a review from a team as a code owner December 6, 2024 08:29
@sondermanish sondermanish self-assigned this Dec 6, 2024
Copy link
Contributor

coderabbitai bot commented Dec 6, 2024

Walkthrough

The changes in this pull request introduce new fields and methods across several classes related to Git operations. The GitArtifactMetadataCE class receives two new transient fields for internal use. The CentralGitServiceCE interface and its implementations gain new overloaded methods for fetching remote changes, enhancing their capabilities. Additionally, the GitAnalyticsUtils class adds a method for sending analytics events. These modifications collectively improve the functionality and structure of the Git service.

Changes

File Change Summary
app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/GitArtifactMetadataCE.java - Added fields: String refName, RefType refType (both transient and for internal use).
- Existing methods and fields remain unchanged.
app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCE.java - Added method: Mono<String> fetchRemoteChanges(String referenceArtifactId, boolean isFileLock, ArtifactType artifactType, GitType gitType, RefType refType).
app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCECompatibleImpl.java - Updated constructor to include SessionUserService.
app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCEImpl.java - Added methods: public Mono<String> fetchRemoteChanges(Artifact baseArtifact, Artifact refArtifact, boolean isFileLock, GitType gitType, RefType refType) and public Mono<String> fetchRemoteChanges(String refArtifactId, boolean isFileLock, ArtifactType artifactType, GitType gitType, RefType refType).
app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceImpl.java - Updated constructor to include SessionUserService.
app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/GitHandlingServiceCE.java - Added method: Mono<String> fetchRemoteChanges(ArtifactJsonTransformationDTO jsonTransformationDTO, GitAuth gitAuth).
app/server/appsmith-server/src/main/java/com/appsmith/server/git/fs/GitFSServiceCEImpl.java - Added method: public Mono<String> fetchRemoteChanges(ArtifactJsonTransformationDTO jsonTransformationDTO, GitAuth gitAuth).
app/server/appsmith-server/src/main/java/com/appsmith/server/git/utils/GitAnalyticsUtils.java - Added method: public Mono<Void> sendUnitExecutionTimeAnalyticsEvent(String flowName, Long elapsedTime, User currentUser, Artifact artifact).

Possibly related PRs

Suggested labels

Enhancement, Git Product, ok-to-test, Task

Suggested reviewers

  • nidhi-nair
  • sharat87

🎉 In the land of code where Git does play,
New fields and methods brighten the day!
With fetches and analytics, all in the mix,
The Git service grows, adding new tricks!
So let's raise a cheer for this code parade,
Enhancements and features, a grand upgrade! 🎊


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.

@github-actions github-actions bot added the skip-changelog Adding this label to a PR prevents it from being listed in the changelog label Dec 6, 2024
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: 2

🧹 Outside diff range and nitpick comments (1)
app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCE.java (1)

28-33: LGTM! Consider adding method documentation.

The new method signature follows reactive patterns and includes all necessary parameters for fetch operations.

Consider adding Javadoc to describe the purpose of each parameter and the expected return value.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a450226 and dfe723d.

📒 Files selected for processing (8)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/GitArtifactMetadataCE.java (2 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCE.java (2 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCECompatibleImpl.java (3 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCEImpl.java (6 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceImpl.java (3 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/GitHandlingServiceCE.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/fs/GitFSServiceCEImpl.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/utils/GitAnalyticsUtils.java (2 hunks)
🔇 Additional comments (6)
app/server/appsmith-server/src/main/java/com/appsmith/server/domains/ce/GitArtifactMetadataCE.java (1)

28-37: LGTM! Note the TODOs for future visibility changes.

The new fields are properly annotated for internal use. The TODO comments clearly indicate the plan to make these fields public once implementation is complete.

Let's verify if these fields are used consistently across the codebase:

✅ Verification successful

LGTM! The new fields are properly used across the codebase.

The fields refName and refType are used consistently in the Git-related functionality:

  • Used in ArtifactJsonTransformationDTO for JSON transformations
  • Utilized in CentralGitServiceCE for remote changes fetching
  • Properly handled in GitFSServiceCEImpl for Git filesystem operations

The transient and internal view annotations are appropriate as these fields are only used internally within the Git-related services.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check usage of refName and refType
ast-grep --pattern 'class $_ {
  $$$
  $_(refName|refType)
  $$$
}'

Length of output: 69


Script:

#!/bin/bash
# Search for usage of refName and refType fields
rg "refName|refType" -A 2 -B 2

# Search for classes that might use these fields
ast-grep --pattern 'class $_ extends GitArtifactMetadata'

# Check for any references to GitArtifactMetadata
rg "GitArtifactMetadata" -A 2 -B 2

Length of output: 101465

app/server/appsmith-server/src/main/java/com/appsmith/server/git/utils/GitAnalyticsUtils.java (1)

127-148: LGTM! Analytics implementation is clean and comprehensive.

The method properly constructs the analytics data map with all relevant Git metadata and follows existing patterns.

app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCE.java (1)

35-36: LGTM! Method overloading is appropriate.

The overloaded version with direct Artifact parameters provides a convenient alternative for cases where artifacts are already loaded.

app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceImpl.java (1)

29-29: LGTM! Clean dependency injection.

The addition of SessionUserService follows proper dependency injection patterns and is correctly propagated to the superclass.

Also applies to: 45-45

app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/GitHandlingServiceCE.java (1)

60-60: LGTM! Verify error handling in implementations.

The method signature is well-designed for Git operations.

app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCECompatibleImpl.java (1)

13-13: Clean implementation of SessionUserService integration

The addition of SessionUserService follows proper dependency injection patterns and maintains clean code structure.

Also applies to: 30-30, 46-46

Comment on lines 972 to 973
jsonTransformationDTO.setRefType(RefType.BRANCH);
jsonTransformationDTO.setWorkspaceId(baseArtifact.getWorkspaceId());
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

Remove redundant assignment of refType in jsonTransformationDTO

The refType is set twice; you can remove the initial assignment.

ArtifactJsonTransformationDTO jsonTransformationDTO = new ArtifactJsonTransformationDTO();
- jsonTransformationDTO.setRefType(RefType.BRANCH);
jsonTransformationDTO.setWorkspaceId(baseArtifact.getWorkspaceId());
jsonTransformationDTO.setBaseArtifactId(baseArtifactGitData.getDefaultArtifactId());
jsonTransformationDTO.setRepoName(baseArtifactGitData.getRepoName());
jsonTransformationDTO.setArtifactType(baseArtifact.getArtifactType());
jsonTransformationDTO.setRefName(refArtifactGitData.getRefName());
jsonTransformationDTO.setRefType(refType);

Also applies to: 978-978

Comment on lines +572 to +591
@Override
public Mono<String> fetchRemoteChanges(ArtifactJsonTransformationDTO jsonTransformationDTO, GitAuth gitAuth) {

String workspaceId = jsonTransformationDTO.getWorkspaceId();
String baseArtifactId = jsonTransformationDTO.getBaseArtifactId();
String repoName = jsonTransformationDTO.getRepoName();
String refName = jsonTransformationDTO.getRefName();

ArtifactType artifactType = jsonTransformationDTO.getArtifactType();
GitArtifactHelper<?> gitArtifactHelper = gitArtifactHelperResolver.getArtifactHelper(artifactType);
Path repoSuffix = gitArtifactHelper.getRepoSuffixPath(workspaceId, baseArtifactId, repoName);

Path repoPath = fsGitHandler.createRepoPath(repoSuffix);
Mono<Boolean> checkoutBranchMono = fsGitHandler.checkoutToBranch(repoSuffix, refName);

Mono<String> fetchRemoteMono = fsGitHandler.fetchRemote(
repoPath, gitAuth.getPublicKey(), gitAuth.getPrivateKey(), true, refName, false);

return checkoutBranchMono.then(Mono.defer(() -> fetchRemoteMono));
}
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

Add error handling for checkout and fetch operations.

While the implementation sequence is correct, the method should handle potential failures in checkout and fetch operations, similar to error handling patterns used in other methods of this class (e.g., pushArtifact).

Consider adding error handling:

 @Override
 public Mono<String> fetchRemoteChanges(ArtifactJsonTransformationDTO jsonTransformationDTO, GitAuth gitAuth) {
     String workspaceId = jsonTransformationDTO.getWorkspaceId();
     String baseArtifactId = jsonTransformationDTO.getBaseArtifactId();
     String repoName = jsonTransformationDTO.getRepoName();
     String refName = jsonTransformationDTO.getRefName();

     ArtifactType artifactType = jsonTransformationDTO.getArtifactType();
     GitArtifactHelper<?> gitArtifactHelper = gitArtifactHelperResolver.getArtifactHelper(artifactType);
     Path repoSuffix = gitArtifactHelper.getRepoSuffixPath(workspaceId, baseArtifactId, repoName);

     Path repoPath = fsGitHandler.createRepoPath(repoSuffix);
-    Mono<Boolean> checkoutBranchMono = fsGitHandler.checkoutToBranch(repoSuffix, refName);
+    Mono<Boolean> checkoutBranchMono = fsGitHandler.checkoutToBranch(repoSuffix, refName)
+            .onErrorResume(error -> {
+                log.error("Error while checking out branch: {}", error.getMessage());
+                return gitAnalyticsUtils
+                        .addAnalyticsForGitOperation(
+                                AnalyticsEvents.GIT_CHECKOUT,
+                                jsonTransformationDTO,
+                                error.getClass().getName(),
+                                error.getMessage(),
+                                false)
+                        .then(Mono.error(new AppsmithException(
+                                AppsmithError.GIT_ACTION_FAILED,
+                                "checkout",
+                                error.getMessage())));
+            });

     Mono<String> fetchRemoteMono = fsGitHandler.fetchRemote(
             repoPath, gitAuth.getPublicKey(), gitAuth.getPrivateKey(), true, refName, false);

-    return checkoutBranchMono.then(Mono.defer(() -> fetchRemoteMono));
+    return checkoutBranchMono.then(Mono.defer(() -> fetchRemoteMono))
+            .onErrorResume(error -> {
+                log.error("Error while fetching remote changes: {}", error.getMessage());
+                return gitAnalyticsUtils
+                        .addAnalyticsForGitOperation(
+                                AnalyticsEvents.GIT_FETCH,
+                                jsonTransformationDTO,
+                                error.getClass().getName(),
+                                error.getMessage(),
+                                false)
+                        .then(Mono.error(new AppsmithException(
+                                AppsmithError.GIT_ACTION_FAILED,
+                                "fetch",
+                                error.getMessage())));
+            });
 }
📝 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
@Override
public Mono<String> fetchRemoteChanges(ArtifactJsonTransformationDTO jsonTransformationDTO, GitAuth gitAuth) {
String workspaceId = jsonTransformationDTO.getWorkspaceId();
String baseArtifactId = jsonTransformationDTO.getBaseArtifactId();
String repoName = jsonTransformationDTO.getRepoName();
String refName = jsonTransformationDTO.getRefName();
ArtifactType artifactType = jsonTransformationDTO.getArtifactType();
GitArtifactHelper<?> gitArtifactHelper = gitArtifactHelperResolver.getArtifactHelper(artifactType);
Path repoSuffix = gitArtifactHelper.getRepoSuffixPath(workspaceId, baseArtifactId, repoName);
Path repoPath = fsGitHandler.createRepoPath(repoSuffix);
Mono<Boolean> checkoutBranchMono = fsGitHandler.checkoutToBranch(repoSuffix, refName);
Mono<String> fetchRemoteMono = fsGitHandler.fetchRemote(
repoPath, gitAuth.getPublicKey(), gitAuth.getPrivateKey(), true, refName, false);
return checkoutBranchMono.then(Mono.defer(() -> fetchRemoteMono));
}
@Override
public Mono<String> fetchRemoteChanges(ArtifactJsonTransformationDTO jsonTransformationDTO, GitAuth gitAuth) {
String workspaceId = jsonTransformationDTO.getWorkspaceId();
String baseArtifactId = jsonTransformationDTO.getBaseArtifactId();
String repoName = jsonTransformationDTO.getRepoName();
String refName = jsonTransformationDTO.getRefName();
ArtifactType artifactType = jsonTransformationDTO.getArtifactType();
GitArtifactHelper<?> gitArtifactHelper = gitArtifactHelperResolver.getArtifactHelper(artifactType);
Path repoSuffix = gitArtifactHelper.getRepoSuffixPath(workspaceId, baseArtifactId, repoName);
Path repoPath = fsGitHandler.createRepoPath(repoSuffix);
Mono<Boolean> checkoutBranchMono = fsGitHandler.checkoutToBranch(repoSuffix, refName)
.onErrorResume(error -> {
log.error("Error while checking out branch: {}", error.getMessage());
return gitAnalyticsUtils
.addAnalyticsForGitOperation(
AnalyticsEvents.GIT_CHECKOUT,
jsonTransformationDTO,
error.getClass().getName(),
error.getMessage(),
false)
.then(Mono.error(new AppsmithException(
AppsmithError.GIT_ACTION_FAILED,
"checkout",
error.getMessage())));
});
Mono<String> fetchRemoteMono = fsGitHandler.fetchRemote(
repoPath, gitAuth.getPublicKey(), gitAuth.getPrivateKey(), true, refName, false);
return checkoutBranchMono.then(Mono.defer(() -> fetchRemoteMono))
.onErrorResume(error -> {
log.error("Error while fetching remote changes: {}", error.getMessage());
return gitAnalyticsUtils
.addAnalyticsForGitOperation(
AnalyticsEvents.GIT_FETCH,
jsonTransformationDTO,
error.getClass().getName(),
error.getMessage(),
false)
.then(Mono.error(new AppsmithException(
AppsmithError.GIT_ACTION_FAILED,
"fetch",
error.getMessage())));
});
}

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 dfe723d and 366bcd8.

📒 Files selected for processing (1)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/fs/GitFSServiceCEImpl.java (1 hunks)
🔇 Additional comments (1)
app/server/appsmith-server/src/main/java/com/appsmith/server/git/fs/GitFSServiceCEImpl.java (1)

579-597: ⚠️ Potential issue

Add error handling and analytics tracking.

The implementation needs error handling for both checkout and fetch operations, similar to other methods in this class.

Apply this diff to add error handling:

 @Override
 public Mono<String> fetchRemoteChanges(ArtifactJsonTransformationDTO jsonTransformationDTO, GitAuth gitAuth) {
     String workspaceId = jsonTransformationDTO.getWorkspaceId();
     String baseArtifactId = jsonTransformationDTO.getBaseArtifactId();
     String repoName = jsonTransformationDTO.getRepoName();
     String refName = jsonTransformationDTO.getRefName();

     ArtifactType artifactType = jsonTransformationDTO.getArtifactType();
     GitArtifactHelper<?> gitArtifactHelper = gitArtifactHelperResolver.getArtifactHelper(artifactType);
     Path repoSuffix = gitArtifactHelper.getRepoSuffixPath(workspaceId, baseArtifactId, repoName);

     Path repoPath = fsGitHandler.createRepoPath(repoSuffix);
-    Mono<Boolean> checkoutBranchMono = fsGitHandler.checkoutToBranch(repoSuffix, refName);
+    Mono<Boolean> checkoutBranchMono = fsGitHandler.checkoutToBranch(repoSuffix, refName)
+            .onErrorResume(error -> {
+                log.error("Error while checking out branch: {}", error.getMessage());
+                return gitAnalyticsUtils
+                        .addAnalyticsForGitOperation(
+                                AnalyticsEvents.GIT_CHECKOUT,
+                                jsonTransformationDTO,
+                                error.getClass().getName(),
+                                error.getMessage(),
+                                false)
+                        .then(Mono.error(new AppsmithException(
+                                AppsmithError.GIT_ACTION_FAILED,
+                                "checkout",
+                                error.getMessage())));
+            });

     Mono<String> fetchRemoteMono = fsGitHandler.fetchRemote(
             repoPath, gitAuth.getPublicKey(), gitAuth.getPrivateKey(), true, refName, false);

-    return checkoutBranchMono.then(Mono.defer(() -> fetchRemoteMono));
+    return checkoutBranchMono
+            .then(Mono.defer(() -> fetchRemoteMono))
+            .onErrorResume(error -> {
+                log.error("Error while fetching remote changes: {}", error.getMessage());
+                return gitAnalyticsUtils
+                        .addAnalyticsForGitOperation(
+                                AnalyticsEvents.GIT_FETCH,
+                                jsonTransformationDTO,
+                                error.getClass().getName(),
+                                error.getMessage(),
+                                false)
+                        .then(Mono.error(new AppsmithException(
+                                AppsmithError.GIT_ACTION_FAILED,
+                                "fetch",
+                                error.getMessage())));
+            });

Comment on lines +579 to +597
public Mono<String> fetchRemoteChanges(ArtifactJsonTransformationDTO jsonTransformationDTO, GitAuth gitAuth) {

String workspaceId = jsonTransformationDTO.getWorkspaceId();
String baseArtifactId = jsonTransformationDTO.getBaseArtifactId();
String repoName = jsonTransformationDTO.getRepoName();
String refName = jsonTransformationDTO.getRefName();

ArtifactType artifactType = jsonTransformationDTO.getArtifactType();
GitArtifactHelper<?> gitArtifactHelper = gitArtifactHelperResolver.getArtifactHelper(artifactType);
Path repoSuffix = gitArtifactHelper.getRepoSuffixPath(workspaceId, baseArtifactId, repoName);

Path repoPath = fsGitHandler.createRepoPath(repoSuffix);
Mono<Boolean> checkoutBranchMono = fsGitHandler.checkoutToBranch(repoSuffix, refName);

Mono<String> fetchRemoteMono = fsGitHandler.fetchRemote(
repoPath, gitAuth.getPublicKey(), gitAuth.getPrivateKey(), true, refName, false);

return checkoutBranchMono.then(Mono.defer(() -> fetchRemoteMono));
}
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 file locking mechanism for concurrent operations.

The method should implement file locking similar to other Git operations in this class to prevent concurrent modifications.

Apply this diff to add file locking:

 @Override
 public Mono<String> fetchRemoteChanges(ArtifactJsonTransformationDTO jsonTransformationDTO, GitAuth gitAuth) {
     String workspaceId = jsonTransformationDTO.getWorkspaceId();
     String baseArtifactId = jsonTransformationDTO.getBaseArtifactId();
     String repoName = jsonTransformationDTO.getRepoName();
     String refName = jsonTransformationDTO.getRefName();

     ArtifactType artifactType = jsonTransformationDTO.getArtifactType();
     GitArtifactHelper<?> gitArtifactHelper = gitArtifactHelperResolver.getArtifactHelper(artifactType);
     Path repoSuffix = gitArtifactHelper.getRepoSuffixPath(workspaceId, baseArtifactId, repoName);

     Path repoPath = fsGitHandler.createRepoPath(repoSuffix);
-    Mono<Boolean> checkoutBranchMono = fsGitHandler.checkoutToBranch(repoSuffix, refName);
+    return addFileLock(baseArtifactId, GitConstants.GitCommandConstants.FETCH, true)
+            .flatMap(isLocked -> {
+                Mono<Boolean> checkoutBranchMono = fsGitHandler.checkoutToBranch(repoSuffix, refName);
+                Mono<String> fetchRemoteMono = fsGitHandler.fetchRemote(
+                        repoPath, gitAuth.getPublicKey(), gitAuth.getPrivateKey(), true, refName, false);
 
-    Mono<String> fetchRemoteMono = fsGitHandler.fetchRemote(
-            repoPath, gitAuth.getPublicKey(), gitAuth.getPrivateKey(), true, refName, false);
-
-    return checkoutBranchMono.then(Mono.defer(() -> fetchRemoteMono));
+                return checkoutBranchMono
+                        .then(Mono.defer(() -> fetchRemoteMono))
+                        .flatMap(result -> releaseFileLock(baseArtifactId, true)
+                                .thenReturn(result));
+            });
📝 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
public Mono<String> fetchRemoteChanges(ArtifactJsonTransformationDTO jsonTransformationDTO, GitAuth gitAuth) {
String workspaceId = jsonTransformationDTO.getWorkspaceId();
String baseArtifactId = jsonTransformationDTO.getBaseArtifactId();
String repoName = jsonTransformationDTO.getRepoName();
String refName = jsonTransformationDTO.getRefName();
ArtifactType artifactType = jsonTransformationDTO.getArtifactType();
GitArtifactHelper<?> gitArtifactHelper = gitArtifactHelperResolver.getArtifactHelper(artifactType);
Path repoSuffix = gitArtifactHelper.getRepoSuffixPath(workspaceId, baseArtifactId, repoName);
Path repoPath = fsGitHandler.createRepoPath(repoSuffix);
Mono<Boolean> checkoutBranchMono = fsGitHandler.checkoutToBranch(repoSuffix, refName);
Mono<String> fetchRemoteMono = fsGitHandler.fetchRemote(
repoPath, gitAuth.getPublicKey(), gitAuth.getPrivateKey(), true, refName, false);
return checkoutBranchMono.then(Mono.defer(() -> fetchRemoteMono));
}
@Override
public Mono<String> fetchRemoteChanges(ArtifactJsonTransformationDTO jsonTransformationDTO, GitAuth gitAuth) {
String workspaceId = jsonTransformationDTO.getWorkspaceId();
String baseArtifactId = jsonTransformationDTO.getBaseArtifactId();
String repoName = jsonTransformationDTO.getRepoName();
String refName = jsonTransformationDTO.getRefName();
ArtifactType artifactType = jsonTransformationDTO.getArtifactType();
GitArtifactHelper<?> gitArtifactHelper = gitArtifactHelperResolver.getArtifactHelper(artifactType);
Path repoSuffix = gitArtifactHelper.getRepoSuffixPath(workspaceId, baseArtifactId, repoName);
Path repoPath = fsGitHandler.createRepoPath(repoSuffix);
return addFileLock(baseArtifactId, GitConstants.GitCommandConstants.FETCH, true)
.flatMap(isLocked -> {
Mono<Boolean> checkoutBranchMono = fsGitHandler.checkoutToBranch(repoSuffix, refName);
Mono<String> fetchRemoteMono = fsGitHandler.fetchRemote(
repoPath, gitAuth.getPublicKey(), gitAuth.getPrivateKey(), true, refName, false);
return checkoutBranchMono
.then(Mono.defer(() -> fetchRemoteMono))
.flatMap(result -> releaseFileLock(baseArtifactId, true)
.thenReturn(result));
});
}

GitType gitType,
RefType refType);

Mono<String> fetchRemoteChanges(
Copy link
Contributor

Choose a reason for hiding this comment

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

Why are these methods getting exposed on the interface twice?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Shouldn't be, revoking the interface access.

@@ -67,6 +70,7 @@
import static com.appsmith.external.helpers.AppsmithBeanUtils.copyNestedNonNullProperties;
import static com.appsmith.server.constants.FieldName.DEFAULT;
import static com.appsmith.server.constants.SerialiseArtifactObjective.VERSION_CONTROL;
import static com.appsmith.server.constants.ce.FieldNameCE.BRANCH_NAME;
Copy link
Contributor

Choose a reason for hiding this comment

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

Gotta create a lint rule for this I think 😶‍🌫️

String baseArtifactId = baseArtifactGitData.getDefaultArtifactId();

if (refArtifactGitData == null || !hasText(refArtifactGitData.getRefName())) {
return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, BRANCH_NAME));
Copy link
Contributor

Choose a reason for hiding this comment

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

TODO for error message accepting git type

gitRedisUtils.acquireGitLock(baseArtifactId, GitConstants.GitCommandConstants.FETCH_REMOTE, isFileLock);

ArtifactJsonTransformationDTO jsonTransformationDTO = new ArtifactJsonTransformationDTO();
jsonTransformationDTO.setRefType(RefType.BRANCH);
Copy link
Contributor

Choose a reason for hiding this comment

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

Duplicate setter

Copy link
Contributor Author

Choose a reason for hiding this comment

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

resolved it.

in case of any error, the global exception handler will release the lock
hence we don't need to do that manually
*/
log.error(
Copy link
Contributor

Choose a reason for hiding this comment

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

Error can already include git type

@sondermanish sondermanish changed the title chore: fetch chore: fetch remote reference in local Dec 6, 2024
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/git/central/CentralGitServiceCEImpl.java (2)

964-964: Include gitType in error message as per TODO comment.

As noted in the TODO at line 962, the error message should include the Git type for better error tracking and debugging.

Apply this diff:

-return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, BRANCH_NAME));
+return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, BRANCH_NAME + " for " + gitType));

988-1001: Enhance error handling with specific error types.

The error handling could be more specific by checking for common Git exceptions like TransportException, InvalidRemoteException, etc., similar to how it's done in the connectArtifactToGit method.

Consider applying this pattern:

.onErrorResume(throwable -> {
    log.error(
            "Error to fetch from remote for application: {}, branch: {}, git type {}",
            baseArtifactId,
            refArtifactGitData.getRefName(),
            gitType,
            throwable);
+   if (throwable instanceof TransportException) {
+       return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_SSH_CONFIGURATION));
+   } else if (throwable instanceof InvalidRemoteException) {
+       return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION, throwable.getMessage()));
+   } else if (throwable instanceof TimeoutException) {
+       return Mono.error(new AppsmithException(AppsmithError.GIT_EXECUTION_TIMEOUT));
+   }
    return Mono.error(new AppsmithException(AppsmithError.GIT_ACTION_FAILED, "fetch", throwable.getMessage()));
})
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 366bcd8 and 2eb6288.

📒 Files selected for processing (2)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCE.java (2 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCEImpl.java (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCE.java
🔇 Additional comments (2)
app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCEImpl.java (2)

21-21: LGTM!

The new imports are necessary for user session management and analytics tracking.

Also applies to: 40-40


1033-1048: LGTM!

The overloaded method follows good practices by:

  • Properly checking permissions
  • Reusing the base implementation
  • Maintaining clear separation of concerns

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 (3)
app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCEImpl.java (3)

951-955: Provide more specific error messages for null checks

Instead of returning a generic error when refArtifact or baseArtifact is null, consider returning specific error messages to aid debugging.

Apply this diff to improve error handling:

 if (refArtifact == null) {
     return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "refArtifact"));
 } else if (baseArtifact == null) {
     return Mono.error(new AppsmithException(AppsmithError.INVALID_PARAMETER, "baseArtifact"));
 } else if (isBaseGitMetadataInvalid(baseArtifact.getGitArtifactMetadata(), gitType)) {
     return Mono.error(new AppsmithException(AppsmithError.INVALID_GIT_CONFIGURATION));
 }

963-963: Address the TODO comment about including gitType in error messages

There's a TODO comment indicating that gitType should be added to all error messages. Would you like assistance implementing this?


993-994: Improve log message wording for clarity

Consider rephrasing the log message to "Error fetching from remote for application" for better readability.

Apply this diff to update the log message:

-log.error(
-        "Error to fetch from remote for application: {}, branch: {}, git type {}",
+log.error(
+        "Error fetching from remote for application: {}, branch: {}, git type {}",
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2eb6288 and d964d59.

📒 Files selected for processing (1)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/central/CentralGitServiceCEImpl.java (6 hunks)

@sondermanish sondermanish enabled auto-merge (squash) December 9, 2024 09:59
@sondermanish sondermanish added the ok-to-test Required label for CI label Dec 9, 2024
@sondermanish sondermanish merged commit 49bed91 into release Dec 9, 2024
47 checks passed
@sondermanish sondermanish deleted the feat/checkout-ref branch December 9, 2024 20:08
@coderabbitai coderabbitai bot mentioned this pull request Dec 12, 2024
2 tasks
github-actions bot pushed a commit to Zeral-Zhang/appsmith that referenced this pull request Dec 12, 2024
## Description
- Added fetch remote CGS Impl

Fixes #
> [!WARNING]  
> _If no issue exists, please create an issue first, and check with the
maintainers if the issue is valid._

## Automation

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

### 🔍 Cypress test results
<!-- This is an auto-generated comment: Cypress test results  -->
> [!WARNING]
> Tests have not run on the HEAD
d964d59 yet
> <hr>Mon, 09 Dec 2024 07:03:35 UTC
<!-- end of auto-generated comment: Cypress test results  -->


## Communication
Should the DevRel and Marketing teams inform users about this change?
- [ ] Yes
- [ ] No


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

## Release Notes

- **New Features**
- Introduced new methods for fetching remote changes in various Git
services, enhancing synchronization capabilities.
	- Added new fields for internal metadata management.
- Implemented user session management improvements for better handling
of user-related data.
- Added analytics tracking for unit execution time to improve
performance insights.

- **Bug Fixes**
	- Enhanced error handling in new fetch methods to ensure robustness.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ok-to-test Required label for CI skip-changelog Adding this label to a PR prevents it from being listed in the changelog
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants