-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpipedream.go
More file actions
384 lines (343 loc) · 9.51 KB
/
pipedream.go
File metadata and controls
384 lines (343 loc) · 9.51 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
// Package pipedream provides a simple interface to multipart Amazon S3
// uploads. It also works with other S3 compatible services such as
// DigitalOcean's spaces.
//
// The general workflow is to create MultipartUpload struct, run Send on the
// struct, and then listen for events on the returned channel.
//
// Example usage:
//
// package main
//
// import (
// "fmt"
// "os"
//
// "github.com/meowgorithm/pipedream"
// )
//
// func main() {
//
// // Prep the multipart upload
// m := pipedream.MultipartUpload{
// AccessKey: os.Getenv("ACCESS_KEY"),
// SecretKey: os.Getenv("SECRET_KEY"),
// Endpoint: "sfo2.digitaloceanspaces.com", // you could use Region for AWS
// Bucket: "my-fave-bucket",
// }
//
// // Get an io.Reader
// f, err := os.Open("big-redis-dump.rdb")
// if err != nil {
// fmt.Printf("Rats: %v\n", err)
// os.Exit(1)
// }
// defer f.Close()
//
// // Send it up! Pipdream returns a channel where you can listen for events.
// ch := m.Send(f, "backups/dump.rdb")
// done := make(chan struct{})
//
// // Listen for activity. For more detailed reporting, see the docs below.
// go func() {
// for {
// e := <-ch
// switch e.(type) {
// case pipedream.Complete:
// fmt.Println("It worked!")
// close(done)
// return
// case pipedream.Error:
// fmt.Println("Rats, it didn't work.")
// close(done)
// return
// }
// }
// }()
//
// <-done
// }
//
// There's also a command line interface available at
// https://github.com/meowgorithm/pipedream/pipedream
package pipedream
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
const (
// Kilobyte is a convenience measurement useful when setting upload part
// sizes.
Kilobyte int64 = 1024
// Megabyte is a convenience measurement useful when setting upload part
// sizes.
Megabyte int64 = Kilobyte * 1024
// DefaultRegion is the region to use as a default. This should be used for
// services that don't use regions, like DigitalOcean spaces.
DefaultRegion = "us-east-1"
)
// Event represents activity that occurred during the upload. Events are sent
// through the channel returned by MultipartUpload.Send(). To figure out which
// event was received use a type switch or type assertion.
type Event interface {
// This is a dummy method for type safety.
event()
}
// Progress is an Event indicating upload progress. It's sent when a part has
// successfully uploaded.
type Progress struct {
PartNumber int
Bytes int
}
// Retry is an Event indicating there was an error uploading a part and the
// part is being retried. An Error will be send if the retries are exhaused and
// the upload fails.
type Retry struct {
PartNumber int
RetryNumber int
MaxRetries int
}
// Complete is an Event sent when an upload has completed successfully. When
// a Complete is received there will be no further activity send on the
// channel, so you can confidently move on.
type Complete struct {
Bytes int
Result *s3.CompleteMultipartUploadOutput
}
// Error is an event indicating that an Error occurred during the upload. When
// an Error is received the operation has failed and no further activity will
// be send, so you can confidently move on.
type Error struct {
Err error
}
// Error returns the a string representation of the error. It satisfies the
// Error interface.
func (e Error) Error() string {
return e.Err.Error()
}
// Implement dummy methods to satisfy Event interface. We're doing this for
// type safety.
func (p Progress) event() {}
func (r Retry) event() {}
func (c Complete) event() {}
func (e Error) event() {}
// MultipartUpload handles multipart uploads to S3 and S3-compatible systems.
type MultipartUpload struct {
Endpoint string
Region string
Bucket string
AccessKey string
SecretKey string
MaxRetries int
MaxPartSize int64
svc *s3.S3
res *s3.CreateMultipartUploadOutput
completedParts []*s3.CompletedPart
currentPartNumber int
path string
reader io.Reader
}
// Send uploads data from a given io.Reader (such as an *os.File or os.Stdin)
// to a given path in a bucket.
func (m *MultipartUpload) Send(reader io.Reader, path string) chan Event {
m.reader = reader
m.path = path
ch := make(chan Event)
go m.run(ch)
return ch
}
func (m *MultipartUpload) run(ch chan Event) {
// Set defaults
if m.MaxRetries == 0 {
m.MaxRetries = 3
}
if m.MaxPartSize == 0 {
m.MaxPartSize = Megabyte * 5
}
if m.Endpoint == "" {
m.Endpoint = "nyc3.digitaloceanspaces.com"
}
if m.Region == "" {
m.Region = DefaultRegion
}
// Validate
var missing []string
if m.AccessKey == "" {
missing = append(missing, "AccessKey")
}
if m.SecretKey == "" {
missing = append(missing, "SecretKey")
}
if m.Bucket == "" {
missing = append(missing, "Bucket")
}
if len(missing) > 0 {
ch <- Error{
Err: errors.New("missing " + EnglishJoin(missing, true)),
}
return
}
// Make S3 config
s3Config := &aws.Config{
Credentials: credentials.NewStaticCredentials(m.AccessKey, m.SecretKey, ""),
Endpoint: aws.String(m.Endpoint),
Region: aws.String(m.Region),
}
// Init S3 session
newSession := session.New(s3Config)
m.svc = s3.New(newSession)
// Upload parts
totalBytes := 0
m.currentPartNumber = 1
buf := make([]byte, m.MaxPartSize)
for {
n, err := m.reader.Read(buf)
if err != nil && err == io.EOF {
// There's no more data, so we've successfully uploaded all parts.
break
}
if err != nil {
if abortErr := m.Abort(); abortErr != nil {
ch <- Error{
Err: fmt.Errorf("upload error: %v, as well as an error aborting the upload: %v", err, abortErr),
}
return
}
ch <- Error{err}
return
}
// Request the upload if we haven't already. We wait until we've read
// some bytes so we can detect the file type.
if m.res == nil {
input := &s3.CreateMultipartUploadInput{
Bucket: aws.String(m.Bucket),
Key: aws.String(m.path),
ContentType: aws.String(http.DetectContentType(buf[:n])),
}
m.res, err = m.svc.CreateMultipartUpload(input)
if err != nil {
ch <- Error{err}
return
}
}
// Perform the upload
part, err := m.uploadPart(ch, buf[:n], m.currentPartNumber)
if err != nil {
if abortErr := m.Abort(); abortErr != nil {
ch <- Error{
Err: fmt.Errorf("upload error: %v, as well as an error aborting the upload: %v", err, abortErr),
}
return
}
ch <- Error{err}
return
}
ch <- Progress{
PartNumber: m.currentPartNumber,
Bytes: n,
}
totalBytes += n
m.completedParts = append(m.completedParts, part)
m.currentPartNumber++
}
res, err := m.complete()
if err != nil {
ch <- Error{err}
}
ch <- Complete{
Bytes: totalBytes,
Result: res,
}
}
// uploadPart performs the technical S3 stuff to upload one part of the
// multipart upload. If it fails we'll retry based on the number set in
// multipartUploadManager.MaxRetries.
func (m MultipartUpload) uploadPart(ch chan Event, chunk []byte, partNum int) (*s3.CompletedPart, error) {
partInput := &s3.UploadPartInput{
Body: bytes.NewReader(chunk),
Bucket: m.res.Bucket,
Key: m.res.Key,
PartNumber: aws.Int64(int64(partNum)),
UploadId: m.res.UploadId,
ContentLength: aws.Int64(int64(len(chunk))),
}
tryNum := 1
for tryNum <= m.MaxRetries {
// Attempt to upload part
res, err := m.svc.UploadPart(partInput)
if err != nil {
// Fail
if tryNum == m.MaxRetries {
if aerr, ok := err.(awserr.Error); ok {
return nil, aerr
}
return nil, err
}
ch <- Retry{
PartNumber: m.currentPartNumber,
RetryNumber: tryNum,
MaxRetries: m.MaxRetries,
}
tryNum++
} else {
// Success
return &s3.CompletedPart{
ETag: res.ETag,
PartNumber: aws.Int64(int64(partNum)),
}, nil
}
}
// This should never happen
return nil, errors.New("could not upload part")
}
// complete finishes up the upload. This must be called after all parts have
// been sent.
func (m MultipartUpload) complete() (*s3.CompleteMultipartUploadOutput, error) {
return m.svc.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
Bucket: m.res.Bucket,
Key: m.res.Key,
UploadId: m.res.UploadId,
MultipartUpload: &s3.CompletedMultipartUpload{
Parts: m.completedParts,
},
})
}
// Abort cancels the upload.
func (m MultipartUpload) Abort() error {
_, err := m.svc.AbortMultipartUpload(&s3.AbortMultipartUploadInput{
Bucket: m.res.Bucket,
Key: m.res.Key,
UploadId: m.res.UploadId,
})
return err
}
// EnglishJoin joins a slice of strings with commas and the word "and" like one
// would in English. Oxford comma optional.
func EnglishJoin(words []string, oxfordComma bool) string {
b := strings.Builder{}
for i, w := range words {
if i == 0 {
b.WriteString(w)
continue
}
if len(words) > 1 && i == len(words)-1 {
if oxfordComma && i > 2 {
b.WriteString(",")
}
b.WriteString(" and")
b.WriteString(" " + w)
continue
}
b.WriteString(", " + w)
}
return b.String()
}