about summary refs log tree commit diff
path: root/lib/public_file_server_middleware.rb
diff options
context:
space:
mode:
authorStarfall <us@starfall.systems>2023-04-14 19:22:47 -0500
committerStarfall <us@starfall.systems>2023-04-14 19:22:47 -0500
commit4fe1689de43f4404eb9530fcfbcbfb26d6c1c13a (patch)
tree6811b845bb7f4966b10dcefa3dea404246f161c7 /lib/public_file_server_middleware.rb
parent65c1e53a32cabcdbb7bca57002bb0f6acdebe07e (diff)
parentbed63f6dae0879ac840066b031229e0d139089cd (diff)
Merge remote-tracking branch 'glitch/main' HEAD main
Diffstat (limited to 'lib/public_file_server_middleware.rb')
-rw-r--r--lib/public_file_server_middleware.rb43
1 files changed, 43 insertions, 0 deletions
diff --git a/lib/public_file_server_middleware.rb b/lib/public_file_server_middleware.rb
new file mode 100644
index 000000000..3799230a2
--- /dev/null
+++ b/lib/public_file_server_middleware.rb
@@ -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