Skip to content

UFAL/Optimize S3 multipart upload#970

Open
milanmajchrak wants to merge 1 commit intodtq-devfrom
ufal/s3-multipart-upload-optimization
Open

UFAL/Optimize S3 multipart upload#970
milanmajchrak wants to merge 1 commit intodtq-devfrom
ufal/s3-multipart-upload-optimization

Conversation

@milanmajchrak
Copy link
Collaborator

@milanmajchrak milanmajchrak commented May 20, 2025

Phases MP MM MB MR JM Total
ETA 0 0 0 0 0 0
Developing 0 0 0 0 0 0
Review 0 0 0 0 0 0
Total - - - - - 0
ETA est. 0
ETA cust. - - - - - 0

Problem description

Reported issues

Not-reported issues

Analysis

(Write here, if there is needed describe some specific problem. Erase it, when it is not needed.)

Problems

(Write here, if some unexpected problems occur during solving issues. Erase it, when it is not needed.)

Summary by CodeRabbit

  • Refactor
    • Simplified and unified the file upload process to Amazon S3 for improved reliability and maintainability. End-users may experience more consistent upload behavior.

@coderabbitai
Copy link

coderabbitai bot commented May 20, 2025

Walkthrough

The put method in SyncS3BitStoreService was refactored to consolidate the S3 upload logic into a new private uploadFile method. This method uses AWS TransferManager's upload for file uploads, simplifying error handling and removing explicit multipart logic. Imports were updated, and local file copying now uses try-with-resources.

Changes

File Path Change Summary
dspace-api/src/main/java/org/dspace/storage/bitstore/SyncS3BitStoreService.java Refactored put method to use a new private uploadFile method for S3 uploads. Updated imports.

Poem

A hop, a skip, a file to send,
Now uploads take a simpler bend.
With TransferManager in the lead,
Multipart worries now recede.
Cleaner code, a happy cheer—
S3 uploads, swift this year!
🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

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.

@milanmajchrak milanmajchrak linked an issue May 20, 2025 that may be closed by this pull request
Copy link

@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 comments (1)
dspace-api/src/main/java/org/dspace/storage/bitstore/SyncS3BitStoreService.java (1)

196-299: 💡 Verification agent

🧩 Analysis chain

Consider removing unused upload methods in a future cleanup.

Now that the upload logic has been consolidated into the new uploadFile method, the following methods appear to be unused:

  • uploadFluently (lines 196-200)
  • uploadByParts (lines 210-274)
  • calculatePartChecksum (lines 286-299)

Consider removing these unused elements in a future cleanup to reduce code complexity and improve maintainability.


🏁 Script executed:

#!/bin/bash
# Check if these methods are called anywhere else in the codebase

echo "Checking for calls to uploadFluently..."
rg -l "uploadFluently" --type java

echo "Checking for calls to uploadByParts..."
rg -l "uploadByParts" --type java

echo "Checking for calls to calculatePartChecksum..."
rg -l "calculatePartChecksum" --type java

Length of output: 629


Remove unused upload methods in SyncS3BitStoreService.java

The following private methods are declared but never invoked anywhere in the codebase and can be removed in a future cleanup to reduce complexity and improve maintainability:

  • File: dspace-api/src/main/java/org/dspace/storage/bitstore/SyncS3BitStoreService.java
    • Lines 196–200: private void uploadFluently(String key, File scratchFile)
    • Lines 210–274: private void uploadByParts(String key, File scratchFile)
    • Lines 286–299: public static String calculatePartChecksum(File file, long offset, long length, MessageDigest digest)
🧰 Tools
🪛 ast-grep (0.38.1)

[warning] 213-213: Detected MD5 hash algorithm which is considered insecure. MD5 is not collision resistant and is therefore not suitable as a cryptographic signature. Use HMAC instead.
Context: "MD5"
Note: [CWE-328] Use of Weak Hash. [REFERENCES]
- https://owasp.org/Top10/A02_2021-Cryptographic_Failures

(use-of-md5-java)

🧹 Nitpick comments (4)
dspace-api/src/main/java/org/dspace/storage/bitstore/SyncS3BitStoreService.java (4)

25-25: Remove unused import.

The import com.amazonaws.services.s3.model.ObjectMetadata appears to be unused in the current implementation. Consider removing it to keep the imports clean.

-import com.amazonaws.services.s3.model.ObjectMetadata;

99-133: Good improvement in resource management, but there's a redundant close() call.

The refactoring of the put method is a significant improvement:

  • Using try-with-resources ensures proper closing of streams
  • Simplifying the upload logic with a unified method improves readability
  • Improved local file copy with try-with-resources

However, there's a redundant in.close() call at line 108 which is unnecessary since in is already managed by the try-with-resources block and will be closed automatically.

            // Copy stream data to scratch file and compute checksum
            Utils.bufferedCopy(dis, fos);
-           in.close();

161-164: Consider adding more detailed error information for debugging.

The error handling catches both AmazonClientException and InterruptedException, which is good. To further improve debuggability, consider including more specific information in the error message, such as file size or specific AWS error codes when available.

        } catch (AmazonClientException | InterruptedException e) {
-            log.error("Upload failed for key: " + key, e);
-            throw new IOException("Upload failed: " + e.getMessage(), e);
+            String errorDetails = e instanceof AmazonClientException ? 
+                "AWS Error: " + ((AmazonClientException)e).getErrorMessage() : 
+                "Thread interrupted during upload";
+            log.error("Upload failed for key: " + key + " - " + errorDetails, e);
+            throw new IOException("Upload failed: " + errorDetails, e);
        }

61-61: Variable uploadByParts seems to be unused now.

Since the upload logic has been consolidated into the uploadFile method which automatically handles multipart uploads via TransferManager, the uploadByParts boolean flag (line 61) and its initialization (lines 93-95) appear to be unused.

Consider removing this variable and its initialization logic if it's no longer needed for its original purpose.

-    /**
-     * Upload large file by parts - check the checksum of every part
-     */
-    private boolean uploadByParts = false;

// And in the init() method:
-        if (!uploadByParts) {
-            uploadByParts = configurationService.getBooleanProperty("s3.upload.by.parts.enabled", false);
-        }

Also applies to: 93-95

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 793a73c and aaa6dd4.

📒 Files selected for processing (1)
  • dspace-api/src/main/java/org/dspace/storage/bitstore/SyncS3BitStoreService.java (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
dspace-api/src/main/java/org/dspace/storage/bitstore/SyncS3BitStoreService.java (1)
dspace-api/src/main/java/org/dspace/core/Utils.java (1)
  • Utils (54-581)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: dspace-dependencies / docker-build (linux/amd64, ubuntu-latest, true)
  • GitHub Check: Run Integration Tests
  • GitHub Check: Run Unit Tests
🔇 Additional comments (2)
dspace-api/src/main/java/org/dspace/storage/bitstore/SyncS3BitStoreService.java (2)

151-165: Well-designed unified upload method with proper error handling.

The new uploadFile method simplifies the upload process by leveraging AWS TransferManager, which automatically handles multipart uploads when appropriate. This approach improves code maintainability while retaining the performance benefits of multipart uploads for large files.

The error handling and logging are well-implemented. The code captures both Amazon client exceptions and interruptions, provides good log messages, and correctly rethrows as IOException with the original cause information.


151-165:

Details

❓ Verification inconclusive

Verify S3 TransferManager configuration.

The code now relies on TransferManager's automatic handling of multipart uploads. To ensure optimal performance, verify that the TransferManager is properly configured with appropriate thresholds for when to use multipart uploads.

The standard TransferManager uses a default threshold of 5 MB, but depending on your file sizes and network conditions, you might want to tune this parameter.


🏁 Script executed:

#!/bin/bash
# Check if the TransferManager is configured elsewhere in the codebase

echo "Checking for TransferManager configuration..."
rg -l "TransferManagerBuilder" --type java

echo "Checking for multipart upload thresholds..."
rg -A 10 "setMultipartUploadThreshold" --type java

Length of output: 367


Confirm S3 TransferManager multipart upload thresholds

It looks like the TransferManager in S3BitStoreService.java is built with its default settings (which use a 5 MB multipart threshold). Depending on your typical object sizes and network characteristics, you may see better throughput by tuning these values. Please verify that the defaults are appropriate, and if needed update the builder, for example:

TransferManager tm = TransferManagerBuilder.standard()
    .withS3Client(s3Client)
    .withMultipartUploadThreshold(10L * 1024 * 1024)   // use 10 MB as the threshold
    .withMinimumUploadPartSize(5L * 1024 * 1024)       // use 5 MB parts
    .build();

• File: dspace-api/src/main/java/org/dspace/storage/bitstore/S3BitStoreService.java
• Section: TransferManagerBuilder.standard() invocation

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.

UFAL/S3 multipart upload optimization

1 participant