|
| 1 | +# Copyright 2022 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 | + |
| 15 | +require 'google/apis/core/http_command' |
| 16 | +require 'google/apis/core/api_command' |
| 17 | +require 'google/apis/errors' |
| 18 | +require 'tempfile' |
| 19 | +require 'mini_mime' |
| 20 | + |
| 21 | +module Google |
| 22 | + module Apis |
| 23 | + module Core |
| 24 | + # Base upload command. Not intended to be used directly |
| 25 | + # @private |
| 26 | + class StorageUploadCommand < ApiCommand |
| 27 | + CONTENT_LENGTH_HEADER = "Content-Length" |
| 28 | + CONTENT_TYPE_HEADER = "Content-Type" |
| 29 | + UPLOAD_CONTENT_TYPE_HEADER = "X-Upload-Content-Type" |
| 30 | + LOCATION_HEADER = "Location" |
| 31 | + CONTENT_RANGE_HEADER = "Content-Range" |
| 32 | + RESUMABLE = "resumable" |
| 33 | + OK_STATUS = 200 |
| 34 | + CHUNK_SIZE = 8 * 1024 * 1024 # 8 MB |
| 35 | + |
| 36 | + # File name or IO containing the content to upload |
| 37 | + # @return [String, File, #read] |
| 38 | + attr_accessor :upload_source |
| 39 | + |
| 40 | + # Content type of the upload material |
| 41 | + # @return [String] |
| 42 | + attr_accessor :upload_content_type |
| 43 | + |
| 44 | + # Content, as UploadIO |
| 45 | + # @return [Google::Apis::Core::UploadIO] |
| 46 | + attr_accessor :upload_io |
| 47 | + |
| 48 | + # Ensure the content is readable and wrapped in an IO instance. |
| 49 | + # |
| 50 | + # @return [void] |
| 51 | + # @raise [Google::Apis::ClientError] if upload source is invalid |
| 52 | + def prepare! |
| 53 | + @upload_url = nil |
| 54 | + @offset = 0 |
| 55 | + @upload_incomplete = true |
| 56 | + # Prevent the command from populating the body with form encoding, by |
| 57 | + # asserting that it already has a body. Form encoding is never used |
| 58 | + # by upload requests. |
| 59 | + self.body = '' unless self.body |
| 60 | + |
| 61 | + super |
| 62 | + if streamable?(upload_source) |
| 63 | + self.upload_io = upload_source |
| 64 | + @close_io_on_finish = false |
| 65 | + elsif self.upload_source.is_a?(String) |
| 66 | + self.upload_io = File.new(upload_source, 'r') |
| 67 | + if self.upload_content_type.nil? |
| 68 | + type = MiniMime.lookup_by_filename(upload_source) |
| 69 | + self.upload_content_type = type&.content_type |
| 70 | + end |
| 71 | + @close_io_on_finish = true |
| 72 | + else |
| 73 | + fail Google::Apis::ClientError, 'Invalid upload source' |
| 74 | + end |
| 75 | + end |
| 76 | + |
| 77 | + # Close IO stream when command done. Only closes the stream if it was opened by the command. |
| 78 | + def release! |
| 79 | + upload_io.close if @close_io_on_finish |
| 80 | + end |
| 81 | + |
| 82 | + # Execute the command, retrying as necessary |
| 83 | + # |
| 84 | + # @param [HTTPClient] client |
| 85 | + # HTTP client |
| 86 | + # @yield [result, err] Result or error if block supplied |
| 87 | + # @return [Object] |
| 88 | + # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried |
| 89 | + # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification |
| 90 | + # @raise [Google::Apis::AuthorizationError] Authorization is required |
| 91 | + def execute(client) |
| 92 | + prepare! |
| 93 | + opencensus_begin_span |
| 94 | + |
| 95 | + do_retry :initiate_resumable_upload, client |
| 96 | + while @upload_incomplete |
| 97 | + res = do_retry :send_upload_command, client |
| 98 | + end |
| 99 | + res |
| 100 | + ensure |
| 101 | + opencensus_end_span |
| 102 | + @http_res = nil |
| 103 | + release! |
| 104 | + end |
| 105 | + |
| 106 | + def initiate_resumable_upload(client) |
| 107 | + logger.debug { sprintf('Intiating resumable upload command to %s', url) } |
| 108 | + |
| 109 | + request_header = header.dup |
| 110 | + apply_request_options(request_header) |
| 111 | + |
| 112 | + request_query = query.dup |
| 113 | + request_query['uploadType'] = RESUMABLE |
| 114 | + |
| 115 | + request_header[CONTENT_LENGTH_HEADER] = upload_io.size.to_s |
| 116 | + request_header[CONTENT_TYPE_HEADER] = JSON_CONTENT_TYPE |
| 117 | + request_header[UPLOAD_CONTENT_TYPE_HEADER] = upload_content_type unless upload_content_type.nil? |
| 118 | + |
| 119 | + response = client.post(url.to_s, query: request_query, |
| 120 | + body: body, |
| 121 | + header: request_header, |
| 122 | + follow_redirect: true) |
| 123 | + result = process_response(response.status_code, response.header, response.body) |
| 124 | + success(result) |
| 125 | + rescue => e |
| 126 | + error(e, rethrow: true) |
| 127 | + end |
| 128 | + |
| 129 | + # Send the actual content |
| 130 | + # |
| 131 | + # @param [HTTPClient] client |
| 132 | + # HTTP client |
| 133 | + # @return [HTTP::Message] |
| 134 | + # @raise [Google::Apis::ServerError] Unable to send the request |
| 135 | + def send_upload_command(client) |
| 136 | + logger.debug { sprintf('Sending upload command to %s', @upload_url) } |
| 137 | + |
| 138 | + remaining_content_size = upload_io.size - @offset |
| 139 | + current_chunk_size = remaining_content_size < CHUNK_SIZE ? remaining_content_size : CHUNK_SIZE |
| 140 | + |
| 141 | + request_header = header.dup |
| 142 | + request_header[CONTENT_RANGE_HEADER] = sprintf('bytes %d-%d/%d', @offset, @offset+current_chunk_size-1, upload_io.size) |
| 143 | + request_header[CONTENT_LENGTH_HEADER] = current_chunk_size |
| 144 | + chunk_body = upload_io.read(current_chunk_size) |
| 145 | + |
| 146 | + response = client.put(@upload_url, body: chunk_body, header: request_header, follow_redirect: true) |
| 147 | + |
| 148 | + result = process_response(response.status_code, response.header, response.body) |
| 149 | + @upload_incomplete = false if response.status_code.eql? OK_STATUS |
| 150 | + @offset += current_chunk_size if @upload_incomplete |
| 151 | + success(result) |
| 152 | + rescue => e |
| 153 | + upload_io.pos = @offset |
| 154 | + error(e, rethrow: true) |
| 155 | + end |
| 156 | + |
| 157 | + # Check the to see if the upload is complete or needs to be resumed. |
| 158 | + # |
| 159 | + # @param [Integer] status |
| 160 | + # HTTP status code of response |
| 161 | + # @param [HTTP::Message::Headers] header |
| 162 | + # Response headers |
| 163 | + # @param [String, #read] body |
| 164 | + # Response body |
| 165 | + # @return [Object] |
| 166 | + # Response object |
| 167 | + # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried |
| 168 | + # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification |
| 169 | + # @raise [Google::Apis::AuthorizationError] Authorization is required |
| 170 | + def process_response(status, header, body) |
| 171 | + @upload_url = header[LOCATION_HEADER].first unless header[LOCATION_HEADER].empty? |
| 172 | + super(status, header, body) |
| 173 | + end |
| 174 | + |
| 175 | + def streamable?(upload_source) |
| 176 | + upload_source.is_a?(IO) || upload_source.is_a?(StringIO) || upload_source.is_a?(Tempfile) |
| 177 | + end |
| 178 | + end |
| 179 | + end |
| 180 | + end |
| 181 | +end |
0 commit comments