-
Notifications
You must be signed in to change notification settings - Fork 13
/
s3.go
310 lines (241 loc) · 8.41 KB
/
s3.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
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
package s3
import (
"bytes"
"context"
"encoding/base64"
"os"
"path/filepath"
"strconv"
"text/template"
"time"
"github.com/aws/aws-sdk-go/aws"
"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/latolukasz/beeorm"
"github.com/coretrix/hitrix/pkg/entity"
)
type AmazonS3 struct {
client *s3.S3
ctx context.Context
environment string
bucketsMapping map[string]uint64
bucketsConfigDefinitions map[string]map[string]string
bucketsPublicUrls map[string]map[string]string
}
func NewAmazonS3(endpoint string,
accessKeyID string,
secretAccessKey string,
allowedBuckets map[string]uint64,
bucketsConfigDefinitions map[string]map[string]string,
bucketsPublicURLConfigMap map[string]map[string]string,
region string,
disableSSL bool,
environment string) *AmazonS3 {
s3Config := &aws.Config{
Credentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, ""),
Endpoint: aws.String(endpoint),
S3ForcePathStyle: aws.Bool(true),
Region: aws.String(region),
DisableSSL: aws.Bool(disableSSL),
}
newSession, _ := session.NewSession(s3Config)
s3Client := s3.New(newSession)
return &AmazonS3{
client: s3Client,
ctx: context.Background(),
bucketsMapping: allowedBuckets,
bucketsConfigDefinitions: bucketsConfigDefinitions,
environment: environment,
bucketsPublicUrls: bucketsPublicURLConfigMap,
}
}
func (amazonS3 *AmazonS3) getCounter(ormService *beeorm.Engine, bucket string) uint64 {
amazonS3.checkBucket(bucket)
bucketID, has := amazonS3.bucketsMapping[bucket]
if !has {
panic("s3 bucket [" + bucket + "] id not found")
}
amazonS3BucketCounterEntity := &entity.OSSBucketCounterEntity{}
locker := ormService.GetRedis().GetLocker()
lock, hasLock := locker.Obtain("locker_amazon_s3_counters_bucket_"+bucket, 2*time.Second, 5*time.Second)
defer lock.Release()
if !hasLock {
panic("Failed to obtain lock for locker_amazon_s3_counters_bucket_" + bucket)
}
has = ormService.LoadByID(bucketID, amazonS3BucketCounterEntity)
if !has {
amazonS3BucketCounterEntity.ID = bucketID
amazonS3BucketCounterEntity.Counter = 1
} else {
amazonS3BucketCounterEntity.Counter = amazonS3BucketCounterEntity.Counter + 1
}
ormService.Flush(amazonS3BucketCounterEntity)
ttl := lock.TTL()
if ttl == 0 {
panic("lock lost")
}
return amazonS3BucketCounterEntity.Counter
}
func (amazonS3 *AmazonS3) checkBucket(bucketName string) {
_, ok := amazonS3.bucketsMapping[bucketName]
if !ok {
panic("bucket [" + bucketName + "] not found")
}
}
func (amazonS3 *AmazonS3) getBucketName(bucketName string) string {
if bucketConfig, ok := amazonS3.bucketsConfigDefinitions[bucketName]; ok {
if bucket, ok := bucketConfig[amazonS3.environment]; ok {
return bucket
}
}
return ""
}
func (amazonS3 *AmazonS3) DeleteObject(bucket string, objects ...*entity.FileObject) bool {
objectIds := make([]*s3.ObjectIdentifier, len(objects))
for i, file := range objects {
objectIds[i] = &s3.ObjectIdentifier{
Key: aws.String(file.StorageKey),
}
}
input := s3.DeleteObjectsInput{
Bucket: aws.String(amazonS3.getBucketName(bucket)),
Delete: &s3.Delete{Objects: objectIds},
}
deletedObjects, err := amazonS3.client.DeleteObjects(&input)
if err != nil {
panic("s3BucketObjectsDelete:" + err.Error())
}
return len(deletedObjects.Deleted) == len(objects)
}
func (amazonS3 *AmazonS3) putObject(ormService *beeorm.Engine, bucket string, objectContent []byte, extension string) Object {
storageCounter := amazonS3.getCounter(ormService, bucket)
objectKey := amazonS3.getObjectKey(storageCounter, extension)
bucket = amazonS3.getBucketName(bucket)
_, err := amazonS3.client.PutObject(&s3.PutObjectInput{
Body: bytes.NewReader(objectContent),
Bucket: aws.String(bucket),
Key: aws.String(objectKey),
})
if err != nil {
panic("s3BucketObjectPut:" + err.Error())
}
return Object{
ID: storageCounter,
StorageKey: objectKey,
}
}
func (amazonS3 *AmazonS3) getObjectKey(storageCounter uint64, fileExtension string) string {
return strconv.FormatUint(storageCounter, 10) + fileExtension
}
func (amazonS3 *AmazonS3) UploadObjectFromFile(ormService *beeorm.Engine, bucket, localFile string) Object {
amazonS3.checkBucket(bucket)
fileContent, ext := amazonS3.ReadFile(localFile)
return amazonS3.putObject(ormService, bucket, fileContent, ext)
}
func (amazonS3 *AmazonS3) UploadObjectFromBase64(ormService *beeorm.Engine, bucket, base64content, extension string) Object {
byteData, err := base64.StdEncoding.DecodeString(base64content)
if err != nil {
panic(err)
}
return amazonS3.putObject(ormService, bucket, byteData, extension)
}
func (amazonS3 *AmazonS3) UploadObjectFromByte(ormService *beeorm.Engine, bucket string, byteData []byte, extension string) Object {
return amazonS3.putObject(ormService, bucket, byteData, extension)
}
func (amazonS3 *AmazonS3) UploadImageFromBase64(ormService *beeorm.Engine, bucket, base64image, extension string) Object {
byteData, err := base64.StdEncoding.DecodeString(base64image)
if err != nil {
panic(err)
}
return amazonS3.putObject(ormService, bucket, byteData, extension)
}
func (amazonS3 *AmazonS3) UploadImageFromFile(ormService *beeorm.Engine, bucket, localFile string) Object {
return amazonS3.UploadObjectFromFile(ormService, bucket, localFile)
}
func (amazonS3 *AmazonS3) ReadFile(localFile string) ([]byte, string) {
fileContent, err := os.ReadFile(localFile)
if err != nil {
panic(err)
}
return fileContent, filepath.Ext(localFile)
}
type CachedObjectURLTemplate struct {
Environment string
BucketName string
StorageKey string
CounterID string
}
func (amazonS3 *AmazonS3) getPublicUrlsForBucket(bucketName string) string {
if bucketConfig, ok := amazonS3.bucketsPublicUrls[bucketName]; ok {
if url, ok := bucketConfig[amazonS3.environment]; ok {
return url
}
}
return ""
}
func (amazonS3 *AmazonS3) GetObjectCachedURL(bucket string, object *entity.FileObject) string {
amazonS3.checkBucket(bucket)
url := amazonS3.getPublicUrlsForBucket(bucket)
obj := CachedObjectURLTemplate{
Environment: amazonS3.environment,
BucketName: bucket,
StorageKey: object.StorageKey,
CounterID: strconv.FormatUint(object.ID, 10),
}
temp, err := template.New("amazon").Parse(url)
if err != nil {
panic("failed creating new template for amazon s3")
}
buf := new(bytes.Buffer)
err = temp.Execute(buf, obj)
if err != nil {
panic("failed executing the new template for amazon s3")
}
text := buf.String()
return text
}
func (amazonS3 *AmazonS3) GetObjectSignedURL(bucket string, object *entity.FileObject, expiresIn time.Duration) string {
amazonS3.checkBucket(bucket)
bucketByEnv := amazonS3.getBucketName(bucket)
req, _ := amazonS3.client.GetObjectRequest(&s3.GetObjectInput{
Bucket: aws.String(bucketByEnv),
Key: aws.String(object.StorageKey)},
)
url, err := req.Presign(expiresIn) // Set link expiration time
if err != nil {
panic(err)
}
return url
}
func (amazonS3 *AmazonS3) CreateObjectFromKey(ormService *beeorm.Engine, bucket, key string) Object {
return Object{
ID: amazonS3.getCounter(ormService, bucket),
StorageKey: key,
}
}
func (amazonS3 *AmazonS3) GetClient() interface{} {
return amazonS3.client
}
func (amazonS3 *AmazonS3) GetBucketName(bucket string) string {
return amazonS3.bucketsConfigDefinitions[bucket][amazonS3.environment]
}
type Object struct {
ID uint64
StorageKey string
CachedURL string
Data interface{}
}
type Client interface {
GetClient() interface{}
GetBucketName(bucket string) string
CreateObjectFromKey(ormService *beeorm.Engine, bucket, key string) Object
GetObjectCachedURL(bucket string, object *entity.FileObject) string
GetObjectSignedURL(bucket string, object *entity.FileObject, expires time.Duration) string
UploadObjectFromFile(ormService *beeorm.Engine, bucket, localFile string) Object
UploadObjectFromBase64(ormService *beeorm.Engine, bucket, content, extension string) Object
UploadObjectFromByte(ormService *beeorm.Engine, bucket string, data []byte, extension string) Object
UploadImageFromFile(ormService *beeorm.Engine, bucket, localFile string) Object
UploadImageFromBase64(ormService *beeorm.Engine, bucket, image, extension string) Object
DeleteObject(bucket string, objects ...*entity.FileObject) bool
}