-
Notifications
You must be signed in to change notification settings - Fork 0
/
blob.go
358 lines (310 loc) · 11 KB
/
blob.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
346
347
348
349
350
351
352
353
354
355
356
357
358
// Copyright 2018 The Go Cloud Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package blob provides an easy way to interact with Blob objects within
// a bucket. It utilizes standard io packages to handle reads and writes.
package blob
import (
"bytes"
"context"
"errors"
"mime"
"net/http"
"regexp"
"time"
"github.com/Lioric/go-cloud/blob/driver"
)
// Reader implements io.ReadCloser to read a blob. It must be closed after
// reads are finished.
type Reader struct {
r driver.Reader
}
// Read implements io.ReadCloser to read from this reader.
func (r *Reader) Read(p []byte) (int, error) {
return r.r.Read(p)
}
// Close implements io.ReadCloser to close this reader.
func (r *Reader) Close() error {
return r.r.Close()
}
// ContentType returns the MIME type of the blob object.
func (r *Reader) ContentType() string {
return r.r.Attrs().ContentType
}
// Size returns the content size of the blob object.
func (r *Reader) Size() int64 {
return r.r.Attrs().Size
}
// ModTime returns the modification time of the blob object.
// This is optional and will be time.Time zero value if unknown.
func (r *Reader) ModTime() time.Time {
return r.r.Attrs().ModTime
}
// Attrs returns metadata attributes of the blob object.
func (r *Reader) Attrs() *driver.ObjectAttrs {
return r.r.Attrs()
}
// Writer implements io.WriteCloser to write to blob. It must be closed after
// all writes are done.
type Writer struct {
w driver.Writer
// These fields exist only when w is not created in the first place when
// NewWriter is called.
//
// A ctx is stored in the Writer since we need to pass it into NewTypedWriter
// when we finish detecting the content type of the object and create the
// underlying driver.Writer. This step happens inside Write or Close and
// neither of them take a context.Context as an argument. The ctx must be set
// to nil after we have passed it.
ctx context.Context
bucket driver.Bucket
key string
opt *driver.WriterOptions
buf *bytes.Buffer
}
// sniffLen is the byte size of Writer.buf used to detect content-type.
const sniffLen = 512
// Write implements the io.Writer interface.
//
// The writes happen asynchronously, which means the returned error can be nil
// even if the actual write fails. Use the error returned from Close to
// check and handle errors.
func (w *Writer) Write(p []byte) (n int, err error) {
if w.w != nil {
return w.w.Write(p)
}
// If w is not yet created due to no content-type being passed in, try to sniff
// the MIME type based on at most 512 bytes of the blob content of p.
// Detect the content-type directly if the first chunk is at least 512 bytes.
if w.buf.Len() == 0 && len(p) >= sniffLen {
return w.open(p)
}
// Store p in w.buf and detect the content-type when the size of content in
// w.buf is at least 512 bytes.
w.buf.Write(p)
if w.buf.Len() >= sniffLen {
return w.open(w.buf.Bytes())
}
return len(p), nil
}
// Close flushes any buffered data and completes the Write. It is the user's
// responsibility to call it after finishing the write and handle the error if returned.
func (w *Writer) Close() error {
if w.w != nil {
return w.w.Close()
}
if _, err := w.open(w.buf.Bytes()); err != nil {
return err
}
return w.w.Close()
}
// open tries to detect the MIME type of p and write it to the blob.
func (w *Writer) open(p []byte) (n int, err error) {
ct := http.DetectContentType(p)
if w.w, err = w.bucket.NewTypedWriter(w.ctx, w.key, ct, w.opt); err != nil {
return 0, err
}
w.buf = nil
w.ctx = nil
w.key = ""
w.opt = nil
return w.w.Write(p)
}
// Bucket manages the underlying blob service and provides read, write and delete
// operations on given object within it.
type Bucket struct {
b driver.Bucket
}
// NewBucket creates a new Bucket for a group of objects for a blob service.
func NewBucket(b driver.Bucket) *Bucket {
return &Bucket{b: b}
}
// CreateUserArea setups a new area with the given id
//
// only local filesystem need to support this
// object storage based providers use object whole path as its key, so there is no need to pre create or setup its area
func (b *Bucket) CreateArea(ctx context.Context, area string, groups []string) error {
return b.b.CreateArea(ctx, area, groups)
}
// Attributes returns attributes for the blob. If the specified object does
// not exist, Attributes must return an error for which ErrorCode returns
// gcerrors.NotFound.
// The portable type will not modify the returned Attributes.
func (b *Bucket) Attributes(ctx context.Context, key string, isUID bool) (*driver.ObjectAttrs, error) {
attrs, err := b.b.Attributes(ctx, key, isUID)
return attrs, newBlobError(err)
}
// NewReader returns a Reader to read from an object, or an error when the object
// is not found by the given key, which can be checked by calling IsNotExist.
//
// The caller must call Close on the returned Reader when done reading.
// if exactName is true, the underlaying implementation must use the name exactly as provided
func (b *Bucket) NewReader(ctx context.Context, key string, exactKeyName bool) (*Reader, error) {
return b.NewRangeReader(ctx, key, 0, -1, exactKeyName)
}
// NewRangeReader returns a Reader that reads part of an object, reading at
// most length bytes starting at the given offset. If length is 0, it will read
// only the metadata. If length is negative, it will read till the end of the
// object. It returns an error if that object does not exist, which can be
// checked by calling IsNotExist.
//
// The caller must call Close on the returned Reader when done reading.
func (b *Bucket) NewRangeReader(ctx context.Context, key string, offset, length int64, exactKeyName bool) (*Reader, error) {
if offset < 0 {
return nil, errors.New("new blob range reader: offset must be non-negative")
}
r, err := b.b.NewRangeReader(ctx, key, offset, length, exactKeyName)
return &Reader{r: r}, newBlobError(err)
}
// NewWriter returns a Writer that writes to an object associated with key.
//
// A new object will be created unless an object with this key already exists.
// Otherwise any previous object with the same key will be replaced. The object
// is not guaranteed to be available until Close has been called.
//
// The call may store the ctx for later use in Write and/or Close. The ctx
// must remain open until the returned Writer is closed.
//
// The caller must call Close on the returned Writer when done writing.
func (b *Bucket) NewWriter(ctx context.Context, key string, opt *WriterOptions) (*Writer, error) {
var dopt *driver.WriterOptions
var w driver.Writer
if opt != nil {
dopt = &driver.WriterOptions{
BufferSize: opt.BufferSize,
// Tiddler metadata
Id: opt.Id,
Name: opt.Name,
Revision: opt.Revision,
Metadata: opt.Meta,
Extra: opt.Extra,
ContentSize: opt.ContentSize,
}
if opt.ContentType != "" {
t, p, err := mime.ParseMediaType(opt.ContentType)
if err != nil {
return nil, err
}
ct := mime.FormatMediaType(t, p)
w, err = b.b.NewTypedWriter(ctx, key, ct, dopt)
return &Writer{w: w}, err
}
}
return &Writer{
ctx: ctx,
bucket: b.b,
key: key,
opt: dopt,
buf: bytes.NewBuffer([]byte{}),
}, nil
}
// Move the object associated with key to a new location. It returns an error if that
// object does not exist, which can be checked by calling IsNotExist.
func (b *Bucket) Move(ctx context.Context, keySrc string, keyDst string) error {
return newBlobError(b.b.Move(ctx, keySrc, keyDst))
}
// Delete deletes the object associated with key. It returns an error if that
// object does not exist, which can be checked by calling IsNotExist.
func (b *Bucket) Delete(ctx context.Context, key string) error {
return newBlobError(b.b.Delete(ctx, key))
}
// WriterOptions controls Writer behaviors.
type WriterOptions struct {
// BufferSize changes the default size in bytes of the maximum part Writer can
// write in a single request. Larger objects will be split into multiple requests.
//
// The support specification of this operation varies depending on the underlying
// blob service. If zero value is given, it is set to a reasonable default value.
// If negative value is given, it will be either disabled (if supported by the
// service), which means Writer will write as a whole, or reset to default value.
// It could be a no-op when not supported at all.
//
// If the Writer is used to write small objects concurrently, set the buffer size
// to a smaller size to avoid high memory usage.
BufferSize int
// ContentType specifies the MIME type of the object being written. If not set,
// then it will be inferred from the content using the algorithm described at
// http://mimesniff.spec.whatwg.org/
ContentType string
// Tiddler metadata
Meta map[string]string
Revision int
// Extra options for platform specific implementations
Id int
Name string
Extra map[string]string
// Size of the text segment
ContentSize int
}
type blobError struct {
msg string
kind driver.ErrorKind
}
func (e *blobError) Error() string {
return e.msg
}
func newBlobError(err error) error {
if err == nil {
return nil
}
berr := &blobError{msg: err.Error()}
if e, ok := err.(driver.Error); ok {
berr.kind = e.BlobError()
}
return berr
}
// IsNotExist returns whether an error is a driver.Error with NotFound kind.
func IsNotExist(err error) bool {
if e, ok := err.(*blobError); ok {
return e.kind == driver.NotFound
}
return false
}
var sObjectNameChars *regexp.Regexp
func init() {
// TASK: review valid file name characters in different platforms
// Amazon characters to avoid:
// Backslash ("\")
// Left curly brace ("{")
// Non-printable ASCII characters (128–255 decimal characters)
// Caret ("^")
// Right curly brace ("}")
// Percent character ("%")
// Grave accent / back tick ("`")
// Right square bracket ("]")
// Quotation marks
// 'Greater Than' symbol (">")
// Left square bracket ("[")
// Tilde ("~")
// 'Less Than' symbol ("<")
// 'Pound' character ("#")
// Vertical bar / pipe ("|")
// Google Cloud characters to avoid:
// [ ] * ? #
// Windows characters to avoid
// < > : " / \ | ? *
sObjectNameChars = regexp.MustCompile(`<|>|\:|\"|\||\?|\*|\^|~|\'`)
}
func GetBlobName(name string) string {
objName := name
// var objName string
// // TASK: review system prefix
// if strings.HasPrefix(name, "$:/") {
// objName = strings.Replace(name, "$:/", "_system/", 1)
// } else {
// objName = name
// }
// cleanup (and sanitize) resulting blob name (replace non valid characters)
blobName := sObjectNameChars.ReplaceAllLiteralString(objName, "_")
return blobName
}