-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths3storage.go
More file actions
169 lines (143 loc) · 4.31 KB
/
Copy paths3storage.go
File metadata and controls
169 lines (143 loc) · 4.31 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
package sebtopic
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"path"
"path/filepath"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/smithy-go"
"github.com/micvbang/go-helpy"
"github.com/micvbang/go-helpy/stringy"
"github.com/micvbang/simple-event-broker/internal/infrastructure/logger"
"github.com/micvbang/simple-event-broker/seberr"
)
// S3Storage is an Amazon S3 backing storage that can be used in Topic.
type S3Storage struct {
log logger.Logger
s3 S3API
bucketName string
s3KeyPrefix string
}
type S3API interface {
GetObject(ctx context.Context, params *s3.GetObjectInput, optFns ...func(*s3.Options)) (*s3.GetObjectOutput, error)
PutObject(ctx context.Context, params *s3.PutObjectInput, optFns ...func(*s3.Options)) (*s3.PutObjectOutput, error)
ListObjectsV2(ctx context.Context, params *s3.ListObjectsV2Input, optFns ...func(*s3.Options)) (*s3.ListObjectsV2Output, error)
}
func NewS3Storage(log logger.Logger, s3 S3API, bucketName string, s3KeyPrefix string) *S3Storage {
return &S3Storage{
log: log,
s3: s3,
bucketName: bucketName,
s3KeyPrefix: s3KeyPrefix,
}
}
func (ss *S3Storage) Writer(ctx context.Context, key string) (io.WriteCloser, error) {
return &s3WriteCloser{
ctx: ctx,
log: ss.log.Name("s3UploadWriteCloser"),
s3: ss.s3,
bucketName: ss.bucketName,
objectKey: path.Join(ss.s3KeyPrefix, key),
}, nil
}
func (ss *S3Storage) Reader(ctx context.Context, key string) (io.ReadCloser, error) {
log := ss.log.WithField("recordBatchPath", key)
log.Debugf("fetching record batch from s3")
obj, err := ss.s3.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(ss.bucketName),
Key: aws.String(path.Join(ss.s3KeyPrefix, key)),
})
if err != nil {
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
if apiErr.ErrorCode() == "NoSuchKey" {
err = errors.Join(err, seberr.ErrNotInStorage)
}
}
return nil, fmt.Errorf("retrieving s3 object: %w", err)
}
// NOTE: intentionally not closing obj.Body, this is caller's responsibility
return obj.Body, nil
}
func (ss *S3Storage) ListFiles(ctx context.Context, topicName string, extension string, startAfter *string) ([]File, error) {
log := ss.log.
WithField("topicPath", topicName).
WithField("extension", extension).
WithField("startAfter", *stringy.StringOrDefault(startAfter, "[not set]"))
topicName = path.Join(ss.s3KeyPrefix, topicName)
topicName, _ = strings.CutPrefix(topicName, "/")
if !strings.HasSuffix(topicName, "/") {
topicName += "/"
}
if startAfter != nil {
startAfter = helpy.Pointer(filepath.Join(topicName, *startAfter))
}
log.Debugf("listing objects in s3")
t0 := time.Now()
files := make([]File, 0, 128)
paginator := s3.NewListObjectsV2Paginator(ss.s3, &s3.ListObjectsV2Input{
Bucket: aws.String(ss.bucketName),
Prefix: &topicName,
StartAfter: startAfter,
})
for paginator.HasMorePages() {
result, err := paginator.NextPage(ctx)
if err != nil {
err = fmt.Errorf("retrieving pages: %w", err)
log.Errorf(err.Error())
return nil, err
}
for _, obj := range result.Contents {
if obj.Key == nil {
continue
}
filePath := *obj.Key
storagePath := filePath
if ss.s3KeyPrefix != "" {
prefix := strings.Trim(ss.s3KeyPrefix, "/")
storagePath, _ = strings.CutPrefix(storagePath, prefix+"/")
}
if filepath.Ext(filePath) == extension {
files = append(files, File{
Path: storagePath,
Size: *obj.Size,
})
}
}
}
log.Debugf("found %d files (%s)", len(files), time.Since(t0))
return files, nil
}
type s3WriteCloser struct {
ctx context.Context
log logger.Logger
s3 S3API
buf bytes.Buffer
bucketName string
objectKey string
}
func (wc *s3WriteCloser) Write(b []byte) (int, error) {
return wc.buf.Write(b)
}
func (wc *s3WriteCloser) Close() error {
size := int64(wc.buf.Len())
wc.log.Debugf("uploading to s3://%s/%s", wc.bucketName, wc.objectKey)
t0 := time.Now()
_, err := wc.s3.PutObject(wc.ctx, &s3.PutObjectInput{
Bucket: &wc.bucketName,
Key: &wc.objectKey,
Body: &wc.buf,
ContentLength: &size,
})
if err != nil {
return fmt.Errorf("uploading to s3: %w", err)
}
wc.log.Debugf("uploaded to %s%s (%s)", wc.bucketName, wc.objectKey, time.Since(t0))
return nil
}