From 4115ebffa70bd367f2b431cb01562f5774cc970c Mon Sep 17 00:00:00 2001 From: Kyle Drake Date: Tue, 12 Jan 2021 23:04:00 -0600 Subject: [PATCH] speed up stats parsing --- models/stat.rb | 78 ++++++++++++++++++++++++-------------------------- 1 file changed, 38 insertions(+), 40 deletions(-) diff --git a/models/stat.rb b/models/stat.rb index c50cab97..d07fe483 100644 --- a/models/stat.rb +++ b/models/stat.rb @@ -92,59 +92,57 @@ class Stat < Sequel::Model logfile.close - site_logs.each do |log_time, usernames| - Site.select(:id, :username).where(username: usernames.keys).all.each do |site| - site_logs[log_time][site.username][:id] = site.id - end + DB[:stats].lock('EXCLUSIVE') do + DB.transaction do + site_logs.each do |log_time, usernames| + Site.select(:id, :username).where(username: usernames.keys).all.each do |site| + usernames[site.username][:id] = site.id + end - usernames.each do |username, site_log| - DB.transaction do - DB['update sites set hits=hits+?, views=views+? where username=?', - site_log[:hits], - site_log[:views], - username - ].first + usernames.each do |username, site_log| + next unless site_log[:id] - opts = {site_id: site_log[:id], created_at: log_time.to_date.to_s} - - stat = nil - - DB[:stats].lock('EXCLUSIVE') { + opts = {site_id: site_log[:id], created_at: log_time.to_date.to_s} stat = Stat.select(:id).where(opts).first stat = Stat.create opts if stat.nil? - } - DB[ - 'update stats set hits=hits+?, views=views+?, bandwidth=bandwidth+? where id=?', - site_log[:hits], - site_log[:views], - site_log[:bandwidth], - stat.id - ].first + DB['update sites set hits=hits+?, views=views+? where id=?', + site_log[:hits], + site_log[:views], + site_log[:id] + ].first + + DB[ + 'update stats set hits=hits+?, views=views+?, bandwidth=bandwidth+? where id=?', + site_log[:hits], + site_log[:views], + site_log[:bandwidth], + stat.id + ].first + end end end end - FileUtils.rm log_path end - total_site_stats.each do |time, stats| - opts = {created_at: time.to_date.to_s} + DB[:daily_site_stats].lock('EXCLUSIVE') do + DB.transaction do + total_site_stats.each do |time, stats| + opts = {created_at: time.to_date.to_s} + stat = DailySiteStat.select(:id).where(opts).first + stat = DailySiteStat.create opts if stat.nil? - DB[:stats].lock('EXCLUSIVE') { - stat = DailySiteStat.select(:id).where(opts).first - stat = DailySiteStat.create opts if stat.nil? - } - - DB[ - 'update daily_site_stats set hits=hits+?, views=views+?, bandwidth=bandwidth+? where created_at=?', - stats[:hits], - stats[:views], - stats[:bandwidth], - time.to_date - ].first + DB[ + 'update daily_site_stats set hits=hits+?, views=views+?, bandwidth=bandwidth+? where created_at=?', + stats[:hits], + stats[:views], + stats[:bandwidth], + time.to_date + ].first + end + end end - end end end