1 # -*- encoding: binary -*-
3 require 'rainbows/error'
8 # global vars because class/instance variables are confusing me :<
9 # this struct is only accessed inside workers and thus private to each
10 # G.cur may not be used in the network concurrency model
11 class State < Struct.new(:alive,:m,:cur,:kato,:server,:tmp)
13 tmp.chmod(self.m = m == 0 ? 1 : 0)
14 alive && server.master_pid == Process.ppid or quit!
19 server.class.const_get(:LISTENERS).map! { |s| s.close rescue nil }
23 G = State.new(true, 0, 0, 2)
26 require 'rainbows/const'
27 require 'rainbows/http_server'
28 require 'rainbows/http_response'
29 require 'rainbows/base'
30 autoload :AppPool, 'rainbows/app_pool'
31 autoload :DevFdResponse, 'rainbows/dev_fd_response'
35 # runs the Rainbows! HttpServer with +app+ and +options+ and does
36 # not return until the server has exited.
37 def run(app, options = {})
38 HttpServer.new(app, options).start.join
42 # configures \Rainbows! with a given concurrency model to +use+ and
43 # a +worker_connections+ upper-bound. This method may be called
44 # inside a Unicorn/Rainbows configuration file:
47 # use :Revactor # this may also be :ThreadSpawn or :ThreadPool
48 # worker_connections 400
49 # keepalive_timeout 0 # zero disables keepalives entirely
52 # # the rest of the Unicorn configuration
55 # See the documentation for the respective Revactor, ThreadSpawn,
56 # and ThreadPool classes for descriptions and recommendations for
57 # each of them. The total number of clients we're able to serve is
58 # +worker_processes+ * +worker_connections+, so in the above example
59 # we can serve 8 * 400 = 3200 clients concurrently.
61 # The default is +keepalive_timeout+ is 2 seconds, which should be
62 # enough under most conditions for browsers to render the page and
63 # start retrieving extra elements for. Increasing this beyond 5
64 # seconds is not recommended. Zero disables keepalive entirely
65 # (but pipelining fully-formed requests is still works).
67 block_given? or raise ArgumentError, "Rainbows! requires a block"
68 HttpServer.setup(block)
71 # maps models to default worker counts, default worker count numbers are
72 # pretty arbitrary and tuning them to your application and hardware is
74 MODEL_WORKER_CONNECTIONS = {
75 :Base => 1, # this one can't change
80 :RevThreadSpawn => 50,
87 u = model.to_s.gsub(/([a-z0-9])([A-Z0-9])/) { "#{$1}_#{$2.downcase!}" }
88 autoload model, "rainbows/#{u.downcase!}"
90 autoload :Fiber, 'rainbows/fiber' # core class
92 # returns nil if accept fails
93 if defined?(Fcntl::FD_CLOEXEC)
95 rv = sock.accept_nonblock
96 rv.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
98 rescue Errno::EAGAIN, Errno::ECONNABORTED
101 def self.accept(sock)
103 rescue Errno::EAGAIN, Errno::ECONNABORTED
109 # inject the Rainbows! method into Unicorn::Configurator
110 Unicorn::Configurator.class_eval { include Rainbows }