Skip to content

Commit

Permalink
perf: cache cell input
Browse files Browse the repository at this point in the history
  • Loading branch information
shaojunda committed Sep 10, 2019
1 parent cefd400 commit 4fbdda6
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ class CellInputLockScriptsController < ApplicationController
before_action :validate_query_params

def show
cell_input = CellInput.find(params[:id])
cell_input = CellInput.cached_find(params[:id])
lock_script = cell_input.find_lock_script!

render json: LockScriptSerializer.new(lock_script)
Expand Down
23 changes: 20 additions & 3 deletions app/models/cell_input.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,18 @@ class CellInput < ApplicationRecord
belongs_to :ckb_transaction
belongs_to :block

after_commit :flush_cache

def find_lock_script!
previous_cell_output!.lock_script
Rails.cache.fetch(["CellInput", id, "lock_script"]) do
previous_cell_output!.lock_script
end
end

def find_type_script!
previous_cell_output!.type_script
Rails.cache.fetch(["CellInput", id, "type_script"]) do
previous_cell_output!.type_script
end
end

def find_cell_output!
Expand All @@ -23,6 +29,15 @@ def previous_cell_output
CellOutput.find_by(tx_hash: tx_hash, cell_index: cell_index)
end

def self.cached_find(id)
Rails.cache.fetch([name, id]) { find(id) }
end

def flush_cache
Rails.cache.delete_matched("CellInput/#{id}*")
Rails.cache.delete_matched("previous_cell_output*")
end

private

def previous_cell_output!
Expand All @@ -31,7 +46,9 @@ def previous_cell_output!
tx_hash = previous_output["tx_hash"]
cell_index = previous_output["index"].to_i

CellOutput.find_by!(tx_hash: tx_hash, cell_index: cell_index)
Rails.cache.fetch("previous_cell_output/#{tx_hash}/#{cell_index}") do
CellOutput.find_by!(tx_hash: tx_hash, cell_index: cell_index)
end
end
end

Expand Down
6 changes: 6 additions & 0 deletions app/models/cell_output.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ class CellOutput < ApplicationRecord

attribute :tx_hash, :ckb_hash

after_commit :flush_cache

def address_hash
address.address_hash
end
Expand All @@ -25,6 +27,10 @@ def node_output
type = type_script.present? ? CKB::Types::Script.new(type_script.to_node_lock) : nil
CKB::Types::Output.new(capacity: capacity.to_i, lock: lock, type: type)
end

def flush_cache
Rails.cache.delete("previous_cell_output/#{tx_hash}/#{cell_index}")
end
end

# == Schema Information
Expand Down

0 comments on commit 4fbdda6

Please sign in to comment.