media.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gensupport
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "mime"
  10. "mime/multipart"
  11. "net/http"
  12. "net/textproto"
  13. "strings"
  14. "sync"
  15. "time"
  16. gax "github.com/googleapis/gax-go/v2"
  17. "google.golang.org/api/googleapi"
  18. )
  19. type typeReader struct {
  20. io.Reader
  21. typ string
  22. }
  23. // multipartReader combines the contents of multiple readers to create a multipart/related HTTP body.
  24. // Close must be called if reads from the multipartReader are abandoned before reaching EOF.
  25. type multipartReader struct {
  26. pr *io.PipeReader
  27. ctype string
  28. mu sync.Mutex
  29. pipeOpen bool
  30. }
  31. // boundary optionally specifies the MIME boundary
  32. func newMultipartReader(parts []typeReader, boundary string) *multipartReader {
  33. mp := &multipartReader{pipeOpen: true}
  34. var pw *io.PipeWriter
  35. mp.pr, pw = io.Pipe()
  36. mpw := multipart.NewWriter(pw)
  37. if boundary != "" {
  38. mpw.SetBoundary(boundary)
  39. }
  40. mp.ctype = "multipart/related; boundary=" + mpw.Boundary()
  41. go func() {
  42. for _, part := range parts {
  43. w, err := mpw.CreatePart(typeHeader(part.typ))
  44. if err != nil {
  45. mpw.Close()
  46. pw.CloseWithError(fmt.Errorf("googleapi: CreatePart failed: %v", err))
  47. return
  48. }
  49. _, err = io.Copy(w, part.Reader)
  50. if err != nil {
  51. mpw.Close()
  52. pw.CloseWithError(fmt.Errorf("googleapi: Copy failed: %v", err))
  53. return
  54. }
  55. }
  56. mpw.Close()
  57. pw.Close()
  58. }()
  59. return mp
  60. }
  61. func (mp *multipartReader) Read(data []byte) (n int, err error) {
  62. return mp.pr.Read(data)
  63. }
  64. func (mp *multipartReader) Close() error {
  65. mp.mu.Lock()
  66. if !mp.pipeOpen {
  67. mp.mu.Unlock()
  68. return nil
  69. }
  70. mp.pipeOpen = false
  71. mp.mu.Unlock()
  72. return mp.pr.Close()
  73. }
  74. // CombineBodyMedia combines a json body with media content to create a multipart/related HTTP body.
  75. // It returns a ReadCloser containing the combined body, and the overall "multipart/related" content type, with random boundary.
  76. //
  77. // The caller must call Close on the returned ReadCloser if reads are abandoned before reaching EOF.
  78. func CombineBodyMedia(body io.Reader, bodyContentType string, media io.Reader, mediaContentType string) (io.ReadCloser, string) {
  79. return combineBodyMedia(body, bodyContentType, media, mediaContentType, "")
  80. }
  81. // combineBodyMedia is CombineBodyMedia but with an optional mimeBoundary field.
  82. func combineBodyMedia(body io.Reader, bodyContentType string, media io.Reader, mediaContentType, mimeBoundary string) (io.ReadCloser, string) {
  83. mp := newMultipartReader([]typeReader{
  84. {body, bodyContentType},
  85. {media, mediaContentType},
  86. }, mimeBoundary)
  87. return mp, mp.ctype
  88. }
  89. func typeHeader(contentType string) textproto.MIMEHeader {
  90. h := make(textproto.MIMEHeader)
  91. if contentType != "" {
  92. h.Set("Content-Type", contentType)
  93. }
  94. return h
  95. }
  96. // PrepareUpload determines whether the data in the supplied reader should be
  97. // uploaded in a single request, or in sequential chunks.
  98. // chunkSize is the size of the chunk that media should be split into.
  99. //
  100. // If chunkSize is zero, media is returned as the first value, and the other
  101. // two return values are nil, true.
  102. //
  103. // Otherwise, a MediaBuffer is returned, along with a bool indicating whether the
  104. // contents of media fit in a single chunk.
  105. //
  106. // After PrepareUpload has been called, media should no longer be used: the
  107. // media content should be accessed via one of the return values.
  108. func PrepareUpload(media io.Reader, chunkSize int) (r io.Reader, mb *MediaBuffer, singleChunk bool) {
  109. if chunkSize == 0 { // do not chunk
  110. return media, nil, true
  111. }
  112. mb = NewMediaBuffer(media, chunkSize)
  113. _, _, _, err := mb.Chunk()
  114. // If err is io.EOF, we can upload this in a single request. Otherwise, err is
  115. // either nil or a non-EOF error. If it is the latter, then the next call to
  116. // mb.Chunk will return the same error. Returning a MediaBuffer ensures that this
  117. // error will be handled at some point.
  118. return nil, mb, err == io.EOF
  119. }
  120. // MediaInfo holds information for media uploads. It is intended for use by generated
  121. // code only.
  122. type MediaInfo struct {
  123. // At most one of Media and MediaBuffer will be set.
  124. media io.Reader
  125. buffer *MediaBuffer
  126. singleChunk bool
  127. mType string
  128. size int64 // mediaSize, if known. Used only for calls to progressUpdater_.
  129. progressUpdater googleapi.ProgressUpdater
  130. chunkRetryDeadline time.Duration
  131. }
  132. // NewInfoFromMedia should be invoked from the Media method of a call. It returns a
  133. // MediaInfo populated with chunk size and content type, and a reader or MediaBuffer
  134. // if needed.
  135. func NewInfoFromMedia(r io.Reader, options []googleapi.MediaOption) *MediaInfo {
  136. mi := &MediaInfo{}
  137. opts := googleapi.ProcessMediaOptions(options)
  138. if !opts.ForceEmptyContentType {
  139. mi.mType = opts.ContentType
  140. if mi.mType == "" {
  141. r, mi.mType = gax.DetermineContentType(r)
  142. }
  143. }
  144. mi.chunkRetryDeadline = opts.ChunkRetryDeadline
  145. mi.media, mi.buffer, mi.singleChunk = PrepareUpload(r, opts.ChunkSize)
  146. return mi
  147. }
  148. // NewInfoFromResumableMedia should be invoked from the ResumableMedia method of a
  149. // call. It returns a MediaInfo using the given reader, size and media type.
  150. func NewInfoFromResumableMedia(r io.ReaderAt, size int64, mediaType string) *MediaInfo {
  151. rdr := ReaderAtToReader(r, size)
  152. mType := mediaType
  153. if mType == "" {
  154. rdr, mType = gax.DetermineContentType(rdr)
  155. }
  156. return &MediaInfo{
  157. size: size,
  158. mType: mType,
  159. buffer: NewMediaBuffer(rdr, googleapi.DefaultUploadChunkSize),
  160. media: nil,
  161. singleChunk: false,
  162. }
  163. }
  164. // SetProgressUpdater sets the progress updater for the media info.
  165. func (mi *MediaInfo) SetProgressUpdater(pu googleapi.ProgressUpdater) {
  166. if mi != nil {
  167. mi.progressUpdater = pu
  168. }
  169. }
  170. // UploadType determines the type of upload: a single request, or a resumable
  171. // series of requests.
  172. func (mi *MediaInfo) UploadType() string {
  173. if mi.singleChunk {
  174. return "multipart"
  175. }
  176. return "resumable"
  177. }
  178. // UploadRequest sets up an HTTP request for media upload. It adds headers
  179. // as necessary, and returns a replacement for the body and a function for http.Request.GetBody.
  180. func (mi *MediaInfo) UploadRequest(reqHeaders http.Header, body io.Reader) (newBody io.Reader, getBody func() (io.ReadCloser, error), cleanup func()) {
  181. cleanup = func() {}
  182. if mi == nil {
  183. return body, nil, cleanup
  184. }
  185. var media io.Reader
  186. if mi.media != nil {
  187. // This only happens when the caller has turned off chunking. In that
  188. // case, we write all of media in a single non-retryable request.
  189. media = mi.media
  190. } else if mi.singleChunk {
  191. // The data fits in a single chunk, which has now been read into the MediaBuffer.
  192. // We obtain that chunk so we can write it in a single request. The request can
  193. // be retried because the data is stored in the MediaBuffer.
  194. media, _, _, _ = mi.buffer.Chunk()
  195. }
  196. toCleanup := []io.Closer{}
  197. if media != nil {
  198. fb := readerFunc(body)
  199. fm := readerFunc(media)
  200. combined, ctype := CombineBodyMedia(body, "application/json", media, mi.mType)
  201. toCleanup = append(toCleanup, combined)
  202. if fb != nil && fm != nil {
  203. getBody = func() (io.ReadCloser, error) {
  204. rb := io.NopCloser(fb())
  205. rm := io.NopCloser(fm())
  206. var mimeBoundary string
  207. if _, params, err := mime.ParseMediaType(ctype); err == nil {
  208. mimeBoundary = params["boundary"]
  209. }
  210. r, _ := combineBodyMedia(rb, "application/json", rm, mi.mType, mimeBoundary)
  211. toCleanup = append(toCleanup, r)
  212. return r, nil
  213. }
  214. }
  215. reqHeaders.Set("Content-Type", ctype)
  216. body = combined
  217. }
  218. if mi.buffer != nil && mi.mType != "" && !mi.singleChunk {
  219. // This happens when initiating a resumable upload session.
  220. // The initial request contains a JSON body rather than media.
  221. // It can be retried with a getBody function that re-creates the request body.
  222. fb := readerFunc(body)
  223. if fb != nil {
  224. getBody = func() (io.ReadCloser, error) {
  225. rb := io.NopCloser(fb())
  226. toCleanup = append(toCleanup, rb)
  227. return rb, nil
  228. }
  229. }
  230. reqHeaders.Set("X-Upload-Content-Type", mi.mType)
  231. }
  232. // Ensure that any bodies created in getBody are cleaned up.
  233. cleanup = func() {
  234. for _, closer := range toCleanup {
  235. _ = closer.Close()
  236. }
  237. }
  238. return body, getBody, cleanup
  239. }
  240. // readerFunc returns a function that always returns an io.Reader that has the same
  241. // contents as r, provided that can be done without consuming r. Otherwise, it
  242. // returns nil.
  243. // See http.NewRequest (in net/http/request.go).
  244. func readerFunc(r io.Reader) func() io.Reader {
  245. switch r := r.(type) {
  246. case *bytes.Buffer:
  247. buf := r.Bytes()
  248. return func() io.Reader { return bytes.NewReader(buf) }
  249. case *bytes.Reader:
  250. snapshot := *r
  251. return func() io.Reader { r := snapshot; return &r }
  252. case *strings.Reader:
  253. snapshot := *r
  254. return func() io.Reader { r := snapshot; return &r }
  255. default:
  256. return nil
  257. }
  258. }
  259. // ResumableUpload returns an appropriately configured ResumableUpload value if the
  260. // upload is resumable, or nil otherwise.
  261. func (mi *MediaInfo) ResumableUpload(locURI string) *ResumableUpload {
  262. if mi == nil || mi.singleChunk {
  263. return nil
  264. }
  265. return &ResumableUpload{
  266. URI: locURI,
  267. Media: mi.buffer,
  268. MediaType: mi.mType,
  269. Callback: func(curr int64) {
  270. if mi.progressUpdater != nil {
  271. mi.progressUpdater(curr, mi.size)
  272. }
  273. },
  274. ChunkRetryDeadline: mi.chunkRetryDeadline,
  275. }
  276. }
  277. // SetGetBody sets the GetBody field of req to f. This was once needed
  278. // to gracefully support Go 1.7 and earlier which didn't have that
  279. // field.
  280. //
  281. // Deprecated: the code generator no longer uses this as of
  282. // 2019-02-19. Nothing else should be calling this anyway, but we
  283. // won't delete this immediately; it will be deleted in as early as 6
  284. // months.
  285. func SetGetBody(req *http.Request, f func() (io.ReadCloser, error)) {
  286. req.GetBody = f
  287. }