Skip to content

Commit

Permalink
Merge pull request #13138 from HertzDevil/feature/static-file-handler…
Browse files Browse the repository at this point in the history
…-time-drift
  • Loading branch information
straight-shoota authored Mar 4, 2023
2 parents 6e9c356 + 2742391 commit 143907a
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
2 changes: 1 addition & 1 deletion spec/std/http/server/handlers/static_file_handler_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ describe HTTP::StaticFileHandler do

it "still serve compressed content when modification time is very close" do
modification_time = File.info(datapath("static_file_handler", "test.txt")).modification_time
File.touch datapath("static_file_handler", "test.txt.gz"), modification_time - 1.microsecond
File.touch datapath("static_file_handler", "test.txt.gz"), modification_time - 1.millisecond

headers = HTTP::Headers{"Accept-Encoding" => "gzip"}
response = handle HTTP::Request.new("GET", "/test.txt", headers), decompress: false
Expand Down
12 changes: 8 additions & 4 deletions src/http/server/handlers/static_file_handler.cr
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ require "mime"
class HTTP::StaticFileHandler
include HTTP::Handler

# In some file systems, using `gz --keep` to compress the file will keep the
# modification time of the original file but truncating some decimals. We
# serve the gzipped file nonetheless if the .gz file is modified by a duration
# of `TIME_DRIFT` before the original file. This value should match the
# granularity of the underlying file system's modification times
private TIME_DRIFT = 10.milliseconds

@public_dir : Path

# Creates a handler that will serve files in the given *public_dir*, after
Expand Down Expand Up @@ -91,10 +98,7 @@ class HTTP::StaticFileHandler
gz_file_path = "#{file_path}.gz"

if (gz_file_info = File.info?(gz_file_path)) &&
# Allow small time drift. In some file systems, using `gz --keep` to
# compress the file will keep the modification time of the original file
# but truncating some decimals
last_modified - gz_file_info.modification_time < 1.millisecond
last_modified - gz_file_info.modification_time < TIME_DRIFT
file_path = gz_file_path
file_info = gz_file_info
context.response.headers["Content-Encoding"] = "gzip"
Expand Down

0 comments on commit 143907a

Please sign in to comment.