writer.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. // Copyright 2014 Google LLC
  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. // http://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. package storage
  15. import (
  16. "context"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "sync"
  21. "time"
  22. "unicode/utf8"
  23. "cloud.google.com/go/internal/trace"
  24. )
  25. // A Writer writes a Cloud Storage object.
  26. type Writer struct {
  27. // ObjectAttrs are optional attributes to set on the object. Any attributes
  28. // must be initialized before the first Write call. Nil or zero-valued
  29. // attributes are ignored.
  30. ObjectAttrs
  31. // SendCRC32C specifies whether to transmit a CRC32C field. It should be set
  32. // to true in addition to setting the Writer's CRC32C field, because zero
  33. // is a valid CRC and normally a zero would not be transmitted.
  34. // If a CRC32C is sent, and the data written does not match the checksum,
  35. // the write will be rejected.
  36. //
  37. // Note: SendCRC32C must be set to true BEFORE the first call to
  38. // Writer.Write() in order to send the checksum. If it is set after that
  39. // point, the checksum will be ignored.
  40. SendCRC32C bool
  41. // ChunkSize controls the maximum number of bytes of the object that the
  42. // Writer will attempt to send to the server in a single request. Objects
  43. // smaller than the size will be sent in a single request, while larger
  44. // objects will be split over multiple requests. The value will be rounded up
  45. // to the nearest multiple of 256K. The default ChunkSize is 16MiB.
  46. //
  47. // Each Writer will internally allocate a buffer of size ChunkSize. This is
  48. // used to buffer input data and allow for the input to be sent again if a
  49. // request must be retried.
  50. //
  51. // If you upload small objects (< 16MiB), you should set ChunkSize
  52. // to a value slightly larger than the objects' sizes to avoid memory bloat.
  53. // This is especially important if you are uploading many small objects
  54. // concurrently. See
  55. // https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#size
  56. // for more information about performance trade-offs related to ChunkSize.
  57. //
  58. // If ChunkSize is set to zero, chunking will be disabled and the object will
  59. // be uploaded in a single request without the use of a buffer. This will
  60. // further reduce memory used during uploads, but will also prevent the writer
  61. // from retrying in case of a transient error from the server or resuming an
  62. // upload that fails midway through, since the buffer is required in order to
  63. // retry the failed request.
  64. //
  65. // ChunkSize must be set before the first Write call.
  66. ChunkSize int
  67. // ChunkRetryDeadline sets a per-chunk retry deadline for multi-chunk
  68. // resumable uploads.
  69. //
  70. // For uploads of larger files, the Writer will attempt to retry if the
  71. // request to upload a particular chunk fails with a transient error.
  72. // If a single chunk has been attempting to upload for longer than this
  73. // deadline and the request fails, it will no longer be retried, and the error
  74. // will be returned to the caller. This is only applicable for files which are
  75. // large enough to require a multi-chunk resumable upload. The default value
  76. // is 32s. Users may want to pick a longer deadline if they are using larger
  77. // values for ChunkSize or if they expect to have a slow or unreliable
  78. // internet connection.
  79. //
  80. // To set a deadline on the entire upload, use context timeout or
  81. // cancellation.
  82. ChunkRetryDeadline time.Duration
  83. // ForceEmptyContentType is an optional parameter that is used to disable
  84. // auto-detection of Content-Type. By default, if a blank Content-Type
  85. // is provided, then gax.DetermineContentType is called to sniff the type.
  86. ForceEmptyContentType bool
  87. // ProgressFunc can be used to monitor the progress of a large write
  88. // operation. If ProgressFunc is not nil and writing requires multiple
  89. // calls to the underlying service (see
  90. // https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload),
  91. // then ProgressFunc will be invoked after each call with the number of bytes of
  92. // content copied so far.
  93. //
  94. // ProgressFunc should return quickly without blocking.
  95. ProgressFunc func(int64)
  96. ctx context.Context
  97. o *ObjectHandle
  98. opened bool
  99. pw *io.PipeWriter
  100. donec chan struct{} // closed after err and obj are set.
  101. obj *ObjectAttrs
  102. mu sync.Mutex
  103. err error
  104. }
  105. // Write appends to w. It implements the io.Writer interface.
  106. //
  107. // Since writes happen asynchronously, Write may return a nil
  108. // error even though the write failed (or will fail). Always
  109. // use the error returned from Writer.Close to determine if
  110. // the upload was successful.
  111. //
  112. // Writes will be retried on transient errors from the server, unless
  113. // Writer.ChunkSize has been set to zero.
  114. func (w *Writer) Write(p []byte) (n int, err error) {
  115. w.mu.Lock()
  116. werr := w.err
  117. w.mu.Unlock()
  118. if werr != nil {
  119. return 0, werr
  120. }
  121. if !w.opened {
  122. if err := w.openWriter(); err != nil {
  123. return 0, err
  124. }
  125. }
  126. n, err = w.pw.Write(p)
  127. if err != nil {
  128. w.mu.Lock()
  129. werr := w.err
  130. w.mu.Unlock()
  131. // Preserve existing functionality that when context is canceled, Write will return
  132. // context.Canceled instead of "io: read/write on closed pipe". This hides the
  133. // pipe implementation detail from users and makes Write seem as though it's an RPC.
  134. if errors.Is(werr, context.Canceled) || errors.Is(werr, context.DeadlineExceeded) {
  135. return n, werr
  136. }
  137. }
  138. return n, err
  139. }
  140. // Close completes the write operation and flushes any buffered data.
  141. // If Close doesn't return an error, metadata about the written object
  142. // can be retrieved by calling Attrs.
  143. func (w *Writer) Close() error {
  144. if !w.opened {
  145. if err := w.openWriter(); err != nil {
  146. return err
  147. }
  148. }
  149. // Closing either the read or write causes the entire pipe to close.
  150. if err := w.pw.Close(); err != nil {
  151. return err
  152. }
  153. <-w.donec
  154. w.mu.Lock()
  155. defer w.mu.Unlock()
  156. trace.EndSpan(w.ctx, w.err)
  157. return w.err
  158. }
  159. func (w *Writer) openWriter() (err error) {
  160. if err := w.validateWriteAttrs(); err != nil {
  161. return err
  162. }
  163. if w.o.gen != defaultGen {
  164. return fmt.Errorf("storage: generation not supported on Writer, got %v", w.o.gen)
  165. }
  166. isIdempotent := w.o.conds != nil && (w.o.conds.GenerationMatch >= 0 || w.o.conds.DoesNotExist == true)
  167. opts := makeStorageOpts(isIdempotent, w.o.retry, w.o.userProject)
  168. params := &openWriterParams{
  169. ctx: w.ctx,
  170. chunkSize: w.ChunkSize,
  171. chunkRetryDeadline: w.ChunkRetryDeadline,
  172. bucket: w.o.bucket,
  173. attrs: &w.ObjectAttrs,
  174. conds: w.o.conds,
  175. encryptionKey: w.o.encryptionKey,
  176. sendCRC32C: w.SendCRC32C,
  177. donec: w.donec,
  178. setError: w.error,
  179. progress: w.progress,
  180. setObj: func(o *ObjectAttrs) { w.obj = o },
  181. forceEmptyContentType: w.ForceEmptyContentType,
  182. }
  183. if err := w.ctx.Err(); err != nil {
  184. return err // short-circuit
  185. }
  186. w.pw, err = w.o.c.tc.OpenWriter(params, opts...)
  187. if err != nil {
  188. return err
  189. }
  190. w.opened = true
  191. go w.monitorCancel()
  192. return nil
  193. }
  194. // monitorCancel is intended to be used as a background goroutine. It monitors the
  195. // context, and when it observes that the context has been canceled, it manually
  196. // closes things that do not take a context.
  197. func (w *Writer) monitorCancel() {
  198. select {
  199. case <-w.ctx.Done():
  200. w.mu.Lock()
  201. werr := w.ctx.Err()
  202. w.err = werr
  203. w.mu.Unlock()
  204. // Closing either the read or write causes the entire pipe to close.
  205. w.CloseWithError(werr)
  206. case <-w.donec:
  207. }
  208. }
  209. // CloseWithError aborts the write operation with the provided error.
  210. // CloseWithError always returns nil.
  211. //
  212. // Deprecated: cancel the context passed to NewWriter instead.
  213. func (w *Writer) CloseWithError(err error) error {
  214. if !w.opened {
  215. return nil
  216. }
  217. return w.pw.CloseWithError(err)
  218. }
  219. // Attrs returns metadata about a successfully-written object.
  220. // It's only valid to call it after Close returns nil.
  221. func (w *Writer) Attrs() *ObjectAttrs {
  222. return w.obj
  223. }
  224. func (w *Writer) validateWriteAttrs() error {
  225. attrs := w.ObjectAttrs
  226. // Check the developer didn't change the object Name (this is unfortunate, but
  227. // we don't want to store an object under the wrong name).
  228. if attrs.Name != w.o.object {
  229. return fmt.Errorf("storage: Writer.Name %q does not match object name %q", attrs.Name, w.o.object)
  230. }
  231. if !utf8.ValidString(attrs.Name) {
  232. return fmt.Errorf("storage: object name %q is not valid UTF-8", attrs.Name)
  233. }
  234. if attrs.KMSKeyName != "" && w.o.encryptionKey != nil {
  235. return errors.New("storage: cannot use KMSKeyName with a customer-supplied encryption key")
  236. }
  237. if w.ChunkSize < 0 {
  238. return errors.New("storage: Writer.ChunkSize must be non-negative")
  239. }
  240. return nil
  241. }
  242. // progress is a convenience wrapper that reports write progress to the Writer
  243. // ProgressFunc if it is set and progress is non-zero.
  244. func (w *Writer) progress(p int64) {
  245. if w.ProgressFunc != nil && p != 0 {
  246. w.ProgressFunc(p)
  247. }
  248. }
  249. // error acquires the Writer's lock, sets the Writer's err to the given error,
  250. // then relinquishes the lock.
  251. func (w *Writer) error(err error) {
  252. w.mu.Lock()
  253. w.err = err
  254. w.mu.Unlock()
  255. }