Sha256: ca9a94f7cd276a2e27b2c91dbf936b8a48e0f138e009a89b2b6afa8a0b1b1526

Contents?: true

Size: 1.92 KB

Versions: 6

Compression:

Stored size: 1.92 KB

Contents

require 'thread'

module TxCatcher

  # Cleans DB so that its size doesn't go above Config.max_db_transactions_stored
  class Cleaner

    class << self

      def stopped?
        @@stopped
      end
    
      def start(run_once: false)
        @@stopped = false
        @@stop    = false
        Thread.new do
          loop do
            @@cleaning_counter = { transactions: 0, deposits: 0, addresses: 0 }
            db_tx_count = TxCatcher::Transaction.last.id - TxCatcher::Transaction.first.id + 1
            $stdout.print "Cleaning transactions in DB..."
            $stdout.print "#{db_tx_count} now, needs to be below #{Config.max_db_transactions_stored}\n"
            if db_tx_count > Config.max_db_transactions_stored
              number_to_delete = (db_tx_count - Config.max_db_transactions_stored) + (Config.max_db_transactions_stored*0.1).round
              clean_transactions(number_to_delete)
              $stdout.puts "DB cleaned: #{@@cleaning_counter.to_s}"
            else
              $stdout.puts "Nothing to be cleaned from DB, size is below threshold."
            end
            if @stop || run_once
              @@stopped = true
              break
            end
            sleep Config.db_clean_period_seconds
          end # loop
        end # Thread
        @@stopped
      end

      def stop
        @@stop = true
      end

      def clean_transactions(n)
        transactions = Transaction.order("created_at ASC").limit(n).each do |t|
          clean_deposits(t)
          t.delete
          @@cleaning_counter[:transactions] += 1
        end
      end

      def clean_deposits(transaction)
        transaction.deposits.each do |d|
          if d.address && d.address.deposits.count == 1
            d.address.delete
            @@cleaning_counter[:addresses] += 1
          end
          d.delete
          @@cleaning_counter[:deposits] += 1
        end
      end

    end # class << self
  end # Cleaner
end # TxCatcher

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
txcatcher-0.1.5 lib/txcatcher/cleaner.rb
txcatcher-0.1.4 lib/txcatcher/cleaner.rb
txcatcher-0.1.3 lib/txcatcher/cleaner.rb
txcatcher-0.1.2 lib/txcatcher/cleaner.rb
txcatcher-0.1.1 lib/txcatcher/cleaner.rb
txcatcher-0.1.0 lib/txcatcher/cleaner.rb