This repository has been archived by the owner on Oct 22, 2021. It is now read-only.
generated from beyondstorage/go-service-example
-
Notifications
You must be signed in to change notification settings - Fork 1
/
storage.go
345 lines (285 loc) · 8.07 KB
/
storage.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
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
package kodo
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"time"
qs "github.com/qiniu/go-sdk/v7/storage"
ps "github.com/beyondstorage/go-storage/v4/pairs"
"github.com/beyondstorage/go-storage/v4/pkg/iowrap"
"github.com/beyondstorage/go-storage/v4/services"
. "github.com/beyondstorage/go-storage/v4/types"
)
func (s *Storage) create(path string, opt pairStorageCreate) (o *Object) {
rp := s.getAbsPath(path)
if opt.HasObjectMode && opt.ObjectMode.IsDir() {
if !s.features.VirtualDir {
return
}
rp += "/"
o = s.newObject(true)
o.Mode = ModeDir
} else {
o = s.newObject(false)
o.Mode = ModeRead
}
o.ID = rp
o.Path = path
return o
}
func (s *Storage) createDir(ctx context.Context, path string, opt pairStorageCreateDir) (o *Object, err error) {
if !s.features.VirtualDir {
err = NewOperationNotImplementedError("create_dir")
return
}
rp := s.getAbsPath(path)
// Add `/` at the end of `path` to simulate a directory.
// ref: https://developer.qiniu.com/kodo/kb/1705/how-to-create-the-folder-under-the-space
rp += "/"
// kodo `put` doesn't support `overwrite`, so we need to check whether the dir exists.
// ref: [GSP-134](https://github.com/beyondstorage/go-storage/blob/master/docs/rfcs/134-write-behavior-consistency.md)
fi, err := s.bucket.Stat(s.name, rp)
if err == nil {
// The dir is exist.
o = s.newObject(true)
o.SetLastModified(convertUnixTimestampToTime(fi.PutTime))
o.SetContentLength(fi.Fsize)
var sm ObjectSystemMetadata
sm.StorageClass = fi.Type
o.SetSystemMetadata(sm)
} else if !checkError(err, responseCodeResourceNotExist) {
// Something error other then ResourceNotExist happened, return directly.
return
} else {
// The dir is not exist, we should create the dir.
uploader := qs.NewFormUploader(s.bucket.Cfg)
ret := qs.PutRet{}
err = uploader.Put(ctx,
&ret, s.putPolicy.UploadToken(s.bucket.Mac), rp, io.LimitReader(nil, 0), 0, nil)
if err != nil {
return
}
o = s.newObject(false)
}
o.Path = path
o.ID = rp
o.Mode = ModeDir
return
}
func (s *Storage) delete(ctx context.Context, path string, opt pairStorageDelete) (err error) {
rp := s.getAbsPath(path)
if opt.HasObjectMode && opt.ObjectMode.IsDir() {
if !s.features.VirtualDir {
err = services.PairUnsupportedError{Pair: ps.WithObjectMode(opt.ObjectMode)}
return
}
rp += "/"
}
err = s.bucket.Delete(s.name, rp)
if err != nil && checkError(err, responseCodeResourceNotExist) {
// Omit `612`(resource to be deleted dose not exist) error code here
//
// References
// - [GSP-46](https://github.com/beyondstorage/specs/blob/master/rfcs/46-idempotent-delete.md)
// - https://developer.qiniu.com/kodo/1257/delete
err = nil
}
if err != nil {
return err
}
return nil
}
func (s *Storage) list(ctx context.Context, path string, opt pairStorageList) (oi *ObjectIterator, err error) {
input := &objectPageStatus{
limit: 1000,
prefix: s.getAbsPath(path),
}
if !opt.HasListMode {
// Support `ListModePrefix` as the default `ListMode`.
// ref: [GSP-654](https://github.com/beyondstorage/go-storage/blob/master/docs/rfcs/654-unify-list-behavior.md)
opt.ListMode = ListModePrefix
}
var nextFn NextObjectFunc
switch {
case opt.ListMode.IsDir():
input.delimiter = "/"
nextFn = s.nextObjectPageByDir
case opt.ListMode.IsPrefix():
nextFn = s.nextObjectPageByPrefix
default:
return nil, services.ListModeInvalidError{Actual: opt.ListMode}
}
return NewObjectIterator(ctx, nextFn, input), nil
}
func (s *Storage) metadata(opt pairStorageMetadata) (meta *StorageMeta) {
meta = NewStorageMeta()
meta.Name = s.name
meta.WorkDir = s.workDir
return meta
}
func (s *Storage) nextObjectPageByDir(ctx context.Context, page *ObjectPage) error {
input := page.Status.(*objectPageStatus)
entries, commonPrefix, nextMarker, _, err := s.bucket.ListFiles(
s.name,
input.prefix,
input.delimiter,
input.marker,
input.limit,
)
if err != nil {
return err
}
for _, v := range commonPrefix {
o := s.newObject(true)
o.ID = v
o.Path = s.getRelPath(v)
o.Mode |= ModeDir
page.Data = append(page.Data, o)
}
for _, v := range entries {
o, err := s.formatFileObject(v)
if err != nil {
return err
}
page.Data = append(page.Data, o)
}
if nextMarker == "" {
return IterateDone
}
input.marker = nextMarker
return nil
}
func (s *Storage) nextObjectPageByPrefix(ctx context.Context, page *ObjectPage) error {
input := page.Status.(*objectPageStatus)
entries, _, nextMarker, _, err := s.bucket.ListFiles(
s.name,
input.prefix,
input.delimiter,
input.marker,
input.limit,
)
if err != nil {
return err
}
for _, v := range entries {
o, err := s.formatFileObject(v)
if err != nil {
return err
}
page.Data = append(page.Data, o)
}
if nextMarker == "" {
return IterateDone
}
input.marker = nextMarker
return nil
}
func (s *Storage) read(ctx context.Context, path string, w io.Writer, opt pairStorageRead) (n int64, err error) {
rp := s.getAbsPath(path)
deadline := time.Now().Add(time.Hour).Unix()
url := qs.MakePrivateURL(s.bucket.Mac, s.domain, rp, deadline)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return 0, err
}
// ref: https://developer.qiniu.com/kodo/1232/download-process
if opt.HasOffset && !opt.HasSize {
rangeBytes := fmt.Sprintf("bytes=%d-", opt.Offset)
req.Header.Add("Range", rangeBytes)
} else if !opt.HasOffset && opt.HasSize {
rangeBytes := fmt.Sprintf("bytes=0-%d", opt.Size-1)
req.Header.Add("Range", rangeBytes)
} else if opt.HasOffset && opt.HasSize {
rangeBytes := fmt.Sprintf("bytes=%d-%d", opt.Offset, opt.Offset+opt.Size-1)
req.Header.Add("Range", rangeBytes)
}
resp, err := s.bucket.Client.Do(ctx, req)
if err != nil {
return 0, err
}
defer func() {
cerr := resp.Body.Close()
if cerr != nil {
err = cerr
}
}()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
err = qs.ResponseError(resp)
return 0, err
}
rc := resp.Body
if opt.HasIoCallback {
rc = iowrap.CallbackReadCloser(resp.Body, opt.IoCallback)
}
return io.Copy(w, rc)
}
func (s *Storage) stat(ctx context.Context, path string, opt pairStorageStat) (o *Object, err error) {
rp := s.getAbsPath(path)
if opt.HasObjectMode && opt.ObjectMode.IsDir() {
if !s.features.VirtualDir {
err = services.PairUnsupportedError{Pair: ps.WithObjectMode(opt.ObjectMode)}
return
}
rp += "/"
}
fi, err := s.bucket.Stat(s.name, rp)
if err != nil {
return nil, err
}
o = s.newObject(true)
o.ID = rp
o.Path = path
if opt.HasObjectMode && opt.ObjectMode.IsDir() {
o.Mode |= ModeDir
} else {
o.Mode |= ModeRead
}
o.SetLastModified(convertUnixTimestampToTime(fi.PutTime))
o.SetContentLength(fi.Fsize)
if fi.Hash != "" {
o.SetEtag(fi.Hash)
}
if fi.MimeType != "" {
o.SetContentType(fi.MimeType)
}
var sm ObjectSystemMetadata
sm.StorageClass = fi.Type
o.SetSystemMetadata(sm)
return o, nil
}
func (s *Storage) write(ctx context.Context, path string, r io.Reader, size int64, opt pairStorageWrite) (n int64, err error) {
rp := s.getAbsPath(path)
// According to GSP-751, we should allow the user to pass in a nil io.Reader.
// ref: https://github.com/beyondstorage/go-storage/blob/master/docs/rfcs/751-write-empty-file-behavior.md
if r == nil && size == 0 {
r = bytes.NewReader([]byte{})
} else if r == nil && size != 0 {
return 0, fmt.Errorf("reader is nil but size is not 0")
} else {
r = io.LimitReader(r, size)
}
// kodo `put` doesn't support `overwrite`, so we need to check and delete the object if exists.
// ref: [GSP-134](https://github.com/beyondstorage/go-storage/blob/master/docs/rfcs/134-write-behavior-consistency.md)
_, err = s.bucket.Stat(s.name, rp)
if err == nil {
err = s.bucket.Delete(s.name, rp)
if err != nil {
return
}
} else if !checkError(err, responseCodeResourceNotExist) {
return
}
if opt.HasIoCallback {
r = iowrap.CallbackReader(r, opt.IoCallback)
}
uploader := qs.NewFormUploader(s.bucket.Cfg)
ret := qs.PutRet{}
err = uploader.Put(ctx,
&ret, s.putPolicy.UploadToken(s.bucket.Mac), rp, r, size, nil)
if err != nil {
return
}
return size, nil
}