public
Fork of KirinDave/fuzed
Description: A new revision of Fuzed, the Erlang-based frontend for web apps.
Clone URL: git://github.com/mojombo/fuzed.git
Search Repo:
mojombo (author)
Sun May 11 17:30:40 -0700 2008
commit  e9db1600a675c78c970ecde8da2fc3ec8f83f3e2
tree    5073e5ef005b3b2dfac2612b3fe5c32e975fbed3
parent  7a31d04b79501e964321222077a5bd630cf5bebe
fuzed / rlibs / rails_node.rb
100644 192 lines (155 sloc) 7.201 kb
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
TESTMODE = false
LOG = true
 
# core
require 'stringio'
require 'logger'
 
# internal
require 'chassis'
require 'rails_adapter'
 
# gems
require 'rack'
 
# get rails root dir
if TESTMODE
  rails_root = File.join(File.dirname(__FILE__), *%w[.. test app])
else
  rails_root = ARGV[0] || File.join(File.dirname(__FILE__), *%w[.. test app])
end
 
# load Rails
require File.join(rails_root, 'config/boot')
require RAILS_ROOT + "/config/environment"
 
# initialize logging info
$total_avg = [0, 0]
$rails_avg = [0, 0]
$logger = Logger.new(RAILS_ROOT + "/log/fuzed.#{Process.pid}.log")
 
# Log the given message
# +msg+ is the message to log
#
# Returns nothing
def log(msg)
  $logger << msg + "\n"
end
 
$app = Rack::Adapter::Rails.new(:root => RAILS_ROOT)
 
def service(request)
  method = request[:method]
  version = request[:http_version] # => e.g. [1, 1]
  path = request[:querypath]
  query = request[:querydata] == :undefined ? '' : request[:querydata]
  server = request[:servername]
  headers = request[:headers]
  cookies = request[:cookies]
  postdata = request[:postdata] == :undefined ? '' : request[:postdata]
          
  translate = {:content_type => 'CONTENT_TYPE',
               :content_length => 'CONTENT_LENGTH',
               :accept => 'HTTP_ACCEPT',
               :'Accept-Charset' => 'HTTP_ACCEPT_CHARSET',
               :'Accept-Encoding' => 'HTTP_ACCEPT_ENCODING',
               :'Accept-Language' => 'HTTP_ACCEPT_LANGUAGE',
               :connection => 'HTTP_CONNECTION',
               :keep_alive => 'HTTP_KEEP_ALIVE',
               :host => 'HTTP_HOST',
               :referer => 'HTTP_REFERER',
               :user_agent => 'HTTP_USER_AGENT',
               'X-Prototype-Version' => 'HTTP_X_PROTOTYPE_VERSION',
               'X-Requested-With' => 'HTTP_X_REQUESTED_WITH'}
               
  env = {}
  env['REQUEST_METHOD'] = method.to_s
  env['QUERY_STRING'] = query
  env["PATH_INFO"] = path
  env = headers.inject(env) { |a, x| a[translate[x[0]] || x[0].to_s] = x[1]; a }
  env.delete_if { |k, v| v.nil? }
  
  env.update({"rack.version" => [0, 1],
              "rack.input" => StringIO.new(postdata),
              "rack.errors" => STDERR,
              
              "rack.multithread" => true,
              "rack.multiprocess" => false,
              "rack.run_once" => false,
              
              "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http"
            })
             
  env['SERVER_NAME'] = server.split(':')[0]
  env['SERVER_PORT'] = server.split(':')[1]
  env['HTTP_VERSION'] = version.join('.')
  
  env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
  env["QUERY_STRING"] ||= ""
  env["REQUEST_PATH"] ||= "/"
  env.delete "PATH_INFO" if env["PATH_INFO"] == ""
  
  cookies.each do |cookie|
    env["HTTP_COOKIE"] = cookie.to_s
  end
  
  log('------------IN------------') if LOG
  log(env.inspect) if LOG
  
  begin
    t1 = Time.now
    
    # status = '200'
    # headers = {}
    # body = ['foo']
    
    status, headers, body = $app.call(env)
    
    rails_delta = Time.now - t1
    $rails_avg[0] += rails_delta
    $rails_avg[1] += 1
    log(">> Rails in #{rails_delta} (#{$rails_avg[0] / $rails_avg[1]} avg) sec") if LOG
  
    html = ''
    body.each do |part|
      html << part
    end
    
    headers['Server'] = 'YAWS + Fuzed 0.0.1'
    headers['Connection'] = 'close'
    
    cookies = headers.delete('cookie')
    #cookies.map! {|c| c.include?('path=') ? c : c + "; path=/"}
    headers['Set-Cookie'] = cookies if cookies
    
    # p headers
    
    status = (headers["Status"].split(" ").first rescue nil) || status
    headers.delete("Status") if headers["Status"]
 
    res =
    [:response,
     [[:status, status.to_i],
      [:allheaders, headers.inject([]) { |a, x| a += x[1].map { |y| [:header, x[0], y] } }],
      [:html, html]]]
  rescue => e
    res =
    [:response,
      [[:status, 500],
       [:allheaders, [
         [:header, "Content-Type", "text/plain; charset=utf-8"],
         [:header, "Cache-Control", "no-cache"]]],
       [:html, "500 Internal Error\n\n#{e}\n\n#{e.backtrace}"]]]
  end
    
  log('-----------OUT------------') if LOG
  log(res.inspect) if LOG
  
  res
end
      
class RailsHandler < Chassis
  kind "rails"
 
  details("rails" => "default")
 
  handle(:handle_request, :request) do |args|
    service(args[:request])
  end
end
 
if TESTMODE
  # [[:method, :POST], [:http_version, [1, 1]], [:querypath, "/main/go"], [:querydata, ""], [:servername, "testing:8002"], [:headers, [[:connection, "keep-alive"], [:accept, "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"], [:host, "localhost:8002"], [:referer, "http://localhost:8002/main/ready"], [:user_agent, "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3"], [:keep_alive, "300"], [:content_length, "7"], [:content_type, "application/x-www-form-urlencoded"], [:"Cache-Control", "max-age=0"], [:"Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"], [:"Accept-Encoding", "gzip,deflate"], [:"Accept-Language", "en-us,en;q=0.5"]]], [:cookies, ["_helloworld_session_id=d3eae987aab3230377abc433b7a8d7c1"]], [:pathinfo, "/Users/tom/dev/fuzed/helloworld/public"], [:postdata, "val=foo"]]
  
  req =
  {:method => :POST,
   :http_version => [1, 1],
   :querypath => "/main/go",
   :querydata => "",
   :servername => "testing:8002",
   :headers => {:connection => "keep-alive",
                :accept => "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
                :host => "localhost:8002",
                :referer => "http://localhost:8002/main/ready",
                :user_agent => "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3",
                :keep_alive => "300",
                :content_length => "7",
                :content_type => "application/x-www-form-urlencoded",
                :"Cache-Control" => "max-age=0",
                :"Accept-Charset" => "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
                :"Accept-Encoding" => "gzip,deflate",
                :"Accept-Language" => "en-us,en;q=0.5"},
   :cookies => ["_helloworld_session_id=d3eae987aab3230377abc433b7a8d7c1"],
   :pathinfo => "/Users/tom/dev/fuzed/helloworld/public",
   :postdata => "val=foo"}
  
  # [[:method, :GET], [:http_version, [1, 1]], [:querypath, "/main/say"], [:querydata, ""], [:servername, "testing:8002"], [:headers, [[:connection, "keep-alive"], [:accept, "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"], [:host, "localhost:8002"], [:user_agent, "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3"], [:keep_alive, "300"], [:"Cache-Control", "max-age=0"], [:"Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"], [:"Accept-Encoding", "gzip,deflate"], [:"Accept-Language", "en-us,en;q=0.5"]]], [:cookies, ["_helloworld_session_id=166098a3c3f702698d0529c6148c6164"]], [:pathinfo, "/Users/tom/dev/fuzed/helloworld/public"], [:postdata, :undefined]]
 
  p service(req)
  p service(req)
  p service(req)
  exit!
end