forked from mastodon/mastodon
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add cache headers to static files served through Rails (mastodon#24120)
- Loading branch information
Showing
5 changed files
with
49 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
# frozen_string_literal: true | ||
|
||
require 'action_dispatch/middleware/static' | ||
|
||
class PublicFileServerMiddleware | ||
SERVICE_WORKER_TTL = 7.days.to_i | ||
CACHE_TTL = 28.days.to_i | ||
|
||
def initialize(app) | ||
@app = app | ||
@file_handler = ActionDispatch::FileHandler.new(Rails.application.paths['public'].first) | ||
end | ||
|
||
def call(env) | ||
file = @file_handler.attempt(env) | ||
|
||
# If the request is not a static file, move on! | ||
return @app.call(env) if file.nil? | ||
|
||
status, headers, response = file | ||
|
||
# Set cache headers on static files. Some paths require different cache headers | ||
headers['Cache-Control'] = begin | ||
request_path = env['REQUEST_PATH'] | ||
|
||
if request_path.start_with?('/sw.js') | ||
"public, max-age=#{SERVICE_WORKER_TTL}, must-revalidate" | ||
elsif request_path.start_with?(paperclip_root_url) | ||
"public, max-age=#{CACHE_TTL}, immutable" | ||
else | ||
"public, max-age=#{CACHE_TTL}, must-revalidate" | ||
end | ||
end | ||
|
||
[status, headers, response] | ||
end | ||
|
||
private | ||
|
||
def paperclip_root_url | ||
ENV.fetch('PAPERCLIP_ROOT_URL', '/system') | ||
end | ||
end |