A platform for community discussion. Free, open, simple.
FIX: Return file paths from FileStore download methods (#37760)
Régis Hanol9d444e8d7a07
diff --git a/app/controllers/static_controller.rb b/app/controllers/static_controller.rbindex 79f25fcbec0..fb20f057263 100644--- a/app/controllers/static_controller.rb+++ b/app/controllers/static_controller.rb@@ -232,8 +232,10 @@ class StaticController < ApplicationControllerDiscourse.cache.fetch("llms_txt_content:#{upload.sha1}") do- Discourse.store.download_safe(upload)&.path&.then { |path| File.read(path) }+ path = Discourse.store.download(upload)+ File.read(path) if pathend+return head(:not_found) if content.blank?render plain: content, content_type: "text/plain"diff --git a/app/models/optimized_image.rb b/app/models/optimized_image.rbindex 1c403a867f2..79731101e1b 100644--- a/app/models/optimized_image.rb+++ b/app/models/optimized_image.rb@@ -67,8 +67,7 @@ class OptimizedImage < ActiveRecord::Baseif original_path.blank?# download is protected with a DistributedMutex- external_copy = store.download_safe(upload)- original_path = external_copy&.path+ original_path = store.download(upload)endif extension == ".svg" && upload.extension != "svg"@@ -147,9 +146,6 @@ class OptimizedImage < ActiveRecord::Basetemp_file.close!end- # make sure we remove the cached copy from external stores- external_copy&.close if store.external?-thumbnailendend@@ -170,7 +166,7 @@ class OptimizedImage < ActiveRecord::Baseif local?Discourse.store.path_for(self)else- Discourse.store.download!(self).path+ Discourse.store.download!(self)endFile.size(path)enddiff --git a/app/models/theme_field.rb b/app/models/theme_field.rbindex 9d8bab100c6..6901f43d050 100644--- a/app/models/theme_field.rb+++ b/app/models/theme_field.rb@@ -271,20 +271,18 @@ class ThemeField < ActiveRecord::Baseenddef validate_svg_sprite_xml- upload =- begin- Upload.find(self.upload_id)- rescue StandardError- nil- end+ upload = Upload.find_by(id: self.upload_id)++ return "Error with #{self.name}: No upload found for the provided upload_id" if upload.nil?if Discourse.store.external?- external_copy = Discourse.store.download_safe(upload)- path = external_copy&.path+ path = Discourse.store.download(upload)elsepath = Discourse.store.path_for(upload)end+ return "Error with #{self.name}: Could not download icon sprite" if path.nil?+error = nilbegin@@ -297,6 +295,7 @@ class ThemeField < ActiveRecord::Baserescue => eerror = "Error with #{self.name}: #{e.inspect}"end+errorenddiff --git a/app/models/upload.rb b/app/models/upload.rbindex b21939a048b..7debe5bdf93 100644--- a/app/models/upload.rb+++ b/app/models/upload.rb@@ -173,16 +173,12 @@ class Upload < ActiveRecord::Basedef contentoriginal_path = Discourse.store.path_for(self)- external_copy = nilif original_path.blank?- external_copy = Discourse.store.download!(self)- original_path = external_copy.path+ File.read(Discourse.store.download!(self))+ else+ File.read(original_path)end-- File.read(original_path)- ensure- File.unlink(external_copy.path) if external_copyenddef fix_image_extension@@ -191,10 +187,7 @@ class Upload < ActiveRecord::Basebegin# this is relatively cheap once cachedoriginal_path = Discourse.store.path_for(self)- if original_path.blank?- external_copy = Discourse.store.download_safe(self)- original_path = external_copy&.path- end+ original_path = Discourse.store.download(self) if original_path.blank?image_info =begin@@ -305,7 +298,7 @@ class Upload < ActiveRecord::Baseif local?Discourse.store.path_for(self)else- Discourse.store.download!(self).path+ Discourse.store.download!(self)endif extension == "svg"@@ -389,7 +382,7 @@ class Upload < ActiveRecord::Baseif local?Discourse.store.path_for(self)else- Discourse.store.download_safe(self)&.path+ Discourse.store.download(self)endif local_path.nil?diff --git a/lib/email/sender.rb b/lib/email/sender.rbindex bbbbba0245b..5592212a44d 100644--- a/lib/email/sender.rb+++ b/lib/email/sender.rb@@ -389,7 +389,7 @@ module Emailif attached_upload.local?Discourse.store.path_for(attached_upload)else- Discourse.store.download!(attached_upload).path+ Discourse.store.download!(attached_upload)end@message_attachments_index[original_upload.sha1] = @message.attachments.sizediff --git a/lib/file_store/base_store.rb b/lib/file_store/base_store.rbindex d2c4e1f43b5..868a8d96aea 100644--- a/lib/file_store/base_store.rb+++ b/lib/file_store/base_store.rb@@ -91,63 +91,27 @@ module FileStorenot_implementedend- # TODO: Remove when #download becomes the canonical safe version.- def download_safe(*, **)- download(*, **, print_deprecation: false)+ def download(*, **)+ perform_download(*, **)rescue StandardErrornilend+ def download_safe(*, **)+ Discourse.deprecate(+ "`FileStore::BaseStore#download_safe` is deprecated. Use `#download` instead.",+ since: "2026.02",+ drop_from: "2026.08",+ )+ download(*, **)+ end+def download!(*, **)- download(*, **, print_deprecation: false)+ perform_download(*, **)rescue StandardErrorraise DownloadErrorend- def download(object, max_file_size_kb: nil, print_deprecation: true)- DistributedMutex.synchronize("download_#{object.sha1}", validity: 3.minutes) do- extension =- File.extname(- object.respond_to?(:original_filename) ? object.original_filename : object.url,- )- filename = "#{object.sha1}#{extension}"- file = get_from_cache(filename)-- if !file- max_file_size_kb ||= [- SiteSetting.max_image_size_kb,- SiteSetting.max_attachment_size_kb,- ].max.kilobytes-- secure = object.respond_to?(:secure) ? object.secure? : object.upload.secure?- url =- (- if secure- Discourse.store.signed_url_for_path(object.url)- else- Discourse.store.cdn_url(object.url)- end- )-- url = SiteSetting.scheme + ":" + url if url =~ %r{\A//}- file =- FileHelper.download(- url,- max_file_size: max_file_size_kb,- tmp_file_name: "discourse-download",- follow_redirect: true,- )-- return nil if file.nil?-- cache_file(file, filename)- file = get_from_cache(filename)- end-- file- end- end-def purge_tombstone(grace_period)end@@ -199,7 +163,7 @@ module FileStoredef get_from_cache(filename)path = get_cache_path_for(filename)- File.open(path) if File.exist?(path)+ path if File.exist?(path)enddef cache_file(file, filename)@@ -217,6 +181,43 @@ module FileStoreprivate+ def perform_download(object, max_file_size_kb: nil)+ DistributedMutex.synchronize("download_#{object.sha1}", validity: 3.minutes) do+ name = object.respond_to?(:original_filename) ? object.original_filename : object.url+ extension = File.extname(name)+ filename = "#{object.sha1}#{extension}"++ unless File.exist?(get_cache_path_for(filename))+ max_file_size_kb ||= [+ SiteSetting.max_image_size_kb,+ SiteSetting.max_attachment_size_kb,+ ].max.kilobytes++ if object.respond_to?(:secure) ? object.secure? : object.upload.secure?+ url = Discourse.store.signed_url_for_path(object.url)+ else+ url = Discourse.store.cdn_url(object.url)+ end++ url = "#{SiteSetting.scheme}:#{url}" if url =~ %r{\A//}++ file =+ FileHelper.download(+ url,+ max_file_size: max_file_size_kb,+ tmp_file_name: "discourse-download",+ follow_redirect: true,+ )++ return if file.nil?++ cache_file(file, filename)+ end++ get_from_cache(filename)+ end+ end+def not_implementedraise "Not implemented."enddiff --git a/lib/tasks/site.rake b/lib/tasks/site.rakeindex 6f6ef037063..dec1d428afe 100644--- a/lib/tasks/site.rake+++ b/lib/tasks/site.rake@@ -45,8 +45,12 @@ class ZippedSiteStructurereturn @uploads[upload.id]end- local_path =- upload.local? ? Discourse.store.path_for(upload) : Discourse.store.download(upload).path+ if upload.local?+ local_path = Discourse.store.path_for(upload)+ else+ local_path = Discourse.store.download(upload)+ end+zip_path = File.join("uploads", File.basename(local_path))zip_path = get_unique_path(zip_path)diff --git a/lib/tasks/uploads.rake b/lib/tasks/uploads.rakeindex 051db9044a7..2092aca4b6b 100644--- a/lib/tasks/uploads.rake+++ b/lib/tasks/uploads.rake@@ -1317,7 +1317,7 @@ task "uploads:downsize" => :environment doif upload.local?Discourse.store.path_for(upload)else- Discourse.store.download_safe(upload, max_file_size_kb: 100.megabytes)&.path+ Discourse.store.download(upload, max_file_size_kb: 100.megabytes)endunless pathdiff --git a/plugins/discourse-ai/app/jobs/regular/digest_rag_upload.rb b/plugins/discourse-ai/app/jobs/regular/digest_rag_upload.rbindex f1a1db8c38f..b579ba6bf3c 100644--- a/plugins/discourse-ai/app/jobs/regular/digest_rag_upload.rb+++ b/plugins/discourse-ai/app/jobs/regular/digest_rag_upload.rb@@ -8,15 +8,10 @@ module Jobs# TODO(roman): Add a way to automatically recover from errors, resulting in unindexed uploads.def execute(args)- return if (upload = Upload.find_by(id: args[:upload_id])).nil?-- target_type = args[:target_type]- target_id = args[:target_id]-- return if !target_type || !target_id-- target = target_type.constantize.find_by(id: target_id)- return if !target+ return unless upload = Upload.find_by(id: args[:upload_id])+ return unless target_type = args[:target_type]+ return unless target_id = args[:target_id]+ return unless target = target_type.constantize.find_by(id: target_id)vector_rep = DiscourseAi::Embeddings::Vector.instance@@ -24,11 +19,11 @@ module Jobschunk_tokens = target.rag_chunk_tokensoverlap_tokens = target.rag_chunk_overlap_tokens- fragment_ids = RagDocumentFragment.where(target: target, upload: upload).pluck(:id)+ fragment_ids = RagDocumentFragment.where(target:, upload:).pluck(:id)# Check if this is the first time we process this upload.if fragment_ids.empty?- document = get_uploaded_file(upload: upload, target: target)+ document = get_uploaded_file(upload:, target:)return if document.nil?RagDocumentFragment.publish_status(upload, { total: 0, indexed: 0, left: 0 })@@ -39,16 +34,16 @@ module JobsActiveRecord::Base.transaction dochunk_document(file: document,- tokenizer: tokenizer,- chunk_tokens: chunk_tokens,- overlap_tokens: overlap_tokens,+ tokenizer:,+ chunk_tokens:,+ overlap_tokens:,) do |chunk, metadata|fragment_ids << RagDocumentFragment.create!(- target: target,+ target:,fragment: chunk,fragment_number: idx + 1,- upload: upload,- metadata: metadata,+ upload:,+ metadata:,).ididx += 1@@ -64,6 +59,8 @@ module Jobsfragment_ids.each_slice(50) do |slice|Jobs.enqueue(:generate_rag_embeddings, fragment_ids: slice)end+ ensure+ @file&.closeendprivate@@ -169,6 +166,7 @@ module Jobs"The setting ai_rag_images_enabled is false, can not index images",)end+if upload.extension == "pdf"return(DiscourseAi::Utils::PdfToText.as_fake_file(@@ -190,12 +188,14 @@ module Jobsendstore = Discourse.store+@file ||=if store.external?# Upload#filesize could be approximate.# add two extra Mbs to make sure that we'll be able to download the upload.max_filesize = upload.filesize + 2.megabytes- store.download(upload, max_file_size_kb: max_filesize)+ path = store.download(upload, max_file_size_kb: max_filesize)+ File.open(path) if pathelseFile.open(store.path_for(upload))enddiff --git a/plugins/discourse-ai/lib/completions/upload_encoder.rb b/plugins/discourse-ai/lib/completions/upload_encoder.rbindex 0ac19d396f4..528f343fb22 100644--- a/plugins/discourse-ai/lib/completions/upload_encoder.rb+++ b/plugins/discourse-ai/lib/completions/upload_encoder.rb@@ -131,14 +131,7 @@ module DiscourseAidef fetch_path(upload)path = Discourse.store.path_for(upload)- if path.blank?- external_copy = Discourse.store.download_safe(upload)- path = external_copy&.path- end- if path.blank?- external_copy = Discourse.store.download(upload)- path = external_copy&.path- end+ path = Discourse.store.download(upload) if path.blank?return if path.blank?return unless File.exist?(path)diff --git a/plugins/discourse-ai/lib/utils/image_to_text.rb b/plugins/discourse-ai/lib/utils/image_to_text.rbindex e340038864f..d892637d8db 100644--- a/plugins/discourse-ai/lib/utils/image_to_text.rb+++ b/plugins/discourse-ai/lib/utils/image_to_text.rb@@ -150,7 +150,7 @@ class DiscourseAi::Utils::ImageToTextif page.local?Discourse.store.path_for(page)else- Discourse.store.download_safe(page, max_file_size_kb: MAX_IMAGE_SIZE)&.path+ Discourse.store.download(page, max_file_size_kb: MAX_IMAGE_SIZE)endreturn "" if !upload_path || !File.exist?(upload_path)diff --git a/plugins/discourse-ai/lib/utils/pdf_to_images.rb b/plugins/discourse-ai/lib/utils/pdf_to_images.rbindex 0411ab7afcf..18c02073e58 100644--- a/plugins/discourse-ai/lib/utils/pdf_to_images.rb+++ b/plugins/discourse-ai/lib/utils/pdf_to_images.rb@@ -24,7 +24,7 @@ class DiscourseAi::Utils::PdfToImagesif upload.local?Discourse.store.path_for(upload)else- Discourse.store.download_safe(upload, max_file_size_kb: MAX_PDF_SIZE)&.path+ Discourse.store.download(upload, max_file_size_kb: MAX_PDF_SIZE)endraise Discourse::InvalidParameters.new("Failed to download PDF") if pdf_path.nil?diff --git a/plugins/discourse-ai/lib/utils/pdf_to_text.rb b/plugins/discourse-ai/lib/utils/pdf_to_text.rbindex 9acd2b89410..44e0c812928 100644--- a/plugins/discourse-ai/lib/utils/pdf_to_text.rb+++ b/plugins/discourse-ai/lib/utils/pdf_to_text.rb@@ -47,7 +47,7 @@ class DiscourseAi::Utils::PdfToTextif upload.local?Discourse.store.path_for(upload)else- Discourse.store.download_safe(upload, max_file_size_kb: MAX_PDF_SIZE)&.path+ Discourse.store.download(upload, max_file_size_kb: MAX_PDF_SIZE)endraise Discourse::InvalidParameters.new("Failed to download PDF") if pdf_path.nil?diff --git a/spec/lib/file_store/base_store_spec.rb b/spec/lib/file_store/base_store_spec.rbindex 1c4dbe4829e..b806a0bf348 100644--- a/spec/lib/file_store/base_store_spec.rb+++ b/spec/lib/file_store/base_store_spec.rb@@ -186,36 +186,34 @@ RSpec.describe FileStore::BaseStore dolet(:store) { FileStore::BaseStore.new }it "should return consistent encodings for fresh and cached downloads" do- # Net::HTTP always returns binary ASCII-8BIT encoding. File.read auto-detects the encoding- # Make sure we File.read after downloading a file for consistency-- first_encoding = store.download(upload_s3, print_deprecation: false).read.encoding-- second_encoding = store.download(upload_s3, print_deprecation: false).read.encoding+ first_encoding = File.read(store.download(upload_s3)).encoding+ second_encoding = File.read(store.download(upload_s3)).encodingexpect(first_encoding).to eq(Encoding::UTF_8)expect(second_encoding).to eq(Encoding::UTF_8)end- it "should return the file" do- file = store.download(upload_s3, print_deprecation: false)+ it "should return a file path" do+ path = store.download(upload_s3)- expect(file.class).to eq(File)+ expect(path).to be_a(String)+ expect(File.exist?(path)).to eq(true)end- it "should return the file when s3 cdn enabled" do+ it "should return the path when s3 cdn enabled" doSiteSetting.s3_cdn_url = "https://cdn.s3.#{SiteSetting.s3_region}.amazonaws.com"stub_request(:get, Discourse.store.cdn_url(upload_s3.url)).to_return(status: 200,body: "Hello world",)- file = store.download(upload_s3, print_deprecation: true)+ path = store.download(upload_s3)- expect(file.class).to eq(File)+ expect(path).to be_a(String)+ expect(File.exist?(path)).to eq(true)end- it "should return the file when secure uploads are enabled" do+ it "should return the path when secure uploads are enabled" doSiteSetting.login_required = trueSiteSetting.secure_uploads = true@@ -223,9 +221,16 @@ RSpec.describe FileStore::BaseStore dosigned_url = Discourse.store.signed_url_for_path(upload_s3.url)stub_request(:get, signed_url).to_return(status: 200, body: "Hello world")- file = store.download(upload_s3, print_deprecation: false)+ path = store.download(upload_s3)- expect(file.class).to eq(File)+ expect(path).to be_a(String)+ expect(File.exist?(path)).to eq(true)+ end++ it "returns nil when download fails" do+ FileHelper.stubs(:download).raises(OpenURI::HTTPError.new("400 error", anything))++ expect(store.download(upload_s3)).to eq(nil)endend@@ -238,11 +243,18 @@ RSpec.describe FileStore::BaseStore dolet(:upload_s3) { Fabricate(:upload_s3) }let(:store) { FileStore::BaseStore.new }- it "does not raise an error when download fails" do+ it "raises DownloadError when download fails" doFileHelper.stubs(:download).raises(OpenURI::HTTPError.new("400 error", anything))expect { store.download!(upload_s3) }.to raise_error(FileStore::DownloadError)end++ it "returns a file path" do+ path = store.download!(upload_s3)++ expect(path).to be_a(String)+ expect(File.exist?(path)).to eq(true)+ endenddescribe "#cache_file" do@@ -294,7 +306,7 @@ RSpec.describe FileStore::BaseStore dolet(:upload_s3) { Fabricate(:upload_s3) }let(:store) { FileStore::BaseStore.new }- it "does not raise an error when download fails" do+ it "delegates to #download and emits a deprecation warning" doFileHelper.stubs(:download).raises(OpenURI::HTTPError.new("400 error", anything))expect(store.download_safe(upload_s3)).to eq(nil)diff --git a/spec/lib/shrink_uploaded_image_spec.rb b/spec/lib/shrink_uploaded_image_spec.rbindex cec4ea60688..1454d8f9589 100644--- a/spec/lib/shrink_uploaded_image_spec.rb+++ b/spec/lib/shrink_uploaded_image_spec.rb@@ -147,7 +147,7 @@ RSpec.describe ShrinkUploadedImage doresult =ShrinkUploadedImage.new(upload: upload,- path: Discourse.store.download(upload).path,+ path: Discourse.store.download(upload),max_pixels: 10_000,).performdiff --git a/spec/lib/svg_sprite/svg_sprite_spec.rb b/spec/lib/svg_sprite/svg_sprite_spec.rbindex a34b27ea05b..6280caf96d2 100644--- a/spec/lib/svg_sprite/svg_sprite_spec.rb+++ b/spec/lib/svg_sprite/svg_sprite_spec.rb@@ -193,8 +193,7 @@ RSpec.describe SvgSprite doSvgSprite.bundle(theme.id)expect(SvgSprite.cache.hash.keys).to include("theme_svg_sprites_#{theme.id}")- external_copy = Discourse.store.download(upload_s3)- File.delete external_copy.try(:path)+ File.delete(Discourse.store.download(upload_s3))SvgSprite.bundle(theme.id)# after a temp file is missing, bundling still worksdiff --git a/spec/models/upload_spec.rb b/spec/models/upload_spec.rbindex 4314f47d437..6fcfcc06a90 100644--- a/spec/models/upload_spec.rb+++ b/spec/models/upload_spec.rb@@ -1040,7 +1040,7 @@ RSpec.describe Upload doit "correctly handles error when file is too large to download" dowhite_image.stubs(:local?).returns(false)- FileStore::LocalStore.any_instance.stubs(:download).returns(nil).once+ FileHelper.stubs(:download).returns(nil)expect(white_image.dominant_color).to eq(nil)expect(white_image.dominant_color(calculate_if_missing: true)).to eq("")@@ -1049,11 +1049,7 @@ RSpec.describe Upload doit "correctly handles error when file has HTTP error" dowhite_image.stubs(:local?).returns(false)- FileStore::LocalStore- .any_instance- .stubs(:download)- .raises(OpenURI::HTTPError.new("Error", nil))- .once+ FileHelper.stubs(:download).raises(OpenURI::HTTPError.new("Error", nil))expect(white_image.dominant_color).to eq(nil)expect(white_image.dominant_color(calculate_if_missing: true)).to eq("")