From 274239110f9add8eab41b11c978d327ea10a7bbc Mon Sep 17 00:00:00 2001 From: Quinton Miller Date: Thu, 2 Mar 2023 20:56:47 +0800 Subject: [PATCH] Increase time drift for `HTTP::StaticFileHandler`'s gzip check --- .../http/server/handlers/static_file_handler_spec.cr | 2 +- src/http/server/handlers/static_file_handler.cr | 12 ++++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/spec/std/http/server/handlers/static_file_handler_spec.cr b/spec/std/http/server/handlers/static_file_handler_spec.cr index 3c2d1a2ae24b..267682754a0c 100644 --- a/spec/std/http/server/handlers/static_file_handler_spec.cr +++ b/spec/std/http/server/handlers/static_file_handler_spec.cr @@ -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 diff --git a/src/http/server/handlers/static_file_handler.cr b/src/http/server/handlers/static_file_handler.cr index 3fbb57ab0bc0..99e268896103 100644 --- a/src/http/server/handlers/static_file_handler.cr +++ b/src/http/server/handlers/static_file_handler.cr @@ -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 @@ -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"