Debian Codegraph @

blob/blob.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 blob provides an easy and portable way to interact with blobs
16 // within a storage location. Subpackages contain driver implementations of
17 // blob for supported services.
18 //
19 // See https://gocloud.dev/howto/blob/ for a detailed how-to guide.
20 //
21 // *blob.Bucket implements io/fs.FS and io/fs.SubFS, so it can be used with
22 // functions in that package.
23 //
24 // # Errors
25 //
26 // The errors returned from this package can be inspected in several ways:
27 //
28 // The Code function from gocloud.dev/gcerrors will return an error code, also
29 // defined in that package, when invoked on an error.
30 //
31 // The Bucket.ErrorAs method can retrieve the driver error underlying the returned
32 // error.
33 //
34 // # OpenTelemetry Integration
35 //
36 // OpenTelemetry supports tracing, metrics, and logs collection for multiple languages and
37 // backend providers. See https://opentelemetry.io.
38 //
39 // This API collects OpenTelemetry traces and metrics for the following methods:
40 // - Attributes
41 // - Copy
42 // - Delete
43 // - ListPage
44 // - NewRangeReader, from creation until the call to Close. (NewReader and ReadAll
45 // are included because they call NewRangeReader.)
46 // - NewWriter, from creation until the call to Close.
47 //
48 // All trace and metric names begin with the package import path.
49 // The traces add the method name.
50 // For example, "gocloud.dev/blob/Attributes".
51 // The metrics are "completed_calls", a count of completed method calls by driver,
52 // method and status (error code); and "latency", a distribution of method latency
53 // by driver and method.
54 // For example, "gocloud.dev/blob/latency".
55 //
56 // It also collects the following metrics:
57 // - gocloud.dev/blob/bytes_read: the total number of bytes read, by driver.
58 // - gocloud.dev/blob/bytes_written: the total number of bytes written, by driver.
59 //
60 // To enable trace collection in your application, see the documentation at
61 // https://opentelemetry.io/docs/instrumentation/go/getting-started/.
62 // To enable metric collection in your application, see the documentation at
63 // https://opentelemetry.io/docs/instrumentation/go/manual/.
64 package blob // import "gocloud.dev/blob"
65
66 import (
67 "bytes"
68 "context"
69 "crypto/md5"
70 "fmt"
71 "hash"
72 "io"
73 "iter"
74 "log"
75 "mime"
76 "net/http"
77 "net/url"
78 "runtime"
79 "strings"
80 "sync"
81 "time"
82 "unicode/utf8"
83
84 "go.opentelemetry.io/otel/metric"
85 "gocloud.dev/blob/driver"
86 "gocloud.dev/gcerrors"
87 "gocloud.dev/internal/gcerr"
88 "gocloud.dev/internal/openurl"
89 gcdkotel "gocloud.dev/internal/otel"
90 )
91
92 // Ensure that Reader implements io.ReadSeekCloser.
93 var _ = io.ReadSeekCloser(&Reader{})
94
95 // Reader reads bytes from a blob.
96 // It implements io.ReadSeekCloser, and must be closed after
97 // reads are finished.
98 type Reader struct {
99 b driver.Bucket
100 r driver.Reader
101 key string
102 ctx context.Context // Used to recreate r after Seeks
103 dopts *driver.ReaderOptions // "
104 baseOffset int64 // The base offset provided to NewRangeReader.
105 baseLength int64 // The length provided to NewRangeReader (may be negative).
106 relativeOffset int64 // Current offset (relative to baseOffset).
107 savedOffset int64 // Last relativeOffset for r, saved after relativeOffset is changed in Seek, or -1 if no Seek.
108 end func(error) // Called at Close to finish trace and metric collection.
109 // for metric collection;
110 bytesReadCounter metric.Int64Counter
111 bytesRead int
112 closed bool
113 }
114
115 // Read implements io.Reader (https://golang.org/pkg/io/#Reader).
116 func (r *Reader) Read(p []byte) (int, error) {
117 if r.savedOffset != -1 {
118 // We've done one or more Seeks since the last read. We may have
119 // to recreate the Reader.
120 //
121 // Note that remembering the savedOffset and lazily resetting the
122 // reader like this allows the caller to Seek, then Seek again back,
123 // to the original offset, without having to recreate the reader.
124 // We only have to recreate the reader if we actually read after a Seek.
125 // This is an important optimization because it's common to Seek
126 // to (SeekEnd, 0) and use the return value to determine the size
127 // of the data, then Seek back to (SeekStart, 0).
128 saved := r.savedOffset
129 if r.relativeOffset == saved {
130 // Nope! We're at the same place we left off.
131 r.savedOffset = -1
132 } else {
133 // Yep! We've changed the offset. Recreate the reader.
134 length := r.baseLength
135 if length >= 0 {
136 length -= r.relativeOffset
137 if length < 0 {
138 // Shouldn't happen based on checks in Seek.
139 return 0, gcerr.Newf(gcerr.Internal, nil, "blob: invalid Seek (base length %d, relative offset %d)", r.baseLength, r.relativeOffset)
140 }
141 }
142 newR, err := r.b.NewRangeReader(r.ctx, r.key, r.baseOffset+r.relativeOffset, length, r.dopts)
143 if err != nil {
144 return 0, wrapError(r.b, err, r.key)
145 }
146 _ = r.r.Close()
147 r.savedOffset = -1
148 r.r = newR
149 }
150 }
151 n, err := r.r.Read(p)
152 r.bytesRead += n
153 r.relativeOffset += int64(n)
154 return n, wrapError(r.b, err, r.key)
155 }
156
157 // Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker).
158 func (r *Reader) Seek(offset int64, whence int) (int64, error) {
159 if r.savedOffset == -1 {
160 // Save the current offset for our reader. If the Seek changes the
161 // offset, and then we try to read, we'll need to recreate the reader.
162 // See comment above in Read for why we do it lazily.
163 r.savedOffset = r.relativeOffset
164 }
165 // The maximum relative offset is the minimum of:
166 // 1. The actual size of the blob, minus our initial baseOffset.
167 // 2. The length provided to NewRangeReader (if it was non-negative).
168 maxRelativeOffset := r.Size() - r.baseOffset
169 if r.baseLength >= 0 && r.baseLength < maxRelativeOffset {
170 maxRelativeOffset = r.baseLength
171 }
172 switch whence {
173 case io.SeekStart:
174 r.relativeOffset = offset
175 case io.SeekCurrent:
176 r.relativeOffset += offset
177 case io.SeekEnd:
178 r.relativeOffset = maxRelativeOffset + offset
179 }
180 if r.relativeOffset < 0 {
181 // "Seeking to an offset before the start of the file is an error."
182 invalidOffset := r.relativeOffset
183 r.relativeOffset = 0
184 return 0, fmt.Errorf("Seek resulted in invalid offset %d, using 0", invalidOffset)
185 }
186 if r.relativeOffset > maxRelativeOffset {
187 // "Seeking to any positive offset is legal, but the behavior of subsequent
188 // I/O operations on the underlying object is implementation-dependent."
189 // We'll choose to set the offset to the EOF.
190 log.Printf("blob.Reader.Seek set an offset after EOF (base offset/length from NewRangeReader %d, %d; actual blob size %d; relative offset %d -> absolute offset %d).", r.baseOffset, r.baseLength, r.Size(), r.relativeOffset, r.baseOffset+r.relativeOffset)
191 r.relativeOffset = maxRelativeOffset
192 }
193 return r.relativeOffset, nil
194 }
195
196 // Close implements io.Closer (https://golang.org/pkg/io/#Closer).
197 func (r *Reader) Close() error {
198 r.closed = true
199 err := wrapError(r.b, r.r.Close(), r.key)
200 r.end(err)
201 // Emit only on close to avoid an allocation on each call to Read().
202 // Record bytes read metric with OpenTelemetry.
203 if r.bytesReadCounter != nil && r.bytesRead > 0 {
204 r.bytesReadCounter.Add(
205 r.ctx,
206 int64(r.bytesRead))
207 }
208 return err
209 }
210
211 // ContentType returns the MIME type of the blob.
212 func (r *Reader) ContentType() string {
213 return r.r.Attributes().ContentType
214 }
215
216 // ModTime returns the time the blob was last modified.
217 func (r *Reader) ModTime() time.Time {
218 return r.r.Attributes().ModTime
219 }
220
221 // Size returns the size of the blob content in bytes.
222 func (r *Reader) Size() int64 {
223 return r.r.Attributes().Size
224 }
225
226 // As converts i to driver-specific types.
227 // See https://gocloud.dev/concepts/as/ for background information, the "As"
228 // examples in this package for examples, and the driver package
229 // documentation for the specific types supported for that driver.
230 func (r *Reader) As(i any) bool {
231 return r.r.As(i)
232 }
233
234 // WriteTo reads from r and writes to w until there's no more data or
235 // an error occurs.
236 // The return value is the number of bytes written to w.
237 //
238 // It implements the io.WriterTo interface.
239 func (r *Reader) WriteTo(w io.Writer) (int64, error) {
240 // If the writer has a ReaderFrom method, use it to do the copy.
241 // Don't do this for our own *Writer to avoid infinite recursion.
242 // Avoids an allocation and a copy.
243 switch w.(type) {
244 case *Writer:
245 default:
246 if rf, ok := w.(io.ReaderFrom); ok {
247 n, err := rf.ReadFrom(r)
248 return n, err
249 }
250 }
251
252 _, nw, err := readFromWriteTo(r, w)
253 return nw, err
254 }
255
256 // downloadAndClose is similar to WriteTo, but ensures it's the only read.
257 // This pattern is more optimal for some drivers.
258 func (r *Reader) downloadAndClose(w io.Writer) (err error) {
259 if r.bytesRead != 0 {
260 // Shouldn't happen.
261 return gcerr.Newf(gcerr.Internal, nil, "blob: downloadAndClose isn't the first read")
262 }
263 driverDownloader, ok := r.r.(driver.Downloader)
264 if ok {
265 err = driverDownloader.Download(w)
266 } else {
267 _, err = r.WriteTo(w)
268 }
269 cerr := r.Close()
270 if err == nil && cerr != nil {
271 err = cerr
272 }
273 return err
274 }
275
276 // readFromWriteTo is a helper for ReadFrom and WriteTo.
277 // It reads data from r and writes to w, until EOF or a read/write error.
278 // It returns the number of bytes read from r and the number of bytes
279 // written to w.
280 func readFromWriteTo(r io.Reader, w io.Writer) (int64, int64, error) {
281 // Note: can't use io.Copy because it will try to use r.WriteTo
282 // or w.WriteTo, which is recursive in this context.
283 buf := make([]byte, 1024*1024)
284 var totalRead, totalWritten int64
285 for {
286 numRead, rerr := r.Read(buf)
287 if numRead > 0 {
288 totalRead += int64(numRead)
289 numWritten, werr := w.Write(buf[0:numRead])
290 totalWritten += int64(numWritten)
291 if werr != nil {
292 return totalRead, totalWritten, werr
293 }
294 }
295 if rerr == io.EOF {
296 // Done!
297 return totalRead, totalWritten, nil
298 }
299 if rerr != nil {
300 return totalRead, totalWritten, rerr
301 }
302 }
303 }
304
305 // Attributes contains attributes about a blob.
306 type Attributes struct {
307 // CacheControl specifies caching attributes that services may use
308 // when serving the blob.
309 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
310 CacheControl string
311 // ContentDisposition specifies whether the blob content is expected to be
312 // displayed inline or as an attachment.
313 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
314 ContentDisposition string
315 // ContentEncoding specifies the encoding used for the blob's content, if any.
316 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
317 ContentEncoding string
318 // ContentLanguage specifies the language used in the blob's content, if any.
319 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language
320 ContentLanguage string
321 // ContentType is the MIME type of the blob. It will not be empty.
322 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
323 ContentType string
324 // Metadata holds key/value pairs associated with the blob.
325 // Keys are guaranteed to be in lowercase, even if the backend service
326 // has case-sensitive keys (although note that Metadata written via
327 // this package will always be lowercased). If there are duplicate
328 // case-insensitive keys (e.g., "foo" and "FOO"), only one value
329 // will be kept, and it is undefined which one.
330 Metadata map[string]string
331 // CreateTime is the time the blob was created, if available. If not available,
332 // CreateTime will be the zero time.
333 CreateTime time.Time
334 // ModTime is the time the blob was last modified.
335 ModTime time.Time
336 // Size is the size of the blob's content in bytes.
337 Size int64
338 // MD5 is an MD5 hash of the blob contents or nil if not available.
339 MD5 []byte
340 // ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag.
341 ETag string
342
343 asFunc func(any) bool
344 }
345
346 // As converts i to driver-specific types.
347 // See https://gocloud.dev/concepts/as/ for background information, the "As"
348 // examples in this package for examples, and the driver package
349 // documentation for the specific types supported for that driver.
350 func (a *Attributes) As(i any) bool {
351 if a.asFunc == nil {
352 return false
353 }
354 return a.asFunc(i)
355 }
356
357 // Writer writes bytes to a blob.
358 //
359 // It implements io.WriteCloser (https://golang.org/pkg/io/#Closer), and must be
360 // closed after all writes are done.
361 type Writer struct {
362 b driver.Bucket
363 w driver.Writer
364 key string
365 end func(err error) // called at Close to finish trace and metric collection
366 cancel func() // cancels the ctx provided to NewTypedWriter if contentMD5 verification fails
367 contentMD5 []byte
368 md5hash hash.Hash
369
370 // Metric collection fields.
371 bytesWrittenCounter metric.Int64Counter
372 bytesWritten int
373 closed bool
374
375 // These fields are non-zero values only when w is nil (not yet created).
376 //
377 // A ctx is stored in the Writer since we need to pass it into NewTypedWriter
378 // when we finish detecting the content type of the blob and create the
379 // underlying driver.Writer. This step happens inside Write or Close and
380 // neither of them take a context.Context as an argument.
381 //
382 // All 3 fields are only initialized when we create the Writer without
383 // setting the w field, and are reset to zero values after w is created.
384 ctx context.Context
385 opts *driver.WriterOptions
386 buf *bytes.Buffer
387 }
388
389 // sniffLen is the byte size of Writer.buf used to detect content-type.
390 const sniffLen = 512
391
392 // Write implements the io.Writer interface (https://golang.org/pkg/io/#Writer).
393 //
394 // Writes may happen asynchronously, so the returned error can be nil
395 // even if the actual write eventually fails. The write is only guaranteed to
396 // have succeeded if Close returns no error.
397 func (w *Writer) Write(p []byte) (int, error) {
398 if len(w.contentMD5) > 0 {
399 if _, err := w.md5hash.Write(p); err != nil {
400 return 0, err
401 }
402 }
403 if w.w != nil {
404 return w.write(p)
405 }
406
407 // If w is not yet created due to no content-type being passed in, try to sniff
408 // the MIME type based on at most 512 bytes of the blob content of p.
409
410 // Detect the content-type directly if the first chunk is at least 512 bytes.
411 if w.buf.Len() == 0 && len(p) >= sniffLen {
412 return w.open(p)
413 }
414
415 // Store p in w.buf and detect the content-type when the size of content in
416 // w.buf is at least 512 bytes.
417 n, err := w.buf.Write(p)
418 if err != nil {
419 return 0, err
420 }
421 if w.buf.Len() >= sniffLen {
422 // Note that w.open will return the full length of the buffer; we don't want
423 // to return that as the length of this write since some of them were written in
424 // previous writes. Instead, we return the n from this write, above.
425 _, err := w.open(w.buf.Bytes())
426 return n, err
427 }
428 return n, nil
429 }
430
431 // Close closes the blob writer. The write operation is not guaranteed to have succeeded until
432 // Close returns with no error.
433 // Close may return an error if the context provided to create the Writer is
434 // canceled or reaches its deadline.
435 func (w *Writer) Close() (err error) {
436 w.closed = true
437 defer func() {
438 w.end(err)
439 // Emit only on close to avoid an allocation on each call to Write().
440 // Record bytes written metric with OpenTelemetry.
441 if w.bytesWrittenCounter != nil && w.bytesWritten > 0 {
442 w.bytesWrittenCounter.Add(
443 w.ctx,
444 int64(w.bytesWritten))
445 }
446 }()
447 if len(w.contentMD5) > 0 {
448 // Verify the MD5 hash of what was written matches the ContentMD5 provided
449 // by the user.
450 md5sum := w.md5hash.Sum(nil)
451 if !bytes.Equal(md5sum, w.contentMD5) {
452 // No match! Return an error, but first cancel the context and call the
453 // driver's Close function to ensure the write is aborted.
454 w.cancel()
455 if w.w != nil {
456 _ = w.w.Close()
457 }
458 return gcerr.Newf(gcerr.FailedPrecondition, nil, "blob: the WriterOptions.ContentMD5 you specified (%X) did not match what was written (%X)", w.contentMD5, md5sum)
459 }
460 }
461
462 defer w.cancel()
463 if w.w != nil {
464 return wrapError(w.b, w.w.Close(), w.key)
465 }
466 if _, err := w.open(w.buf.Bytes()); err != nil {
467 return err
468 }
469 return wrapError(w.b, w.w.Close(), w.key)
470 }
471
472 // open tries to detect the MIME type of p and write it to the blob.
473 // The error it returns is wrapped.
474 func (w *Writer) open(p []byte) (int, error) {
475 ct := http.DetectContentType(p)
476 var err error
477 if w.w, err = w.b.NewTypedWriter(w.ctx, w.key, ct, w.opts); err != nil {
478 return 0, wrapError(w.b, err, w.key)
479 }
480 // Set the 3 fields needed for lazy NewTypedWriter back to zero values
481 // (see the comment on Writer).
482 w.buf = nil
483 w.ctx = nil
484 w.opts = nil
485 return w.write(p)
486 }
487
488 func (w *Writer) write(p []byte) (int, error) {
489 n, err := w.w.Write(p)
490 w.bytesWritten += n
491 return n, wrapError(w.b, err, w.key)
492 }
493
494 // ReadFrom reads from r and writes to w until EOF or error.
495 // The return value is the number of bytes read from r.
496 //
497 // It implements the io.ReaderFrom interface.
498 func (w *Writer) ReadFrom(r io.Reader) (int64, error) {
499 // If the reader has a WriteTo method, use it to do the copy.
500 // Don't do this for our own *Reader to avoid infinite recursion.
501 // Avoids an allocation and a copy.
502 switch r.(type) {
503 case *Reader:
504 default:
505 if wt, ok := r.(io.WriterTo); ok {
506 n, err := wt.WriteTo(w)
507 return n, err
508 }
509 }
510
511 nr, _, err := readFromWriteTo(r, w)
512 return nr, err
513 }
514
515 // uploadAndClose is similar to ReadFrom, but ensures it's the only write.
516 // This pattern is more optimal for some drivers.
517 func (w *Writer) uploadAndClose(r io.Reader) (err error) {
518 if w.bytesWritten != 0 {
519 // Shouldn't happen.
520 return gcerr.Newf(gcerr.Internal, nil, "blob: uploadAndClose must be the first write")
521 }
522 // When ContentMD5 is being checked, we can't use Upload.
523 if len(w.contentMD5) > 0 {
524 _, err = w.ReadFrom(r)
525 } else {
526 driverUploader, ok := w.w.(driver.Uploader)
527 if ok {
528 err = driverUploader.Upload(r)
529 } else {
530 _, err = w.ReadFrom(r)
531 }
532 }
533 cerr := w.Close()
534 if err == nil && cerr != nil {
535 err = cerr
536 }
537 return err
538 }
539
540 // ListOptions sets options for listing blobs via Bucket.List.
541 type ListOptions struct {
542 // Prefix indicates that only blobs with a key starting with this prefix
543 // should be returned.
544 Prefix string
545 // Delimiter sets the delimiter used to define a hierarchical namespace,
546 // like a filesystem with "directories". It is highly recommended that you
547 // use "" or "/" as the Delimiter. Other values should work through this API,
548 // but service UIs generally assume "/".
549 //
550 // An empty delimiter means that the bucket is treated as a single flat
551 // namespace.
552 //
553 // A non-empty delimiter means that any result with the delimiter in its key
554 // after Prefix is stripped will be returned with ListObject.IsDir = true,
555 // ListObject.Key truncated after the delimiter, and zero values for other
556 // ListObject fields. These results represent "directories". Multiple results
557 // in a "directory" are returned as a single result.
558 Delimiter string
559
560 // BeforeList is a callback that will be called before each call to the
561 // the underlying service's list functionality.
562 // asFunc converts its argument to driver-specific types.
563 // See https://gocloud.dev/concepts/as/ for background information.
564 BeforeList func(asFunc func(any) bool) error
565 }
566
567 // ListIterator iterates over List results.
568 type ListIterator struct {
569 b *Bucket
570 opts *driver.ListOptions
571 page *driver.ListPage
572 nextIdx int
573 }
574
575 // Next returns a *ListObject for the next blob. It returns (nil, io.EOF) if
576 // there are no more.
577 func (i *ListIterator) Next(ctx context.Context) (*ListObject, error) {
578 if i.page != nil {
579 // We've already got a page of results.
580 if i.nextIdx < len(i.page.Objects) {
581 // Next object is in the page; return it.
582 dobj := i.page.Objects[i.nextIdx]
583 i.nextIdx++
584 return &ListObject{
585 Key: dobj.Key,
586 ModTime: dobj.ModTime,
587 Size: dobj.Size,
588 MD5: dobj.MD5,
589 IsDir: dobj.IsDir,
590 asFunc: dobj.AsFunc,
591 }, nil
592 }
593 if len(i.page.NextPageToken) == 0 {
594 // Done with current page, and there are no more; return io.EOF.
595 return nil, io.EOF
596 }
597 // We need to load the next page.
598 i.opts.PageToken = i.page.NextPageToken
599 }
600 i.b.mu.RLock()
601 defer i.b.mu.RUnlock()
602 if i.b.closed {
603 return nil, errClosed
604 }
605 // Loading a new page.
606 p, err := i.b.b.ListPaged(ctx, i.opts)
607 if err != nil {
608 return nil, wrapError(i.b.b, err, "")
609 }
610 i.page = p
611 i.nextIdx = 0
612 return i.Next(ctx)
613 }
614
615 type errorState struct {
616 mu sync.Mutex
617 done bool
618 err error
619 }
620
621 func (es *errorState) Done() {
622 es.mu.Lock()
623 es.done = true
624 es.mu.Unlock()
625 }
626
627 func (es *errorState) Set(err error) {
628 if err != nil {
629 es.mu.Lock()
630 es.err = err
631 es.mu.Unlock()
632 }
633 }
634
635 func (es *errorState) Err() error {
636 es.mu.Lock()
637 defer es.mu.Unlock()
638 return es.err
639 }
640
641 func (es *errorState) Func() func() error {
642 return func() error {
643 es.mu.Lock()
644 defer es.mu.Unlock()
645 if !es.done {
646 panic("error function called before iteration completed")
647 }
648 return es.err
649 }
650 }
651
652 // All iterates over the iterator, returning a *ListObject and a download function for each entry.
653 //
654 // Once iteration is complete, the returned "func() error" will return any errors; a non-nil return
655 // value implies that the iteration did not complete.
656 // Calling this function before iteration is complete will panic.
657 func (i *ListIterator) All(ctx context.Context) (iter.Seq2[*ListObject, func(io.Writer, *ReaderOptions) error], func() error) {
658 var es errorState
659 return func(yield func(*ListObject, func(io.Writer, *ReaderOptions) error) bool) {
660 defer es.Done()
661 for {
662 obj, itErr := i.Next(ctx)
663 if itErr == io.EOF {
664 return
665 }
666 if itErr != nil {
667 es.Set(itErr)
668 return
669 }
670 downloadFunc := func(w io.Writer, opts *ReaderOptions) error {
671 return i.b.Download(ctx, obj.Key, w, opts)
672 }
673 if !yield(obj, downloadFunc) {
674 return
675 }
676 }
677 }, es.Func()
678 }
679
680 // ListObject represents a single blob returned from List.
681 type ListObject struct {
682 // Key is the key for this blob.
683 Key string
684 // ModTime is the time the blob was last modified.
685 ModTime time.Time
686 // Size is the size of the blob's content in bytes.
687 Size int64
688 // MD5 is an MD5 hash of the blob contents or nil if not available.
689 MD5 []byte
690 // IsDir indicates that this result represents a "directory" in the
691 // hierarchical namespace, ending in ListOptions.Delimiter. Key can be
692 // passed as ListOptions.Prefix to list items in the "directory".
693 // Fields other than Key and IsDir will not be set if IsDir is true.
694 IsDir bool
695
696 asFunc func(any) bool
697 }
698
699 // As converts i to driver-specific types.
700 // See https://gocloud.dev/concepts/as/ for background information, the "As"
701 // examples in this package for examples, and the driver package
702 // documentation for the specific types supported for that driver.
703 func (o *ListObject) As(i any) bool {
704 if o.asFunc == nil {
705 return false
706 }
707 return o.asFunc(i)
708 }
709
710 // Bucket provides an easy and portable way to interact with blobs
711 // within a "bucket", including read, write, and list operations.
712 // To create a Bucket, use constructors found in driver subpackages.
713 type Bucket struct {
714 b driver.Bucket
715 tracer *gcdkotel.Tracer
716
717 bytesReadCounter metric.Int64Counter
718 bytesWrittenCounter metric.Int64Counter
719
720 // ioFSCallback is set via SetIOFSCallback, which must be
721 // called before calling various functions implementing interfaces
722 // from the io/fs package.
723 ioFSCallback func() (context.Context, *ReaderOptions)
724
725 // mu protects the closed variable.
726 // Read locks are kept to allow holding a read lock for long-running calls,
727 // and thereby prevent closing until a call finishes.
728 mu sync.RWMutex
729 closed bool
730 }
731
732 const pkgName = "gocloud.dev/blob"
733
734 var (
735
736 // OpenTelemetryViews are predefined views for OpenTelemetry metrics.
737 // The views include counts and latency distributions for API method calls.
738 // See the explanations at https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for usage.
739 OpenTelemetryViews = append(
740 append(
741 gcdkotel.Views(pkgName),
742 gcdkotel.CounterView(pkgName, "/bytes_read", "Sum of bytes read from the service.")...),
743 gcdkotel.CounterView(pkgName, "/bytes_written", "Sum of bytes written to the service.")...)
744 )
745
746 // NewBucket is intended for use by drivers only. Do not use in application code.
747 var NewBucket = newBucket
748
749 // newBucket creates a new *Bucket based on a specific driver implementation.
750 // End users should use subpackages to construct a *Bucket instead of this
751 // function; see the package documentation for details.
752 func newBucket(b driver.Bucket) *Bucket {
753 providerName := gcdkotel.ProviderName(b)
754
755 return &Bucket{
756 b: b,
757 ioFSCallback: func() (context.Context, *ReaderOptions) { return context.Background(), nil },
758 tracer: gcdkotel.NewTracer(pkgName, providerName),
759 bytesReadCounter: gcdkotel.BytesMeasure(pkgName, providerName, "/bytes_read", "Total bytes read from blob storage"),
760 bytesWrittenCounter: gcdkotel.BytesMeasure(pkgName, providerName, "/bytes_written", "Total bytes written to blob storage"),
761 }
762 }
763
764 // As converts i to driver-specific types.
765 // See https://gocloud.dev/concepts/as/ for background information, the "As"
766 // examples in this package for examples, and the driver package
767 // documentation for the specific types supported for that driver.
768 func (b *Bucket) As(i any) bool {
769 if i == nil {
770 return false
771 }
772 return b.b.As(i)
773 }
774
775 // ErrorAs converts err to driver-specific types.
776 // ErrorAs panics if i is nil or not a pointer.
777 // ErrorAs returns false if err == nil.
778 // See https://gocloud.dev/concepts/as/ for background information.
779 func (b *Bucket) ErrorAs(err error, i any) bool {
780 return gcerr.ErrorAs(err, i, b.b.ErrorAs)
781 }
782
783 // ReadAll is a shortcut for creating a Reader via NewReader with nil
784 // ReaderOptions, and reading the entire blob.
785 //
786 // Using Download may be more efficient.
787 func (b *Bucket) ReadAll(ctx context.Context, key string) (_ []byte, err error) {
788 b.mu.RLock()
789 defer b.mu.RUnlock()
790 if b.closed {
791 return nil, errClosed
792 }
793 r, err := b.NewReader(ctx, key, nil)
794 if err != nil {
795 return nil, err
796 }
797 defer func() { _ = r.Close() }()
798 return io.ReadAll(r)
799 }
800
801 // Download writes the content of a blob into an io.Writer w.
802 func (b *Bucket) Download(ctx context.Context, key string, w io.Writer, opts *ReaderOptions) error {
803 b.mu.RLock()
804 defer b.mu.RUnlock()
805 if b.closed {
806 return errClosed
807 }
808 r, err := b.NewReader(ctx, key, opts)
809 if err != nil {
810 return err
811 }
812 return r.downloadAndClose(w)
813 }
814
815 // List returns a ListIterator that can be used to iterate over blobs in a
816 // bucket, in lexicographical order of UTF-8 encoded keys. The underlying
817 // implementation fetches results in pages.
818 //
819 // A nil ListOptions is treated the same as the zero value.
820 //
821 // List is not guaranteed to include all recently-written blobs;
822 // some services are only eventually consistent.
823 func (b *Bucket) List(opts *ListOptions) *ListIterator {
824 if opts == nil {
825 opts = &ListOptions{}
826 }
827 dopts := &driver.ListOptions{
828 Prefix: opts.Prefix,
829 Delimiter: opts.Delimiter,
830 BeforeList: opts.BeforeList,
831 }
832 return &ListIterator{b: b, opts: dopts}
833 }
834
835 // FirstPageToken is the pageToken to pass to ListPage to retrieve the first page of results.
836 var FirstPageToken = []byte("first page")
837
838 // ListPage returns a page of ListObject results for blobs in a bucket, in lexicographical
839 // order of UTF-8 encoded keys.
840 //
841 // To fetch the first page, pass FirstPageToken as the pageToken. For subsequent pages, pass
842 // the pageToken returned from a previous call to ListPage.
843 // It is not possible to "skip ahead" pages.
844 //
845 // Each call will return pageSize results, unless there are not enough blobs to fill the
846 // page, in which case it will return fewer results (possibly 0).
847 //
848 // If there are no more blobs available, ListPage will return an empty pageToken. Note that
849 // this may happen regardless of the number of returned results -- the last page might have
850 // 0 results (i.e., if the last item was deleted), pageSize results, or anything in between.
851 //
852 // Calling ListPage with an empty pageToken will immediately return io.EOF. When looping
853 // over pages, callers can either check for an empty pageToken, or they can make one more
854 // call and check for io.EOF.
855 //
856 // The underlying implementation fetches results in pages, but one call to ListPage may
857 // require multiple page fetches (and therefore, multiple calls to the BeforeList callback).
858 //
859 // A nil ListOptions is treated the same as the zero value.
860 //
861 // ListPage is not guaranteed to include all recently-written blobs;
862 // some services are only eventually consistent.
863 func (b *Bucket) ListPage(ctx context.Context, pageToken []byte, pageSize int, opts *ListOptions) (retval []*ListObject, nextPageToken []byte, err error) {
864 if opts == nil {
865 opts = &ListOptions{}
866 }
867 if pageSize <= 0 {
868 return nil, nil, gcerr.Newf(gcerr.InvalidArgument, nil, "blob: pageSize must be > 0")
869 }
870
871 // Nil pageToken means no more results.
872 if len(pageToken) == 0 {
873 return nil, nil, io.EOF
874 }
875
876 // FirstPageToken fetches the first page. Drivers use nil.
877 // The public API doesn't use nil for the first page because it would be too easy to
878 // keep fetching forever (since the last page return nil for the next pageToken).
879 if bytes.Equal(pageToken, FirstPageToken) {
880 pageToken = nil
881 }
882 b.mu.RLock()
883 defer b.mu.RUnlock()
884 if b.closed {
885 return nil, nil, errClosed
886 }
887
888 ctx, span := b.tracer.Start(ctx, "ListPage")
889 defer func() { b.tracer.End(ctx, span, err) }()
890
891 dopts := &driver.ListOptions{
892 Prefix: opts.Prefix,
893 Delimiter: opts.Delimiter,
894 BeforeList: opts.BeforeList,
895 PageToken: pageToken,
896 PageSize: pageSize,
897 }
898 retval = make([]*ListObject, 0, pageSize)
899 for len(retval) < pageSize {
900 p, err := b.b.ListPaged(ctx, dopts)
901 if err != nil {
902 return nil, nil, wrapError(b.b, err, "")
903 }
904 for _, dobj := range p.Objects {
905 retval = append(retval, &ListObject{
906 Key: dobj.Key,
907 ModTime: dobj.ModTime,
908 Size: dobj.Size,
909 MD5: dobj.MD5,
910 IsDir: dobj.IsDir,
911 asFunc: dobj.AsFunc,
912 })
913 }
914 // ListPaged may return fewer results than pageSize. If there are more results
915 // available, signalled by non-empty p.NextPageToken, try to fetch the remainder
916 // of the page.
917 // It does not work to ask for more results than we need, because then we'd have
918 // a NextPageToken on a non-page boundary.
919 dopts.PageSize = pageSize - len(retval)
920 dopts.PageToken = p.NextPageToken
921 if len(dopts.PageToken) == 0 {
922 dopts.PageToken = nil
923 break
924 }
925 }
926 return retval, dopts.PageToken, nil
927 }
928
929 // IsAccessible returns true if the bucket is accessible, false otherwise.
930 // It is a shortcut for calling ListPage and checking if it returns an error
931 // with code gcerrors.NotFound.
932 func (b *Bucket) IsAccessible(ctx context.Context) (bool, error) {
933 _, _, err := b.ListPage(ctx, FirstPageToken, 1, nil)
934 if err == nil {
935 return true, nil
936 }
937 if gcerrors.Code(err) == gcerrors.NotFound {
938 return false, nil
939 }
940 return false, err
941 }
942
943 // Exists returns true if a blob exists at key, false if it does not exist, or
944 // an error.
945 // It is a shortcut for calling Attributes and checking if it returns an error
946 // with code gcerrors.NotFound.
947 func (b *Bucket) Exists(ctx context.Context, key string) (bool, error) {
948 _, err := b.Attributes(ctx, key)
949 if err == nil {
950 return true, nil
951 }
952 if gcerrors.Code(err) == gcerrors.NotFound {
953 return false, nil
954 }
955 return false, err
956 }
957
958 // Attributes returns attributes for the blob stored at key.
959 //
960 // If the blob does not exist, Attributes returns an error for which
961 // gcerrors.Code will return gcerrors.NotFound.
962 func (b *Bucket) Attributes(ctx context.Context, key string) (_ *Attributes, err error) {
963 if !utf8.ValidString(key) {
964 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "blob: Attributes key must be a valid UTF-8 string: %q", key)
965 }
966
967 b.mu.RLock()
968 defer b.mu.RUnlock()
969 if b.closed {
970 return nil, errClosed
971 }
972 ctx, span := b.tracer.Start(ctx, "Attributes")
973 defer func() { b.tracer.End(ctx, span, err) }()
974
975 a, err := b.b.Attributes(ctx, key)
976 if err != nil {
977 return nil, wrapError(b.b, err, key)
978 }
979 var md map[string]string
980 if len(a.Metadata) > 0 {
981 // Services are inconsistent, but at least some treat keys
982 // as case-insensitive. To make the behavior consistent, we
983 // force-lowercase them when writing and reading.
984 md = make(map[string]string, len(a.Metadata))
985 for k, v := range a.Metadata {
986 md[strings.ToLower(k)] = v
987 }
988 }
989 return &Attributes{
990 CacheControl: a.CacheControl,
991 ContentDisposition: a.ContentDisposition,
992 ContentEncoding: a.ContentEncoding,
993 ContentLanguage: a.ContentLanguage,
994 ContentType: a.ContentType,
995 Metadata: md,
996 CreateTime: a.CreateTime,
997 ModTime: a.ModTime,
998 Size: a.Size,
999 MD5: a.MD5,
1000 ETag: a.ETag,
1001 asFunc: a.AsFunc,
1002 }, nil
1003 }
1004
1005 // NewReader is a shortcut for NewRangeReader with offset=0 and length=-1.
1006 func (b *Bucket) NewReader(ctx context.Context, key string, opts *ReaderOptions) (*Reader, error) {
1007 return b.newRangeReader(ctx, key, 0, -1, opts)
1008 }
1009
1010 // NewRangeReader returns a Reader to read content from the blob stored at key.
1011 // It reads at most length bytes starting at offset (>= 0).
1012 // If length is negative, it will read till the end of the blob.
1013 //
1014 // For the purposes of Seek, the returned Reader will start at offset and
1015 // end at the minimum of the actual end of the blob or (if length > 0) offset + length.
1016 //
1017 // Note that ctx is used for all reads performed during the lifetime of the reader.
1018 //
1019 // If the blob does not exist, NewRangeReader returns an error for which
1020 // gcerrors.Code will return gcerrors.NotFound. Exists is a lighter-weight way
1021 // to check for existence.
1022 //
1023 // A nil ReaderOptions is treated the same as the zero value.
1024 //
1025 // The caller must call Close on the returned Reader when done reading.
1026 func (b *Bucket) NewRangeReader(ctx context.Context, key string, offset, length int64, opts *ReaderOptions) (_ *Reader, err error) {
1027 return b.newRangeReader(ctx, key, offset, length, opts)
1028 }
1029
1030 func (b *Bucket) newRangeReader(ctx context.Context, key string, offset, length int64, opts *ReaderOptions) (_ *Reader, err error) {
1031 b.mu.RLock()
1032 defer b.mu.RUnlock()
1033 if b.closed {
1034 return nil, errClosed
1035 }
1036 if offset < 0 {
1037 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "blob: NewRangeReader offset must be non-negative (%d)", offset)
1038 }
1039 if !utf8.ValidString(key) {
1040 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "blob: NewRangeReader key must be a valid UTF-8 string: %q", key)
1041 }
1042 if opts == nil {
1043 opts = &ReaderOptions{}
1044 }
1045 dopts := &driver.ReaderOptions{
1046 BeforeRead: opts.BeforeRead,
1047 }
1048 ctx, span := b.tracer.Start(ctx, "NewRangeReader")
1049 defer func() {
1050 // If err == nil, we handed the end closure off to the returned *Reader; it
1051 // will be called when the Reader is Closed.
1052 if err != nil {
1053 b.tracer.End(ctx, span, err)
1054 }
1055 }()
1056 var dr driver.Reader
1057 dr, err = b.b.NewRangeReader(ctx, key, offset, length, dopts)
1058 if err != nil {
1059 return nil, wrapError(b.b, err, key)
1060 }
1061 end := func(err error) { b.tracer.End(ctx, span, err) }
1062 r := &Reader{
1063 b: b.b,
1064 r: dr,
1065 key: key,
1066 ctx: ctx,
1067 dopts: dopts,
1068 baseOffset: offset,
1069 baseLength: length,
1070 savedOffset: -1,
1071 end: end,
1072 bytesReadCounter: b.bytesReadCounter,
1073 }
1074 _, file, lineno, ok := runtime.Caller(2)
1075 runtime.SetFinalizer(r, func(r *Reader) {
1076 if !r.closed {
1077 var caller string
1078 if ok {
1079 caller = fmt.Sprintf(" (%s:%d)", file, lineno)
1080 }
1081 log.Printf("A blob.Reader reading from %q was never closed%s", key, caller)
1082 }
1083 })
1084 return r, nil
1085 }
1086
1087 // WriteAll is a shortcut for creating a Writer via NewWriter and writing p.
1088 //
1089 // If opts.ContentMD5 is not set, WriteAll will compute the MD5 of p and use it
1090 // as the ContentMD5 option for the Writer it creates.
1091 //
1092 // Using Upload may be more efficient.
1093 func (b *Bucket) WriteAll(ctx context.Context, key string, p []byte, opts *WriterOptions) (err error) {
1094 realOpts := new(WriterOptions)
1095 if opts != nil {
1096 *realOpts = *opts
1097 }
1098 if len(realOpts.ContentMD5) == 0 {
1099 sum := md5.Sum(p)
1100 realOpts.ContentMD5 = sum[:]
1101 }
1102 w, err := b.NewWriter(ctx, key, realOpts)
1103 if err != nil {
1104 return err
1105 }
1106 if _, err := w.Write(p); err != nil {
1107 _ = w.Close()
1108 return err
1109 }
1110 return w.Close()
1111 }
1112
1113 // Upload reads from an io.Reader r and writes into a blob.
1114 //
1115 // opts.ContentType is required.
1116 func (b *Bucket) Upload(ctx context.Context, key string, r io.Reader, opts *WriterOptions) error {
1117 if opts == nil || opts.ContentType == "" {
1118 return gcerr.Newf(gcerr.InvalidArgument, nil, "blob: Upload requires WriterOptions.ContentType")
1119 }
1120 w, err := b.NewWriter(ctx, key, opts)
1121 if err != nil {
1122 return err
1123 }
1124 return w.uploadAndClose(r)
1125 }
1126
1127 // NewWriter returns a Writer that writes to the blob stored at key.
1128 // A nil WriterOptions is treated the same as the zero value.
1129 //
1130 // If a blob with this key already exists, it will be replaced.
1131 // The blob being written is not guaranteed to be readable until Close
1132 // has been called; until then, any previous blob will still be readable.
1133 // Even after Close is called, newly written blobs are not guaranteed to be
1134 // returned from List; some services are only eventually consistent.
1135 //
1136 // The returned Writer will store ctx for later use in Write and/or Close.
1137 // To abort a write, cancel ctx; otherwise, it must remain open until
1138 // Close is called.
1139 //
1140 // The caller must call Close on the returned Writer, even if the write is
1141 // aborted.
1142 func (b *Bucket) NewWriter(ctx context.Context, key string, opts *WriterOptions) (_ *Writer, err error) {
1143 if !utf8.ValidString(key) {
1144 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "blob: NewWriter key must be a valid UTF-8 string: %q", key)
1145 }
1146 if opts == nil {
1147 opts = &WriterOptions{}
1148 }
1149 dopts := &driver.WriterOptions{
1150 CacheControl: opts.CacheControl,
1151 ContentDisposition: opts.ContentDisposition,
1152 ContentEncoding: opts.ContentEncoding,
1153 ContentLanguage: opts.ContentLanguage,
1154 ContentMD5: opts.ContentMD5,
1155 BufferSize: opts.BufferSize,
1156 MaxConcurrency: opts.MaxConcurrency,
1157 BeforeWrite: opts.BeforeWrite,
1158 DisableContentTypeDetection: opts.DisableContentTypeDetection,
1159 IfNotExist: opts.IfNotExist,
1160 }
1161 if len(opts.Metadata) > 0 {
1162 // Services are inconsistent, but at least some treat keys
1163 // as case-insensitive. To make the behavior consistent, we
1164 // force-lowercase them when writing and reading.
1165 md := make(map[string]string, len(opts.Metadata))
1166 for k, v := range opts.Metadata {
1167 if k == "" {
1168 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "blob: WriterOptions.Metadata keys may not be empty strings")
1169 }
1170 if !utf8.ValidString(k) {
1171 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "blob: WriterOptions.Metadata keys must be valid UTF-8 strings: %q", k)
1172 }
1173 if !utf8.ValidString(v) {
1174 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "blob: WriterOptions.Metadata values must be valid UTF-8 strings: %q", v)
1175 }
1176 lowerK := strings.ToLower(k)
1177 if _, found := md[lowerK]; found {
1178 return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "blob: WriterOptions.Metadata has a duplicate case-insensitive metadata key: %q", lowerK)
1179 }
1180 md[lowerK] = v
1181 }
1182 dopts.Metadata = md
1183 }
1184 b.mu.RLock()
1185 defer b.mu.RUnlock()
1186 if b.closed {
1187 return nil, errClosed
1188 }
1189 ctx, cancel := context.WithCancel(ctx)
1190 ctx, span := b.tracer.Start(ctx, "NewWriter")
1191 end := func(err error) { b.tracer.End(ctx, span, err) }
1192 defer func() {
1193 if err != nil {
1194 end(err)
1195 }
1196 }()
1197
1198 w := &Writer{
1199 b: b.b,
1200 end: end,
1201 cancel: cancel,
1202 key: key,
1203 contentMD5: opts.ContentMD5,
1204 md5hash: md5.New(),
1205 bytesWrittenCounter: b.bytesWrittenCounter,
1206 }
1207 if opts.ContentType != "" || opts.DisableContentTypeDetection {
1208 var ct string
1209 if opts.ContentType != "" {
1210 t, p, err := mime.ParseMediaType(opts.ContentType)
1211 if err != nil {
1212 cancel()
1213 return nil, err
1214 }
1215 ct = mime.FormatMediaType(t, p)
1216 }
1217 dw, err := b.b.NewTypedWriter(ctx, key, ct, dopts)
1218 if err != nil {
1219 cancel()
1220 return nil, wrapError(b.b, err, key)
1221 }
1222 w.w = dw
1223 } else {
1224 // Save the fields needed to called NewTypedWriter later, once we've gotten
1225 // sniffLen bytes; see the comment on Writer.
1226 w.ctx = ctx
1227 w.opts = dopts
1228 w.buf = bytes.NewBuffer([]byte{})
1229 }
1230 _, file, lineno, ok := runtime.Caller(1)
1231 runtime.SetFinalizer(w, func(w *Writer) {
1232 if !w.closed {
1233 var caller string
1234 if ok {
1235 caller = fmt.Sprintf(" (%s:%d)", file, lineno)
1236 }
1237 log.Printf("A blob.Writer writing to %q was never closed%s", key, caller)
1238 }
1239 })
1240 return w, nil
1241 }
1242
1243 // Copy the blob stored at srcKey to dstKey.
1244 // A nil CopyOptions is treated the same as the zero value.
1245 //
1246 // If the source blob does not exist, Copy returns an error for which
1247 // gcerrors.Code will return gcerrors.NotFound.
1248 //
1249 // If the destination blob already exists, it is overwritten.
1250 func (b *Bucket) Copy(ctx context.Context, dstKey, srcKey string, opts *CopyOptions) (err error) {
1251 if !utf8.ValidString(srcKey) {
1252 return gcerr.Newf(gcerr.InvalidArgument, nil, "blob: Copy srcKey must be a valid UTF-8 string: %q", srcKey)
1253 }
1254 if !utf8.ValidString(dstKey) {
1255 return gcerr.Newf(gcerr.InvalidArgument, nil, "blob: Copy dstKey must be a valid UTF-8 string: %q", dstKey)
1256 }
1257 if opts == nil {
1258 opts = &CopyOptions{}
1259 }
1260 dopts := &driver.CopyOptions{
1261 BeforeCopy: opts.BeforeCopy,
1262 }
1263 b.mu.RLock()
1264 defer b.mu.RUnlock()
1265 if b.closed {
1266 return errClosed
1267 }
1268 ctx, span := b.tracer.Start(ctx, "Copy")
1269 defer func() { b.tracer.End(ctx, span, err) }()
1270 return wrapError(b.b, b.b.Copy(ctx, dstKey, srcKey, dopts), fmt.Sprintf("%s -> %s", srcKey, dstKey))
1271 }
1272
1273 // Delete deletes the blob stored at key.
1274 //
1275 // If the blob does not exist, Delete returns an error for which
1276 // gcerrors.Code will return gcerrors.NotFound.
1277 func (b *Bucket) Delete(ctx context.Context, key string) (err error) {
1278 if !utf8.ValidString(key) {
1279 return gcerr.Newf(gcerr.InvalidArgument, nil, "blob: Delete key must be a valid UTF-8 string: %q", key)
1280 }
1281 b.mu.RLock()
1282 defer b.mu.RUnlock()
1283 if b.closed {
1284 return errClosed
1285 }
1286 ctx, span := b.tracer.Start(ctx, "Delete")
1287 defer func() { b.tracer.End(ctx, span, err) }()
1288 return wrapError(b.b, b.b.Delete(ctx, key), key)
1289 }
1290
1291 // SignedURL returns a URL that can be used to GET (default), PUT or DELETE
1292 // the blob for the duration specified in opts.Expiry.
1293 //
1294 // A nil SignedURLOptions is treated the same as the zero value.
1295 //
1296 // It is valid to call SignedURL for a key that does not exist.
1297 //
1298 // If the driver does not support this functionality, SignedURL
1299 // will return an error for which gcerrors.Code will return gcerrors.Unimplemented.
1300 func (b *Bucket) SignedURL(ctx context.Context, key string, opts *SignedURLOptions) (string, error) {
1301 if !utf8.ValidString(key) {
1302 return "", gcerr.Newf(gcerr.InvalidArgument, nil, "blob: SignedURL key must be a valid UTF-8 string: %q", key)
1303 }
1304 dopts := new(driver.SignedURLOptions)
1305 if opts == nil {
1306 opts = new(SignedURLOptions)
1307 }
1308 switch {
1309 case opts.Expiry < 0:
1310 return "", gcerr.Newf(gcerr.InvalidArgument, nil, "blob: SignedURLOptions.Expiry must be >= 0 (%v)", opts.Expiry)
1311 case opts.Expiry == 0:
1312 dopts.Expiry = DefaultSignedURLExpiry
1313 default:
1314 dopts.Expiry = opts.Expiry
1315 }
1316 switch opts.Method {
1317 case "":
1318 dopts.Method = http.MethodGet
1319 case http.MethodGet, http.MethodPut, http.MethodDelete:
1320 dopts.Method = opts.Method
1321 default:
1322 return "", fmt.Errorf("blob: unsupported SignedURLOptions.Method %q", opts.Method)
1323 }
1324 if opts.ContentType != "" && opts.Method != http.MethodPut {
1325 return "", fmt.Errorf("blob: SignedURLOptions.ContentType must be empty for signing a %s URL", opts.Method)
1326 }
1327 if opts.EnforceAbsentContentType && opts.Method != http.MethodPut {
1328 return "", fmt.Errorf("blob: SignedURLOptions.EnforceAbsentContentType must be false for signing a %s URL", opts.Method)
1329 }
1330 dopts.ContentType = opts.ContentType
1331 dopts.EnforceAbsentContentType = opts.EnforceAbsentContentType
1332 dopts.BeforeSign = opts.BeforeSign
1333 b.mu.RLock()
1334 defer b.mu.RUnlock()
1335 if b.closed {
1336 return "", errClosed
1337 }
1338 sURL, err := b.b.SignedURL(ctx, key, dopts)
1339 return sURL, wrapError(b.b, err, key)
1340 }
1341
1342 // Close releases any resources used for the bucket.
1343 func (b *Bucket) Close() error {
1344 b.mu.Lock()
1345 prev := b.closed
1346 b.closed = true
1347 b.mu.Unlock()
1348 if prev {
1349 return errClosed
1350 }
1351 return wrapError(b.b, b.b.Close(), "")
1352 }
1353
1354 // DefaultSignedURLExpiry is the default duration for SignedURLOptions.Expiry.
1355 const DefaultSignedURLExpiry = 1 * time.Hour
1356
1357 // SignedURLOptions sets options for SignedURL.
1358 type SignedURLOptions struct {
1359 // Expiry sets how long the returned URL is valid for.
1360 // Defaults to DefaultSignedURLExpiry.
1361 Expiry time.Duration
1362
1363 // Method is the HTTP method that can be used on the URL; one of "GET", "PUT",
1364 // or "DELETE". Defaults to "GET".
1365 Method string
1366
1367 // ContentType specifies the Content-Type HTTP header the user agent is
1368 // permitted to use in the PUT request. It must match exactly. See
1369 // EnforceAbsentContentType for behavior when ContentType is the empty string.
1370 // If a bucket does not implement this verification, then it returns an
1371 // Unimplemented error.
1372 //
1373 // Must be empty for non-PUT requests.
1374 ContentType string
1375
1376 // If EnforceAbsentContentType is true and ContentType is the empty string,
1377 // then PUTing to the signed URL will fail if the Content-Type header is
1378 // present. Not all buckets support this: ones that do not will return an
1379 // Unimplemented error.
1380 //
1381 // If EnforceAbsentContentType is false and ContentType is the empty string,
1382 // then PUTing without a Content-Type header will succeed, but it is
1383 // implementation-specific whether providing a Content-Type header will fail.
1384 //
1385 // Must be false for non-PUT requests.
1386 EnforceAbsentContentType bool
1387
1388 // BeforeSign is a callback that will be called before each call to the
1389 // the underlying service's sign functionality.
1390 // asFunc converts its argument to driver-specific types.
1391 // See https://gocloud.dev/concepts/as/ for background information.
1392 BeforeSign func(asFunc func(any) bool) error
1393 }
1394
1395 // ReaderOptions sets options for NewReader and NewRangeReader.
1396 type ReaderOptions struct {
1397 // BeforeRead is a callback that will be called before
1398 // any data is read (unless NewReader returns an error before then, in which
1399 // case it may not be called at all).
1400 //
1401 // Calling Seek may reset the underlying reader, and result in BeforeRead
1402 // getting called again with a different underlying provider-specific reader..
1403 //
1404 // asFunc converts its argument to driver-specific types.
1405 // See https://gocloud.dev/concepts/as/ for background information.
1406 BeforeRead func(asFunc func(any) bool) error
1407 }
1408
1409 // WriterOptions sets options for NewWriter.
1410 type WriterOptions struct {
1411 // BufferSize changes the default size in bytes of the chunks that
1412 // Writer will upload in a single request; larger blobs will be split into
1413 // multiple requests.
1414 //
1415 // This option may be ignored by some drivers.
1416 //
1417 // If 0, the driver will choose a reasonable default.
1418 //
1419 // If the Writer is used to do many small writes concurrently, using a
1420 // smaller BufferSize may reduce memory usage.
1421 BufferSize int
1422
1423 // MaxConcurrency changes the default concurrency for parts of an upload.
1424 //
1425 // This option may be ignored by some drivers.
1426 //
1427 // If 0, the driver will choose a reasonable default.
1428 MaxConcurrency int
1429
1430 // CacheControl specifies caching attributes that services may use
1431 // when serving the blob.
1432 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
1433 CacheControl string
1434
1435 // ContentDisposition specifies whether the blob content is expected to be
1436 // displayed inline or as an attachment.
1437 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
1438 ContentDisposition string
1439
1440 // ContentEncoding specifies the encoding used for the blob's content, if any.
1441 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
1442 ContentEncoding string
1443
1444 // ContentLanguage specifies the language used in the blob's content, if any.
1445 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language
1446 ContentLanguage string
1447
1448 // ContentType specifies the MIME type of the blob being written. If not set,
1449 // it will be inferred from the content using the algorithm described at
1450 // http://mimesniff.spec.whatwg.org/.
1451 // Set DisableContentTypeDetection to true to disable the above and force
1452 // the ContentType to stay empty.
1453 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
1454 ContentType string
1455
1456 // When true, if ContentType is the empty string, it will stay the empty
1457 // string rather than being inferred from the content.
1458 // Note that while the blob will be written with an empty string ContentType,
1459 // most providers will fill one in during reads, so don't expect an empty
1460 // ContentType if you read the blob back.
1461 DisableContentTypeDetection bool
1462
1463 // ContentMD5 is used as a message integrity check.
1464 // If len(ContentMD5) > 0, the MD5 hash of the bytes written must match
1465 // ContentMD5, or Close will return an error without completing the write.
1466 // https://tools.ietf.org/html/rfc1864
1467 ContentMD5 []byte
1468
1469 // Metadata holds key/value strings to be associated with the blob, or nil.
1470 // Keys may not be empty, and are lowercased before being written.
1471 // Duplicate case-insensitive keys (e.g., "foo" and "FOO") will result in
1472 // an error.
1473 Metadata map[string]string
1474
1475 // BeforeWrite is a callback that will be called exactly once, before
1476 // any data is written (unless NewWriter returns an error, in which case
1477 // it will not be called at all). Note that this is not necessarily during
1478 // or after the first Write call, as drivers may buffer bytes before
1479 // sending an upload request.
1480 //
1481 // asFunc converts its argument to driver-specific types.
1482 // See https://gocloud.dev/concepts/as/ for background information.
1483 BeforeWrite func(asFunc func(any) bool) error
1484
1485 // IfNotExist is used for conditional writes. When set to 'true',
1486 // if a blob exists for the same key in the bucket, the write
1487 // operation won't succeed and the current blob for the key will
1488 // be left untouched. An error for which gcerrors.Code will return
1489 // gcerrors.PreconditionFailed will be returned by Write or Close.
1490 IfNotExist bool
1491 }
1492
1493 // CopyOptions sets options for Copy.
1494 type CopyOptions struct {
1495 // BeforeCopy is a callback that will be called before the copy is
1496 // initiated.
1497 //
1498 // asFunc converts its argument to driver-specific types.
1499 // See https://gocloud.dev/concepts/as/ for background information.
1500 BeforeCopy func(asFunc func(any) bool) error
1501 }
1502
1503 // BucketURLOpener represents types that can open buckets based on a URL.
1504 // The opener must not modify the URL argument. OpenBucketURL must be safe to
1505 // call from multiple goroutines.
1506 //
1507 // This interface is generally implemented by types in driver packages.
1508 type BucketURLOpener interface {
1509 OpenBucketURL(ctx context.Context, u *url.URL) (*Bucket, error)
1510 }
1511
1512 // URLMux is a URL opener multiplexer. It matches the scheme of the URLs
1513 // against a set of registered schemes and calls the opener that matches the
1514 // URL's scheme.
1515 // See https://gocloud.dev/concepts/urls/ for more information.
1516 //
1517 // The zero value is a multiplexer with no registered schemes.
1518 type URLMux struct {
1519 schemes openurl.SchemeMap
1520 }
1521
1522 // BucketSchemes returns a sorted slice of the registered Bucket schemes.
1523 func (mux *URLMux) BucketSchemes() []string { return mux.schemes.Schemes() }
1524
1525 // ValidBucketScheme returns true iff scheme has been registered for Buckets.
1526 func (mux *URLMux) ValidBucketScheme(scheme string) bool { return mux.schemes.ValidScheme(scheme) }
1527
1528 // RegisterBucket registers the opener with the given scheme. If an opener
1529 // already exists for the scheme, RegisterBucket panics.
1530 func (mux *URLMux) RegisterBucket(scheme string, opener BucketURLOpener) {
1531 mux.schemes.Register("blob", "Bucket", scheme, opener)
1532 }
1533
1534 // OpenBucket calls OpenBucketURL with the URL parsed from urlstr.
1535 // OpenBucket is safe to call from multiple goroutines.
1536 func (mux *URLMux) OpenBucket(ctx context.Context, urlstr string) (*Bucket, error) {
1537 opener, u, err := mux.schemes.FromString("Bucket", urlstr)
1538 if err != nil {
1539 return nil, err
1540 }
1541 return applyPrefixParam(ctx, opener.(BucketURLOpener), u)
1542 }
1543
1544 // OpenBucketURL dispatches the URL to the opener that is registered with the
1545 // URL's scheme. OpenBucketURL is safe to call from multiple goroutines.
1546 func (mux *URLMux) OpenBucketURL(ctx context.Context, u *url.URL) (*Bucket, error) {
1547 opener, err := mux.schemes.FromURL("Bucket", u)
1548 if err != nil {
1549 return nil, err
1550 }
1551 return applyPrefixParam(ctx, opener.(BucketURLOpener), u)
1552 }
1553
1554 func applyPrefixParam(ctx context.Context, opener BucketURLOpener, u *url.URL) (*Bucket, error) {
1555 prefix := u.Query().Get("prefix")
1556 singleKey := u.Query().Get("key")
1557 if prefix != "" || singleKey != "" {
1558 // Make a copy of u with the "prefix" and "key" parameters removed.
1559 urlCopy := *u
1560 q := urlCopy.Query()
1561 q.Del("prefix")
1562 q.Del("key")
1563 urlCopy.RawQuery = q.Encode()
1564 u = &urlCopy
1565 }
1566 bucket, err := opener.OpenBucketURL(ctx, u)
1567 if err != nil {
1568 return nil, err
1569 }
1570 if prefix != "" {
1571 bucket = PrefixedBucket(bucket, prefix)
1572 }
1573 if singleKey != "" {
1574 bucket = SingleKeyBucket(bucket, singleKey)
1575 }
1576 return bucket, nil
1577 }
1578
1579 var defaultURLMux = new(URLMux)
1580
1581 // DefaultURLMux returns the URLMux used by OpenBucket.
1582 //
1583 // Driver packages can use this to register their BucketURLOpener on the mux.
1584 func DefaultURLMux() *URLMux {
1585 return defaultURLMux
1586 }
1587
1588 // OpenBucket opens the bucket identified by the URL given.
1589 //
1590 // See the URLOpener documentation in driver subpackages for
1591 // details on supported URL formats, and https://gocloud.dev/concepts/urls/
1592 // for more information.
1593 //
1594 // In addition to driver-specific query parameters, OpenBucket supports
1595 // the following query parameters:
1596 //
1597 // - prefix: wraps the resulting Bucket using PrefixedBucket with the
1598 // given prefix.
1599 // - key: wraps the resulting Bucket using SingleKeyBucket with the
1600 // given key.
1601 func OpenBucket(ctx context.Context, urlstr string) (*Bucket, error) {
1602 return defaultURLMux.OpenBucket(ctx, urlstr)
1603 }
1604
1605 func wrapError(b driver.Bucket, err error, key string) error {
1606 if err == nil {
1607 return nil
1608 }
1609 if gcerr.DoNotWrap(err) {
1610 return err
1611 }
1612 msg := "blob"
1613 if key != "" {
1614 msg += fmt.Sprintf(" (key %q)", key)
1615 }
1616 code := gcerrors.Code(err)
1617 if code == gcerrors.Unknown {
1618 code = b.ErrorCode(err)
1619 }
1620 return gcerr.New(code, err, 2, msg)
1621 }
1622
1623 var errClosed = gcerr.Newf(gcerr.FailedPrecondition, nil, "blob: Bucket has been closed")
1624
1625 // PrefixedBucket returns a *Bucket based on b with all keys modified to have
1626 // prefix, which will usually end with a "/" to target a subdirectory in the
1627 // bucket.
1628 //
1629 // bucket will be closed and no longer usable after this function returns.
1630 func PrefixedBucket(bucket *Bucket, prefix string) *Bucket {
1631 bucket.mu.Lock()
1632 defer bucket.mu.Unlock()
1633 bucket.closed = true
1634 return NewBucket(driver.NewPrefixedBucket(bucket.b, prefix))
1635 }
1636
1637 // SingleKeyBucket returns a *Bucket based on b that always references singleKey.
1638 // List methods will not work.
1639 // singleKey acts as srcKey for Copy.
1640 //
1641 // bucket will be closed and no longer usable after this function returns.
1642 func SingleKeyBucket(bucket *Bucket, singleKey string) *Bucket {
1643 bucket.mu.Lock()
1644 defer bucket.mu.Unlock()
1645 bucket.closed = true
1646 return NewBucket(driver.NewSingleKeyBucket(bucket.b, singleKey))
1647 }