Created
May 13, 2019 17:52
-
-
Save poctek/a439fc125ddf4a4473c61db4dcd1cf71 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
module StatsApi | |
module Operations | |
module UpdateRealtimeStatsViews | |
class UpdateLastShareTimestamps < Operations::BaseOperation | |
include Dry::Monads::Try::Mixin | |
include Import[ | |
:application_config, | |
:logger | |
] | |
def call(_input = {}) | |
if pg.views(materialized: true).include? view_name | |
update_view | |
else | |
create_view | |
end | |
end | |
private | |
def update_view | |
Try() { pg.execute "REFRESH MATERIALIZED VIEW CONCURRENTLY #{view_name}" } | |
.fmap { logger.info "#{view_name} materialized view updated" } | |
end | |
def pg | |
StatsApi::Container[:pg] | |
end | |
def create_view | |
Try() do | |
logger.info "Creating #{view_name} materialized view" | |
pg.create_view view_name, query, materialized: true | |
logger.info "Created #{view_name} materialized view" | |
logger.info "Creating #{view_name} index" | |
pg.add_index view_name, %i[wallet worker coin], unique: true | |
logger.info "Created #{view_name} index" | |
end | |
end | |
def query | |
max_lit = Sequel.lit('max(shares.created_at)') | |
join = { miner: :miner, worker_id: :worker_id, created_at: :created_at } | |
pg[:shares].join(max_ts, join) | |
.group_append { Sequel.lit('shares.miner') } | |
.group_append { Sequel.lit('shares.worker_id') } | |
.group_append(:coin) | |
.select { Sequel.lit('shares.miner').as :wallet } | |
.select_append { Sequel.lit('shares.worker_id').as :worker } | |
.select_append(:coin) | |
.select_append { Sequel.extract(:epoch, max_lit).as(:timestamp) } | |
end | |
def max_ts | |
sql_lit = <<~LITERAL | |
shares.created_at >= (now() - '#{application_config.short_window_duration} s'::interval) | |
LITERAL | |
time_lit = Sequel.lit(sql_lit) | |
Share.select { max(created_at).as(:created_at) } | |
.select_append(:miner) | |
.select_append(:worker_id) | |
.group(:miner) | |
.group_append(:worker_id) | |
.where { time_lit } | |
end | |
def view_name | |
application_config.last_share_timestamps_view_name | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment