Debian Codegraph @

blob/driver/driver.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package driver defines interfaces to be implemented by blob drivers, which
16 // will be used by the blob package to interact with the underlying services.
17 // Application code should use package blob.
18 package driver // import "gocloud.dev/blob/driver"
19
20 import (
21 "context"
22 "errors"
23 "io"
24 "strings"
25 "time"
26
27 "gocloud.dev/gcerrors"
28 )
29
30 // ReaderOptions controls Reader behaviors.
31 type ReaderOptions struct {
32 // BeforeRead is a callback that must be called exactly once before
33 // any data is read, unless NewRangeReader returns an error before then, in
34 // which case it should not be called at all.
35 // asFunc allows drivers to expose driver-specific types;
36 // see Bucket.As for more details.
37 BeforeRead func(asFunc func(any) bool) error
38 }
39
40 // Reader reads an object from the blob.
41 type Reader interface {
42 io.ReadCloser
43
44 // Attributes returns a subset of attributes about the blob.
45 // The portable type will not modify the returned ReaderAttributes.
46 Attributes() *ReaderAttributes
47
48 // As allows drivers to expose driver-specific types;
49 // see Bucket.As for more details.
50 As(any) bool
51 }
52
53 // Downloader has an optional extra method for readers.
54 // It is similar to io.WriteTo, but without the count of bytes returned.
55 type Downloader interface {
56 // Download is similar to io.WriteTo, but without the count of bytes returned.
57 Download(w io.Writer) error
58 }
59
60 // Writer writes an object to the blob.
61 type Writer interface {
62 io.WriteCloser
63 }
64
65 // Uploader has an optional extra method for writers.
66 type Uploader interface {
67 // Upload is similar to io.ReadFrom, but without the count of bytes returned.
68 Upload(r io.Reader) error
69 }
70
71 // WriterOptions controls behaviors of Writer.
72 type WriterOptions struct {
73 // BufferSize changes the default size in byte of the maximum part Writer can
74 // write in a single request, if supported. Larger objects will be split into
75 // multiple requests.
76 BufferSize int
77 // MaxConcurrency changes the default concurrency for uploading parts.
78 MaxConcurrency int
79 // CacheControl specifies caching attributes that services may use
80 // when serving the blob.
81 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
82 CacheControl string
83 // ContentDisposition specifies whether the blob content is expected to be
84 // displayed inline or as an attachment.
85 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
86 ContentDisposition string
87 // ContentEncoding specifies the encoding used for the blob's content, if any.
88 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
89 ContentEncoding string
90 // ContentLanguage specifies the language used in the blob's content, if any.
91 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language
92 ContentLanguage string
93 // ContentMD5 is used as a message integrity check.
94 // The portable type checks that the MD5 hash of the bytes written matches
95 // ContentMD5.
96 // If len(ContentMD5) > 0, driver implementations may pass it to their
97 // underlying network service to guarantee the integrity of the bytes in
98 // transit.
99 ContentMD5 []byte
100 // Metadata holds key/value strings to be associated with the blob.
101 // Keys are guaranteed to be non-empty and lowercased.
102 Metadata map[string]string
103 // When true, the driver should attempt to disable any automatic
104 // content-type detection that the provider applies on writes with an
105 // empty ContentType.
106 DisableContentTypeDetection bool
107 // BeforeWrite is a callback that must be called exactly once before
108 // any data is written, unless NewTypedWriter returns an error, in
109 // which case it should not be called.
110 // asFunc allows drivers to expose driver-specific types;
111 // see Bucket.As for more details.
112 BeforeWrite func(asFunc func(any) bool) error
113
114 // IfNotExist is used for conditional writes.
115 // When set to true, if a blob exists for the same key in the bucket, the write operation
116 // won't take place.
117 IfNotExist bool
118 }
119
120 // CopyOptions controls options for Copy.
121 type CopyOptions struct {
122 // BeforeCopy is a callback that must be called before initiating the Copy.
123 // asFunc allows drivers to expose driver-specific types;
124 // see Bucket.As for more details.
125 BeforeCopy func(asFunc func(any) bool) error
126 }
127
128 // ReaderAttributes contains a subset of attributes about a blob that are
129 // accessible from Reader.
130 type ReaderAttributes struct {
131 // ContentType is the MIME type of the blob object. It must not be empty.
132 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
133 ContentType string
134 // ModTime is the time the blob object was last modified.
135 ModTime time.Time
136 // Size is the size of the object in bytes.
137 Size int64
138 }
139
140 // Attributes contains attributes about a blob.
141 type Attributes struct {
142 // CacheControl specifies caching attributes that services may use
143 // when serving the blob.
144 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
145 CacheControl string
146 // ContentDisposition specifies whether the blob content is expected to be
147 // displayed inline or as an attachment.
148 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
149 ContentDisposition string
150 // ContentEncoding specifies the encoding used for the blob's content, if any.
151 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
152 ContentEncoding string
153 // ContentLanguage specifies the language used in the blob's content, if any.
154 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language
155 ContentLanguage string
156 // ContentType is the MIME type of the blob object. It must not be empty.
157 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
158 ContentType string
159 // Metadata holds key/value pairs associated with the blob.
160 // Keys will be lowercased by the portable type before being returned
161 // to the user. If there are duplicate case-insensitive keys (e.g.,
162 // "foo" and "FOO"), only one value will be kept, and it is undefined
163 // which one.
164 Metadata map[string]string
165 // CreateTime is the time the blob object was created. If not available,
166 // leave as the zero time.
167 CreateTime time.Time
168 // ModTime is the time the blob object was last modified.
169 ModTime time.Time
170 // Size is the size of the object in bytes.
171 Size int64
172 // MD5 is an MD5 hash of the blob contents or nil if not available.
173 MD5 []byte
174 // ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag.
175 ETag string
176 // AsFunc allows drivers to expose driver-specific types;
177 // see Bucket.As for more details.
178 // If not set, no driver-specific types are supported.
179 AsFunc func(any) bool
180 }
181
182 // ListOptions sets options for listing objects in the bucket.
183 type ListOptions struct {
184 // Prefix indicates that only results with the given prefix should be
185 // returned.
186 Prefix string
187 // Delimiter sets the delimiter used to define a hierarchical namespace,
188 // like a filesystem with "directories".
189 //
190 // An empty delimiter means that the bucket is treated as a single flat
191 // namespace.
192 //
193 // A non-empty delimiter means that any result with the delimiter in its key
194 // after Prefix is stripped will be returned with ListObject.IsDir = true,
195 // ListObject.Key truncated after the delimiter, and zero values for other
196 // ListObject fields. These results represent "directories". Multiple results
197 // in a "directory" are returned as a single result.
198 Delimiter string
199 // PageSize sets the maximum number of objects to be returned.
200 // 0 means no maximum; driver implementations should choose a reasonable
201 // max. It is guaranteed to be >= 0.
202 PageSize int
203 // PageToken may be filled in with the NextPageToken from a previous
204 // ListPaged call.
205 PageToken []byte
206 // BeforeList is a callback that must be called exactly once during ListPaged,
207 // before the underlying service's list is executed.
208 // asFunc allows drivers to expose driver-specific types;
209 // see Bucket.As for more details.
210 BeforeList func(asFunc func(any) bool) error
211 }
212
213 // ListObject represents a specific blob object returned from ListPaged.
214 type ListObject struct {
215 // Key is the key for this blob.
216 Key string
217 // ModTime is the time the blob object was last modified.
218 ModTime time.Time
219 // Size is the size of the object in bytes.
220 Size int64
221 // MD5 is an MD5 hash of the blob contents or nil if not available.
222 MD5 []byte
223 // IsDir indicates that this result represents a "directory" in the
224 // hierarchical namespace, ending in ListOptions.Delimiter. Key can be
225 // passed as ListOptions.Prefix to list items in the "directory".
226 // Fields other than Key and IsDir will not be set if IsDir is true.
227 IsDir bool
228 // AsFunc allows drivers to expose driver-specific types;
229 // see Bucket.As for more details.
230 // If not set, no driver-specific types are supported.
231 AsFunc func(any) bool
232 }
233
234 // ListPage represents a page of results return from ListPaged.
235 type ListPage struct {
236 // Objects is the slice of objects found. If ListOptions.PageSize > 0,
237 // it should have at most ListOptions.PageSize entries.
238 //
239 // Objects should be returned in lexicographical order of UTF-8 encoded keys,
240 // including across pages. I.e., all objects returned from a ListPage request
241 // made using a PageToken from a previous ListPage request's NextPageToken
242 // should have Key >= the Key for all objects from the previous request.
243 Objects []*ListObject
244 // NextPageToken should be left empty unless there are more objects
245 // to return. The value may be returned as ListOptions.PageToken on a
246 // subsequent ListPaged call, to fetch the next page of results.
247 // It can be an arbitrary []byte; it need not be a valid key.
248 NextPageToken []byte
249 }
250
251 // Bucket provides read, write and delete operations on objects within it on the
252 // blob service.
253 type Bucket interface {
254 // ErrorCode should return a code that describes the error, which was returned by
255 // one of the other methods in this interface.
256 ErrorCode(error) gcerrors.ErrorCode
257
258 // As converts i to driver-specific types.
259 // See https://gocloud.dev/concepts/as/ for background information.
260 As(i any) bool
261
262 // ErrorAs allows drivers to expose driver-specific types for returned
263 // errors.
264 // See https://gocloud.dev/concepts/as/ for background information.
265 ErrorAs(error, any) bool
266
267 // Attributes returns attributes for the blob. If the specified object does
268 // not exist, Attributes must return an error for which ErrorCode returns
269 // gcerrors.NotFound.
270 // The portable type will not modify the returned Attributes.
271 Attributes(ctx context.Context, key string) (*Attributes, error)
272
273 // ListPaged lists objects in the bucket, in lexicographical order by
274 // UTF-8-encoded key, returning pages of objects at a time.
275 // Services are only required to be eventually consistent with respect
276 // to recently written or deleted objects. That is to say, there is no
277 // guarantee that an object that's been written will immediately be returned
278 // from ListPaged.
279 // opts is guaranteed to be non-nil.
280 ListPaged(ctx context.Context, opts *ListOptions) (*ListPage, error)
281
282 // NewRangeReader returns a Reader that reads part of an object, reading at
283 // most length bytes starting at the given offset. If length is negative, it
284 // will read until the end of the object. If the specified object does not
285 // exist, NewRangeReader must return an error for which ErrorCode returns
286 // gcerrors.NotFound.
287 // opts is guaranteed to be non-nil.
288 //
289 // The returned Reader *may* also implement Downloader if the underlying
290 // implementation can take advantage of that. The Download call is guaranteed
291 // to be the only call to the Reader. For such readers, offset will always
292 // be 0 and length will always be -1.
293 NewRangeReader(ctx context.Context, key string, offset, length int64, opts *ReaderOptions) (Reader, error)
294
295 // NewTypedWriter returns Writer that writes to an object associated with key.
296 //
297 // A new object will be created unless an object with this key already exists.
298 // Otherwise any previous object with the same key will be replaced.
299 // The object may not be available (and any previous object will remain)
300 // until Close has been called.
301 //
302 // contentType sets the MIME type of the object to be written.
303 // opts is guaranteed to be non-nil.
304 //
305 // The caller must call Close on the returned Writer when done writing.
306 //
307 // Implementations should abort an ongoing write if ctx is later canceled,
308 // and do any necessary cleanup in Close. Close should then return ctx.Err().
309 //
310 // The returned Writer *may* also implement Uploader if the underlying
311 // implementation can take advantage of that. The Upload call is guaranteed
312 // to be the only non-Close call to the Writer..
313 NewTypedWriter(ctx context.Context, key, contentType string, opts *WriterOptions) (Writer, error)
314
315 // Copy copies the object associated with srcKey to dstKey.
316 //
317 // If the source object does not exist, Copy must return an error for which
318 // ErrorCode returns gcerrors.NotFound.
319 //
320 // If the destination object already exists, it should be overwritten.
321 //
322 // opts is guaranteed to be non-nil.
323 Copy(ctx context.Context, dstKey, srcKey string, opts *CopyOptions) error
324
325 // Delete deletes the object associated with key. If the specified object does
326 // not exist, Delete must return an error for which ErrorCode returns
327 // gcerrors.NotFound.
328 Delete(ctx context.Context, key string) error
329
330 // SignedURL returns a URL that can be used to GET the blob for the duration
331 // specified in opts.Expiry. opts is guaranteed to be non-nil.
332 // If not supported, return an error for which ErrorCode returns
333 // gcerrors.Unimplemented.
334 SignedURL(ctx context.Context, key string, opts *SignedURLOptions) (string, error)
335
336 // Close cleans up any resources used by the Bucket. Once Close is called,
337 // there will be no method calls to the Bucket other than As, ErrorAs, and
338 // ErrorCode. There may be open readers or writers that will receive calls.
339 // It is up to the driver as to how these will be handled.
340 Close() error
341 }
342
343 // SignedURLOptions sets options for SignedURL.
344 type SignedURLOptions struct {
345 // Expiry sets how long the returned URL is valid for. It is guaranteed to be > 0.
346 Expiry time.Duration
347
348 // Method is the HTTP method that can be used on the URL; one of "GET", "PUT",
349 // or "DELETE". Drivers must implement all 3.
350 Method string
351
352 // ContentType specifies the Content-Type HTTP header the user agent is
353 // permitted to use in the PUT request. It must match exactly. See
354 // EnforceAbsentContentType for behavior when ContentType is the empty string.
355 // If this field is not empty and the bucket cannot enforce the Content-Type
356 // header, it must return an Unimplemented error.
357 //
358 // This field will not be set for any non-PUT requests.
359 ContentType string
360
361 // If EnforceAbsentContentType is true and ContentType is the empty string,
362 // then PUTing to the signed URL must fail if the Content-Type header is
363 // present or the implementation must return an error if it cannot enforce
364 // this. If EnforceAbsentContentType is false and ContentType is the empty
365 // string, implementations should validate the Content-Type header if possible.
366 // If EnforceAbsentContentType is true and the bucket cannot enforce the
367 // Content-Type header, it must return an Unimplemented error.
368 //
369 // This field will always be false for non-PUT requests.
370 EnforceAbsentContentType bool
371
372 // BeforeSign is a callback that will be called before each call to the
373 // the underlying service's sign functionality.
374 // asFunc converts its argument to driver-specific types.
375 // See https://gocloud.dev/concepts/as/ for background information.
376 BeforeSign func(asFunc func(any) bool) error
377 }
378
379 // prefixedBucket implements Bucket by prepending prefix to all keys.
380 type prefixedBucket struct {
381 base Bucket
382 prefix string
383 }
384
385 // NewPrefixedBucket returns a Bucket based on b with all keys modified to have
386 // prefix.
387 func NewPrefixedBucket(b Bucket, prefix string) Bucket {
388 return &prefixedBucket{base: b, prefix: prefix}
389 }
390
391 func (b *prefixedBucket) ErrorCode(err error) gcerrors.ErrorCode { return b.base.ErrorCode(err) }
392 func (b *prefixedBucket) As(i any) bool { return b.base.As(i) }
393 func (b *prefixedBucket) ErrorAs(err error, i any) bool { return b.base.ErrorAs(err, i) }
394 func (b *prefixedBucket) Attributes(ctx context.Context, key string) (*Attributes, error) {
395 return b.base.Attributes(ctx, b.prefix+key)
396 }
397
398 func (b *prefixedBucket) ListPaged(ctx context.Context, opts *ListOptions) (*ListPage, error) {
399 var myopts ListOptions
400 if opts != nil {
401 myopts = *opts
402 }
403 myopts.Prefix = b.prefix + myopts.Prefix
404 page, err := b.base.ListPaged(ctx, &myopts)
405 if err != nil {
406 return nil, err
407 }
408 for _, p := range page.Objects {
409 p.Key = strings.TrimPrefix(p.Key, b.prefix)
410 }
411 return page, nil
412 }
413
414 func (b *prefixedBucket) NewRangeReader(ctx context.Context, key string, offset, length int64, opts *ReaderOptions) (Reader, error) {
415 return b.base.NewRangeReader(ctx, b.prefix+key, offset, length, opts)
416 }
417
418 func (b *prefixedBucket) NewTypedWriter(ctx context.Context, key, contentType string, opts *WriterOptions) (Writer, error) {
419 if key == "" {
420 return nil, errors.New("invalid key (empty string)")
421 }
422 return b.base.NewTypedWriter(ctx, b.prefix+key, contentType, opts)
423 }
424
425 func (b *prefixedBucket) Copy(ctx context.Context, dstKey, srcKey string, opts *CopyOptions) error {
426 return b.base.Copy(ctx, b.prefix+dstKey, b.prefix+srcKey, opts)
427 }
428
429 func (b *prefixedBucket) Delete(ctx context.Context, key string) error {
430 return b.base.Delete(ctx, b.prefix+key)
431 }
432
433 func (b *prefixedBucket) SignedURL(ctx context.Context, key string, opts *SignedURLOptions) (string, error) {
434 return b.base.SignedURL(ctx, b.prefix+key, opts)
435 }
436 func (b *prefixedBucket) Close() error { return b.base.Close() }
437
438 // singleKeyBucket implements Bucket by hardwiring a specific key.
439 type singleKeyBucket struct {
440 base Bucket
441 key string
442 }
443
444 // NewSingleKeyBucket returns a Bucket based on b that always references key.
445 func NewSingleKeyBucket(b Bucket, key string) Bucket {
446 return &singleKeyBucket{base: b, key: key}
447 }
448
449 func (b *singleKeyBucket) ErrorCode(err error) gcerrors.ErrorCode { return b.base.ErrorCode(err) }
450 func (b *singleKeyBucket) As(i any) bool { return b.base.As(i) }
451 func (b *singleKeyBucket) ErrorAs(err error, i any) bool { return b.base.ErrorAs(err, i) }
452 func (b *singleKeyBucket) Attributes(ctx context.Context, _ string) (*Attributes, error) {
453 return b.base.Attributes(ctx, b.key)
454 }
455
456 func (b *singleKeyBucket) ListPaged(ctx context.Context, opts *ListOptions) (*ListPage, error) {
457 return nil, errors.New("List not supported for SingleKey buckets")
458 }
459
460 func (b *singleKeyBucket) NewRangeReader(ctx context.Context, _ string, offset, length int64, opts *ReaderOptions) (Reader, error) {
461 return b.base.NewRangeReader(ctx, b.key, offset, length, opts)
462 }
463
464 func (b *singleKeyBucket) NewTypedWriter(ctx context.Context, _, contentType string, opts *WriterOptions) (Writer, error) {
465 return b.base.NewTypedWriter(ctx, b.key, contentType, opts)
466 }
467
468 func (b *singleKeyBucket) Copy(ctx context.Context, dstKey, _ string, opts *CopyOptions) error {
469 return b.base.Copy(ctx, dstKey, b.key, opts)
470 }
471
472 func (b *singleKeyBucket) Delete(ctx context.Context, _ string) error {
473 return b.base.Delete(ctx, b.key)
474 }
475
476 func (b *singleKeyBucket) SignedURL(ctx context.Context, _ string, opts *SignedURLOptions) (string, error) {
477 return b.base.SignedURL(ctx, b.key, opts)
478 }
479 func (b *singleKeyBucket) Close() error { return b.base.Close() }