From b5b20a4db16b6787399a75db6b5d5dfc8b0caa95 Mon Sep 17 00:00:00 2001 From: Eric Proulx Date: Fri, 20 Nov 2026 23:35:33 +0100 Subject: [PATCH] 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 --- CHANGELOG.md | 1 + README.md | 2 + UPGRADING.md | 14 +++ lib/grape/api/instance.rb | 15 ++- lib/grape/middleware/tempfile_reaper.rb | 35 +++++++ spec/grape/integration/rack_spec.rb | 117 ++++++++++++++++++++++++ 6 files changed, 179 insertions(+), 5 deletions(-) create mode 100644 lib/grape/middleware/tempfile_reaper.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index dd2c99bb2..19125a1c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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). diff --git a/README.md b/README.md index 9a38a9889..5cc412345 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/UPGRADING.md b/UPGRADING.md index 98cd7020e..becc35091 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -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)`. diff --git a/lib/grape/api/instance.rb b/lib/grape/api/instance.rb index 09b25f2f7..60353ffb7 100644 --- a/lib/grape/api/instance.rb +++ b/lib/grape/api/instance.rb @@ -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 diff --git a/lib/grape/middleware/tempfile_reaper.rb b/lib/grape/middleware/tempfile_reaper.rb new file mode 100644 index 000000000..25f9e4649 --- /dev/null +++ b/lib/grape/middleware/tempfile_reaper.rb @@ -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 diff --git a/spec/grape/integration/rack_spec.rb b/spec/grape/integration/rack_spec.rb index 174da5858..2af70a7c6 100644 --- a/spec/grape/integration/rack_spec.rb +++ b/spec/grape/integration/rack_spec.rb @@ -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