-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoperations.go
More file actions
846 lines (713 loc) · 24.2 KB
/
operations.go
File metadata and controls
846 lines (713 loc) · 24.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
package s3
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"go.uber.org/zap"
)
// Operations handles all S3 file operations
type Operations struct {
plugin *Plugin
log *zap.Logger
}
// NewOperations creates a new Operations instance
func NewOperations(plugin *Plugin, log *zap.Logger) *Operations {
return &Operations{
plugin: plugin,
log: log,
}
}
// Write uploads a file to S3
func (o *Operations) Write(ctx context.Context, req *WriteRequest, resp *WriteResponse) error {
// Track operation for graceful shutdown
o.plugin.TrackOperation()
defer o.plugin.CompleteOperation()
start := time.Now()
// Validate request
if err := o.validatePathname(req.Pathname); err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "write", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrInvalidPathname)
return err
}
// Get bucket
bucket, err := o.plugin.buckets.GetBucket(req.Bucket)
if err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "write", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrBucketNotFound)
return NewBucketNotFoundError(req.Bucket)
}
// Acquire semaphore
bucket.Acquire()
defer bucket.Release()
// Determine visibility
visibility := req.Visibility
if visibility == "" {
visibility = bucket.GetVisibility()
}
// Get full S3 key
key := bucket.GetFullPath(req.Pathname)
// Detect content type
contentType := o.detectContentType(req.Pathname, req.Content)
// Prepare upload input
putInput := &s3.PutObjectInput{
Bucket: aws.String(bucket.Config.Bucket),
Key: aws.String(key),
Body: bytes.NewReader(req.Content),
ACL: types.ObjectCannedACL(visibility),
ContentType: aws.String(contentType),
}
// Add custom metadata if provided
if len(req.Config) > 0 {
metadata := make(map[string]string)
for k, v := range req.Config {
metadata[k] = v
}
putInput.Metadata = metadata
}
// Use upload manager for better performance with large files
uploader := manager.NewUploader(bucket.Client, func(u *manager.Uploader) {
u.PartSize = bucket.Config.PartSize
u.Concurrency = bucket.Config.Concurrency
})
// Upload file
result, err := uploader.Upload(ctx, putInput)
if err != nil {
o.log.Error("failed to upload file",
zap.String("bucket", req.Bucket),
zap.String("pathname", req.Pathname),
zap.Error(err),
)
o.plugin.metrics.RecordOperation(req.Bucket, "write", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrS3Operation)
return NewS3OperationError("upload", err)
}
// Get metadata for response
headResult, err := bucket.Client.HeadObject(ctx, &s3.HeadObjectInput{
Bucket: aws.String(bucket.Config.Bucket),
Key: aws.String(key),
})
if err != nil {
o.log.Warn("failed to get object metadata after upload",
zap.String("bucket", req.Bucket),
zap.String("pathname", req.Pathname),
zap.Error(err),
)
// Don't fail the operation, just return without metadata
resp.Success = true
resp.Pathname = req.Pathname
resp.Size = int64(len(req.Content))
resp.LastModified = time.Now().Unix()
o.plugin.metrics.RecordOperation(req.Bucket, "write", "success")
return nil
}
resp.Success = true
resp.Pathname = req.Pathname
resp.Size = *headResult.ContentLength
resp.LastModified = headResult.LastModified.Unix()
o.plugin.metrics.RecordOperation(req.Bucket, "write", "success")
o.log.Debug("file uploaded successfully",
zap.String("bucket", req.Bucket),
zap.String("pathname", req.Pathname),
zap.Int64("size", resp.Size),
zap.Duration("duration", time.Since(start)),
)
_ = result // Use result to avoid unused variable warning
return nil
}
// Read downloads a file from S3
func (o *Operations) Read(ctx context.Context, req *ReadRequest, resp *ReadResponse) error {
o.plugin.TrackOperation()
defer o.plugin.CompleteOperation()
start := time.Now()
// Validate request
if err := o.validatePathname(req.Pathname); err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "read", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrInvalidPathname)
return err
}
// Get bucket
bucket, err := o.plugin.buckets.GetBucket(req.Bucket)
if err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "read", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrBucketNotFound)
return NewBucketNotFoundError(req.Bucket)
}
bucket.Acquire()
defer bucket.Release()
// Get full S3 key
key := bucket.GetFullPath(req.Pathname)
// Download file
result, err := bucket.Client.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(bucket.Config.Bucket),
Key: aws.String(key),
})
if err != nil {
var nsk *types.NoSuchKey
if errors.As(err, &nsk) {
o.plugin.metrics.RecordOperation(req.Bucket, "read", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrFileNotFound)
return NewFileNotFoundError(req.Pathname)
}
o.log.Error("failed to download file",
zap.String("bucket", req.Bucket),
zap.String("pathname", req.Pathname),
zap.Error(err),
)
o.plugin.metrics.RecordOperation(req.Bucket, "read", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrS3Operation)
return NewS3OperationError("download", err)
}
defer result.Body.Close()
// Read content
content, err := io.ReadAll(result.Body)
if err != nil {
o.log.Error("failed to read file content",
zap.String("bucket", req.Bucket),
zap.String("pathname", req.Pathname),
zap.Error(err),
)
o.plugin.metrics.RecordOperation(req.Bucket, "read", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrS3Operation)
return NewS3OperationError("read content", err)
}
resp.Content = content
resp.Size = *result.ContentLength
resp.MimeType = *result.ContentType
resp.LastModified = result.LastModified.Unix()
o.plugin.metrics.RecordOperation(req.Bucket, "read", "success")
o.log.Debug("file downloaded successfully",
zap.String("bucket", req.Bucket),
zap.String("pathname", req.Pathname),
zap.Int64("size", resp.Size),
zap.Duration("duration", time.Since(start)),
)
return nil
}
// Exists checks if a file exists in S3
func (o *Operations) Exists(ctx context.Context, req *ExistsRequest, resp *ExistsResponse) error {
o.plugin.TrackOperation()
defer o.plugin.CompleteOperation()
// Validate request
if err := o.validatePathname(req.Pathname); err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "exists", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrInvalidPathname)
return err
}
// Get bucket
bucket, err := o.plugin.buckets.GetBucket(req.Bucket)
if err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "exists", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrBucketNotFound)
return NewBucketNotFoundError(req.Bucket)
}
bucket.Acquire()
defer bucket.Release()
// Get full S3 key
key := bucket.GetFullPath(req.Pathname)
// Check if object exists
_, err = bucket.Client.HeadObject(ctx, &s3.HeadObjectInput{
Bucket: aws.String(bucket.Config.Bucket),
Key: aws.String(key),
})
if err != nil {
var nsk *types.NoSuchKey
var nf *types.NotFound
if errors.As(err, &nsk) || errors.As(err, &nf) {
resp.Exists = false
o.plugin.metrics.RecordOperation(req.Bucket, "exists", "success")
return nil
}
// Other errors should be returned
o.log.Error("failed to check file existence",
zap.String("bucket", req.Bucket),
zap.String("pathname", req.Pathname),
zap.Error(err),
)
o.plugin.metrics.RecordOperation(req.Bucket, "exists", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrS3Operation)
return NewS3OperationError("head object", err)
}
resp.Exists = true
o.plugin.metrics.RecordOperation(req.Bucket, "exists", "success")
return nil
}
// Delete deletes a file from S3
func (o *Operations) Delete(ctx context.Context, req *DeleteRequest, resp *DeleteResponse) error {
o.plugin.TrackOperation()
defer o.plugin.CompleteOperation()
// Validate request
if err := o.validatePathname(req.Pathname); err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "delete", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrInvalidPathname)
return err
}
// Get bucket
bucket, err := o.plugin.buckets.GetBucket(req.Bucket)
if err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "delete", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrBucketNotFound)
return NewBucketNotFoundError(req.Bucket)
}
bucket.Acquire()
defer bucket.Release()
// Get full S3 key
key := bucket.GetFullPath(req.Pathname)
// Delete object
_, err = bucket.Client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(bucket.Config.Bucket),
Key: aws.String(key),
})
if err != nil {
o.log.Error("failed to delete file",
zap.String("bucket", req.Bucket),
zap.String("pathname", req.Pathname),
zap.Error(err),
)
o.plugin.metrics.RecordOperation(req.Bucket, "delete", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrS3Operation)
return NewS3OperationError("delete", err)
}
resp.Success = true
o.plugin.metrics.RecordOperation(req.Bucket, "delete", "success")
o.log.Debug("file deleted successfully",
zap.String("bucket", req.Bucket),
zap.String("pathname", req.Pathname),
)
return nil
}
// Copy copies a file within or between buckets
func (o *Operations) Copy(ctx context.Context, req *CopyRequest, resp *CopyResponse) error {
o.plugin.TrackOperation()
defer o.plugin.CompleteOperation()
start := time.Now()
// Validate request
if err := o.validatePathname(req.SourcePathname); err != nil {
o.plugin.metrics.RecordOperation(req.SourceBucket, "copy", "error")
o.plugin.metrics.RecordError(req.SourceBucket, ErrInvalidPathname)
return err
}
if err := o.validatePathname(req.DestPathname); err != nil {
o.plugin.metrics.RecordOperation(req.DestBucket, "copy", "error")
o.plugin.metrics.RecordError(req.DestBucket, ErrInvalidPathname)
return err
}
// Get source bucket
sourceBucket, err := o.plugin.buckets.GetBucket(req.SourceBucket)
if err != nil {
o.plugin.metrics.RecordOperation(req.SourceBucket, "copy", "error")
o.plugin.metrics.RecordError(req.SourceBucket, ErrBucketNotFound)
return NewBucketNotFoundError(req.SourceBucket)
}
// Get destination bucket
destBucket, err := o.plugin.buckets.GetBucket(req.DestBucket)
if err != nil {
o.plugin.metrics.RecordOperation(req.DestBucket, "copy", "error")
o.plugin.metrics.RecordError(req.DestBucket, ErrBucketNotFound)
return NewBucketNotFoundError(req.DestBucket)
}
// Acquire semaphores
sourceBucket.Acquire()
defer sourceBucket.Release()
if req.SourceBucket != req.DestBucket {
destBucket.Acquire()
defer destBucket.Release()
}
// Get full S3 keys
sourceKey := sourceBucket.GetFullPath(req.SourcePathname)
destKey := destBucket.GetFullPath(req.DestPathname)
// Prepare copy source
copySource := fmt.Sprintf("%s/%s", sourceBucket.Config.Bucket, sourceKey)
// Determine visibility
visibility := req.Visibility
if visibility == "" {
visibility = destBucket.GetVisibility()
}
// Copy object
_, err = destBucket.Client.CopyObject(ctx, &s3.CopyObjectInput{
Bucket: aws.String(destBucket.Config.Bucket),
Key: aws.String(destKey),
CopySource: aws.String(copySource),
ACL: types.ObjectCannedACL(visibility),
})
if err != nil {
o.log.Error("failed to copy file",
zap.String("source_bucket", req.SourceBucket),
zap.String("source_pathname", req.SourcePathname),
zap.String("dest_bucket", req.DestBucket),
zap.String("dest_pathname", req.DestPathname),
zap.Error(err),
)
o.plugin.metrics.RecordOperation(req.DestBucket, "copy", "error")
o.plugin.metrics.RecordError(req.DestBucket, ErrS3Operation)
return NewS3OperationError("copy", err)
}
// Get metadata for response
headResult, err := destBucket.Client.HeadObject(ctx, &s3.HeadObjectInput{
Bucket: aws.String(destBucket.Config.Bucket),
Key: aws.String(destKey),
})
if err == nil {
resp.Size = *headResult.ContentLength
resp.LastModified = headResult.LastModified.Unix()
}
resp.Success = true
resp.Pathname = req.DestPathname
o.plugin.metrics.RecordOperation(req.DestBucket, "copy", "success")
o.log.Debug("file copied successfully",
zap.String("source_bucket", req.SourceBucket),
zap.String("source_pathname", req.SourcePathname),
zap.String("dest_bucket", req.DestBucket),
zap.String("dest_pathname", req.DestPathname),
zap.Duration("duration", time.Since(start)),
)
return nil
}
// Move moves a file within or between buckets (copy + delete)
func (o *Operations) Move(ctx context.Context, req *MoveRequest, resp *MoveResponse) error {
// First, copy the file
copyReq := &CopyRequest{
SourceBucket: req.SourceBucket,
SourcePathname: req.SourcePathname,
DestBucket: req.DestBucket,
DestPathname: req.DestPathname,
Config: req.Config,
Visibility: req.Visibility,
}
copyResp := &CopyResponse{}
if err := o.Copy(ctx, copyReq, copyResp); err != nil {
return err
}
// Then delete the source file
deleteReq := &DeleteRequest{
Bucket: req.SourceBucket,
Pathname: req.SourcePathname,
}
deleteResp := &DeleteResponse{}
if err := o.Delete(ctx, deleteReq, deleteResp); err != nil {
o.log.Error("failed to delete source file after copy",
zap.String("bucket", req.SourceBucket),
zap.String("pathname", req.SourcePathname),
zap.Error(err),
)
// Return error but note that copy succeeded
return fmt.Errorf("copy succeeded but delete failed: %w", err)
}
resp.Success = true
resp.Pathname = copyResp.Pathname
resp.Size = copyResp.Size
resp.LastModified = copyResp.LastModified
return nil
}
// GetMetadata retrieves file metadata
func (o *Operations) GetMetadata(ctx context.Context, req *GetMetadataRequest, resp *GetMetadataResponse) error {
o.plugin.TrackOperation()
defer o.plugin.CompleteOperation()
// Validate request
if err := o.validatePathname(req.Pathname); err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "get_metadata", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrInvalidPathname)
return err
}
// Get bucket
bucket, err := o.plugin.buckets.GetBucket(req.Bucket)
if err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "get_metadata", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrBucketNotFound)
return NewBucketNotFoundError(req.Bucket)
}
bucket.Acquire()
defer bucket.Release()
// Get full S3 key
key := bucket.GetFullPath(req.Pathname)
// Get object metadata
result, err := bucket.Client.HeadObject(ctx, &s3.HeadObjectInput{
Bucket: aws.String(bucket.Config.Bucket),
Key: aws.String(key),
})
if err != nil {
var nsk *types.NoSuchKey
var nf *types.NotFound
if errors.As(err, &nsk) || errors.As(err, &nf) {
o.plugin.metrics.RecordOperation(req.Bucket, "get_metadata", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrFileNotFound)
return NewFileNotFoundError(req.Pathname)
}
o.log.Error("failed to get file metadata",
zap.String("bucket", req.Bucket),
zap.String("pathname", req.Pathname),
zap.Error(err),
)
o.plugin.metrics.RecordOperation(req.Bucket, "get_metadata", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrS3Operation)
return NewS3OperationError("head object", err)
}
resp.Size = *result.ContentLength
if result.ContentType != nil {
resp.MimeType = *result.ContentType
}
resp.LastModified = result.LastModified.Unix()
if result.ETag != nil {
resp.ETag = *result.ETag
}
// Determine visibility from ACL (if available)
resp.Visibility = "private" // Default
o.plugin.metrics.RecordOperation(req.Bucket, "get_metadata", "success")
return nil
}
// SetVisibility changes file visibility (ACL)
func (o *Operations) SetVisibility(ctx context.Context, req *SetVisibilityRequest, resp *SetVisibilityResponse) error {
o.plugin.TrackOperation()
defer o.plugin.CompleteOperation()
// Validate request
if err := o.validatePathname(req.Pathname); err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "set_visibility", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrInvalidPathname)
return err
}
if req.Visibility != "public" && req.Visibility != "private" {
o.plugin.metrics.RecordOperation(req.Bucket, "set_visibility", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrInvalidVisibility)
return NewS3Error(ErrInvalidVisibility, "visibility must be 'public' or 'private'", req.Visibility)
}
// Get bucket
bucket, err := o.plugin.buckets.GetBucket(req.Bucket)
if err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "set_visibility", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrBucketNotFound)
return NewBucketNotFoundError(req.Bucket)
}
bucket.Acquire()
defer bucket.Release()
// Get full S3 key
key := bucket.GetFullPath(req.Pathname)
// Map visibility to ACL
acl := types.ObjectCannedACLPrivate
if req.Visibility == "public" {
acl = types.ObjectCannedACLPublicRead
}
// Set ACL
_, err = bucket.Client.PutObjectAcl(ctx, &s3.PutObjectAclInput{
Bucket: aws.String(bucket.Config.Bucket),
Key: aws.String(key),
ACL: acl,
})
if err != nil {
o.log.Error("failed to set file visibility",
zap.String("bucket", req.Bucket),
zap.String("pathname", req.Pathname),
zap.String("visibility", req.Visibility),
zap.Error(err),
)
o.plugin.metrics.RecordOperation(req.Bucket, "set_visibility", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrS3Operation)
return NewS3OperationError("put object acl", err)
}
resp.Success = true
o.plugin.metrics.RecordOperation(req.Bucket, "set_visibility", "success")
o.log.Debug("file visibility changed",
zap.String("bucket", req.Bucket),
zap.String("pathname", req.Pathname),
zap.String("visibility", req.Visibility),
)
return nil
}
// GetPublicURL generates a public or presigned URL for a file
func (o *Operations) GetPublicURL(ctx context.Context, req *GetPublicURLRequest, resp *GetPublicURLResponse) error {
o.plugin.TrackOperation()
defer o.plugin.CompleteOperation()
// Validate request
if err := o.validatePathname(req.Pathname); err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "get_url", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrInvalidPathname)
return err
}
// Get bucket
bucket, err := o.plugin.buckets.GetBucket(req.Bucket)
if err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "get_url", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrBucketNotFound)
return NewBucketNotFoundError(req.Bucket)
}
// Get full S3 key
key := bucket.GetFullPath(req.Pathname)
// If no expiration, generate permanent public URL
if req.ExpiresIn == 0 {
// Generate public URL (assuming public-read ACL)
endpoint := bucket.ServerConfig.Endpoint
if endpoint == "" {
endpoint = fmt.Sprintf("https://s3.%s.amazonaws.com", bucket.ServerConfig.Region)
}
resp.URL = fmt.Sprintf("%s/%s/%s", endpoint, bucket.Config.Bucket, key)
o.plugin.metrics.RecordOperation(req.Bucket, "get_url", "success")
return nil
}
// Generate presigned URL
presignClient := s3.NewPresignClient(bucket.Client)
presignResult, err := presignClient.PresignGetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(bucket.Config.Bucket),
Key: aws.String(key),
}, func(opts *s3.PresignOptions) {
opts.Expires = time.Duration(req.ExpiresIn) * time.Second
})
if err != nil {
o.log.Error("failed to generate presigned URL",
zap.String("bucket", req.Bucket),
zap.String("pathname", req.Pathname),
zap.Error(err),
)
o.plugin.metrics.RecordOperation(req.Bucket, "get_url", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrS3Operation)
return NewS3OperationError("presign get object", err)
}
resp.URL = presignResult.URL
resp.ExpiresAt = time.Now().Add(time.Duration(req.ExpiresIn) * time.Second).Unix()
o.plugin.metrics.RecordOperation(req.Bucket, "get_url", "success")
return nil
}
// ListObjects lists objects in a bucket with optional filtering and pagination
func (o *Operations) ListObjects(ctx context.Context, req *ListObjectsRequest, resp *ListObjectsResponse) error {
o.plugin.TrackOperation()
defer o.plugin.CompleteOperation()
start := time.Now()
// Get bucket
bucket, err := o.plugin.buckets.GetBucket(req.Bucket)
if err != nil {
o.plugin.metrics.RecordOperation(req.Bucket, "list", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrBucketNotFound)
return NewBucketNotFoundError(req.Bucket)
}
bucket.Acquire()
defer bucket.Release()
// Set default max keys if not specified
maxKeys := req.MaxKeys
if maxKeys <= 0 {
maxKeys = 1000
}
// Prepare prefix - include bucket prefix if configured
prefix := bucket.GetFullPath(req.Prefix)
// Prepare list objects input
input := &s3.ListObjectsV2Input{
Bucket: aws.String(bucket.Config.Bucket),
MaxKeys: aws.Int32(maxKeys),
}
// Add optional parameters
if prefix != "" {
input.Prefix = aws.String(prefix)
}
if req.Delimiter != "" {
input.Delimiter = aws.String(req.Delimiter)
}
if req.ContinuationToken != "" {
input.ContinuationToken = aws.String(req.ContinuationToken)
}
// List objects
result, err := bucket.Client.ListObjectsV2(ctx, input)
if err != nil {
o.log.Error("failed to list objects",
zap.String("bucket", req.Bucket),
zap.String("prefix", req.Prefix),
zap.Error(err),
)
o.plugin.metrics.RecordOperation(req.Bucket, "list", "error")
o.plugin.metrics.RecordError(req.Bucket, ErrS3Operation)
return NewS3OperationError("list objects", err)
}
// Convert results to response format
resp.Objects = make([]ObjectInfo, 0, len(result.Contents))
for _, obj := range result.Contents {
// Remove bucket prefix from key if present
key := *obj.Key
if bucket.Config.Prefix != "" && strings.HasPrefix(key, bucket.Config.Prefix) {
key = strings.TrimPrefix(key, bucket.Config.Prefix)
}
objectInfo := ObjectInfo{
Key: key,
Size: *obj.Size,
LastModified: obj.LastModified.Unix(),
}
if obj.ETag != nil {
objectInfo.ETag = *obj.ETag
}
if obj.StorageClass != "" {
objectInfo.StorageClass = string(obj.StorageClass)
}
resp.Objects = append(resp.Objects, objectInfo)
}
// Process common prefixes (directories)
if len(result.CommonPrefixes) > 0 {
resp.CommonPrefixes = make([]CommonPrefix, 0, len(result.CommonPrefixes))
for _, cp := range result.CommonPrefixes {
prefix := *cp.Prefix
// Remove bucket prefix if present
if bucket.Config.Prefix != "" && strings.HasPrefix(prefix, bucket.Config.Prefix) {
prefix = strings.TrimPrefix(prefix, bucket.Config.Prefix)
}
resp.CommonPrefixes = append(resp.CommonPrefixes, CommonPrefix{
Prefix: prefix,
})
}
}
// Set pagination info
resp.IsTruncated = result.IsTruncated != nil && *result.IsTruncated
if result.NextContinuationToken != nil {
resp.NextContinuationToken = *result.NextContinuationToken
}
resp.KeyCount = *result.KeyCount
o.plugin.metrics.RecordOperation(req.Bucket, "list", "success")
o.log.Debug("objects listed successfully",
zap.String("bucket", req.Bucket),
zap.String("prefix", req.Prefix),
zap.Int32("count", resp.KeyCount),
zap.Bool("truncated", resp.IsTruncated),
zap.Duration("duration", time.Since(start)),
)
return nil
}
// validatePathname validates a file pathname
func (o *Operations) validatePathname(pathname string) error {
if pathname == "" {
return NewInvalidPathnameError(pathname, "pathname cannot be empty")
}
if strings.HasPrefix(pathname, "/") {
return NewInvalidPathnameError(pathname, "pathname cannot start with '/'")
}
if strings.Contains(pathname, "..") {
return NewInvalidPathnameError(pathname, "pathname cannot contain '..'")
}
return nil
}
// detectContentType attempts to detect content type from filename and content
func (o *Operations) detectContentType(pathname string, content []byte) string {
// Simple content type detection based on file extension
ext := strings.ToLower(pathname[strings.LastIndex(pathname, ".")+1:])
contentTypes := map[string]string{
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
"gif": "image/gif",
"webp": "image/webp",
"svg": "image/svg+xml",
"pdf": "application/pdf",
"txt": "text/plain",
"html": "text/html",
"css": "text/css",
"js": "application/javascript",
"json": "application/json",
"xml": "application/xml",
"zip": "application/zip",
"mp4": "video/mp4",
"mp3": "audio/mpeg",
}
if contentType, ok := contentTypes[ext]; ok {
return contentType
}
return "application/octet-stream"
}