/
server.rb
74 lines (67 loc) · 2.1 KB
/
server.rb
1
2
3
4
5
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
require 'bundler'
Bundler.require
require 'cgi'
require 'json'
WINDOW_SIZE = 100
class TachyServer < EM::Connection
include EM::HttpServer
def post_init
super
no_environment_strings
end
def process_http_request
# the http request details are available via the following instance variables:
# @http_protocol
# @http_request_method
# @http_cookie
# @http_if_none_match
# @http_content_type
# @http_path_info
# @http_request_uri
# @http_query_string
# @http_post_content
# @http_headers
puts "#{Time.now.to_f} accessing #{@http_request_uri}"
if @http_request_uri == "/api/log"
params = CGI.parse(@http_post_content)
$redis.sadd('tachy_lists', params["name"][0])
$redis.lpush(params["name"][0], "#{Time.now.to_f}:#{params["data"][0]}")
$redis.ltrim(params["name"][0], 0, WINDOW_SIZE)
response = EM::DelegatedHttpResponse.new(self)
response.status = 200
response.content_type 'text/plain'
response.content = 'OK'
response.send_response
end
if @http_request_uri == "/api/funcs"
$redis.smembers('tachy_lists') do |members|
response = EM::DelegatedHttpResponse.new(self)
response.status = 200
response.content_type 'application/json'
response.content = members.to_json
response.send_response
end
end
if @http_request_uri.include?("/api/view")
func_name = @http_request_uri.split("/").last.gsub('/','')
$redis.lrange(func_name, 100, WINDOW_SIZE) do |last|
response = EM::DelegatedHttpResponse.new(self)
response.status = 200
response.content_type 'text/plain'
response.content = last[0]
response.send_response
end
end
if @http_request_uri == "/dashboard"
response = EM::DelegatedHttpResponse.new(self)
response.status = 200
response.content_type 'text/html'
response.content = File.read('index.html')
response.send_response
end
end
end
EM.run{
$redis = EM::Protocols::Redis.connect
EM.start_server '0.0.0.0', 8080, TachyServer
}