Class: Miasma::Models::Storage::Aws

Inherits:
Miasma::Models::Storage show all
Includes:
Contrib::AwsApiCore::ApiCommon, Contrib::AwsApiCore::RequestUtils
Defined in:
lib/miasma/contrib/aws/storage.rb

Constant Summary collapse

API_SERVICE =

Service name of the API

's3'
API_VERSION =

Supported version of the AutoScaling API

'2006-03-01'

Constants inherited from Miasma::Models::Storage

MAX_BODY_SIZE_FOR_STRINGIFY, READ_BODY_CHUNK_SIZE

Instance Method Summary collapse

Methods included from Contrib::AwsApiCore::RequestUtils

#all_result_pages

Methods included from Contrib::AwsApiCore::ApiCommon

#api_for, #connect, #connection, #endpoint, included, #make_request, #uri_escape

Methods inherited from Miasma::Models::Storage

#buckets

Methods inherited from Types::Api

#api_for, #connect, #connection, #endpoint, #format_response, #make_request, #provider, #request

Methods included from Utils::Memoization

#_memo, #clear_memoizations!, #memoize, #unmemoize

Methods included from Utils::Lazy

included

Constructor Details

#initialize(args) ⇒ Aws

Simple init override to force HOST and adjust region for signatures if required



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/miasma/contrib/aws/storage.rb', line 20

def initialize(args)
  args = args.to_smash
  cache_region = args[:aws_region]
  args[:aws_region] = args.fetch(:aws_bucket_region, 'us-east-1')
  super(args)
  aws_region = cache_region
  if(aws_bucket_region)
    self.aws_host = "s3-#{aws_bucket_region}.amazonaws.com"
  else
    self.aws_host = 's3.amazonaws.com'
  end
end

Instance Method Details

#bucket_allArray<Models::Storage::Bucket>

Return all buckets

Returns:



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/miasma/contrib/aws/storage.rb', line 119

def bucket_all
  result = all_result_pages(nil, :body, 'ListAllMyBucketsResult', 'Buckets', 'Bucket') do |options|
    request(
      :path => '/',
      :params => options
    )
  end
  result.map do |bkt|
    Bucket.new(
      self,
      :id => bkt['Name'],
      :name => bkt['Name'],
      :created => bkt['CreationDate']
    ).valid_state
  end
end

#bucket_destroy(bucket) ⇒ TrueClass, FalseClass

Destroy bucket

Parameters:

Returns:

  • (TrueClass, FalseClass)


69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/miasma/contrib/aws/storage.rb', line 69

def bucket_destroy(bucket)
  if(bucket.persisted?)
    request(
      :path => '/',
      :method => :delete,
      :endpoint => bucket_endpoint(bucket),
      :expects => 204
    )
    true
  else
    false
  end
end

#bucket_endpoint(bucket) ⇒ String

TODO:

properly escape bucket name

Custom bucket endpoint

Parameters:

Returns:

  • (String)


112
113
114
# File 'lib/miasma/contrib/aws/storage.rb', line 112

def bucket_endpoint(bucket)
  ::File.join(endpoint, bucket.name)
end

#bucket_reload(bucket) ⇒ Models::Storage::Bucket

Reload the bucket

Parameters:

Returns:



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/miasma/contrib/aws/storage.rb', line 87

def bucket_reload(bucket)
  if(bucket.persisted?)
    begin
      result = request(
        :path => '/',
        :method => :head,
        :endpoint => bucket_endpoint(bucket)
      )
    rescue Error::ApiError::RequestError => e
      if(e.response.status == 404)
        bucket.data.clear
        bucket.dirty.clear
      else
        raise
      end
    end
  end
  bucket
end

#bucket_save(bucket) ⇒ Models::Storage::Bucket

Save bucket

Parameters:

Returns:



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/miasma/contrib/aws/storage.rb', line 37

def bucket_save(bucket)
  unless(bucket.persisted?)
    req_args = Smash.new(
      :method => :put,
      :path => '/',
      :endpoint => bucket_endpoint(bucket)
    )
    if(aws_bucket_region)
      req_args[:body] = XmlSimple.xml_out(
        Smash.new(
          'CreateBucketConfiguration' => {
            'LocationConstraint' => aws_bucket_region
          }
        ),
        'AttrPrefix' => true,
        'KeepRoot' => true
      )
      req_args[:headers] = Smash.new(
        'Content-Length' => req_args[:body].size.to_s
      )
    end
    request(req_args)
    bucket.id = bucket.name
    bucket.valid_state
  end
  bucket
end

#file_all(bucket) ⇒ Array<File>

Return all files within bucket

Parameters:

Returns:



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/miasma/contrib/aws/storage.rb', line 167

def file_all(bucket)
  result = all_result_pages(nil, :body, 'ListBucketResult', 'Contents') do |options|
    request(
      :path => '/',
      :params => options,
      :endpoint => bucket_endpoint(bucket)
    )
  end
  result.map do |file|
    File.new(
      bucket,
      :id => ::File.join(bucket.name, file['Key']),
      :name => file['Key'],
      :updated => file['LastModified'],
      :size => file['Size'].to_i
    ).valid_state
  end
end

#file_body(file) ⇒ IO, HTTP::Response::Body

Fetch the contents of the file

Parameters:

Returns:

  • (IO, HTTP::Response::Body)


356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/miasma/contrib/aws/storage.rb', line 356

def file_body(file)
  if(file.persisted?)
    result = request(
      :path => file_path(file),
      :endpoint => bucket_endpoint(file.bucket),
      :disable_body_extraction => true
    )
    content = result[:body]
    begin
      if(content.is_a?(String))
        StringIO.new(content)
      else
        if(content.respond_to?(:stream!))
          content.stream!
        end
        content
      end
    rescue HTTP::StateError
      StringIO.new(content.to_s)
    end
  else
    StringIO.new('')
  end
end

#file_destroy(file) ⇒ TrueClass, FalseClass

Destroy file

Parameters:

Returns:

  • (TrueClass, FalseClass)


292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/miasma/contrib/aws/storage.rb', line 292

def file_destroy(file)
  if(file.persisted?)
    request(
      :method => :delete,
      :path => file_path(file),
      :endpoint => bucket_endpoint(file.bucket),
      :expects => 204
    )
    true
  else
    false
  end
end

#file_filter(bucket, args) ⇒ Array<Models::Storage::File>

Return filtered files

Parameters:

  • args (Hash)

    filter options

Returns:



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/miasma/contrib/aws/storage.rb', line 140

def file_filter(bucket, args)
  if(args[:prefix])
    result = request(
      :path => '/',
      :endpoint => bucket_endpoint(bucket),
      :params => Smash.new(
        :prefix => args[:prefix]
      )
    )
    [result.get(:body, 'ListBucketResult', 'Contents')].flatten.compact.map do |file|
      File.new(
        bucket,
        :id => ::File.join(bucket.name, file['Key']),
        :name => file['Key'],
        :updated => file['LastModified'],
        :size => file['Size'].to_i
      ).valid_state
    end
  else
    bucket_all
  end
end

#file_path(file) ⇒ String

Returns escaped file path.

Returns:

  • (String)

    escaped file path



396
397
398
399
400
# File 'lib/miasma/contrib/aws/storage.rb', line 396

def file_path(file)
  file.name.split('/').map do |part|
    uri_escape(part)
  end.join('/')
end

#file_reload(file) ⇒ Models::Storage::File

Reload the file

Parameters:

Returns:



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/miasma/contrib/aws/storage.rb', line 310

def file_reload(file)
  if(file.persisted?)
    name = file.name
    result = request(
      :path => file_path(file),
      :endpoint => bucket_endpoint(file.bucket)
    )
    file.data.clear && file.dirty.clear
    info = result[:headers]
    file.load_data(
      :id => ::File.join(file.bucket.name, name),
      :name => name,
      :updated => info[:last_modified],
      :etag => info[:etag],
      :size => info[:content_length].to_i,
      :content_type => info[:content_type]
    ).valid_state
  end
  file
end

#file_save(file) ⇒ Models::Storage::File

Save file

Parameters:

Returns:



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/miasma/contrib/aws/storage.rb', line 190

def file_save(file)
  if(file.dirty?)
    file.load_data(file.attributes)
    args = Smash.new
    args[:headers] = Smash[
      Smash.new(
        :content_type => 'Content-Type',
        :content_disposition => 'Content-Disposition',
        :content_encoding => 'Content-Encoding'
      ).map do |attr, key|
        if(file.attributes[attr])
          [key, file.attributes[attr]]
        end
      end.compact
    ]
    if(file.attributes[:body].is_a?(IO) && file.body.size >= Storage::MAX_BODY_SIZE_FOR_STRINGIFY)
      upload_id = request(
        args.merge(
          Smash.new(
            :path => file_path(file),
            :endpoint => bucket_endpoint(bucket),
            :params => {
              :uploads => true
            }
          )
        )
      ).get(:body, 'InitiateMultipartUploadResult', 'UploadId')
      count = 1
      parts = []
      file.body.rewind
      while(content = file.body.read(Storage::READ_BODY_CHUNK_SIZE))
        parts << [
          count,
          request(
            :method => :put,
            :path => file_path(file),
            :endpoint => bucket_endpoint(bucket),
            :headers => Smash.new(
              'Content-Length' => content.size,
              'Content-MD5' => Digest::MD5.hexdigest(content)
            ),
            :params => Smash.new(
              'partNumber' => count,
              'uploadId' => upload_id
            ),
            :body => content
          ).get(:body, :headers, :etag)
        ]
        count += 1
      end
      complete = SimpleXml.xml_out(
        Smash.new(
          'CompleteMultipartUpload' => {
            'Part' => parts.map{|part|
              {'PartNumber' => part.first, 'ETag' => part.last}
            }
          }
        ),
        'AttrPrefix' => true,
        'KeepRoot' => true
      )
      result = request(
        :method => :post,
        :path => file_path(file),
        :endpoint => bucket_endpoint(file.bucket),
        :params => Smash.new(
          'UploadId' => upload_id
        ),
        :headers => Smash.new(
          'Content-Length' => complete.size
        ),
        :body => complete
      )
      file.etag = result.get(:body, 'CompleteMultipartUploadResult', 'ETag')
    else
      if(file.attributes[:body].is_a?(IO) || file.attributes[:body].is_a?(StringIO))
        args[:headers]['Content-Length'] = file.body.size.to_s
        file.body.rewind
        args[:body] = file.body.read
        file.body.rewind
      end
      result = request(
        args.merge(
          Smash.new(
            :method => :put,
            :path => file_path(file),
            :endpoint => bucket_endpoint(file.bucket)
          )
        )
      )
      file.etag = result.get(:headers, :etag)
    end
    file.id = ::File.join(file.bucket.name, file.name)
    file.valid_state
  end
  file
end

#file_url(file, timeout_secs) ⇒ String

Create publicly accessible URL

Parameters:

  • timeout_secs (Integer)

    seconds available

Returns:

  • (String)

    URL



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/miasma/contrib/aws/storage.rb', line 335

def file_url(file, timeout_secs)
  if(file.persisted?)
    signer.generate_url(
      :get, ::File.join(uri_escape(file.bucket.name), file_path(file)),
      :headers => Smash.new(
        'Host' => aws_host
      ),
      :params => Smash.new(
        'X-Amz-Date' => Contrib::AwsApiCore.time_iso8601,
        'X-Amz-Expires' => timeout_secs
      )
    )
  else
    raise Error::ModelPersistError.new "#{file} has not been saved!"
  end
end

#update_request(con, opts) ⇒ TrueClass

Note:

this only updates when :body is defined. if a :post is

Simple callback to allow request option adjustments prior to signature calculation

happening (which implicitly forces :form) or :json is used it will not properly checksum. (but that’s probably okay)

Parameters:

  • opts (Smash)

    request options

Returns:

  • (TrueClass)


389
390
391
392
393
# File 'lib/miasma/contrib/aws/storage.rb', line 389

def update_request(con, opts)
  con.default_headers['x-amz-content-sha256'] = Digest::SHA256.
    hexdigest(opts.fetch(:body, ''))
  true
end