2019-05-02 18:17:27 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-03-15 17:10:45 -04:00
|
|
|
class WebCrawlerRequest < ActiveRecord::Base
|
|
|
|
include CachedCounting
|
|
|
|
|
|
|
|
cattr_accessor :max_record_age, :max_records_per_day
|
|
|
|
|
|
|
|
# only keep the top records based on request count
|
|
|
|
self.max_records_per_day = 200
|
|
|
|
|
|
|
|
# delete records older than this
|
|
|
|
self.max_record_age = 30.days
|
|
|
|
|
2022-02-22 11:45:25 -05:00
|
|
|
def self.increment!(user_agent)
|
|
|
|
perform_increment!(user_agent)
|
2018-03-15 17:10:45 -04:00
|
|
|
end
|
|
|
|
|
2022-02-22 11:45:25 -05:00
|
|
|
def self.write_cache!(user_agent, count, date)
|
2023-01-09 07:20:10 -05:00
|
|
|
where(id: request_id(date: date, user_agent: user_agent)).update_all(
|
|
|
|
["count = count + ?", count],
|
|
|
|
)
|
2018-03-15 17:10:45 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
protected
|
|
|
|
|
2022-02-22 11:45:25 -05:00
|
|
|
def self.request_id(date:, user_agent:, retries: 0)
|
|
|
|
id = where(date: date, user_agent: user_agent).pluck_first(:id)
|
|
|
|
id ||= create!({ date: date, user_agent: user_agent }.merge(count: 0)).id
|
2023-01-09 07:20:10 -05:00
|
|
|
rescue StandardError # primary key violation
|
2022-02-22 11:45:25 -05:00
|
|
|
if retries == 0
|
|
|
|
request_id(date: date, user_agent: user_agent, retries: 1)
|
|
|
|
else
|
|
|
|
raise
|
|
|
|
end
|
2018-03-15 17:10:45 -04:00
|
|
|
end
|
|
|
|
end
|
2018-03-28 14:40:26 -04:00
|
|
|
|
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: web_crawler_requests
|
|
|
|
#
|
2019-05-02 18:34:12 -04:00
|
|
|
# id :bigint not null, primary key
|
2018-03-28 14:40:26 -04:00
|
|
|
# date :date not null
|
|
|
|
# user_agent :string not null
|
|
|
|
# count :integer default(0), not null
|
|
|
|
#
|
|
|
|
# Indexes
|
|
|
|
#
|
|
|
|
# index_web_crawler_requests_on_date_and_user_agent (date,user_agent) UNIQUE
|
|
|
|
#
|