Sha256: 99bc8dd789d6f8187b6671bc13883f2c6215c65283663ed67bc819a3c9d4c07e

Contents?: true

Size: 1.8 KB

Versions: 6

Compression:

Stored size: 1.8 KB

Contents

require 'set'

module DbCrap
  class NoDbConnections < StandardError ; end

  def list
    if use_peer_dbs?
      out = []
      seen = []
      on_each_peer do |db|
        db.send('cmd' => 'LIST')
        new_recs = db.recv
        new_recs.each do |rec|
          unless seen.include?(rec['key'])
            out << rec
            seen << rec['key']
          end
        end
      end
      out
    else
      db = get_read_db
      if db
        db.send('cmd' => 'LIST')
        db.recv
      else
        raise NoDbConnections
      end
    end
  end

  def write(key,value)
    if use_peer_dbs?
      db = get_peer_db_for(key)
    else
      db = get_write_db
    end
    
    if db
      db.send 'cmd' => 'PUT', 'key' => request.params['key'], 'value' => request.params['value']
      db.recv
    else
      raise NoDbConnections
    end
  rescue Errno::ECONNREFUSED
    puts "Hm... I couldn't get a connection to a database node."
  end
  
  def get_write_db
    db_addr = @active_links['db_write'].sort_by { rand }.first
    DemoSocket.connect(db_addr, DbRole::PORT)
  end
  
  def on_each_peer
    @active_links['db_peer'].each do |db_addr|
      begin
        yield DemoSocket.connect(db_addr, DbRole::PORT)
      rescue Errno::ECONNREFUSED
      end
    end
  end
  
  def get_peer_db_for(key)
    index = (key.hash % @manifest['db_peer'].size)
    db_addr = @manifest['db_peer'][index]
    if @active_links['db_peer'].include?(db_addr)
      DemoSocket.connect(db_addr, DbRole::PORT)
    end
  end
  
  def get_read_db
    addrs = @active_links['db_read'].sort_by { rand }
    begin
      db_addr = addrs.pop
      DemoSocket.connect(db_addr, DbRole::PORT)
    rescue Errno::ECONNREFUSED
      retry if addrs.size > 0
    end
  end
  
  def use_peer_dbs?
    @manifest['db_peer'] && @manifest['db_peer'].size > 0
  end
  
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
bum-0.0.17 lib/db_crap.rb
bum-0.0.16 lib/db_crap.rb
bum-0.0.15 lib/db_crap.rb
bum-0.0.14 lib/db_crap.rb
bum-0.0.13 lib/db_crap.rb
bum-0.0.12 lib/db_crap.rb