Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
* [#3080](https://github.com/ruby-grape/grape/pull/3080): Drop the `active_support/isolated_execution_state` require that ActiveSupport now autoloads - [@ericproulx](https://github.com/ericproulx).
* [#3082](https://github.com/ruby-grape/grape/pull/3082): Stop reporting the keys of a param its validators rejected as undeclared - [@ericproulx](https://github.com/ericproulx).
* [#3083](https://github.com/ruby-grape/grape/pull/3083): Apply a mounting API's `default_error_status` to routes defined before the mount - [@ericproulx](https://github.com/ericproulx).
* [#3086](https://github.com/ruby-grape/grape/pull/3086): Close and delete multipart upload tempfiles once the response is closed - [@anyingiit](https://github.com/anyingiit), [@ericproulx](https://github.com/ericproulx).
* [#3087](https://github.com/ruby-grape/grape/pull/3087): Let a mounted API `use` the named params of the scope it is mounted in - [@ericproulx](https://github.com/ericproulx).
* [#3093](https://github.com/ruby-grape/grape/pull/3093): Move the endpoint Rack stack building into `Endpoint::RackStack` to fix RuboCop - [@ericproulx](https://github.com/ericproulx).
* [#3099](https://github.com/ruby-grape/grape/pull/3099): Report a nested Array scope that got no Array under its own name only - [@ericproulx](https://github.com/ericproulx).
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1294,6 +1294,8 @@ post '/' do
end
```

Grape closes and deletes the tempfiles of an upload once the response is closed, or once an exception escapes the API, as Rails does. To keep an uploaded file, copy or move it before the response is closed.

### First-Class `JSON` Types

Grape supports complex parameters given as JSON-formatted strings using the special `type: JSON` declaration. JSON objects and arrays of objects are accepted equally, with nested validation rules applied to all objects in either case:
Expand Down
14 changes: 14 additions & 0 deletions UPGRADING.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,20 @@ Upgrading Grape

### Upgrading to >= 4.2.0

#### Upload tempfiles are deleted once the response is closed

Grape now closes and deletes the tempfiles of a multipart upload once the response is closed, or once an exception escapes the API ([#3086](https://github.com/ruby-grape/grape/pull/3086)). It used to leave them until garbage collection or the process exited, unless the API ran inside an application that already did this, such as Rails with its `Rack::TempfileReaper`.

Code that keeps an uploaded tempfile after the response, for instance by handing its path to a background job, has to copy or move the file first:

```ruby
post 'avatar' do
path = Rails.root.join('tmp', 'uploads', SecureRandom.uuid)
FileUtils.cp(params[:avatar][:tempfile].path, path)
ProcessAvatarJob.perform_later(path.to_s)
end
```

#### `Grape::Util::MediaType` parses for a vendor's pattern

`Grape::Util::MediaType.parse`, `.best_quality` and `.new` take `vendor_pattern:`, the pattern `Grape::Util::MediaType.vendor_pattern(vendor)` answers, in place of `vendor:` ([#3098](https://github.com/ruby-grape/grape/pull/3098)). The header versioner looks its vendor's pattern up as it is built, so a request no longer reads a cache. Only code calling these internals is affected: pass `vendor_pattern: Grape::Util::MediaType.vendor_pattern(vendor)`.
Expand Down
15 changes: 10 additions & 5 deletions lib/grape/api/instance.rb
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,16 @@ def initialize

@router.compile!
@router.freeze
# One Rack::Head around the router strips the body of every HEAD
# response the API gives, including the router's own 404 and a mounted
# Rack app's, which go through no endpoint's stack. Rack::Lint goes
# outside it, where it sees the response that is served.
@app = Rack::Head.new(@router)
# Rack::Head and the tempfile reaper wrap the router once rather than
# each endpoint's stack, so they also reach the router's own 404 and a
# mounted Rack app's response, which go through no endpoint's stack.
# Rack::Head strips the body of every HEAD response. The reaper closes
# and unlinks the request's multipart tempfiles once the response is
# closed. Around an endpoint, it would also do so when a route cascades
# and the router closes that route's body, before the next route reads
# the same upload. Rack::Lint goes outside both, where it sees the
# response that is served.
@app = Grape::Middleware::TempfileReaper.new(Rack::Head.new(@router))
@app = Rack::Lint.new(@app) if lint?
@cascade = self.class.cascade
end
Expand Down
35 changes: 35 additions & 0 deletions lib/grape/middleware/tempfile_reaper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# frozen_string_literal: true

module Grape
module Middleware
# Closes and unlinks a request's multipart tempfiles once its response is
# closed, or as soon as an exception escapes, as Rack::TempfileReaper does.
# Rack's multipart parser records the tempfiles it creates in
# +rack.tempfiles+, so this looks there once the app has answered and
# wraps the body only when there are some. Rack's reaper allocates the
# Array and the BodyProxy for every request, and most requests upload
# nothing. A tempfile created after the response was returned, by a body
# that parses the upload as it is streamed, is left to garbage collection,
# as it was before Grape reaped them.
class TempfileReaper
def initialize(app)
@app = app
end

def call(env)
response = begin
@app.call(env)
rescue Exception # rubocop:disable Lint/RescueException
env[Rack::RACK_TEMPFILES]&.each(&:close!)
raise
end

tempfiles = env[Rack::RACK_TEMPFILES]
return response if tempfiles.nil? || tempfiles.empty?

# A new triplet: a mounted Rack app is free to answer a frozen one.
[response[0], response[1], Rack::BodyProxy.new(response[2]) { tempfiles.each(&:close!) }]
end
end
end
end
117 changes: 117 additions & 0 deletions spec/grape/integration/rack_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,123 @@
end
end

# https://github.com/ruby-grape/grape/issues/2487
describe 'multipart tempfiles' do
let(:uploaded_paths) { [] }
let(:upload) { Rack::Test::UploadedFile.new(__FILE__, 'text/plain') }

let(:app) do
paths = uploaded_paths
Class.new(Grape::API) do
params do
requires :file, type: File
end

post 'upload' do
paths << params[:file][:tempfile].path
'ok'
end

post 'failed_upload' do
paths << params[:file][:tempfile].path
error!('failed', 422)
end

post 'raising_upload' do
paths << params[:file][:tempfile].path
raise ArgumentError, 'boom'
end
end
end

it 'unlinks the tempfile once the response is closed' do
post '/upload', file: upload
expect(last_response.body).to eq('ok')
expect(uploaded_paths.size).to eq(1)
expect(File.exist?(uploaded_paths.first)).to be(false)
end

it 'unlinks the tempfile when the endpoint returns an error' do
post '/failed_upload', file: upload
expect(last_response.status).to eq(422)
expect(uploaded_paths.size).to eq(1)
expect(File.exist?(uploaded_paths.first)).to be(false)
end

it 'unlinks the tempfile when an exception escapes the API' do
expect { post '/raising_upload', file: upload }.to raise_error(ArgumentError, 'boom')
expect(uploaded_paths.size).to eq(1)
expect(File.exist?(uploaded_paths.first)).to be(false)
end

context 'when the route that read the upload cascades' do
let(:app) do
paths = uploaded_paths
declines = Class.new(Grape::API) do
post 'upload' do
paths << params[:file][:tempfile].path
error!('not mine', 404, 'X-Cascade' => 'pass')
end
end
answers = Class.new(Grape::API) do
post('upload') { params[:file][:tempfile].read.bytesize.to_s }
end
Class.new(Grape::API) do
mount declines
mount answers
end
end

it 'leaves the tempfile open for the next route and unlinks it once the response is closed' do
post '/upload', file: upload
expect(last_response.status).to eq(201)
expect(last_response.body).to eq(File.size(__FILE__).to_s)
expect(uploaded_paths.size).to eq(1)
expect(File.exist?(uploaded_paths.first)).to be(false)
end
end

context 'when a mounted Rack app reads the upload' do
let(:app) do
paths = uploaded_paths
rack_app = lambda do |env|
paths << Rack::Request.new(env).POST['file'][:tempfile].path
[200, { 'content-type' => 'text/plain' }, ['ok']].freeze
end
Class.new(Grape::API) do
mount rack_app => '/rack'
end
end

it 'unlinks the tempfile once the response is closed' do
post '/rack', file: upload
expect(last_response.body).to eq('ok')
expect(uploaded_paths.size).to eq(1)
expect(File.exist?(uploaded_paths.first)).to be(false)
end
end

context 'when Rack::TempfileReaper wraps the API too, as in a Rails application' do
let(:grape_api) do
paths = uploaded_paths
Class.new(Grape::API) do
post 'upload' do
paths << params[:file][:tempfile].path
'ok'
end
end
end
let(:app) { Rack::TempfileReaper.new(grape_api) }

it 'unlinks the tempfile once the response is closed' do
post '/upload', file: upload
expect(last_response.body).to eq('ok')
expect(uploaded_paths.size).to eq(1)
expect(File.exist?(uploaded_paths.first)).to be(false)
end
end
end

context 'when the app is mounted' do
let(:ping_mount) do
Class.new(Grape::API) do
Expand Down
Loading