/
service.go
265 lines (229 loc) · 6.26 KB
/
service.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
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
package s3util
import (
"bytes"
"io"
"sync"
"time"
"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"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/monstercat/golib/data"
strutil "github.com/monstercat/golib/string"
)
const DefaultChunkSizeLimit = 1024 * 1024 * 50
const DefaultIncompleteExpiry = time.Hour * 24
// Adheres to the data.Service interface
type Service struct {
data.ChunkManager
Bucket string
Region string
Timeout time.Duration
Concurrency int // Concurrent downloading
//incomplete map[string]*Upload
lock sync.RWMutex
Session *session.Session
Client *s3.S3
}
func (s *Service) SetTimeout(tm time.Duration) {
s.Timeout = tm
}
func (s *Service) SetConcurrency(concurrency int) {
s.Concurrency = concurrency
}
func (s *Service) Init(id, secret string) error {
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials(id, secret, ""),
Region: aws.String(s.Region),
})
if err != nil {
return err
}
if s.ChunkSizeLimit == 0 {
s.ChunkSizeLimit = DefaultChunkSizeLimit
}
if s.IncompleteUploadExpiry == 0 {
s.IncompleteUploadExpiry = DefaultIncompleteExpiry
}
s.Client = s3.New(sess)
s.Session = sess
return nil
}
func (s *Service) Head(filepath string) (*data.HeadInfo, error) {
obj, err := s.Client.HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(s.Bucket),
Key: aws.String(filepath),
})
if err != nil {
aerr, ok := err.(awserr.Error)
if !ok {
return nil, err
}
if aerr.Code() == "NotFound" {
return &data.HeadInfo{
Exists: false,
}, nil
}
}
info := &data.HeadInfo{
Exists: true,
}
if obj.LastModified != nil {
info.LastModified = *obj.LastModified
}
if obj.ContentLength != nil {
info.ContentLength = *obj.ContentLength
}
return info, nil
}
func (s *Service) SignedUrl(filename string, tm time.Duration, config *data.SignedUrlConfig) (string, error) {
// Before signing, the filename needs to be in ISO 8859 1 format.
var err error
config.Filename, err = strutil.ToISO_8859_1(config.Filename)
if err != nil {
return "", err
}
req, _ := s.Client.GetObjectRequest(GetObjectInputFromConfig(
config,
s.Bucket,
filename,
))
return req.Presign(tm)
}
// Checks if the file exists
func (s *Service) Exists(filepath string) (bool, error) {
_, err := s.Client.HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(s.Bucket),
Key: aws.String(filepath),
})
if err == nil {
return true, nil
}
aerr, ok := err.(awserr.Error)
if !ok || aerr.Code() != "NotFound" {
return false, err
}
return false, nil
}
func (s *Service) Put(filepath string, r io.Reader) error {
ch := s.putSimply(filepath, r)
select {
case <-time.After(s.Timeout):
return ErrTimeout
case status := <-ch:
switch status.Code {
case data.UploadStatusCodeError:
return status.Error
default:
return nil
}
}
}
// Upload here is generally only used if you do not care about progress or status updates as it hides
// this information from the user. You only get the final error or non-error code.
func (s *Service) Upload(filepath string, filesize int, r io.Reader) error {
ch := s.PutWithStatus(filepath, filesize, r)
for {
select {
case <-time.After(s.Timeout):
return ErrTimeout
case status := <-ch:
switch status.Code {
case data.UploadStatusCodeOk:
return nil
case data.UploadStatusCodeError:
return status.Error
}
}
}
}
// Delete the file from FS
func (s *Service) Delete(filepath string) error {
_, err := s.Client.DeleteObject(&s3.DeleteObjectInput{
Bucket: aws.String(s.Bucket),
Key: aws.String(filepath),
})
return err
}
func (s *Service) putSimply(filepath string, r io.Reader) chan data.UploadStatus {
upl := s3manager.NewUploader(s.Session)
_, err := upl.Upload(&s3manager.UploadInput{
Bucket: aws.String(s.Bucket),
Key: aws.String(filepath),
Body: r,
})
ch := make(chan data.UploadStatus, 1)
if err != nil {
ch <- data.ErrUploadStatus(err)
} else {
ch <- data.OkUploadStatus()
}
return ch
}
// ChunkFileService is a data.ChunkFileService specific for FS.
type ChunkFileService struct {
Bucket string
Client *s3.S3
// Filepath stored from initialization
Filepath string
// ID provided by AWS
uploadId *string
// Completed Parts to be sent back when operation is finished.
completedParts []*s3.CompletedPart
}
// IsInitialized should return true if the ChunkFileService has already been initialized.
func (s *ChunkFileService) IsInitialized() bool {
return s.uploadId != nil
}
// InitializeChunk initializes the chunk upload operation.
func (s *ChunkFileService) InitializeChunk(u *data.ChunkUpload) error {
resp, err := s.Client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{
Bucket: aws.String(s.Bucket),
Key: aws.String(u.Filepath),
})
if err != nil {
return err
}
s.uploadId = resp.UploadId
s.Filepath = u.Filepath
return nil
}
// UploadPart should upload the provided bytes to the cloud. Uploaded parts should be completely sequential.
func (s *ChunkFileService) UploadPart(part []byte) error {
currPartNum := len(s.completedParts) + 1
res, err := s.Client.UploadPart(&s3.UploadPartInput{
Body: bytes.NewReader(part),
Bucket: aws.String(s.Bucket),
Key: aws.String(s.Filepath),
PartNumber: aws.Int64(int64(currPartNum)),
UploadId: s.uploadId,
ContentLength: aws.Int64(int64(len(part))),
})
if err != nil {
return err
}
s.completedParts = append(s.completedParts, &s3.CompletedPart{
PartNumber: aws.Int64(int64(currPartNum)),
ETag: res.ETag,
})
return nil
}
// CompleteUpload should perform any necessary steps to finalize the multipart upload.
func (s *ChunkFileService) CompleteUpload() error {
_, err := s.Client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
Bucket: aws.String(s.Bucket),
Key: aws.String(s.Filepath),
UploadId: s.uploadId,
MultipartUpload: &s3.CompletedMultipartUpload{
Parts: s.completedParts,
},
})
return err
}
// Cleanup should delete the ChunkFileService and do any other cleanup necessary. It is only called when an
// incomplete upload has timed out.
func (s *ChunkFileService) Cleanup() {
// do nothing for now.
}