Skip to content

Commit 98ea28d

Browse files
ericproulxanyingiitclaude
committed
Close and delete multipart upload tempfiles once the response is closed
Rack's multipart parser leaves its tempfiles to whatever reaps them, and outside Rails nothing did, so a standalone Grape API kept every upload on disk until garbage collection or exit (#2487). A reaper now wraps the router, next to Rack::Head. There it also covers a mounted Rack app. Unlike one in each endpoint's stack, it doesn't fire when a route cascades and the router closes that route's body before the next route reads the same upload. Rack::TempfileReaper allocates an Array and a BodyProxy for every request, which cost 13-18% of a bare GET. Grape's reaper instead reads rack.tempfiles once the app has answered, and wraps the body only when the request uploaded something. Replaces #3041. Fixes #2487. Co-Authored-By: anyingiit <49945850+anyingiit@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f9a05c4 commit 98ea28d

5 files changed

Lines changed: 178 additions & 5 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1293,6 +1293,8 @@ post '/' do
12931293
end
12941294
```
12951295

1296+
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.
1297+
12961298
### First-Class `JSON` Types
12971299

12981300
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:

‎UPGRADING.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,20 @@ end
113113

114114
To keep the enclosing handler for such an exception, register its class in the nested scope as well: a scope's class handlers still rank ahead of its own `rescue_from :all`. An exception `rescue_from :all` does not catch, one that is not a `StandardError`, still reaches the enclosing scope's handlers, and so does one raised inside the catch-all's block.
115115

116+
#### Upload tempfiles are deleted once the response is closed
117+
118+
Grape now closes and deletes the tempfiles of a multipart upload once the response is closed, or once an exception escapes the API ([#PR](https://github.com/ruby-grape/grape/pull/PR)). 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`.
119+
120+
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:
121+
122+
```ruby
123+
post 'avatar' do
124+
path = Rails.root.join('tmp', 'uploads', SecureRandom.uuid)
125+
FileUtils.cp(params[:avatar][:tempfile].path, path)
126+
ProcessAvatarJob.perform_later(path.to_s)
127+
end
128+
```
129+
116130
### Upgrading to >= 4.1.0
117131

118132
#### `Rack::Head` wraps the router instead of each endpoint's stack

‎lib/grape/api/instance.rb‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -135,11 +135,16 @@ def initialize
135135

136136
@router.compile!
137137
@router.freeze
138-
# One Rack::Head around the router strips the body of every HEAD
139-
# response the API gives, including the router's own 404 and a mounted
140-
# Rack app's, which go through no endpoint's stack. Rack::Lint goes
141-
# outside it, where it sees the response that is served.
142-
@app = Rack::Head.new(@router)
138+
# Rack::Head and the tempfile reaper wrap the router once rather than
139+
# each endpoint's stack, so they also reach the router's own 404 and a
140+
# mounted Rack app's response, which go through no endpoint's stack.
141+
# Rack::Head strips the body of every HEAD response. The reaper closes
142+
# and unlinks the request's multipart tempfiles once the response is
143+
# closed. Around an endpoint, it would also do so when a route cascades
144+
# and the router closes that route's body, before the next route reads
145+
# the same upload. Rack::Lint goes outside both, where it sees the
146+
# response that is served.
147+
@app = Grape::Middleware::TempfileReaper.new(Rack::Head.new(@router))
143148
@app = Rack::Lint.new(@app) if lint?
144149
@cascade = self.class.cascade
145150
end
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# frozen_string_literal: true
2+
3+
module Grape
4+
module Middleware
5+
# Closes and unlinks a request's multipart tempfiles once its response is
6+
# closed, or as soon as an exception escapes, as Rack::TempfileReaper does.
7+
# Rack's multipart parser records the tempfiles it creates in
8+
# +rack.tempfiles+, so this looks there once the app has answered and
9+
# wraps the body only when there are some. Rack's reaper allocates the
10+
# Array and the BodyProxy for every request, and most requests upload
11+
# nothing. A tempfile created after the response was returned, by a body
12+
# that parses the upload as it is streamed, is left to garbage collection,
13+
# as it was before Grape reaped them.
14+
class TempfileReaper
15+
def initialize(app)
16+
@app = app
17+
end
18+
19+
def call(env)
20+
response = begin
21+
@app.call(env)
22+
rescue Exception # rubocop:disable Lint/RescueException
23+
env[Rack::RACK_TEMPFILES]&.each(&:close!)
24+
raise
25+
end
26+
27+
tempfiles = env[Rack::RACK_TEMPFILES]
28+
return response if tempfiles.nil? || tempfiles.empty?
29+
30+
# A new triplet: a mounted Rack app is free to answer a frozen one.
31+
[response[0], response[1], Rack::BodyProxy.new(response[2]) { tempfiles.each(&:close!) }]
32+
end
33+
end
34+
end
35+
end

‎spec/grape/integration/rack_spec.rb‎

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,123 @@
5050
end
5151
end
5252

53+
# https://github.com/ruby-grape/grape/issues/2487
54+
describe 'multipart tempfiles' do
55+
let(:uploaded_paths) { [] }
56+
let(:upload) { Rack::Test::UploadedFile.new(__FILE__, 'text/plain') }
57+
58+
let(:app) do
59+
paths = uploaded_paths
60+
Class.new(Grape::API) do
61+
params do
62+
requires :file, type: File
63+
end
64+
65+
post 'upload' do
66+
paths << params[:file][:tempfile].path
67+
'ok'
68+
end
69+
70+
post 'failed_upload' do
71+
paths << params[:file][:tempfile].path
72+
error!('failed', 422)
73+
end
74+
75+
post 'raising_upload' do
76+
paths << params[:file][:tempfile].path
77+
raise ArgumentError, 'boom'
78+
end
79+
end
80+
end
81+
82+
it 'unlinks the tempfile once the response is closed' do
83+
post '/upload', file: upload
84+
expect(last_response.body).to eq('ok')
85+
expect(uploaded_paths.size).to eq(1)
86+
expect(File.exist?(uploaded_paths.first)).to be(false)
87+
end
88+
89+
it 'unlinks the tempfile when the endpoint returns an error' do
90+
post '/failed_upload', file: upload
91+
expect(last_response.status).to eq(422)
92+
expect(uploaded_paths.size).to eq(1)
93+
expect(File.exist?(uploaded_paths.first)).to be(false)
94+
end
95+
96+
it 'unlinks the tempfile when an exception escapes the API' do
97+
expect { post '/raising_upload', file: upload }.to raise_error(ArgumentError, 'boom')
98+
expect(uploaded_paths.size).to eq(1)
99+
expect(File.exist?(uploaded_paths.first)).to be(false)
100+
end
101+
102+
context 'when the route that read the upload cascades' do
103+
let(:app) do
104+
paths = uploaded_paths
105+
declines = Class.new(Grape::API) do
106+
post 'upload' do
107+
paths << params[:file][:tempfile].path
108+
error!('not mine', 404, 'X-Cascade' => 'pass')
109+
end
110+
end
111+
answers = Class.new(Grape::API) do
112+
post('upload') { params[:file][:tempfile].read.bytesize.to_s }
113+
end
114+
Class.new(Grape::API) do
115+
mount declines
116+
mount answers
117+
end
118+
end
119+
120+
it 'leaves the tempfile open for the next route and unlinks it once the response is closed' do
121+
post '/upload', file: upload
122+
expect(last_response.status).to eq(201)
123+
expect(last_response.body).to eq(File.size(__FILE__).to_s)
124+
expect(uploaded_paths.size).to eq(1)
125+
expect(File.exist?(uploaded_paths.first)).to be(false)
126+
end
127+
end
128+
129+
context 'when a mounted Rack app reads the upload' do
130+
let(:app) do
131+
paths = uploaded_paths
132+
rack_app = lambda do |env|
133+
paths << Rack::Request.new(env).POST['file'][:tempfile].path
134+
[200, { 'content-type' => 'text/plain' }, ['ok']].freeze
135+
end
136+
Class.new(Grape::API) do
137+
mount rack_app => '/rack'
138+
end
139+
end
140+
141+
it 'unlinks the tempfile once the response is closed' do
142+
post '/rack', file: upload
143+
expect(last_response.body).to eq('ok')
144+
expect(uploaded_paths.size).to eq(1)
145+
expect(File.exist?(uploaded_paths.first)).to be(false)
146+
end
147+
end
148+
149+
context 'when Rack::TempfileReaper wraps the API too, as in a Rails application' do
150+
let(:grape_api) do
151+
paths = uploaded_paths
152+
Class.new(Grape::API) do
153+
post 'upload' do
154+
paths << params[:file][:tempfile].path
155+
'ok'
156+
end
157+
end
158+
end
159+
let(:app) { Rack::TempfileReaper.new(grape_api) }
160+
161+
it 'unlinks the tempfile once the response is closed' do
162+
post '/upload', file: upload
163+
expect(last_response.body).to eq('ok')
164+
expect(uploaded_paths.size).to eq(1)
165+
expect(File.exist?(uploaded_paths.first)).to be(false)
166+
end
167+
end
168+
end
169+
53170
context 'when the app is mounted' do
54171
let(:ping_mount) do
55172
Class.new(Grape::API) do

0 commit comments

Comments
 (0)