feat: click controller performance improvements

- return tuple directly from the block
- avoid to parse remote_address in the main thread
- avoid to replace headers, add only
- avoid separate variables for one-single use
This commit is contained in:
sjdonado
2025-03-20 20:43:15 +01:00
parent 4ae6ef39d5
commit e67ed7165b
3 changed files with 61 additions and 40 deletions
+9 -19
View File
@@ -11,21 +11,19 @@ module App::Controllers
def self.redirect_handler
->(env : HTTP::Server::Context) {
slug = env.params.url["slug"]
link_id, url = Database.raw_query("SELECT id, url FROM links WHERE slug = (?) LIMIT 1", env.params.url["slug"]) do |result|
result.move_next ? {result.read(Int64), result.read(String)} : nil
end || raise App::NotFoundException.new(env)
link_data = nil
Database.raw_query("SELECT id, url FROM links WHERE slug = (?) LIMIT 1", slug) do |result|
if result.move_next
link_data = {result.read(Int64), result.read(String)}
end
end
raise App::NotFoundException.new(env) unless link_data
remote_address = env.request.headers["Cf-Connecting-Ip"]? || env.request.remote_address.to_s
link_id, url = link_data
client_ip = IpLookup.ip_from_address(env.request.headers["Cf-Connecting-Ip"]? || env.request.remote_address.to_s)
env.response.status_code = 301
env.response.headers.add("Location", url)
env.response.headers.add("X-Forwarded-For", remote_address)
spawn do
begin
client_ip = IpLookup.ip_from_address(remote_address)
user_agent_str = env.request.headers["User-Agent"]?
referer = env.request.headers["Referer"]?.try { |r| URI.parse(r).host rescue r } || env.params.query["utm_source"]? || "Direct"
@@ -34,7 +32,7 @@ module App::Controllers
click = App::Models::Click.new
click.link_id = link_id
click.country = client_ip ? IpLookup.new(client_ip).try(&.country.try(&.code)) : nil
click.user_agent = ua_parser.to_s
click.user_agent = user_agent_str
click.browser = ua_parser.try(&.family)
click.os = ua_parser.try(&.os.try(&.family))
click.referer = referer
@@ -44,14 +42,6 @@ module App::Controllers
Log.error { "Click tracking error: #{ex.message}" }
end
end
env.response.status_code = 301
env.response.headers.add("Location", url)
env.response.headers.add("X-Forwarded-For", client_ip.to_s)
env.response.print ""
env.response.close
return
}
end
end