lib/oria/server.rb in oria-0.0.2 vs lib/oria/server.rb in oria-0.0.3
- old
+ new
@@ -1,14 +1,20 @@
require 'yaml'
require 'tmpdir'
module Oria
class Server < EventMachine::Connection
class << self
+ @@timer = nil
+
def debug?
@@debug
end
+ def log(value, app_key = nil)
+ logger.debug("#{"#{app_key}: " if app_key}#{value}") if debug?
+ end
+
def logger
require 'logger'
@@logger ||= Logger.new(log_file, 0, 100 * 1024 * 1024)
end
@@ -40,15 +46,18 @@
end
File.unlink(pid_file)
end
end
- def write_hash
- @@write_hash ||= proc do
+ def store_hash(app_key)
+ @@timer.cancel if @@timer
+ @@timer = EventMachine::Timer.new(10) do
+ log "Writing changes to disk", app_key
File.open(yaml_store, 'w') do |store|
store.puts YAML.dump(@@servers)
end
+ @@timer = nil
end
end
protected
def log_file
@@ -67,15 +76,15 @@
@@yaml_store ||= File.join(Dir.tmpdir, 'oria.yml')
end
end
def post_init
- log "Client connected"
+ Oria::Server.log "Client connected"
end
def receive_data(data)
- log "Responding to #{data}"
+ Oria::Server.log "Responding to #{data}"
data = data.split(' ')
method = data.shift
data = JSON.parse(data.join(' '))
@app_key = data.delete('app_key')
case method
@@ -96,27 +105,23 @@
hash[response] = data['value']
end
end
if defined?(response)
response = JSON.generate({:response => response})
- log "Sending response: #{response}"
+ Oria::Server.log "Sending response: #{response}"
+ Oria::Server.store_hash(@app_key)
send_data response
end
- EventMachine.defer(Oria::Server.write_hash)
+ rescue JSON::ParserError
+ send_data "Invalid request"
end
def unbind
end
private
def hash
@hash ||= @@servers[@app_key || 'default'] ||= {}
- end
-
- def log(value)
- if Oria::Server.debug?
- Oria::Server.logger.debug(value)
- end
end
def random_key
chars = ['a'..'z', 'A'..'Z', 0..9].map(&:to_a).flatten
max = [hash.length, 2].max
\ No newline at end of file