Skip to content

Commit 658e0ec

Browse files
authored
Merge pull request #31 from GRACENOBLE/22-feat-cloudflare-r2-storage
feat(storage): integrate Cloudflare R2 for object storage
2 parents fe3b1af + d922b2c commit 658e0ec

33 files changed

Lines changed: 1612 additions & 78 deletions

‎backend/.env.example‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,14 @@ MAILJET_API_KEY=your_mailjet_api_key_here
2929
MAILJET_SECRET_KEY=your_mailjet_secret_key_here
3030
# Sender identity — must be a verified Mailjet sender address
3131
FROM_EMAIL=no-reply@example.com
32-
FROM_NAME=MyApp
32+
FROM_NAME=MyApp
33+
# Cloudflare R2 object storage (optional; omit or leave empty to disable file storage)
34+
# Account ID from: Cloudflare Dashboard → R2 → Overview
35+
R2_ACCOUNT_ID=your_r2_account_id_here
36+
# API token credentials (create from: Cloudflare Dashboard → R2 → Manage API Tokens)
37+
R2_ACCESS_KEY=your_r2_access_key_here
38+
R2_SECRET_KEY=your_r2_secret_key_here
39+
# The name of your R2 bucket
40+
R2_BUCKET=your_bucket_name_here
41+
# Public URL for the bucket (set up a custom domain or use r2.dev subdomain)
42+
R2_PUBLIC_URL=https://pub-xxxxxxxxxxxx.r2.dev

‎backend/docs/_index.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,4 @@ The `docs` agent reads this index first to locate the right file before diving i
2020
| Redis Streams event fan-out (producer, consumer, consumer groups) | [streams.md](streams.md) | `internal/infrastructure/streams/events.go`, `internal/infrastructure/streams/producer.go`, `internal/infrastructure/streams/consumer.go` |
2121
| Firebase Cloud Messaging — token storage, send API, FCM endpoints | [fcm.md](fcm.md) | `internal/domain/fcm_token.go`, `internal/usecase/notification.go`, `internal/infrastructure/database/postgres/fcm_token_repository.go`, `internal/transport/handlers/fcm_handler.go`, `pkg/firebase/app.go`, `pkg/firebase/messaging.go` |
2222
| Transactional email (Mailjet) — EmailSender interface, MailjetSender, sandbox mode, templates | [email.md](email.md) | `internal/usecase/email.go`, `internal/infrastructure/email/mailjet.go`, `internal/infrastructure/email/templates/welcome.html`, `internal/bootstrap/bootstrap.go`, `internal/server/server.go`, `internal/transport/handlers/handler.go` |
23+
| Object storage (Cloudflare R2) — StorageService interface, R2 implementation, presign/delete endpoints | [storage.md](storage.md) | `internal/usecase/storage.go`, `internal/infrastructure/storage/r2/storage.go`, `internal/transport/handlers/storage_handler.go`, `internal/transport/handlers/routes.go`, `internal/bootstrap/bootstrap.go` |

‎backend/docs/bootstrap.md‎

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,18 @@ sources:
1515
## App struct
1616
```go
1717
type App struct {
18-
DB *sql.DB
19-
Cache usecase.CacheService // nil when REDIS_URL is not set
20-
Enqueuer usecase.Enqueuer // nil when REDIS_URL is not set
21-
Firebase usecase.FirebaseAdminClient // nil when FIREBASE_PROJECT_ID is not set
22-
FCMSender usecase.NotificationSender // nil when FIREBASE_PROJECT_ID is not set
23-
EmailSender usecase.EmailSender // nil when MAILJET_API_KEY/SECRET_KEY are not set
24-
Config Config
25-
Log *slog.Logger
18+
DB *sql.DB
19+
Cache usecase.CacheService // nil when REDIS_URL is not set
20+
Enqueuer usecase.Enqueuer // nil when REDIS_URL is not set
21+
Firebase usecase.FirebaseAdminClient // nil when FIREBASE_PROJECT_ID is not set
22+
FCMSender usecase.NotificationSender // nil when FIREBASE_PROJECT_ID is not set
23+
EmailSender usecase.EmailSender // nil when MAILJET_API_KEY is not set
24+
StorageService usecase.StorageService // nil when R2_ACCOUNT_ID is not set
25+
Config Config
26+
Log *slog.Logger
2627
}
2728
```
28-
`App` is constructed once by `Run` and passed to `server.NewServer`. Nothing re-initialises dependencies after this point. Optional fields (`Cache`, `Enqueuer`, `Firebase`, `FCMSender`, `EmailSender`) are nil when their corresponding env vars are absent.
29+
`App` is constructed once by `Run` and passed to `server.NewServer`. Nothing re-initialises dependencies after this point. Optional fields (`Cache`, `Enqueuer`, `Firebase`, `FCMSender`, `EmailSender`, `StorageService`) are nil when their corresponding env vars are absent.
2930

3031
## Config struct
3132
```go
@@ -39,6 +40,15 @@ type Config struct {
3940
FirebaseProjectID string
4041
FirebaseServiceAccountJSON string
4142
SentryDSN string
43+
MailjetAPIKey string
44+
MailjetSecretKey string
45+
FromEmail string
46+
FromName string
47+
R2AccountID string
48+
R2AccessKey string
49+
R2SecretKey string
50+
R2Bucket string
51+
R2PublicURL string
4252
}
4353
```
4454
`loadConfig()` reads all values from environment variables. `PORT` defaults to `8080`; `BLUEPRINT_DB_SCHEMA` defaults to `public`; `BLUEPRINT_DB_SSLMODE` defaults to `disable`. `RateLimitBurst` is derived as `int(RPS)*5` when omitted and RPS is set. Optional fields (`RedisURL`, `FirebaseProjectID`, `FirebaseServiceAccountJSON`) default to empty string — their respective services are skipped when empty.
@@ -54,7 +64,8 @@ type Config struct {
5464
6. Init Asynq enqueuer via `queue.NewClient(cfg.RedisURL)` — skipped when `REDIS_URL` is empty
5565
7. Init Firebase app via `firebase.NewApp(ctx, ...)`, then init Auth client (`firebase.NewAuthClient`) and FCM messaging client (`firebase.NewMessagingClient`) from the same app instance — all skipped when `FIREBASE_PROJECT_ID` is empty
5666
8. Init Mailjet email sender via `email.NewMailjetSender(...)` — skipped when `MAILJET_API_KEY` or `MAILJET_SECRET_KEY` is empty; startup fails if only a partial Mailjet config is provided
57-
9. Return `*App` on success; return a non-nil error on any failure
67+
9. Init R2 storage client via `r2.New(...)` — skipped when `R2_ACCOUNT_ID` is empty; startup fails if `R2_ACCOUNT_ID` is set but any other R2 var is missing
68+
10. Return `*App` on success; return a non-nil error on any failure
5869

5970
```go
6071
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)

‎backend/docs/environment.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ This runs on package init before any env var is read — no explicit `godotenv.L
4141
| `MAILJET_SECRET_KEY` | `bootstrap.go` | — | Mailjet secret key. Must be provided alongside `MAILJET_API_KEY`. |
4242
| `FROM_EMAIL` | `bootstrap.go` | — | Verified Mailjet sender address (e.g. `no-reply@example.com`). Required when `MAILJET_API_KEY` and `MAILJET_SECRET_KEY` are set; startup fails if omitted. |
4343
| `FROM_NAME` | `bootstrap.go` | — | Sender display name (e.g. `MyApp`). Only read when both Mailjet credentials are set. |
44+
| `R2_ACCOUNT_ID` | `bootstrap.go` | — | Cloudflare account ID. When omitted, `App.StorageService` is `nil` and storage routes are not registered. |
45+
| `R2_ACCESS_KEY` | `bootstrap.go` | — | R2 API token access key. Required when `R2_ACCOUNT_ID` is set; startup fails if omitted. |
46+
| `R2_SECRET_KEY` | `bootstrap.go` | — | R2 API token secret key. Required when `R2_ACCOUNT_ID` is set; startup fails if omitted. |
47+
| `R2_BUCKET` | `bootstrap.go` | — | R2 bucket name. Required when `R2_ACCOUNT_ID` is set; startup fails if omitted. |
48+
| `R2_PUBLIC_URL` | `bootstrap.go` | — | Public base URL for the R2 bucket (custom domain or `r2.dev` subdomain). Required when `R2_ACCOUNT_ID` is set; startup fails if omitted. |
4449

4550
Variables marked **required** are validated by `bootstrap.validateConfig` at startup — the process exits before attempting a DB connection if any are missing.
4651

‎backend/docs/error-handling.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
topic: error-handling
3-
last_verified: 2026-06-15
3+
last_verified: 2026-06-23
44
sources:
55
- internal/infrastructure/database/postgres/health_repository.go
66
- internal/transport/handlers/health_handler.go
@@ -19,7 +19,7 @@ Never use `log.Fatal` or `os.Exit` inside `internal/`.
1919
| `cmd/api/main.go: main()` | `fmt.Fprintf(os.Stderr, ...) + os.Exit(1)` | `bootstrap.Run()` returned an error — process cannot start |
2020

2121
This is the only permitted early-exit path and it lives in `cmd/`, not `internal/`.
22-
`server.NewServer` does not return an error — all fallible startup work is done by `bootstrap.Run`.
22+
`server.NewServer` returns `(*http.Server, error)` — the caller in `cmd/api/main.go` checks the error and exits on failure. Fallible startup work is split between `bootstrap.Run` and `server.NewServer` (e.g. registering Prometheus collectors).
2323

2424
## Repository errors
2525
Repository methods return `(Result, error)`. On failure, wrap with context using `fmt.Errorf`:

‎backend/docs/routing.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ if app.Config.RedisURL != "" {
5959
// parse URL and build asynqmon.New(...)
6060
}
6161

62-
h := handlers.NewHandler(healthUC, app.Firebase, hub, app.Enqueuer, queueUI, app.FCMSender, fcmTokenRepo)
62+
h := handlers.NewHandler(healthUC, app.Firebase, hub, app.Enqueuer, queueUI, app.FCMSender, fcmTokenRepo, app.EmailSender)
6363

6464
// Register DB pool metrics collector (AlreadyRegisteredError is silenced).
6565
prometheus.Register(postgres.NewDBStatsCollector(app.DB))

‎backend/docs/storage.md‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
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+
```

‎backend/docs/swagger/docs.go‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,99 @@ const docTemplate = `{
246246
}
247247
}
248248
},
249+
"/api/v1/storage/presign": {
250+
"post": {
251+
"security": [
252+
{
253+
"BearerAuth": []
254+
}
255+
],
256+
"description": "Returns a presigned PUT URL and the final public URL. The client uploads directly to R2 using the presigned URL.",
257+
"consumes": [
258+
"application/json"
259+
],
260+
"produces": [
261+
"application/json"
262+
],
263+
"tags": [
264+
"storage"
265+
],
266+
"summary": "Request a presigned upload URL",
267+
"parameters": [
268+
{
269+
"description": "Upload request",
270+
"name": "body",
271+
"in": "body",
272+
"required": true,
273+
"schema": {
274+
"$ref": "#/definitions/handlers.presignRequest"
275+
}
276+
}
277+
],
278+
"responses": {
279+
"200": {
280+
"description": "OK",
281+
"schema": {
282+
"$ref": "#/definitions/handlers.presignResponse"
283+
}
284+
},
285+
"400": {
286+
"description": "Bad Request",
287+
"schema": {
288+
"type": "object",
289+
"additionalProperties": {
290+
"type": "string"
291+
}
292+
}
293+
},
294+
"500": {
295+
"description": "Internal Server Error",
296+
"schema": {
297+
"type": "object",
298+
"additionalProperties": {
299+
"type": "string"
300+
}
301+
}
302+
}
303+
}
304+
}
305+
},
306+
"/api/v1/storage/{key}": {
307+
"delete": {
308+
"security": [
309+
{
310+
"BearerAuth": []
311+
}
312+
],
313+
"tags": [
314+
"storage"
315+
],
316+
"summary": "Delete a stored object",
317+
"parameters": [
318+
{
319+
"type": "string",
320+
"description": "Object key",
321+
"name": "key",
322+
"in": "path",
323+
"required": true
324+
}
325+
],
326+
"responses": {
327+
"204": {
328+
"description": "No Content"
329+
},
330+
"500": {
331+
"description": "Internal Server Error",
332+
"schema": {
333+
"type": "object",
334+
"additionalProperties": {
335+
"type": "string"
336+
}
337+
}
338+
}
339+
}
340+
}
341+
},
249342
"/health": {
250343
"get": {
251344
"produces": [
@@ -386,6 +479,32 @@ const docTemplate = `{
386479
}
387480
}
388481
},
482+
"handlers.presignRequest": {
483+
"type": "object",
484+
"required": [
485+
"content_type",
486+
"filename"
487+
],
488+
"properties": {
489+
"content_type": {
490+
"type": "string"
491+
},
492+
"filename": {
493+
"type": "string"
494+
}
495+
}
496+
},
497+
"handlers.presignResponse": {
498+
"type": "object",
499+
"properties": {
500+
"public_url": {
501+
"type": "string"
502+
},
503+
"upload_url": {
504+
"type": "string"
505+
}
506+
}
507+
},
389508
"handlers.registerFCMTokenRequest": {
390509
"type": "object",
391510
"required": [

0 commit comments

Comments
 (0)