initial cut of the RevThreadSpawn model
[rainbows.git] / lib / rainbows.rb
blob4686f2bed0de7d0bfd68904e1494c70c3b637212
1 # -*- encoding: binary -*-
2 require 'unicorn'
4 module Rainbows
6   # global vars because class/instance variables are confusing me :<
7   # this struct is only accessed inside workers and thus private to each
8   # G.cur may not be used the network concurrency model
9   class State < Struct.new(:alive,:m,:cur,:server,:tmp)
10     def tick
11       tmp.chmod(self.m = m == 0 ? 1 : 0)
12       alive && server.master_pid == Process.ppid or quit!
13     end
15     def quit!
16       self.alive = false
17       server.class.const_get(:LISTENERS).map! { |s| s.close rescue nil }
18       false
19     end
20   end
21   G = State.new(true, 0, 0)
23   require 'rainbows/const'
24   require 'rainbows/http_server'
25   require 'rainbows/http_response'
26   require 'rainbows/base'
27   autoload :AppPool, 'rainbows/app_pool'
28   autoload :DevFdResponse, 'rainbows/dev_fd_response'
30   class << self
32     # runs the Rainbows! HttpServer with +app+ and +options+ and does
33     # not return until the server has exited.
34     def run(app, options = {})
35       HttpServer.new(app, options).start.join
36     end
37   end
39   # configures \Rainbows! with a given concurrency model to +use+ and
40   # a +worker_connections+ upper-bound.  This method may be called
41   # inside a Unicorn/Rainbows configuration file:
42   #
43   #   Rainbows! do
44   #     use :Revactor # this may also be :ThreadSpawn or :ThreadPool
45   #     worker_connections 400
46   #   end
47   #
48   #   # the rest of the Unicorn configuration
49   #   worker_processes 8
50   #
51   # See the documentation for the respective Revactor, ThreadSpawn,
52   # and ThreadPool classes for descriptions and recommendations for
53   # each of them.  The total number of clients we're able to serve is
54   # +worker_processes+ * +worker_connections+, so in the above example
55   # we can serve 8 * 400 = 3200 clients concurrently.
56   def Rainbows!(&block)
57     block_given? or raise ArgumentError, "Rainbows! requires a block"
58     HttpServer.setup(block)
59   end
61   # maps models to default worker counts, default worker count numbers are
62   # pretty arbitrary and tuning them to your application and hardware is
63   # highly recommended
64   MODEL_WORKER_CONNECTIONS = {
65     :Base => 1, # this one can't change
66     :Revactor => 50,
67     :ThreadSpawn => 30,
68     :ThreadPool => 10,
69     :Rev => 50,
70     :RevThreadSpawn => 50,
71     :EventMachine => 50,
72   }.each do |model, _|
73     u = model.to_s.gsub(/([a-z0-9])([A-Z0-9])/) { "#{$1}_#{$2.downcase!}" }
74     autoload model, "rainbows/#{u.downcase!}"
75   end
77 end
79 # inject the Rainbows! method into Unicorn::Configurator
80 Unicorn::Configurator.class_eval { include Rainbows }