Skip to content

fix: revert r2 to minio for file storage#218

Merged
andostronaut merged 1 commit into
mainfrom
fix/revert-r2-to-minio
May 7, 2025
Merged

fix: revert r2 to minio for file storage#218
andostronaut merged 1 commit into
mainfrom
fix/revert-r2-to-minio

Conversation

@andostronaut
Copy link
Copy Markdown
Member

@andostronaut andostronaut commented May 7, 2025

This is an automated pull request for branch fix/revert-r2-to-minio

Summary by CodeRabbit

  • New Features
    • Introduced support for MinIO as the file storage backend, including new environment variables and configuration options.
  • Bug Fixes
    • Improved error handling and validation for file uploads and deletions.
  • Refactor
    • Replaced all Cloudflare R2 integrations with MinIO throughout the application.
    • Updated file upload and deletion processes to use MinIO’s API and bucket-based organization.
    • Removed legacy R2-related files and configurations.
  • Chores
    • Added the "minio" package as a dependency.
    • Updated environment variable documentation to reflect the switch to MinIO.
    • Restricted allowed remote image sources for improved security.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 7, 2025

Walkthrough

The codebase transitions its file storage integration from Cloudflare R2 to MinIO. All R2-related configuration, types, helpers, and service modules are removed and replaced with new MinIO equivalents. Environment variables, type definitions, and service logic are updated accordingly, including file upload and deletion flows. The Next.js image configuration is also restricted to local MinIO sources.

Changes

File(s) Change Summary
.env.example, src/env.d.ts Removed R2-related environment variables and declarations; added MinIO-related variables and updated comments.
package.json Added minio package as a new dependency.
next.config.mjs Removed external remote image source for "bucket.kinotio.io"; now only allows local MinIO image sources.
src/server/actions/file/upload.ts Refactored file upload logic to use MinIO instead of R2, updated input validation, file handling, bucket management, compression logic, and result structure. Removed all logging.
src/server/actions/user/delete.ts Updated user file deletion logic to use MinIO, extracting bucket and object from URL, and calling MinIO's remove API. Enhanced error logging.
src/server/services/minio/client.ts Added: Initializes and exports a MinIO client using new environment variables.
src/server/services/minio/config.ts Added: Provides a function to generate an S3-compatible public-read bucket policy for MinIO.
src/server/services/minio/types.ts Added: Defines MinioConfig, MinioUploadOptions, and MinioUploadResult interfaces for MinIO operations.
src/server/services/minio/index.ts Added: Centralizes and re-exports MinIO client, policy helper, and related types. Provides a default export object.
src/server/services/r2/client.ts, src/server/services/r2/config.ts,
src/server/services/r2/helpers.ts, src/server/services/r2/index.ts,
src/server/services/r2/types.ts
Deleted all R2 service, config, helper, index, and type files, removing all R2-related exports and logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Frontend
    participant Backend
    participant MinIO

    User->>Frontend: Uploads file via form (with bucket)
    Frontend->>Backend: Sends FormData (file, bucket)
    Backend->>MinIO: Check/Create bucket
    Backend->>MinIO: Set bucket policy (public read)
    Backend->>MinIO: Upload file (with metadata)
    MinIO-->>Backend: Returns upload result
    Backend-->>Frontend: Responds with file URL and info
    Frontend-->>User: Shows uploaded file URL/info
Loading

Poem

🐇
A hop from R2 to MinIO’s den,
We burrow new tunnels, again and again!
Buckets are ready, the files take flight,
With configs and types all shining bright.
Goodbye, old clouds—hello, new store—
This bunny’s code leaps evermore!
🥕

✨ 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.
    • 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.

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.

Copy link
Copy Markdown

@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: 3

🧹 Nitpick comments (5)
src/server/services/minio/index.ts (1)

1-2: Inconsistent import styles

You're using two different import styles in these lines - absolute path with '@/' prefix for the client and relative path for the config. Consider standardizing to one approach for better maintainability.

-import { minioClient } from '@/server/services/minio/client'
-import { getBucketPolicy } from './config'
+import { minioClient } from './client'
+import { getBucketPolicy } from './config'
src/env.d.ts (1)

16-22: MinIO environment variables properly defined

The environment variables for MinIO are well-structured and complete, covering all necessary configuration options. However, consider adding documentation explaining which variables need to be public and which should be kept server-side only.

Consider adding a brief comment explaining why some variables have the NEXT_PUBLIC prefix while others don't, to guide future developers on security considerations.

src/server/actions/file/upload.ts (3)

45-47: Simplified filename generation

The filename generation for data URLs has been simplified to use only a timestamp instead of a UUID. While this works, it could potentially lead to filename collisions in high-traffic scenarios.

Consider using a more unique identifier for filename generation:

-fileName = `${Date.now()}.${extension}`
+fileName = `${Date.now()}-${Math.random().toString(36).substring(2, 10)}.${extension}`

93-102: File upload with proper metadata

The MinIO upload includes content type and cache control headers, which is good for proper file serving.

Consider making the cache control duration configurable based on the bucket or file type, rather than hardcoding it to one year for all files:

-'Cache-Control': 'max-age=31536000' // Cache for 1 year
+// Adjust cache time based on bucket type
+'Cache-Control': bucket === 'avatars' || bucket === 'banners' 
+  ? 'max-age=31536000' // Cache for 1 year for stable content
+  : 'max-age=604800' // Cache for 1 week for other content

117-122: Error handling is present but minimal

The error handling captures and returns errors appropriately, but lacks any logging which might be useful for debugging in production.

Consider adding logging for critical errors to aid in troubleshooting:

} catch (error) {
+  console.error('File upload error:', error);
  return {
    success: false,
    error: error instanceof Error ? error.message : 'An error occurred while uploading file.'
  }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d4427df and 22c0fbf.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (15)
  • .env.example (0 hunks)
  • next.config.mjs (0 hunks)
  • package.json (1 hunks)
  • src/env.d.ts (2 hunks)
  • src/server/actions/file/upload.ts (2 hunks)
  • src/server/actions/user/delete.ts (2 hunks)
  • src/server/services/minio/client.ts (1 hunks)
  • src/server/services/minio/config.ts (1 hunks)
  • src/server/services/minio/index.ts (1 hunks)
  • src/server/services/minio/types.ts (1 hunks)
  • src/server/services/r2/client.ts (0 hunks)
  • src/server/services/r2/config.ts (0 hunks)
  • src/server/services/r2/helpers.ts (0 hunks)
  • src/server/services/r2/index.ts (0 hunks)
  • src/server/services/r2/types.ts (0 hunks)
💤 Files with no reviewable changes (7)
  • .env.example
  • next.config.mjs
  • src/server/services/r2/types.ts
  • src/server/services/r2/index.ts
  • src/server/services/r2/helpers.ts
  • src/server/services/r2/config.ts
  • src/server/services/r2/client.ts
🧰 Additional context used
🧬 Code Graph Analysis (4)
src/server/services/minio/client.ts (1)
src/server/services/minio/index.ts (1)
  • minioClient (11-11)
src/server/services/minio/config.ts (1)
src/server/services/minio/index.ts (1)
  • getBucketPolicy (11-11)
src/server/services/minio/index.ts (1)
src/server/services/minio/client.ts (1)
  • minioClient (3-9)
src/server/actions/file/upload.ts (6)
src/server/utils/types.ts (1)
  • ActionResponse (1-5)
src/server/services/minio/types.ts (1)
  • MinioUploadResult (16-21)
src/server/validations/file.ts (1)
  • FileValidation (5-21)
src/server/services/minio/client.ts (1)
  • minioClient (3-9)
src/server/services/minio/config.ts (1)
  • getBucketPolicy (1-12)
src/server/utils/image-processor.ts (3)
  • compressAvatar (107-117)
  • compressBanner (119-129)
  • compressImage (21-104)
🔇 Additional comments (14)
package.json (1)

56-56: Dependency added for MinIO integration.

The addition of the minio package is consistent with the PR objective to revert from Cloudflare R2 to MinIO for file storage.

src/server/services/minio/client.ts (1)

4-6: Review security implications of NEXT_PUBLIC_ prefixed environment variables.

Using the NEXT_PUBLIC_ prefix exposes these environment variables to the client-side JavaScript, which could potentially expose connection details of your MinIO instance.

Verify if these connection details should be exposed to client-side. Consider removing the NEXT_PUBLIC_ prefix if these are meant to be server-side only.

src/server/services/minio/config.ts (1)

1-12: Bucket policy grants broad public read access.

The bucket policy grants public read access to all objects within the specified bucket. While this may be necessary for publicly accessible files, it's a broad permission that should be carefully considered from a security perspective.

Consider if all files need to be publicly readable or if more restrictive policies would be appropriate for certain buckets. You might want to:

  1. Create different policy functions for different access levels
  2. Add conditional statements to restrict access to specific paths
  3. Add time-limited access policies for sensitive content
export const getBucketPolicy = (bucketName: string) => ({
  Version: '2012-10-17',
  Statement: [
    {
      Sid: 'PublicRead',
      Effect: 'Allow',
      Principal: '*',
      Action: ['s3:GetObject'],
-     Resource: [`arn:aws:s3:::${bucketName}/*`]
+     Resource: [`arn:aws:s3:::${bucketName}/public/*`] // Example: Only allow public access to files in a "public" prefix
    }
  ]
})
src/server/actions/user/delete.ts (1)

56-56: Improved error logging.

The change from console.log to console.error and the inclusion of the file URL in the error message is a good improvement for debugging.

src/server/services/minio/index.ts (2)

9-11: Export type signatures look good

The type exports and function exports are properly structured, making it easy for other modules to import these entities.


13-18: Well-organized default export

The default export provides a clean interface for importing all Minio functionality with a single import. This pattern works well for service modules.

src/env.d.ts (1)

6-7: Comment update reflects database change

The comment change from "Xata" to "PostgreSQL" accurately reflects the database system in use. This is a good practice for documentation.

src/server/services/minio/types.ts (3)

1-7: MinioConfig interface is well-structured

The MinioConfig interface correctly defines all the properties needed for connecting to a MinIO server, matching the parameters used in the client configuration.


9-14: MinioUploadOptions provides flexible configuration

The upload options interface includes all necessary parameters and makes metadata and cache control optional, which is good for flexibility.


16-21: MinioUploadResult interface is complete

The result interface captures all the essential information about an uploaded file. This aligns well with what clients typically need after an upload operation.

src/server/actions/file/upload.ts (4)

3-10: Updated import and function signature

The function signature has been properly updated to use MinIO types instead of R2 types.


13-19: Improved validation for required parameters

The validation now checks for both file and bucket presence, which is a good practice.


85-91: Image compression based on bucket name

The code now determines the compression method based on the bucket name instead of a type parameter. This is a clear and maintainable approach.


104-106: URL generation from environment variables

The URL generation uses the environment variable correctly to construct the complete URL to the uploaded file.

Comment thread src/server/services/minio/client.ts
Comment thread src/server/actions/user/delete.ts
Comment thread src/server/actions/file/upload.ts
@andostronaut andostronaut merged commit 81e7bcb into main May 7, 2025
3 checks passed
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.

1 participant