|
| 1 | +--- |
| 2 | +topic: storage |
| 3 | +last_verified: 2026-06-23 |
| 4 | +sources: |
| 5 | + - backend/internal/usecase/storage.go |
| 6 | + - backend/internal/infrastructure/storage/r2/storage.go |
| 7 | + - backend/internal/transport/handlers/storage_handler.go |
| 8 | + - backend/internal/transport/handlers/routes.go |
| 9 | + - backend/internal/bootstrap/bootstrap.go |
| 10 | +--- |
| 11 | + |
| 12 | +# Storage (Cloudflare R2) |
| 13 | + |
| 14 | +## Overview |
| 15 | +R2 is the optional object storage backend. The integration is enabled only when `R2_ACCOUNT_ID` is set in the environment. When absent, `App.StorageService` is `nil` and the storage routes are not registered. |
| 16 | + |
| 17 | +## Interface |
| 18 | +`usecase.StorageService` is defined in `internal/usecase/storage.go` and sits at the use-case layer to keep the transport and infrastructure layers decoupled from any concrete SDK: |
| 19 | + |
| 20 | +```go |
| 21 | +type StorageService interface { |
| 22 | + PresignUpload(ctx context.Context, key string, contentType string, ttl time.Duration) (string, error) |
| 23 | + Delete(ctx context.Context, key string) error |
| 24 | + PublicURL(key string) string |
| 25 | +} |
| 26 | +``` |
| 27 | + |
| 28 | +## R2 implementation |
| 29 | +Package `internal/infrastructure/storage/r2` provides the concrete implementation using the AWS SDK v2 (R2 is S3-compatible). |
| 30 | + |
| 31 | +### Constructors |
| 32 | + |
| 33 | +```go |
| 34 | +// Production — uses default AWS SDK HTTP client. |
| 35 | +func New(accountID, accessKey, secretKey, bucket, publicBaseURL string) (usecase.StorageService, error) |
| 36 | + |
| 37 | +// Test-friendly — accepts a custom *http.Client to inject a mock transport. |
| 38 | +// Pass nil to behave identically to New. |
| 39 | +func NewWithHTTPClient(accountID, accessKey, secretKey, bucket, publicBaseURL string, httpClient *http.Client) (usecase.StorageService, error) |
| 40 | +``` |
| 41 | + |
| 42 | +Both constructors return an error if any argument is empty. The R2 endpoint is derived as: |
| 43 | +``` |
| 44 | +https://<accountID>.r2.cloudflarestorage.com |
| 45 | +``` |
| 46 | +The S3 client is configured with `UsePathStyle: true` and region `"auto"`. |
| 47 | + |
| 48 | +### Method behaviour |
| 49 | +- `PresignUpload` calls `s3.PresignClient.PresignPutObject` and returns the signed URL. TTL is caller-controlled; the handler passes `15 * time.Minute`. |
| 50 | +- `Delete` calls `s3.Client.DeleteObject` directly (no presigning). |
| 51 | +- `PublicURL` returns `publicBaseURL + "/" + url.PathEscape(key)`. |
| 52 | + |
| 53 | +## HTTP endpoints |
| 54 | + |
| 55 | +Both routes live under the `/api/v1` group, which applies `FirebaseAuth` middleware when `h.verifier != nil`. They are only registered when `h.storageService != nil`. |
| 56 | + |
| 57 | +```go |
| 58 | +if h.storageService != nil { |
| 59 | + api.POST("/storage/presign", h.PresignHandler) |
| 60 | + api.DELETE("/storage/:key", h.DeleteObjectHandler) |
| 61 | +} |
| 62 | +``` |
| 63 | + |
| 64 | +### POST /api/v1/storage/presign |
| 65 | +Returns a presigned PUT URL for the client to upload directly to R2, plus the resulting public URL. |
| 66 | + |
| 67 | +Request body (`presignRequest`): |
| 68 | +```json |
| 69 | +{ "filename": "avatar.png", "content_type": "image/png" } |
| 70 | +``` |
| 71 | + |
| 72 | +Response body (`presignResponse`): |
| 73 | +```json |
| 74 | +{ "upload_url": "https://...", "public_url": "https://pub-xxx.r2.dev/avatar.png" } |
| 75 | +``` |
| 76 | + |
| 77 | +The `filename` field is used as-is as the R2 object key. The presigned URL expires in 15 minutes. |
| 78 | + |
| 79 | +Responses: `200 OK` | `400 Bad Request` (binding failure) | `500 Internal Server Error` |
| 80 | + |
| 81 | +### DELETE /api/v1/storage/:key |
| 82 | +Deletes the object with the given key from R2. |
| 83 | + |
| 84 | +Responses: `204 No Content` | `500 Internal Server Error` |
| 85 | + |
| 86 | +## Bootstrap wiring |
| 87 | +In `bootstrap.Run`: |
| 88 | +```go |
| 89 | +var storageService usecase.StorageService |
| 90 | +if cfg.R2AccountID != "" { |
| 91 | + svc, err := r2.New(cfg.R2AccountID, cfg.R2AccessKey, cfg.R2SecretKey, cfg.R2Bucket, cfg.R2PublicURL) |
| 92 | + if err != nil { |
| 93 | + return nil, fmt.Errorf("bootstrap: r2: %w", err) |
| 94 | + } |
| 95 | + storageService = svc |
| 96 | + log.Info("bootstrap: R2 storage client initialised", "bucket", cfg.R2Bucket) |
| 97 | +} |
| 98 | +``` |
| 99 | +No `validateConfig` checks guard the R2 block — if `R2_ACCOUNT_ID` is non-empty but other R2 vars are empty, `r2.New` returns an error that aborts startup. |
| 100 | + |
| 101 | +## Environment variables |
| 102 | + |
| 103 | +| Variable | Required | Description | |
| 104 | +|---|---|---| |
| 105 | +| `R2_ACCOUNT_ID` | Conditional — presence enables the feature | Cloudflare account ID. Found in the R2 dashboard overview. | |
| 106 | +| `R2_ACCESS_KEY` | Required when `R2_ACCOUNT_ID` is set | R2 API token access key. | |
| 107 | +| `R2_SECRET_KEY` | Required when `R2_ACCOUNT_ID` is set | R2 API token secret key. | |
| 108 | +| `R2_BUCKET` | Required when `R2_ACCOUNT_ID` is set | Name of the R2 bucket. | |
| 109 | +| `R2_PUBLIC_URL` | Required when `R2_ACCOUNT_ID` is set | Public base URL for the bucket (custom domain or `r2.dev` subdomain). | |
| 110 | + |
| 111 | +## Testing |
| 112 | + |
| 113 | +### Handler unit tests |
| 114 | +Handler tests inject a `mockStorageService` struct that implements `usecase.StorageService`. No real R2 credentials or network calls are needed: |
| 115 | + |
| 116 | +```go |
| 117 | +type mockStorageService struct { |
| 118 | + presignURL string |
| 119 | + publicURL string |
| 120 | + presignErr error |
| 121 | + deleteErr error |
| 122 | +} |
| 123 | +func (m *mockStorageService) PresignUpload(_ context.Context, _ string, _ string, _ time.Duration) (string, error) { |
| 124 | + return m.presignURL, m.presignErr |
| 125 | +} |
| 126 | +func (m *mockStorageService) Delete(_ context.Context, _ string) error { return m.deleteErr } |
| 127 | +func (m *mockStorageService) PublicURL(_ string) string { return m.publicURL } |
| 128 | +``` |
| 129 | + |
| 130 | +### r2 package tests |
| 131 | +Tests in `internal/infrastructure/storage/r2/` use `NewWithHTTPClient` with a custom `http.RoundTripper` to intercept S3 and presign requests without making real network calls: |
| 132 | + |
| 133 | +```go |
| 134 | +transport := &mockTransport{handler: func(r *http.Request) *http.Response { ... }} |
| 135 | +svc, _ := r2.NewWithHTTPClient("acct", "key", "secret", "bucket", "https://pub.example.com", |
| 136 | + &http.Client{Transport: transport}) |
| 137 | +``` |
0 commit comments