Skip to content

feat(minio): ensure bucket exists on storage init#43

Open
oismaelash wants to merge 2 commits intoEvolutionAPI:mainfrom
oismaelash:main
Open

feat(minio): ensure bucket exists on storage init#43
oismaelash wants to merge 2 commits intoEvolutionAPI:mainfrom
oismaelash:main

Conversation

@oismaelash
Copy link
Copy Markdown

@oismaelash oismaelash commented Apr 24, 2026

Create the configured bucket when missing, matching fix/create-bucket-if-no-exist-minio. Add unit tests (fake client) and optional integration test behind -tags=integration.

Made-with: Cursor

Description

Related Issue

Closes #(issue_number)

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)
  • Performance improvement

Testing

  • Manual testing completed
  • Functionality verified in development environment
  • No breaking changes introduced

Screenshots (if applicable)

Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have tested my changes thoroughly
  • Any dependent changes have been merged and published

Additional Notes

Summary by Sourcery

Ensure the configured MinIO bucket is created during media storage initialization and add coverage for this behavior.

New Features:

  • Automatically create the configured MinIO bucket during media storage initialization if it does not already exist.

Tests:

  • Add unit tests using a fake MinIO client to verify bucket existence and creation error paths.
  • Add an optional integration test (behind the integration build tag) that validates bucket creation against a real MinIO/S3-compatible endpoint.

Create the configured bucket when missing, matching fix/create-bucket-if-no-exist-minio.
Add unit tests (fake client) and optional integration test behind -tags=integration.

Made-with: Cursor
@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Apr 24, 2026

Reviewer's Guide

This PR updates MinIO-backed media storage initialization to ensure the configured bucket exists at startup, introducing a small abstraction over the MinIO client plus unit and optional integration tests for bucket creation behavior.

Sequence diagram for MinIO media storage initialization with bucket creation

sequenceDiagram
    actor Application
    participant NewMinioMediaStorage
    participant MinioClient as minio.Client

    Application->>NewMinioMediaStorage: initialize(bucketName, region, otherParams)
    NewMinioMediaStorage->>MinioClient: minio.New(endpoint, credentials, useSSL)
    MinioClient-->>NewMinioMediaStorage: client or error
    alt client_creation_error
        NewMinioMediaStorage-->>Application: error
    else client_created
        NewMinioMediaStorage->>MinioClient: BucketExists(ctx, bucketName)
        MinioClient-->>NewMinioMediaStorage: exists, error
        alt bucket_exists_error
            NewMinioMediaStorage-->>Application: error
        else bucket_missing
            NewMinioMediaStorage->>MinioClient: MakeBucket(ctx, bucketName, MakeBucketOptions{Region: region})
            MinioClient-->>NewMinioMediaStorage: error or success
            alt bucket_creation_error
                NewMinioMediaStorage-->>Application: error
            else bucket_created
                NewMinioMediaStorage->>MinioClient: setBucketPolicy(client, bucketName)
                MinioClient-->>NewMinioMediaStorage: error or success
                NewMinioMediaStorage-->>Application: *MinioMediaStorage or error
            end
        else bucket_already_exists
            NewMinioMediaStorage->>MinioClient: setBucketPolicy(client, bucketName)
            MinioClient-->>NewMinioMediaStorage: error or success
            NewMinioMediaStorage-->>Application: *MinioMediaStorage or error
        end
    end
Loading

Class diagram for MinIO media storage and bucket admin abstraction

classDiagram
    class minioBucketAdmin {
        <<interface>>
        +BucketExists(ctx context.Context, bucketName string) bool, error
        +MakeBucket(ctx context.Context, bucketName string, opts minio.MakeBucketOptions) error
    }

    class MinioClient {
        <<struct from minio.Client>>
    }

    class MinioMediaStorage {
        -client *minio.Client
        -bucketName string
        -baseURL string
        -useSSL bool
        +NewMinioMediaStorage(endpoint string, accessKeyID string, secretAccessKey string, useSSL bool, bucketName string, region string, baseURL string) *MinioMediaStorage, error
        +Upload(ctx context.Context, objectName string, reader io.Reader, size int64, contentType string) (string, error)
        +Delete(ctx context.Context, objectName string) error
        +GetURL(objectName string) string
    }

    class ensureBucketExists {
        +ensureBucketExists(ctx context.Context, client minioBucketAdmin, bucketName string, region string) error
    }

    MinioClient ..|> minioBucketAdmin
    MinioMediaStorage o--> MinioClient : uses
    ensureBucketExists ..> minioBucketAdmin : depends_on
    MinioMediaStorage ..> ensureBucketExists : calls_during_init
Loading

File-Level Changes

Change Details Files
Ensure the configured MinIO bucket is created on storage initialization when missing, with clear error propagation.
  • Introduce a minioBucketAdmin interface abstracting BucketExists and MakeBucket for testability
  • Add ensureBucketExists helper that checks bucket existence and creates it with the configured region when absent, wrapping errors with context
  • Invoke ensureBucketExists from NewMinioMediaStorage after client construction and before applying bucket policies
pkg/storage/minio/media_storage.go
Add tests validating bucket existence/creation logic with a fake client and an optional integration test against a real MinIO/S3 endpoint.
  • Implement a fakeMinioBucket test double tracking BucketExists/MakeBucket calls and errors
  • Add unit tests covering existing bucket, missing bucket creation, and error paths in ensureBucketExists
  • Add an integration test (guarded by the integration build tag and env vars) that verifies NewMinioMediaStorage can connect and ensure the bucket exists against a real endpoint
pkg/storage/minio/media_storage_test.go
pkg/storage/minio/media_storage_integration_test.go

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 2 issues, and left some high level feedback:

  • Avoid using fmt.Printf in ensureBucketExists; either remove the side-effectful log or route it through the existing logging/observability mechanism used elsewhere in the package.
  • Consider accepting a context parameter for NewMinioMediaStorage (and passing it into ensureBucketExists) instead of using context.Background(), so callers can control cancellation/timeouts for the potentially slow bucket-existence and creation operations.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Avoid using fmt.Printf in ensureBucketExists; either remove the side-effectful log or route it through the existing logging/observability mechanism used elsewhere in the package.
- Consider accepting a context parameter for NewMinioMediaStorage (and passing it into ensureBucketExists) instead of using context.Background(), so callers can control cancellation/timeouts for the potentially slow bucket-existence and creation operations.

## Individual Comments

### Comment 1
<location path="pkg/storage/minio/media_storage.go" line_range="28-34" />
<code_context>
+		if err != nil {
+			return fmt.Errorf("failed to create bucket: %w", err)
+		}
+		fmt.Printf("Successfully created bucket %s\n", bucketName)
+	}
+
</code_context>
<issue_to_address>
**suggestion:** Avoid direct fmt.Printf in library code and rely on a logger or remove non-essential logging.

Writing to stdout from this helper can be unexpected for callers and noisy in production. Please either remove this success log or send it through the service’s logger so callers can control log levels and outputs.

```suggestion
	if !exists {
		err = client.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{Region: region})
		if err != nil {
			return fmt.Errorf("failed to create bucket: %w", err)
		}
	}
```
</issue_to_address>

### Comment 2
<location path="pkg/storage/minio/media_storage_integration_test.go" line_range="22" />
<code_context>
+func TestNewMinioMediaStorage_CreatesBucket(t *testing.T) {
</code_context>
<issue_to_address>
**suggestion (testing):** Integration test name suggests bucket creation but the test only asserts successful initialization

Right now it only verifies that `NewMinioMediaStorage` returns a non-nil storage without error. Please either extend it to assert that the bucket actually exists after initialization (e.g. via a MinIO client and `BucketExists` on the configured bucket), or rename the test (for example to `TestNewMinioMediaStorage_InitializesStorage`) so the behavior is accurately described.

```suggestion
func TestNewMinioMediaStorage_InitializesStorage(t *testing.T) {
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +28 to +34
if !exists {
err = client.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{Region: region})
if err != nil {
return fmt.Errorf("failed to create bucket: %w", err)
}
fmt.Printf("Successfully created bucket %s\n", bucketName)
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: Avoid direct fmt.Printf in library code and rely on a logger or remove non-essential logging.

Writing to stdout from this helper can be unexpected for callers and noisy in production. Please either remove this success log or send it through the service’s logger so callers can control log levels and outputs.

Suggested change
if !exists {
err = client.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{Region: region})
if err != nil {
return fmt.Errorf("failed to create bucket: %w", err)
}
fmt.Printf("Successfully created bucket %s\n", bucketName)
}
if !exists {
err = client.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{Region: region})
if err != nil {
return fmt.Errorf("failed to create bucket: %w", err)
}
}

// MINIO_REGION=us-east-1 \
// MINIO_USE_SSL=false \
// go test -tags=integration ./pkg/storage/minio/...
func TestNewMinioMediaStorage_CreatesBucket(t *testing.T) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion (testing): Integration test name suggests bucket creation but the test only asserts successful initialization

Right now it only verifies that NewMinioMediaStorage returns a non-nil storage without error. Please either extend it to assert that the bucket actually exists after initialization (e.g. via a MinIO client and BucketExists on the configured bucket), or rename the test (for example to TestNewMinioMediaStorage_InitializesStorage) so the behavior is accurately described.

Suggested change
func TestNewMinioMediaStorage_CreatesBucket(t *testing.T) {
func TestNewMinioMediaStorage_InitializesStorage(t *testing.T) {

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