Skip to content

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.rb
index 79f25fcbec0..fb20f057263 100644
--- a/app/controllers/static_controller.rb
+++ b/app/controllers/static_controller.rb
@@ -232,8 +232,10 @@ class StaticController < ApplicationController
Discourse
.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 path
end
+
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.rb
index 1c403a867f2..79731101e1b 100644
--- a/app/models/optimized_image.rb
+++ b/app/models/optimized_image.rb
@@ -67,8 +67,7 @@ class OptimizedImage < ActiveRecord::Base
if 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)
end
if extension == ".svg" && upload.extension != "svg"
@@ -147,9 +146,6 @@ class OptimizedImage < ActiveRecord::Base
temp_file.close!
end
- # make sure we remove the cached copy from external stores
- external_copy&.close if store.external?
-
thumbnail
end
end
@@ -170,7 +166,7 @@ class OptimizedImage < ActiveRecord::Base
if local?
Discourse.store.path_for(self)
else
- Discourse.store.download!(self).path
+ Discourse.store.download!(self)
end
File.size(path)
end
diff --git a/app/models/theme_field.rb b/app/models/theme_field.rb
index 9d8bab100c6..6901f43d050 100644
--- a/app/models/theme_field.rb
+++ b/app/models/theme_field.rb
@@ -271,20 +271,18 @@ class ThemeField < ActiveRecord::Base
end
def 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)
else
path = Discourse.store.path_for(upload)
end
+ return "Error with #{self.name}: Could not download icon sprite" if path.nil?
+
error = nil
begin
@@ -297,6 +295,7 @@ class ThemeField < ActiveRecord::Base
rescue => e
error = "Error with #{self.name}: #{e.inspect}"
end
+
error
end
diff --git a/app/models/upload.rb b/app/models/upload.rb
index b21939a048b..7debe5bdf93 100644
--- a/app/models/upload.rb
+++ b/app/models/upload.rb
@@ -173,16 +173,12 @@ class Upload < ActiveRecord::Base
def content
original_path = Discourse.store.path_for(self)
- external_copy = nil
if 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_copy
end
def fix_image_extension
@@ -191,10 +187,7 @@ class Upload < ActiveRecord::Base
begin
# this is relatively cheap once cached
original_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::Base
if local?
Discourse.store.path_for(self)
else
- Discourse.store.download!(self).path
+ Discourse.store.download!(self)
end
if extension == "svg"
@@ -389,7 +382,7 @@ class Upload < ActiveRecord::Base
if local?
Discourse.store.path_for(self)
else
- Discourse.store.download_safe(self)&.path
+ Discourse.store.download(self)
end
if local_path.nil?
diff --git a/lib/email/sender.rb b/lib/email/sender.rb
index bbbbba0245b..5592212a44d 100644
--- a/lib/email/sender.rb
+++ b/lib/email/sender.rb
@@ -389,7 +389,7 @@ module Email
if 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.size
diff --git a/lib/file_store/base_store.rb b/lib/file_store/base_store.rb
index d2c4e1f43b5..868a8d96aea 100644
--- a/lib/file_store/base_store.rb
+++ b/lib/file_store/base_store.rb
@@ -91,63 +91,27 @@ module FileStore
not_implemented
end
- # TODO: Remove when #download becomes the canonical safe version.
- def download_safe(*, **)
- download(*, **, print_deprecation: false)
+ def download(*, **)
+ perform_download(*, **)
rescue StandardError
nil
end
+ 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 StandardError
raise DownloadError
end
- 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 FileStore
def get_from_cache(filename)
path = get_cache_path_for(filename)
- File.open(path) if File.exist?(path)
+ path if File.exist?(path)
end
def cache_file(file, filename)
@@ -217,6 +181,43 @@ module FileStore
private
+ 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_implemented
raise "Not implemented."
end
diff --git a/lib/tasks/site.rake b/lib/tasks/site.rake
index 6f6ef037063..dec1d428afe 100644
--- a/lib/tasks/site.rake
+++ b/lib/tasks/site.rake
@@ -45,8 +45,12 @@ class ZippedSiteStructure
return @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.rake
index 051db9044a7..2092aca4b6b 100644
--- a/lib/tasks/uploads.rake
+++ b/lib/tasks/uploads.rake
@@ -1317,7 +1317,7 @@ task "uploads:downsize" => :environment do
if 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)
end
unless path
diff --git a/plugins/discourse-ai/app/jobs/regular/digest_rag_upload.rb b/plugins/discourse-ai/app/jobs/regular/digest_rag_upload.rb
index 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 Jobs
chunk_tokens = target.rag_chunk_tokens
overlap_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 Jobs
ActiveRecord::Base.transaction do
chunk_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:,
).id
idx += 1
@@ -64,6 +59,8 @@ module Jobs
fragment_ids.each_slice(50) do |slice|
Jobs.enqueue(:generate_rag_embeddings, fragment_ids: slice)
end
+ ensure
+ @file&.close
end
private
@@ -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 Jobs
end
store = 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 path
else
File.open(store.path_for(upload))
end
diff --git a/plugins/discourse-ai/lib/completions/upload_encoder.rb b/plugins/discourse-ai/lib/completions/upload_encoder.rb
index 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 DiscourseAi
def 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.rb
index 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::ImageToText
if 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)
end
return "" 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.rb
index 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::PdfToImages
if 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)
end
raise 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.rb
index 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::PdfToText
if 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)
end
raise 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.rb
index 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 do
let(: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)).encoding
expect(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" do
SiteSetting.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" do
SiteSetting.login_required = true
SiteSetting.secure_uploads = true
@@ -223,9 +221,16 @@ RSpec.describe FileStore::BaseStore do
signed_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)
end
end
@@ -238,11 +243,18 @@ RSpec.describe FileStore::BaseStore do
let(: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" do
FileHelper.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)
+ end
end
describe "#cache_file" do
@@ -294,7 +306,7 @@ RSpec.describe FileStore::BaseStore do
let(: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" do
FileHelper.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.rb
index 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 do
result =
ShrinkUploadedImage.new(
upload: upload,
- path: Discourse.store.download(upload).path,
+ path: Discourse.store.download(upload),
max_pixels: 10_000,
).perform
diff --git a/spec/lib/svg_sprite/svg_sprite_spec.rb b/spec/lib/svg_sprite/svg_sprite_spec.rb
index 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 do
SvgSprite.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 works
diff --git a/spec/models/upload_spec.rb b/spec/models/upload_spec.rb
index 4314f47d437..6fcfcc06a90 100644
--- a/spec/models/upload_spec.rb
+++ b/spec/models/upload_spec.rb
@@ -1040,7 +1040,7 @@ RSpec.describe Upload do
it "correctly handles error when file is too large to download" do
white_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 do
it "correctly handles error when file has HTTP error" do
white_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("")