-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
236 lines (190 loc) · 4.99 KB
/
reader.go
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
package s3io
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"log/slog"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/aws/smithy-go"
)
// ObjectReader is an io.Reader implementation for an S3 Object
type ObjectReader struct {
ctx context.Context
cli *s3.Client
bucket string
key string
rd *io.PipeReader
logger *slog.Logger
chunkSize int
concurrency int
s3Opts []func(*s3.Options)
}
// NewObjectReader returns a new ObjectReader to do io.Reader opperations on your s3 object
func NewObjectReader(ctx context.Context, cli *s3.Client, bucketName, key string, opts ...ObjectReaderOption) (*ObjectReader, error) {
rd := &ObjectReader{
ctx: ctx,
cli: cli,
bucket: bucketName,
key: key,
chunkSize: DefaultChunkSize,
concurrency: defaultConcurrency,
logger: noopLogger,
}
if err := ObjectReaderOptions(opts...)(rd); err != nil {
return nil, err
}
return rd, nil
}
// ObjectReaderOption is an option for the given read operation
type ObjectReaderOption func(*ObjectReader) error
// ObjectReaderOptions is a collection of ObjectReaderOption's
func ObjectReaderOptions(opts ...ObjectReaderOption) ObjectReaderOption {
return func(r *ObjectReader) error {
for _, op := range opts {
if err := op(r); err != nil {
return err
}
}
return nil
}
}
// Read is the io.Reader implementation for the ObjectReader.
//
// It returns an fs.ErrNotExists if the object doesn't exist in the given bucket.
// And returns an io.EOF when all bytes are read.
func (r *ObjectReader) Read(p []byte) (int, error) {
if r.rd == nil {
if err := r.preRead(); err != nil {
return 0, err
}
}
c, err := r.rd.Read(p)
if err != nil && err == io.ErrClosedPipe {
err = fs.ErrClosed
}
return c, err
}
func (r *ObjectReader) preRead() error {
ctx := r.ctx
rd, wr := io.Pipe()
r.rd = rd
res, err := r.cli.HeadObject(ctx, &s3.HeadObjectInput{
Bucket: &r.bucket,
Key: &r.key,
}, r.s3Opts...)
if err != nil {
var apiError smithy.APIError
if errors.As(err, &apiError) {
switch apiError.(type) {
case *types.NotFound:
rd.CloseWithError(io.EOF)
return fs.ErrNotExist
default:
return apiError
}
}
}
contentLen := *res.ContentLength
r.logger.Debug("pre read", slog.Int64("content-length", contentLen))
cl := newConcurrencyLock(r.concurrency)
nextLock := make(chan struct{}, 1)
go r.getChunk(ctx, wr, cl, nextLock, 0, contentLen)
defer close(nextLock)
return nil
}
func (r *ObjectReader) getChunk(
ctx context.Context,
wr *io.PipeWriter,
cl *concurrencyLock,
sequenceLock chan struct{},
start, contentLen int64,
) {
if start == contentLen+1 { // EOF
defer cl.Close()
select {
case <-ctx.Done():
case <-sequenceLock:
wr.CloseWithError(io.EOF)
}
return
}
cl.Lock()
defer cl.Unlock()
end := start + int64(r.chunkSize)
if end > contentLen {
end = contentLen
}
nextLock := make(chan struct{}, 1)
defer close(nextLock)
go r.getChunk(ctx, wr, cl, nextLock, end+1, contentLen)
res, err := r.getObject(ctx, start, end)
if err != nil {
wr.CloseWithError(err)
return
}
defer res.Body.Close()
select {
case <-ctx.Done():
return
case <-sequenceLock:
if _, err := io.Copy(wr, res.Body); err != nil && err != io.EOF {
wr.CloseWithError(err)
}
r.logger.DebugContext(ctx, "chunk read",
slog.Group("chunk", slog.Int64("start", start), slog.Int64("end", end), slog.Int64("content_lenght", contentLen)),
)
}
}
func (r *ObjectReader) getObject(ctx context.Context, start, end int64) (*s3.GetObjectOutput, error) {
r.logger.DebugContext(ctx, "getting chunk", slog.Group("chunk", slog.Int64("start", start), slog.Int64("end", end)))
byteRange := fmt.Sprintf("bytes=%d-%d", start, end)
input := &s3.GetObjectInput{
Bucket: &r.bucket,
Key: &r.key,
Range: &byteRange,
}
return r.cli.GetObject(ctx, input, r.s3Opts...)
}
/*
* Options
*/
// WithReaderLogger sets the logger for this reader
func WithReaderLogger(logger *slog.Logger) ObjectReaderOption {
return func(r *ObjectReader) error {
if logger != nil {
r.logger = logger
}
return nil
}
}
// WithReaderChunkSize sets the chunksize for this reader
func WithReaderChunkSize(size uint) ObjectReaderOption {
return func(r *ObjectReader) error {
r.chunkSize = int(size)
return nil
}
}
// WithReaderConcurrency set the concurency amount for this reader
func WithReaderConcurrency(i uint8) ObjectReaderOption {
return func(r *ObjectReader) error {
r.concurrency = int(i)
return nil
}
}
// WithReaderRetries sets the retry count for this reader
func WithReaderRetries(i uint8) ObjectReaderOption {
return func(r *ObjectReader) error {
r.s3Opts = append(r.s3Opts, withS3Retries(int(i)))
return nil
}
}
// WithReaderS3Options adds s3 options to the reader opperations
func WithReaderS3Options(opts ...func(*s3.Options)) ObjectReaderOption {
return func(r *ObjectReader) error {
r.s3Opts = append(r.s3Opts, opts...)
return nil
}
}