oneie 3.6.33 → 3.6.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,777 @@
1
+ ---
2
+ title: Cloudflare R2 Storage
3
+ dimension: things
4
+ category: plans
5
+ tags: storage, cloudflare, r2, video, audio, uploads
6
+ related_dimensions: connections, events, knowledge
7
+ scope: global
8
+ created: 2025-11-10
9
+ updated: 2025-11-10
10
+ version: 1.0.0
11
+ ai_context: |
12
+ This document is part of the things dimension in the plans category.
13
+ Location: one/things/plans/r2.md
14
+ Purpose: Documents Cloudflare R2 storage implementation for video/audio uploads
15
+ Related dimensions: connections, events, knowledge
16
+ For AI agents: Read this to understand R2 storage integration.
17
+ ---
18
+
19
+ # Cloudflare R2 Storage Implementation Plan
20
+
21
+ **Goal:** Implement Cloudflare R2 object storage for video and audio file uploads, leveraging the free tier (10GB storage, 1M uploads/month, unlimited free egress).
22
+
23
+ **Vision:** Enable creators to upload, manage, and serve video/audio content directly from the ONE Platform using Cloudflare R2 as the storage backend, with full integration into the 6-dimension ontology.
24
+
25
+ ## Cloudflare R2 Free Tier Overview
26
+
27
+ ### What's Included (Free)
28
+ - **Storage:** 10 GB/month
29
+ - **Class A Operations:** 1 million/month (uploads, lists, writes)
30
+ - **Class B Operations:** 10 million/month (downloads, reads)
31
+ - **Egress:** **FREE and UNLIMITED** (huge advantage over S3)
32
+ - **File Types:** No restrictions (videos, MP3s, images, any file type)
33
+
34
+ ### Key Advantages
35
+ 1. **Zero egress fees** - No bandwidth charges for downloads (S3 charges ~$0.09/GB)
36
+ 2. **S3-compatible API** - Use existing S3 SDKs and tools
37
+ 3. **Global CDN** - Cloudflare's edge network for fast delivery
38
+ 4. **Simple pricing** - Only pay for storage and operations, never bandwidth
39
+
40
+ ### When to Upgrade (Paid Tier)
41
+ - Storage >10GB: $0.015/GB-month (~$1.50 for 100GB)
42
+ - Class A >1M/month: $4.50 per million requests
43
+ - Class B >10M/month: $0.36 per million requests
44
+
45
+ **For most use cases, free tier is plenty to start.**
46
+
47
+ ## 6-Dimension Ontology Mapping
48
+
49
+ ### Things
50
+ - `media_file` - Uploaded video/audio files
51
+ - Properties: `fileKey`, `fileName`, `fileSize`, `mimeType`, `duration`, `uploadedAt`
52
+ - Metadata: `r2Bucket`, `r2Key`, `publicUrl`
53
+ - `media_folder` - Organization structure for files
54
+ - Properties: `name`, `path`, `parentFolderId`
55
+ - `upload_session` - Track multi-part uploads
56
+ - Properties: `status`, `bytesUploaded`, `totalBytes`, `resumeKey`
57
+
58
+ ### Connections
59
+ - `creator` → `media_file` (relationshipType: "uploaded")
60
+ - `media_file` → `media_folder` (relationshipType: "stored_in")
61
+ - `course` → `media_file` (relationshipType: "contains_media")
62
+ - `post` → `media_file` (relationshipType: "attached_media")
63
+
64
+ ### Events
65
+ - `media_uploaded` - File successfully uploaded to R2
66
+ - `media_deleted` - File removed from R2
67
+ - `media_viewed` - File accessed/streamed
68
+ - `upload_started` - Upload initiated
69
+ - `upload_failed` - Upload error occurred
70
+ - `upload_resumed` - Multi-part upload continued
71
+
72
+ ### Knowledge
73
+ - Tags for categorization: `video`, `audio`, `podcast`, `course-content`, `tutorial`
74
+ - Vector embeddings for media content (transcriptions, descriptions)
75
+ - Search indexing for file discovery
76
+
77
+ ### Groups
78
+ - All media files scoped by `groupId` (multi-tenant isolation)
79
+ - Organization-level storage quotas
80
+ - Team-based access control
81
+
82
+ ### People
83
+ - **platform_owner** - Manage R2 configuration, view all uploads
84
+ - **org_owner** - Manage org storage, set quotas
85
+ - **org_user** - Upload files within quota
86
+ - **customer** - View/stream purchased content
87
+
88
+ ## Technical Architecture
89
+
90
+ ### Backend Layer (Convex + Effect.ts)
91
+
92
+ #### Service Layer (Effect.ts)
93
+
94
+ ```typescript
95
+ // backend/convex/services/storage/r2.ts
96
+ export class R2Service extends Effect.Service<R2Service>()("R2Service", {
97
+ effect: Effect.gen(function* () {
98
+ const db = yield* ConvexDatabase;
99
+ const config = yield* ConfigService; // R2 credentials
100
+
101
+ return {
102
+ // Core operations
103
+ uploadFile: (args: UploadFileArgs) =>
104
+ Effect.gen(function* () {
105
+ // 1. Validate file (size, type)
106
+ // 2. Generate unique R2 key
107
+ // 3. Get presigned upload URL
108
+ // 4. Return upload URL + metadata
109
+ }),
110
+
111
+ getPresignedUrl: (fileKey: string, expiresIn: number = 3600) =>
112
+ Effect.gen(function* () {
113
+ // Generate presigned URL for direct upload
114
+ // Reduces server load (client → R2 directly)
115
+ }),
116
+
117
+ deleteFile: (fileKey: string) =>
118
+ Effect.gen(function* () {
119
+ // 1. Delete from R2
120
+ // 2. Remove from database
121
+ // 3. Log event
122
+ }),
123
+
124
+ listFiles: (prefix?: string) =>
125
+ Effect.gen(function* () {
126
+ // List files in bucket (with pagination)
127
+ }),
128
+
129
+ getFileUrl: (fileKey: string) =>
130
+ Effect.gen(function* () {
131
+ // Return public URL or presigned URL for private files
132
+ }),
133
+
134
+ // Multi-part upload for large files
135
+ initiateMultipartUpload: (fileName: string) =>
136
+ Effect.gen(function* () {
137
+ /* ... */
138
+ }),
139
+
140
+ completeMultipartUpload: (uploadId: string, parts: Part[]) =>
141
+ Effect.gen(function* () {
142
+ /* ... */
143
+ }),
144
+ };
145
+ }),
146
+ dependencies: [ConvexDatabase.Default, ConfigService.Default],
147
+ }) {}
148
+ ```
149
+
150
+ #### Convex Layer (Thin Wrappers)
151
+
152
+ ```typescript
153
+ // backend/convex/mutations/storage.ts
154
+ export const requestUpload = confect.mutation({
155
+ args: {
156
+ fileName: v.string(),
157
+ fileSize: v.number(),
158
+ mimeType: v.string(),
159
+ folderId: v.optional(v.id("things")),
160
+ },
161
+ handler: (ctx, args) =>
162
+ Effect.gen(function* () {
163
+ const r2Service = yield* R2Service;
164
+ const identity = yield* getIdentity(ctx);
165
+
166
+ // Check quota
167
+ yield* checkStorageQuota(ctx, identity.groupId, args.fileSize);
168
+
169
+ // Generate upload URL
170
+ const uploadData = yield* r2Service.getPresignedUrl(args.fileName);
171
+
172
+ // Create pending media_file record
173
+ const fileId = yield* db.insert("things", {
174
+ type: "media_file",
175
+ groupId: identity.groupId,
176
+ createdBy: identity.userId,
177
+ metadata: {
178
+ fileName: args.fileName,
179
+ fileSize: args.fileSize,
180
+ mimeType: args.mimeType,
181
+ status: "uploading",
182
+ r2Key: uploadData.key,
183
+ uploadUrl: uploadData.url,
184
+ },
185
+ });
186
+
187
+ // Log event
188
+ yield* logEvent(ctx, {
189
+ type: "upload_started",
190
+ thingId: fileId,
191
+ });
192
+
193
+ return { fileId, uploadUrl: uploadData.url };
194
+ }).pipe(Effect.provide(MainLayer)),
195
+ });
196
+
197
+ export const confirmUpload = confect.mutation({
198
+ args: {
199
+ fileId: v.id("things"),
200
+ },
201
+ handler: (ctx, args) =>
202
+ Effect.gen(function* () {
203
+ // Mark file as completed
204
+ yield* db.patch(args.fileId, {
205
+ "metadata.status": "completed",
206
+ "metadata.uploadedAt": Date.now(),
207
+ });
208
+
209
+ // Log event
210
+ yield* logEvent(ctx, {
211
+ type: "media_uploaded",
212
+ thingId: args.fileId,
213
+ });
214
+
215
+ return { success: true };
216
+ }).pipe(Effect.provide(MainLayer)),
217
+ });
218
+
219
+ export const deleteFile = confect.mutation({
220
+ args: {
221
+ fileId: v.id("things"),
222
+ },
223
+ handler: (ctx, args) =>
224
+ Effect.gen(function* () {
225
+ const r2Service = yield* R2Service;
226
+
227
+ // Get file
228
+ const file = yield* db.get(args.fileId);
229
+ if (!file || file.type !== "media_file") {
230
+ return yield* Effect.fail(new Error("File not found"));
231
+ }
232
+
233
+ // Delete from R2
234
+ yield* r2Service.deleteFile(file.metadata.r2Key);
235
+
236
+ // Delete from database
237
+ yield* db.delete(args.fileId);
238
+
239
+ // Log event
240
+ yield* logEvent(ctx, {
241
+ type: "media_deleted",
242
+ thingId: args.fileId,
243
+ });
244
+
245
+ return { success: true };
246
+ }).pipe(Effect.provide(MainLayer)),
247
+ });
248
+ ```
249
+
250
+ #### Queries
251
+
252
+ ```typescript
253
+ // backend/convex/queries/storage.ts
254
+ export const listFiles = confect.query({
255
+ args: {
256
+ folderId: v.optional(v.id("things")),
257
+ fileType: v.optional(v.union(v.literal("video"), v.literal("audio"))),
258
+ },
259
+ handler: (ctx, args) =>
260
+ Effect.gen(function* () {
261
+ const identity = yield* getIdentity(ctx);
262
+
263
+ return yield* db
264
+ .query("things")
265
+ .withIndex("by_type", (q) =>
266
+ q.eq("type", "media_file").eq("groupId", identity.groupId),
267
+ )
268
+ .filter((q) => {
269
+ if (args.folderId) {
270
+ return q.eq(q.field("metadata.folderId"), args.folderId);
271
+ }
272
+ if (args.fileType) {
273
+ return q.eq(
274
+ q.field("metadata.mimeType"),
275
+ args.fileType === "video" ? "video/*" : "audio/*",
276
+ );
277
+ }
278
+ return true;
279
+ })
280
+ .collect();
281
+ }).pipe(Effect.provide(MainLayer)),
282
+ });
283
+
284
+ export const getFileUrl = confect.query({
285
+ args: {
286
+ fileId: v.id("things"),
287
+ },
288
+ handler: (ctx, args) =>
289
+ Effect.gen(function* () {
290
+ const r2Service = yield* R2Service;
291
+ const file = yield* db.get(args.fileId);
292
+
293
+ if (!file || file.type !== "media_file") {
294
+ return yield* Effect.fail(new Error("File not found"));
295
+ }
296
+
297
+ const url = yield* r2Service.getFileUrl(file.metadata.r2Key);
298
+
299
+ return { url, fileName: file.metadata.fileName };
300
+ }).pipe(Effect.provide(MainLayer)),
301
+ });
302
+ ```
303
+
304
+ ### Frontend Layer (Astro + React)
305
+
306
+ #### Upload Component
307
+
308
+ ```typescript
309
+ // web/src/components/features/storage/FileUploader.tsx
310
+ import { useMutation } from "convex/react";
311
+ import { api } from "@/convex/_generated/api";
312
+ import { Button } from "@/components/ui/button";
313
+ import { Progress } from "@/components/ui/progress";
314
+ import { Upload } from "lucide-react";
315
+ import { useState } from "react";
316
+
317
+ export function FileUploader({ folderId }: { folderId?: Id<"things"> }) {
318
+ const requestUpload = useMutation(api.storage.requestUpload);
319
+ const confirmUpload = useMutation(api.storage.confirmUpload);
320
+
321
+ const [uploading, setUploading] = useState(false);
322
+ const [progress, setProgress] = useState(0);
323
+
324
+ const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
325
+ const file = e.target.files?.[0];
326
+ if (!file) return;
327
+
328
+ setUploading(true);
329
+ setProgress(0);
330
+
331
+ try {
332
+ // 1. Request presigned upload URL
333
+ const { fileId, uploadUrl } = await requestUpload({
334
+ fileName: file.name,
335
+ fileSize: file.size,
336
+ mimeType: file.type,
337
+ folderId,
338
+ });
339
+
340
+ // 2. Upload directly to R2
341
+ const xhr = new XMLHttpRequest();
342
+ xhr.upload.onprogress = (e) => {
343
+ if (e.lengthComputable) {
344
+ setProgress((e.loaded / e.total) * 100);
345
+ }
346
+ };
347
+
348
+ await new Promise((resolve, reject) => {
349
+ xhr.onload = () => (xhr.status === 200 ? resolve(null) : reject());
350
+ xhr.onerror = reject;
351
+ xhr.open("PUT", uploadUrl);
352
+ xhr.setRequestHeader("Content-Type", file.type);
353
+ xhr.send(file);
354
+ });
355
+
356
+ // 3. Confirm upload completion
357
+ await confirmUpload({ fileId });
358
+
359
+ toast.success(`${file.name} uploaded successfully!`);
360
+ } catch (error) {
361
+ console.error("Upload failed:", error);
362
+ toast.error("Upload failed");
363
+ } finally {
364
+ setUploading(false);
365
+ setProgress(0);
366
+ }
367
+ };
368
+
369
+ return (
370
+ <div className="space-y-4">
371
+ <Button asChild disabled={uploading}>
372
+ <label>
373
+ <Upload className="mr-2 h-4 w-4" />
374
+ {uploading ? "Uploading..." : "Upload File"}
375
+ <input
376
+ type="file"
377
+ className="sr-only"
378
+ accept="video/*,audio/*"
379
+ onChange={handleFileSelect}
380
+ disabled={uploading}
381
+ />
382
+ </label>
383
+ </Button>
384
+
385
+ {uploading && (
386
+ <div className="space-y-2">
387
+ <Progress value={progress} />
388
+ <p className="text-sm text-muted-foreground">{progress.toFixed(0)}%</p>
389
+ </div>
390
+ )}
391
+ </div>
392
+ );
393
+ }
394
+ ```
395
+
396
+ #### Media Library Component
397
+
398
+ ```typescript
399
+ // web/src/components/features/storage/MediaLibrary.tsx
400
+ import { useQuery, useMutation } from "convex/react";
401
+ import { api } from "@/convex/_generated/api";
402
+ import { Button } from "@/components/ui/button";
403
+ import { Trash2, Play, Download } from "lucide-react";
404
+
405
+ export function MediaLibrary() {
406
+ const files = useQuery(api.storage.listFiles);
407
+ const deleteFile = useMutation(api.storage.deleteFile);
408
+ const getUrl = useMutation(api.storage.getFileUrl);
409
+
410
+ const handlePlay = async (fileId: Id<"things">) => {
411
+ const { url } = await getUrl({ fileId });
412
+ // Open in video/audio player
413
+ window.open(url, "_blank");
414
+ };
415
+
416
+ const handleDelete = async (fileId: Id<"things">) => {
417
+ if (confirm("Delete this file?")) {
418
+ await deleteFile({ fileId });
419
+ toast.success("File deleted");
420
+ }
421
+ };
422
+
423
+ return (
424
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
425
+ {files?.map((file) => (
426
+ <div key={file._id} className="border rounded-lg p-4 space-y-2">
427
+ <h3 className="font-medium truncate">{file.metadata.fileName}</h3>
428
+ <p className="text-sm text-muted-foreground">
429
+ {formatBytes(file.metadata.fileSize)}
430
+ </p>
431
+
432
+ <div className="flex gap-2">
433
+ <Button size="sm" onClick={() => handlePlay(file._id)}>
434
+ <Play className="h-4 w-4" />
435
+ </Button>
436
+ <Button
437
+ size="sm"
438
+ variant="destructive"
439
+ onClick={() => handleDelete(file._id)}
440
+ >
441
+ <Trash2 className="h-4 w-4" />
442
+ </Button>
443
+ </div>
444
+ </div>
445
+ ))}
446
+ </div>
447
+ );
448
+ }
449
+ ```
450
+
451
+ ## File Structure
452
+
453
+ ### Backend
454
+
455
+ ```
456
+ backend/convex/
457
+ ├── services/
458
+ │ └── storage/
459
+ │ ├── r2.ts # R2 service (Effect.ts)
460
+ │ ├── quota.ts # Storage quota management
461
+ │ └── multipart.ts # Multi-part upload service
462
+ ├── mutations/
463
+ │ └── storage.ts # Upload, delete mutations
464
+ ├── queries/
465
+ │ └── storage.ts # List, get file queries
466
+ ├── actions/
467
+ │ └── storage.ts # R2 API interactions
468
+ └── http/
469
+ └── webhooks/
470
+ └── r2.ts # R2 event notifications (optional)
471
+ ```
472
+
473
+ ### Frontend
474
+
475
+ ```
476
+ web/src/
477
+ ├── components/
478
+ │ └── features/
479
+ │ └── storage/
480
+ │ ├── FileUploader.tsx # Upload component
481
+ │ ├── MediaLibrary.tsx # File browser
482
+ │ ├── VideoPlayer.tsx # Video player
483
+ │ ├── AudioPlayer.tsx # Audio player
484
+ │ ├── FolderTree.tsx # Folder navigation
485
+ │ └── StorageQuota.tsx # Quota display
486
+ └── pages/
487
+ └── media/
488
+ ├── index.astro # Media library page
489
+ ├── upload.astro # Upload page
490
+ └── [id].astro # File detail page
491
+ ```
492
+
493
+ ## Configuration
494
+
495
+ ### Environment Variables
496
+
497
+ ```bash
498
+ # .env.local (backend)
499
+ R2_ACCOUNT_ID=your_account_id
500
+ R2_ACCESS_KEY_ID=your_access_key
501
+ R2_SECRET_ACCESS_KEY=your_secret_key
502
+ R2_BUCKET_NAME=one-platform-media
503
+ R2_PUBLIC_URL=https://media.one.ie # Custom domain (optional)
504
+ ```
505
+
506
+ ### R2 Setup Steps
507
+
508
+ 1. **Create R2 Bucket**
509
+ - Go to Cloudflare Dashboard → R2
510
+ - Create bucket: `one-platform-media`
511
+ - Enable public access (or use presigned URLs)
512
+
513
+ 2. **Generate API Tokens**
514
+ - R2 → Manage R2 API Tokens
515
+ - Create token with read/write permissions
516
+ - Copy Account ID, Access Key, Secret Key
517
+
518
+ 3. **Custom Domain (Optional)**
519
+ - Connect custom domain: `media.one.ie`
520
+ - Add CNAME: `media.one.ie` → `<bucket>.r2.cloudflarestorage.com`
521
+ - Free SSL via Cloudflare
522
+
523
+ 4. **CORS Configuration**
524
+ ```json
525
+ [
526
+ {
527
+ "AllowedOrigins": ["https://one.ie", "http://localhost:4321"],
528
+ "AllowedMethods": ["GET", "PUT", "POST", "DELETE"],
529
+ "AllowedHeaders": ["*"],
530
+ "ExposeHeaders": ["ETag"],
531
+ "MaxAgeSeconds": 3600
532
+ }
533
+ ]
534
+ ```
535
+
536
+ ## Implementation Phases
537
+
538
+ ### Phase 1: Basic Upload (Week 1)
539
+
540
+ **Goal:** Single file upload to R2 with presigned URLs
541
+
542
+ - [ ] Set up R2 bucket and credentials
543
+ - [ ] Create `R2Service` (Effect.ts)
544
+ - [ ] Implement `requestUpload` mutation
545
+ - [ ] Build `FileUploader` component
546
+ - [ ] Test video/audio uploads
547
+ - [ ] Verify files in R2 dashboard
548
+
549
+ **Success Metrics:**
550
+ - Upload video files <100MB
551
+ - Upload audio files <50MB
552
+ - 95%+ upload success rate
553
+
554
+ ### Phase 2: Media Library (Week 2)
555
+
556
+ **Goal:** Browse, play, and delete uploaded files
557
+
558
+ - [ ] Create `listFiles` query
559
+ - [ ] Build `MediaLibrary` component
560
+ - [ ] Implement file deletion
561
+ - [ ] Add video/audio preview
562
+ - [ ] Create folder organization
563
+
564
+ **Success Metrics:**
565
+ - List 100+ files without lag
566
+ - Preview videos in-browser
567
+ - Organize files in folders
568
+
569
+ ### Phase 3: Advanced Features (Week 3)
570
+
571
+ **Goal:** Multi-part uploads, quotas, analytics
572
+
573
+ - [ ] Multi-part upload for large files (>100MB)
574
+ - [ ] Storage quota per organization
575
+ - [ ] Usage analytics (storage, bandwidth)
576
+ - [ ] Resumable uploads (pause/resume)
577
+ - [ ] Thumbnail generation (via Cloudflare Images)
578
+
579
+ **Success Metrics:**
580
+ - Upload files >1GB
581
+ - Enforce storage quotas
582
+ - Track bandwidth usage
583
+ - Resume interrupted uploads
584
+
585
+ ### Phase 4: Streaming & CDN (Week 4)
586
+
587
+ **Goal:** Optimized video/audio delivery
588
+
589
+ - [ ] HLS/DASH streaming support
590
+ - [ ] Adaptive bitrate streaming
591
+ - [ ] CDN caching optimization
592
+ - [ ] Download acceleration
593
+ - [ ] Mobile-optimized delivery
594
+
595
+ **Success Metrics:**
596
+ - Stream 4K video smoothly
597
+ - <2s initial playback time
598
+ - Cache hit rate >80%
599
+
600
+ ## Integration with ONE Platform Features
601
+
602
+ ### Course Content
603
+ - Upload video lessons to R2
604
+ - Attach audio files to course modules
605
+ - Stream content to enrolled students
606
+ - Track video completion (events)
607
+
608
+ ### Podcasts
609
+ - Upload podcast episodes (MP3/M4A)
610
+ - Generate RSS feed with R2 URLs
611
+ - Track listens and downloads
612
+ - Auto-transcription (Whisper API)
613
+
614
+ ### Creator Content
615
+ - Upload content for sale
616
+ - Protect files with presigned URLs
617
+ - Track views per customer
618
+ - Revenue attribution per file
619
+
620
+ ### Marketing Assets
621
+ - Store product demo videos
622
+ - Host webinar recordings
623
+ - Share promotional audio
624
+ - Track engagement metrics
625
+
626
+ ## Cost Optimization
627
+
628
+ ### Free Tier Strategy
629
+ - Compress videos before upload (H.264, medium quality)
630
+ - Use MP3 128kbps for audio (vs. lossless)
631
+ - Delete unused files regularly
632
+ - Archive old content to cheaper storage
633
+
634
+ ### Monitoring
635
+ - Track storage usage daily
636
+ - Alert at 80% quota (8GB)
637
+ - Monitor Class A operations
638
+ - Estimate monthly costs
639
+
640
+ ### Scaling Beyond Free Tier
641
+ - At 10GB: Upgrade to paid ($1.50/month for 100GB)
642
+ - At 1M uploads/month: Review upload patterns
643
+ - Consider Cloudflare Stream for video (separate product)
644
+
645
+ ## Security Considerations
646
+
647
+ 1. **Access Control**
648
+ - Use presigned URLs (expiring tokens)
649
+ - Validate file types server-side
650
+ - Scan for malware (optional: VirusTotal API)
651
+ - Rate limit uploads per user
652
+
653
+ 2. **Data Privacy**
654
+ - Encrypt sensitive files (AES-256)
655
+ - GDPR compliance (delete on request)
656
+ - Private files use presigned URLs only
657
+ - Audit access logs
658
+
659
+ 3. **Quota Enforcement**
660
+ - Check quota before upload
661
+ - Block uploads if exceeded
662
+ - Notify users at 80% usage
663
+ - Auto-delete old files (configurable)
664
+
665
+ 4. **File Validation**
666
+ - Max file size: 5GB
667
+ - Allowed types: video/*, audio/*
668
+ - Sanitize file names
669
+ - Virus scanning (optional)
670
+
671
+ ## Testing Strategy
672
+
673
+ ### Unit Tests
674
+ ```typescript
675
+ // tests/unit/services/r2.test.ts
676
+ describe("R2Service", () => {
677
+ it("should generate presigned upload URL", async () => {
678
+ const result = await Effect.runPromise(
679
+ Effect.gen(function* () {
680
+ const service = yield* R2Service;
681
+ return yield* service.getPresignedUrl("test-video.mp4");
682
+ }).pipe(Effect.provide(TestLayer)),
683
+ );
684
+
685
+ expect(result.url).toContain("https://");
686
+ expect(result.key).toMatch(/^media\/.+\.mp4$/);
687
+ });
688
+
689
+ it("should enforce storage quota", async () => {
690
+ // Test that upload fails when quota exceeded
691
+ });
692
+ });
693
+ ```
694
+
695
+ ### Integration Tests
696
+ ```typescript
697
+ // tests/integration/upload-flow.test.ts
698
+ describe("Upload Flow", () => {
699
+ it("should complete full upload lifecycle", async () => {
700
+ // 1. Request upload URL
701
+ // 2. Upload file to R2
702
+ // 3. Confirm upload
703
+ // 4. Verify file in database
704
+ // 5. Verify file in R2
705
+ // 6. Delete file
706
+ });
707
+ });
708
+ ```
709
+
710
+ ### E2E Tests
711
+ - Upload 10MB video file
712
+ - Upload 5MB audio file
713
+ - Delete uploaded file
714
+ - Exceed storage quota (fails gracefully)
715
+ - Play uploaded video in browser
716
+
717
+ ## Migration Path
718
+
719
+ ### From Current State
720
+ 1. ✅ No existing storage system (greenfield)
721
+ 2. ⏭️ Set up R2 bucket
722
+ 3. ⏭️ Create R2Service
723
+ 4. ⏭️ Build upload UI
724
+ 5. ⏭️ Add media library
725
+
726
+ ### Future Enhancements
727
+ - Cloudflare Stream (video transcoding, $1/1000 minutes)
728
+ - Cloudflare Images (thumbnail generation, $5/100k images)
729
+ - AI transcription (Whisper API)
730
+ - Auto-captioning for videos
731
+ - Content moderation (AI)
732
+
733
+ ## Resources
734
+
735
+ **Documentation:**
736
+ - [Cloudflare R2 Docs](https://developers.cloudflare.com/r2/)
737
+ - [R2 API Reference](https://developers.cloudflare.com/r2/api/s3/)
738
+ - [AWS S3 SDK](https://aws.amazon.com/sdk-for-javascript/) (S3-compatible)
739
+
740
+ **Tools:**
741
+ - [s3cmd](https://s3tools.org/s3cmd) - Command-line R2 client
742
+ - [Cyberduck](https://cyberduck.io/) - GUI R2 browser
743
+ - [Rclone](https://rclone.org/) - File sync to R2
744
+
745
+ **Examples:**
746
+ - `backend/convex/services/` - Effect.ts service patterns
747
+ - `web/src/components/ui/` - shadcn/ui components
748
+
749
+ ## Success Metrics
750
+
751
+ ### Phase 1: Basic Upload
752
+ - [ ] Upload video files successfully
753
+ - [ ] Upload audio files successfully
754
+ - [ ] Files accessible via public URL
755
+ - [ ] 95%+ upload success rate
756
+
757
+ ### Phase 2: Media Library
758
+ - [ ] Browse uploaded files
759
+ - [ ] Play videos in browser
760
+ - [ ] Delete files
761
+ - [ ] Organize in folders
762
+
763
+ ### Phase 3: Advanced Features
764
+ - [ ] Upload files >1GB (multi-part)
765
+ - [ ] Enforce storage quotas
766
+ - [ ] Resume interrupted uploads
767
+ - [ ] Track usage analytics
768
+
769
+ ### Phase 4: Streaming & CDN
770
+ - [ ] Stream 4K video smoothly
771
+ - [ ] Adaptive bitrate working
772
+ - [ ] Cache hit rate >80%
773
+ - [ ] <2s initial playback time
774
+
775
+ ---
776
+
777
+ **Success = Production-ready media storage with 10GB free tier, unlimited bandwidth, and seamless integration with the ONE Platform's 6-dimension ontology.**