Module: DbCrap

Included in:
RailsRole::MyApp, StatsRole::StatsApp
Defined in:
lib/db_crap.rb

Defined Under Namespace

Classes: NoDbConnections

Instance Method Summary collapse

Instance Method Details

#get_peer_db_for(key) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/db_crap.rb', line 63

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

#get_read_dbObject



71
72
73
74
75
76
77
78
79
# File 'lib/db_crap.rb', line 71

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

#get_write_dbObject



49
50
51
52
# File 'lib/db_crap.rb', line 49

def get_write_db
  db_addr = @active_links['db_write'].sort_by { rand }.first
  DemoSocket.connect(db_addr, DbRole::PORT)
end

#listObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/db_crap.rb', line 6

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

#on_each_peerObject



54
55
56
57
58
59
60
61
# File 'lib/db_crap.rb', line 54

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

#use_peer_dbs?Boolean

Returns:

  • (Boolean)


81
82
83
# File 'lib/db_crap.rb', line 81

def use_peer_dbs?
  @manifest['db_peer'] && @manifest['db_peer'].size > 0
end

#write(key, value) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/db_crap.rb', line 32

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